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, '');
183 $privacy = CRM_Utils_Array
::value('privacy', $params);
185 is_array($privacy) &&
189 foreach (self
::$_commPrefs as $name) {
190 $contact->$name = CRM_Utils_Array
::value($name, $privacy, FALSE);
194 // Since hash was required, make sure we have a 0 value for it (CRM-1063).
195 // @todo - does this mean we can remove this block?
196 // Fixed in 1.5 by making hash optional, only do this in create mode, not update.
197 if ((!array_key_exists('hash', $contact) ||
!$contact->hash
) && !$contact->id
) {
199 $contact->hash
= md5(uniqid(rand(), TRUE));
202 // Even if we don't need $employerId, it's important to call getFieldValue() before
203 // the contact is saved because we want the existing value to be cached.
204 // createCurrentEmployerRelationship() needs the old value not the updated one. CRM-10788
205 $employerId = empty($contact->id
) ?
NULL : CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contact->id
, 'employer_id');
210 CRM_Core_BAO_Log
::register($contact->id
,
216 if ($contact->contact_type
== 'Individual' && (isset($params['current_employer']) ||
isset($params['employer_id']))) {
217 // Create current employer.
218 $newEmployer = !empty($params['employer_id']) ?
$params['employer_id'] : CRM_Utils_Array
::value('current_employer', $params);
221 if (empty($params['contact_id'])) {
225 CRM_Contact_BAO_Contact_Utils
::createCurrentEmployerRelationship($contact->id
, $newEmployer, $employerId, $newContact);
229 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($contact->id
, $employerId);
234 // Update cached employer name.
235 if ($contact->contact_type
== 'Organization') {
236 CRM_Contact_BAO_Contact_Utils
::updateCurrentEmployer($contact->id
);
245 * takes an associative array and creates a contact object and all the associated
246 * derived objects (i.e. individual, location, email, phone etc)
248 * This function is invoked from within the web form layer and also from the api layer
250 * @param array $params
251 * (reference ) an assoc array of name/value pairs.
252 * @param bool $fixAddress
253 * If we need to fix address.
254 * @param bool $invokeHooks
255 * If we need to invoke hooks.
257 * @param bool $skipDelete
258 * Unclear parameter, passed to website create
260 * @todo explain this parameter
263 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
264 * Created or updated contribution object. We are deprecating returning an error in
265 * favour of exceptions
267 public static function &create(&$params, $fixAddress = TRUE, $invokeHooks = TRUE, $skipDelete = FALSE) {
269 if (empty($params['contact_type']) && empty($params['contact_id'])) {
275 if (!empty($params['contact_id'])) {
276 CRM_Utils_Hook
::pre('edit', $params['contact_type'], $params['contact_id'], $params);
279 CRM_Utils_Hook
::pre('create', $params['contact_type'], NULL, $params);
284 $config = CRM_Core_Config
::singleton();
286 // CRM-6942: set preferred language to the current language if it’s unset (and we’re creating a contact).
287 if (empty($params['contact_id'])) {
288 // A case could be made for checking isset rather than empty but this is more consistent with previous behaviour.
289 if (empty($params['preferred_language']) && ($language = CRM_Core_I18n
::getContactDefaultLanguage()) != FALSE) {
290 $params['preferred_language'] = $language;
293 // CRM-9739: set greeting & addressee if unset and we’re creating a contact.
294 foreach (self
::$_greetingTypes as $greeting) {
295 if (empty($params[$greeting . '_id'])) {
296 if ($defaultGreetingTypeId
297 = CRM_Contact_BAO_Contact_Utils
::defaultGreeting($params['contact_type'], $greeting)
299 $params[$greeting . '_id'] = $defaultGreetingTypeId;
305 $transaction = new CRM_Core_Transaction();
307 $contact = self
::add($params);
309 // Not dying here is stupid, since we get into weird situation and into a bug that
310 // is impossible to figure out for the user or for us
312 CRM_Core_Error
::fatal();
315 $params['contact_id'] = $contact->id
;
317 if (Civi
::settings()->get('is_enabled')) {
318 // Enabling multisite causes the contact to be added to the domain group.
319 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
320 if (!empty($domainGroupID)) {
321 if (!empty($params['group']) && is_array($params['group'])) {
322 $params['group'][$domainGroupID] = 1;
325 $params['group'] = array($domainGroupID => 1);
330 if (array_key_exists('group', $params)) {
331 $contactIds = array($params['contact_id']);
332 foreach ($params['group'] as $groupId => $flag) {
334 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
336 elseif ($flag == -1) {
337 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $groupId);
342 // Add location Block data.
343 $blocks = CRM_Core_BAO_Location
::create($params, $fixAddress);
344 foreach ($blocks as $name => $value) {
345 $contact->$name = $value;
347 if (!empty($params['updateBlankLocInfo'])) {
352 CRM_Core_BAO_Website
::create($params['website'], $contact->id
, $skipDelete);
354 //get userID from session
355 $session = CRM_Core_Session
::singleton();
356 $userID = $session->get('userID');
358 if (!empty($params['note'])) {
359 if (is_array($params['note'])) {
360 foreach ($params['note'] as $note) {
361 $contactId = $contact->id
;
362 if (isset($note['contact_id'])) {
363 $contactId = $note['contact_id'];
365 //if logged in user, overwrite contactId
367 $contactId = $userID;
371 'entity_id' => $contact->id
,
372 'entity_table' => 'civicrm_contact',
373 'note' => $note['note'],
374 'subject' => CRM_Utils_Array
::value('subject', $note),
375 'contact_id' => $contactId,
377 CRM_Core_BAO_Note
::add($noteParams, CRM_Core_DAO
::$_nullArray);
381 $contactId = $contact->id
;
382 if (isset($note['contact_id'])) {
383 $contactId = $note['contact_id'];
385 //if logged in user, overwrite contactId
387 $contactId = $userID;
391 'entity_id' => $contact->id
,
392 'entity_table' => 'civicrm_contact',
393 'note' => $params['note'],
394 'subject' => CRM_Utils_Array
::value('subject', $params),
395 'contact_id' => $contactId,
397 CRM_Core_BAO_Note
::add($noteParams, CRM_Core_DAO
::$_nullArray);
401 // update the UF user_unique_id if that has changed
402 CRM_Core_BAO_UFMatch
::updateUFName($contact->id
);
404 if (!empty($params['custom']) &&
405 is_array($params['custom'])
407 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contact', $contact->id
);
410 // make a civicrm_subscription_history entry only on contact create (CRM-777)
411 if (empty($params['contact_id'])) {
412 $subscriptionParams = array(
413 'contact_id' => $contact->id
,
417 CRM_Contact_BAO_SubscriptionHistory
::create($subscriptionParams);
420 $transaction->commit();
422 // CRM-6367: fetch the right label for contact type’s display
423 $contact->contact_type_display
= CRM_Core_DAO
::getFieldValue(
424 'CRM_Contact_DAO_ContactType',
425 $contact->contact_type
,
430 if (!$config->doNotResetCache
) {
431 // Note: doNotResetCache flag is currently set by import contact process and merging,
432 // since resetting and
433 // rebuilding cache could be expensive (for many contacts). We might come out with better
434 // approach in future.
435 CRM_Contact_BAO_Contact_Utils
::clearContactCaches($contact->id
);
440 CRM_Utils_Hook
::post('edit', $params['contact_type'], $contact->id
, $contact);
443 CRM_Utils_Hook
::post('create', $params['contact_type'], $contact->id
, $contact);
447 // process greetings CRM-4575, cache greetings
448 self
::processGreetings($contact);
454 * Get the display name and image of a contact.
459 * @param bool $includeTypeInReturnParameters
460 * Should type be part of the returned array?
463 * the displayName and contactImage for this contact
465 public static function getDisplayAndImage($id, $includeTypeInReturnParameters = FALSE) {
466 //CRM-14276 added the * on the civicrm_contact table so that we have all the contact info available
468 SELECT civicrm_contact.*,
469 civicrm_email.email as email
471 LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
472 AND civicrm_email.is_primary = 1
473 WHERE civicrm_contact.id = " . CRM_Utils_Type
::escape($id, 'Integer');
474 $dao = new CRM_Core_DAO();
477 $image = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
478 $dao->contact_sub_type
: $dao->contact_type
, FALSE, $id
480 $imageUrl = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
481 $dao->contact_sub_type
: $dao->contact_type
, TRUE, $id
484 // use email if display_name is empty
485 if (empty($dao->display_name
)) {
486 $displayName = $dao->email
;
489 $displayName = $dao->display_name
;
492 CRM_Utils_Hook
::alterDisplayName($displayName, $id, $dao);
494 return $includeTypeInReturnParameters ?
array(
498 $dao->contact_sub_type
,
500 ) : array($displayName, $image, $imageUrl);
506 * Add billing fields to the params if appropriate.
508 * If we have ANY name fields then we want to ignore all the billing name fields. However, if we
509 * don't then we should set the name fields to the filling fields AND add the preserveDBName
510 * parameter (which will tell the BAO only to set those fields if none already exist.
512 * We specifically don't want to set first name from billing and last name form an on-page field. Mixing &
513 * matching is best done by hipsters.
515 * @param array $params
517 public static function addBillingNameFieldsIfOtherwiseNotSet(&$params) {
518 $nameFields = array('first_name', 'middle_name', 'last_name', 'nick_name', 'prefix_id', 'suffix_id');
519 foreach ($nameFields as $field) {
520 if (!empty($params[$field])) {
524 // There are only 3 - we can iterate through them twice :-)
525 foreach ($nameFields as $field) {
526 if (!empty($params['billing_' . $field])) {
527 $params[$field] = $params['billing_' . $field];
529 $params['preserveDBName'] = TRUE;
535 * Create last viewed link to recently updated contact.
537 * @param array $crudLinkSpec
538 * - action: int, CRM_Core_Action::UPDATE or CRM_Core_Action::VIEW [default: VIEW]
539 * - entity_table: string, eg "civicrm_contact"
543 * NULL if unavailable, or
544 * [path: string, query: string, title: string]
545 * @see CRM_Utils_System::createDefaultCrudLink
547 public function createDefaultCrudLink($crudLinkSpec) {
548 switch ($crudLinkSpec['action']) {
549 case CRM_Core_Action
::VIEW
:
551 'title' => $this->display_name
,
552 'path' => 'civicrm/contact/view',
560 case CRM_Core_Action
::UPDATE
:
562 'title' => $this->display_name
,
563 'path' => 'civicrm/contact/add',
566 'action' => 'update',
576 * Get the values for pseudoconstants for name->value and reverse.
578 * @param array $defaults
579 * (reference) the default values, some of which need to be resolved.
580 * @param bool $reverse
581 * True if we want to resolve the values in the reverse direction (value -> name).
583 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
584 // Hack for birth_date.
585 if (!empty($defaults['birth_date'])) {
586 if (is_array($defaults['birth_date'])) {
587 $defaults['birth_date'] = CRM_Utils_Date
::format($defaults['birth_date'], '-');
591 CRM_Utils_Array
::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id'), $reverse);
592 CRM_Utils_Array
::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'suffix_id'), $reverse);
593 CRM_Utils_Array
::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'), $reverse);
594 CRM_Utils_Array
::lookupValue($defaults, 'communication_style', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'communication_style_id'), $reverse);
596 //lookup value of email/postal greeting, addressee, CRM-4575
597 foreach (self
::$_greetingTypes as $greeting) {
598 $filterCondition = array(
599 'contact_type' => CRM_Utils_Array
::value('contact_type', $defaults),
600 'greeting_type' => $greeting,
602 CRM_Utils_Array
::lookupValue($defaults, $greeting,
603 CRM_Core_PseudoConstant
::greeting($filterCondition), $reverse
607 $blocks = array('address', 'im', 'phone');
608 foreach ($blocks as $name) {
609 if (!array_key_exists($name, $defaults) ||
!is_array($defaults[$name])) {
612 foreach ($defaults[$name] as $count => & $values) {
614 //get location type id.
615 CRM_Utils_Array
::lookupValue($values, 'location_type', CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id'), $reverse);
617 if ($name == 'address') {
618 // FIXME: lookupValue doesn't work for vcard_name
619 if (!empty($values['location_type_id'])) {
620 $vcardNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array('labelColumn' => 'vcard_name'));
621 $values['vcard_name'] = $vcardNames[$values['location_type_id']];
624 if (!CRM_Utils_Array
::lookupValue($values,
626 CRM_Core_PseudoConstant
::country(),
631 CRM_Utils_Array
::lookupValue($values,
633 CRM_Core_PseudoConstant
::countryIsoCode(),
639 // if we find a country id above, we need to restrict it to that country
640 // rather than the list of all countries
642 if (!empty($values['country_id'])) {
643 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($values['country_id']);
646 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvince();
648 if (!CRM_Utils_Array
::lookupValue($values,
656 if (!empty($values['country_id'])) {
657 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($values['country_id'], 'abbreviation');
660 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviation();
662 CRM_Utils_Array
::lookupValue($values,
669 if (!empty($values['state_province_id'])) {
670 $countyList = CRM_Core_PseudoConstant
::countyForState($values['state_province_id']);
673 $countyList = CRM_Core_PseudoConstant
::county();
675 CRM_Utils_Array
::lookupValue($values,
683 CRM_Utils_Array
::lookupValue($values,
685 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id'),
690 if ($name == 'phone') {
691 CRM_Utils_Array
::lookupValue($values,
693 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id'),
698 // Kill the reference.
705 * Fetch object based on array of properties.
707 * @param array $params
708 * (reference ) an assoc array of name/value pairs.
709 * @param array $defaults
710 * (reference ) an assoc array to hold the name / value pairs.
711 * in a hierarchical manner
712 * @param bool $microformat
713 * For location in microformat.
715 * @return CRM_Contact_BAO_Contact
717 public static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
718 if (array_key_exists('contact_id', $params)) {
719 $params['id'] = $params['contact_id'];
721 elseif (array_key_exists('id', $params)) {
722 $params['contact_id'] = $params['id'];
725 $contact = self
::getValues($params, $defaults);
727 unset($params['id']);
729 //get the block information for this contact
730 $entityBlock = array('contact_id' => $params['contact_id']);
731 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock, $microformat);
732 $defaults = array_merge($defaults, $blocks);
733 foreach ($blocks as $block => $value) {
734 $contact->$block = $value;
737 if (!isset($params['noNotes'])) {
738 $contact->notes
= CRM_Core_BAO_Note
::getValues($params, $defaults);
741 if (!isset($params['noRelationships'])) {
742 $contact->relationship
= CRM_Contact_BAO_Relationship
::getValues($params, $defaults);
745 if (!isset($params['noGroups'])) {
746 $contact->groupContact
= CRM_Contact_BAO_GroupContact
::getValues($params, $defaults);
749 if (!isset($params['noWebsite'])) {
750 $contact->website
= CRM_Core_BAO_Website
::getValues($params, $defaults);
757 * Get the display name of a contact.
762 * @return null|string
763 * display name of the contact if found
765 public static function displayName($id) {
768 $displayName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
775 * Delete a contact and all its associated records.
778 * Id of the contact to delete.
779 * @param bool $restore
780 * Whether to actually restore, not delete.
781 * @param bool $skipUndelete
782 * Whether to force contact delete or not.
783 * @param bool $checkPermissions
786 * Was contact deleted?
788 public static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE, $checkPermissions = TRUE) {
793 // If trash is disabled in system settings then we always skip
794 if (!Civi
::settings()->get('contact_undelete')) {
795 $skipUndelete = TRUE;
798 // make sure we have edit permission for this contact
800 if ($checkPermissions && (($skipUndelete && !CRM_Core_Permission
::check('delete contacts')) ||
801 ($restore && !CRM_Core_Permission
::check('access deleted contacts')))
807 // Restrict contact to be delete if contact has financial trxns
809 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent(array($id), $error)) {
813 // make sure this contact_id does not have any membership types
814 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
817 'member_of_contact_id'
819 if ($membershipTypeID) {
823 $contact = new CRM_Contact_DAO_Contact();
825 if (!$contact->find(TRUE)) {
829 $contactType = $contact->contact_type
;
830 // currently we only clear employer cache.
831 // we are now deleting inherited membership if any.
832 if ($contact->contact_type
== 'Organization') {
833 $action = $restore ? CRM_Core_Action
::ENABLE
: CRM_Core_Action
::DISABLE
;
834 $relationshipDtls = CRM_Contact_BAO_Relationship
::getRelationship($id);
835 if (!empty($relationshipDtls)) {
836 foreach ($relationshipDtls as $rId => $details) {
837 CRM_Contact_BAO_Relationship
::disableEnableRelationship($rId, $action);
840 CRM_Contact_BAO_Contact_Utils
::clearAllEmployee($id);
844 return self
::contactTrashRestore($contact, TRUE);
847 // start a new transaction
848 $transaction = new CRM_Core_Transaction();
851 CRM_Utils_Hook
::pre('delete', $contactType, $id, CRM_Core_DAO
::$_nullArray);
853 //delete billing address if exists.
854 CRM_Contribute_BAO_Contribution
::deleteAddress(NULL, $id);
856 // delete the log entries since we dont have triggers enabled as yet
857 $logDAO = new CRM_Core_DAO_Log();
858 $logDAO->entity_table
= 'civicrm_contact';
859 $logDAO->entity_id
= $id;
862 // delete contact participants CRM-12155
863 CRM_Event_BAO_Participant
::deleteContactParticipant($id);
865 // delete contact contributions CRM-12155
866 CRM_Contribute_BAO_Contribution
::deleteContactContribution($id);
868 // do activity cleanup, CRM-5604
869 CRM_Activity_BAO_Activity
::cleanupActivity($id);
871 // delete all notes related to contact
872 CRM_Core_BAO_Note
::cleanContactNotes($id);
874 // delete cases related to contact
875 $contactCases = CRM_Case_BAO_Case
::retrieveCaseIdsByContactId($id);
876 if (!empty($contactCases)) {
877 foreach ($contactCases as $caseId) {
878 //check if case is associate with other contact or not.
879 $caseContactId = CRM_Case_BAO_Case
::getCaseClients($caseId);
880 if (count($caseContactId) <= 1) {
881 CRM_Case_BAO_Case
::deleteCase($caseId);
889 self
::contactTrashRestore($contact);
892 //delete the contact id from recently view
893 CRM_Utils_Recent
::delContact($id);
894 self
::updateContactCache($id, empty($restore));
896 // delete any dupe cache entry
897 CRM_Core_BAO_PrevNextCache
::deleteItem($id);
899 $transaction->commit();
902 CRM_Utils_Hook
::post('delete', $contactType, $contact->id
, $contact);
905 // also reset the DB_DO global array so we can reuse the memory
906 // http://issues.civicrm.org/jira/browse/CRM-4387
907 CRM_Core_DAO
::freeResult();
913 * Action to update any caches relating to a recently update contact.
915 * I was going to call this from delete as well as from create to ensure the delete is being
916 * done whenever a contact is set to is_deleted=1 BUT I found create is already over-aggressive in
917 * that regard so adding it to delete seems to be enough to remove it from CRM_Contact_BAO_Contact_Permission
918 * where the call involved a subquery that was locking the table.
920 * @param int $contactID
921 * @param bool $isTrashed
923 public static function updateContactCache($contactID, $isTrashed = FALSE) {
926 CRM_Contact_BAO_GroupContactCache
::removeContact($contactID);
927 // This has been moved to here from CRM_Contact_BAO_Contact_Permission as that was causing
928 // a table-locking query. It still seems a bit inadequate as it assumes the acl users can't see deleted
929 // but this should not cause any change as long as contacts are not being trashed outside the
930 // main functions for that.
931 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_acl_contact_cache WHERE contact_id = %1', array(1 => array($contactID, 'Integer')));
934 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
939 * Delete the image of a contact.
945 * Was contact image deleted?
947 public static function deleteContactImage($id) {
952 UPDATE civicrm_contact
955 CRM_Core_DAO
::executeQuery($query);
960 * Return proportional height and width of the image.
962 * @param int $imageWidth
965 * @param int $imageHeight
969 * Thumb dimension of image
971 public static function getThumbSize($imageWidth, $imageHeight) {
973 if ($imageWidth && $imageHeight) {
974 $imageRatio = $imageWidth / $imageHeight;
979 if ($imageRatio > 1) {
980 $imageThumbWidth = $thumbWidth;
981 $imageThumbHeight = round($thumbWidth / $imageRatio);
984 $imageThumbHeight = $thumbWidth;
985 $imageThumbWidth = round($thumbWidth * $imageRatio);
988 return array($imageThumbWidth, $imageThumbHeight);
992 * Validate type of contact image.
994 * @param array $params
995 * @param string $imageIndex
996 * Index of image field.
997 * @param string $statusMsg
998 * Status message to be set after operation.
999 * @param string $opType
1000 * Type of operation like fatal, bounce etc.
1003 * true if valid image extension
1005 public static function processImageParams(
1007 $imageIndex = 'image_URL',
1021 if (in_array($params[$imageIndex]['type'], $mimeType)) {
1022 $photo = basename($params[$imageIndex]['name']);
1023 $params[$imageIndex] = CRM_Utils_System
::url('civicrm/contact/imagefile', 'photo=' . $photo, TRUE, NULL, TRUE, TRUE);
1027 unset($params[$imageIndex]);
1029 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
1031 if ($opType == 'status') {
1032 CRM_Core_Session
::setStatus($statusMsg, 'Sorry', 'error');
1034 // FIXME: additional support for fatal, bounce etc could be added.
1040 * Extract contact id from url for deleting contact image.
1042 public static function processImage() {
1044 $action = CRM_Utils_Request
::retrieve('action', 'String');
1045 $cid = CRM_Utils_Request
::retrieve('cid', 'Positive');
1046 // retrieve contact id in case of Profile context
1047 $id = CRM_Utils_Request
::retrieve('id', 'Positive');
1048 $cid = $cid ?
$cid : $id;
1049 if ($action & CRM_Core_Action
::DELETE
) {
1050 if (CRM_Utils_Request
::retrieve('confirmed', 'Boolean')) {
1051 CRM_Contact_BAO_Contact
::deleteContactImage($cid);
1052 CRM_Core_Session
::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
1053 $session = CRM_Core_Session
::singleton();
1054 $toUrl = $session->popUserContext();
1055 CRM_Utils_System
::redirect($toUrl);
1061 * Function to set is_delete true or restore deleted contact.
1063 * @param CRM_Contact_DAO_Contact $contact
1064 * Contact DAO object.
1065 * @param bool $restore
1066 * True to set the is_delete = 1 else false to restore deleted contact,
1067 * i.e. is_delete = 0
1071 public static function contactTrashRestore($contact, $restore = FALSE) {
1072 $updateParams = array(
1073 'id' => $contact->id
,
1074 'is_deleted' => $restore ?
0 : 1,
1077 CRM_Utils_Hook
::pre('update', $contact->contact_type
, $contact->id
, $updateParams);
1079 $params = array(1 => array($contact->id
, 'Integer'));
1081 $query = "DELETE FROM civicrm_uf_match WHERE contact_id = %1";
1082 CRM_Core_DAO
::executeQuery($query, $params);
1085 $contact->copyValues($updateParams);
1088 CRM_Utils_Hook
::post('update', $contact->contact_type
, $contact->id
, $contact);
1094 * Get contact type for a contact.
1097 * Id of the contact whose contact type is needed.
1100 * contact_type if $id found else null ""
1102 public static function getContactType($id) {
1103 return CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1107 * Get contact sub type for a contact.
1110 * Id of the contact whose contact sub type is needed.
1112 * @param string $implodeDelimiter
1115 * contact_sub_type if $id found else null ""
1117 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1118 $subtype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1120 return $implodeDelimiter ?
NULL : array();
1123 $subtype = CRM_Utils_Array
::explodePadded($subtype);
1125 if ($implodeDelimiter) {
1126 $subtype = implode($implodeDelimiter, $subtype);
1132 * Get pair of contact-type and sub-type for a contact.
1135 * Id of the contact whose contact sub/contact type is needed.
1139 public static function getContactTypes($id) {
1140 $params = array('id' => $id);
1142 $contact = CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact',
1145 array('contact_type', 'contact_sub_type')
1149 $contactTypes = array();
1150 if ($contact->contact_sub_type
) {
1151 $contactTypes = CRM_Utils_Array
::explodePadded($contact->contact_sub_type
);
1153 array_unshift($contactTypes, $contact->contact_type
);
1155 return $contactTypes;
1158 CRM_Core_Error
::fatal();
1163 * Combine all the importable fields from the lower levels object.
1165 * The ordering is important, since currently we do not have a weight
1166 * scheme. Adding weight is super important
1168 * @param int|string $contactType contact Type
1169 * @param bool $status
1170 * Status is used to manipulate first title.
1171 * @param bool $showAll
1172 * If true returns all fields (includes disabled fields).
1173 * @param bool $isProfile
1174 * If its profile mode.
1175 * @param bool $checkPermission
1176 * If false, do not include permissioning clause (for custom data).
1178 * @param bool $withMultiCustomFields
1181 * array of importable Fields
1183 public static function importableFields(
1184 $contactType = 'Individual',
1188 $checkPermission = TRUE,
1189 $withMultiCustomFields = FALSE
1191 if (empty($contactType)) {
1192 $contactType = 'All';
1195 $cacheKeyString = "importableFields $contactType";
1196 $cacheKeyString .= $status ?
'_1' : '_0';
1197 $cacheKeyString .= $showAll ?
'_1' : '_0';
1198 $cacheKeyString .= $isProfile ?
'_1' : '_0';
1199 $cacheKeyString .= $checkPermission ?
'_1' : '_0';
1201 $fields = CRM_Utils_Array
::value($cacheKeyString, self
::$_importableFields);
1204 // check if we can retrieve from database cache
1205 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1209 $fields = CRM_Contact_DAO_Contact
::import();
1211 // get the fields thar are meant for contact types
1212 if (in_array($contactType, array(
1218 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1221 $locationFields = array_merge(CRM_Core_DAO_Address
::import(),
1222 CRM_Core_DAO_Phone
::import(),
1223 CRM_Core_DAO_Email
::import(),
1224 CRM_Core_DAO_IM
::import(TRUE),
1225 CRM_Core_DAO_OpenID
::import()
1228 $locationFields = array_merge($locationFields,
1229 CRM_Core_BAO_CustomField
::getFieldsForImport('Address',
1237 foreach ($locationFields as $key => $field) {
1238 $locationFields[$key]['hasLocationType'] = TRUE;
1241 $fields = array_merge($fields, $locationFields);
1243 $fields = array_merge($fields, CRM_Contact_DAO_Contact
::import());
1244 $fields = array_merge($fields, CRM_Core_DAO_Note
::import());
1247 $fields = array_merge($fields, CRM_Core_DAO_Website
::import());
1248 $fields['url']['hasWebsiteType'] = TRUE;
1250 if ($contactType != 'All') {
1251 $fields = array_merge($fields,
1252 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType,
1257 $withMultiCustomFields
1260 //unset the fields, which are not related to their
1262 $commonValues = array(
1263 'Individual' => array(
1267 'organization_name',
1269 'Household' => array(
1279 'organization_name',
1287 'Organization' => array(
1302 foreach ($commonValues[$contactType] as $value) {
1303 unset($fields[$value]);
1307 foreach (array('Individual', 'Household', 'Organization') as $type) {
1308 $fields = array_merge($fields,
1309 CRM_Core_BAO_CustomField
::getFieldsForImport($type,
1314 $withMultiCustomFields
1321 $fields = array_merge($fields, array(
1323 'title' => ts('Group(s)'),
1327 'title' => ts('Tag(s)'),
1331 'title' => ts('Note(s)'),
1334 'communication_style_id' => array(
1335 'title' => ts('Communication Style'),
1336 'name' => 'communication_style_id',
1341 //Sorting fields in alphabetical order(CRM-1507)
1342 $fields = CRM_Utils_Array
::crmArraySortByField($fields, 'title');
1344 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1347 self
::$_importableFields[$cacheKeyString] = $fields;
1351 $fields = array_merge(array('do_not_import' => array('title' => ts('- do not import -'))),
1352 self
::$_importableFields[$cacheKeyString]
1356 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1357 self
::$_importableFields[$cacheKeyString]
1365 * Combine all the exportable fields from the lower levels object.
1367 * Currently we are using importable fields as exportable fields
1369 * @param int|string $contactType contact Type
1370 * @param bool $status
1371 * True while exporting primary contacts.
1372 * @param bool $export
1373 * True when used during export.
1374 * @param bool $search
1375 * True when used during search, might conflict with export param?.
1377 * @param bool $withMultiRecord
1380 * array of exportable Fields
1382 public static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE, $checkPermissions = TRUE) {
1383 if (empty($contactType)) {
1384 $contactType = 'All';
1387 $cacheKeyString = "exportableFields $contactType";
1388 $cacheKeyString .= $export ?
'_1' : '_0';
1389 $cacheKeyString .= $status ?
'_1' : '_0';
1390 $cacheKeyString .= $search ?
'_1' : '_0';
1391 //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
1392 //calculates custom fields takes into account the logged in user & caches that for all users
1393 //as an interim fix we will cache the fields by contact
1394 $cacheKeyString .= '_' . CRM_Core_Session
::getLoggedInContactID();
1396 if (!self
::$_exportableFields ||
!CRM_Utils_Array
::value($cacheKeyString, self
::$_exportableFields)) {
1397 if (!self
::$_exportableFields) {
1398 self
::$_exportableFields = array();
1401 // check if we can retrieve from database cache
1402 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1405 $fields = CRM_Contact_DAO_Contact
::export();
1407 // The fields are meant for contact types.
1408 if (in_array($contactType, array(
1415 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1417 // add current employer for individuals
1418 $fields = array_merge($fields, array(
1419 'current_employer' =>
1421 'name' => 'organization_name',
1422 'title' => ts('Current Employer'),
1426 $locationType = array(
1427 'location_type' => array(
1428 'name' => 'location_type',
1429 'where' => 'civicrm_location_type.name',
1430 'title' => ts('Location Type'),
1434 $IMProvider = array(
1435 'im_provider' => array(
1436 'name' => 'im_provider',
1437 'where' => 'civicrm_im.provider_id',
1438 'title' => ts('IM Provider'),
1442 $locationFields = array_merge($locationType,
1443 CRM_Core_DAO_Address
::export(),
1444 CRM_Core_DAO_Phone
::export(),
1445 CRM_Core_DAO_Email
::export(),
1447 CRM_Core_DAO_IM
::export(TRUE),
1448 CRM_Core_DAO_OpenID
::export()
1451 $locationFields = array_merge($locationFields,
1452 CRM_Core_BAO_CustomField
::getFieldsForImport('Address')
1455 foreach ($locationFields as $key => $field) {
1456 $locationFields[$key]['hasLocationType'] = TRUE;
1459 $fields = array_merge($fields, $locationFields);
1462 $fields = array_merge($fields,
1463 CRM_Core_DAO_Worldregion
::export()
1466 $fields = array_merge($fields,
1467 CRM_Contact_DAO_Contact
::export()
1471 $fields = array_merge($fields, CRM_Core_DAO_Website
::export());
1473 if ($contactType != 'All') {
1474 $fields = array_merge($fields,
1475 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType, $status, FALSE, $search, $checkPermissions, $withMultiRecord)
1484 $fields = array_merge($fields,
1485 CRM_Core_BAO_CustomField
::getFieldsForImport($type, FALSE, FALSE, $search, $checkPermissions, $withMultiRecord)
1489 $fields['current_employer_id']['title'] = ts('Current Employer ID');
1492 $fields = array_merge($fields, array(
1494 'title' => ts('Group(s)'),
1498 'title' => ts('Tag(s)'),
1502 'title' => ts('Note(s)'),
1508 $fields = array_merge($fields, array(
1510 'title' => ts('Group(s)'),
1514 'title' => ts('Tag(s)'),
1518 'title' => ts('Note(s)'),
1524 //Sorting fields in alphabetical order(CRM-1507)
1525 foreach ($fields as $k => $v) {
1526 $sortArray[$k] = CRM_Utils_Array
::value('title', $v);
1529 $fields = array_merge($sortArray, $fields);
1530 //unset the field which are not related to their contact type.
1531 if ($contactType != 'All') {
1532 $commonValues = array(
1533 'Individual' => array(
1537 'organization_name',
1538 'email_greeting_custom',
1539 'postal_greeting_custom',
1542 'Household' => array(
1552 'organization_name',
1560 'email_greeting_custom',
1561 'postal_greeting_custom',
1566 'Organization' => array(
1577 'email_greeting_custom',
1578 'postal_greeting_custom',
1588 foreach ($commonValues[$contactType] as $value) {
1589 unset($fields[$value]);
1593 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1595 self
::$_exportableFields[$cacheKeyString] = $fields;
1599 $fields = self
::$_exportableFields[$cacheKeyString];
1602 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1603 self
::$_exportableFields[$cacheKeyString]
1611 * Get the all contact details (Hierarchical).
1613 * @param int $contactId
1615 * @param array $fields
1621 public static function getHierContactDetails($contactId, &$fields) {
1622 $params = array(array('contact_id', '=', $contactId, 0, 0));
1625 $returnProperties = self
::makeHierReturnProperties($fields, $contactId);
1627 // We don't know the contents of return properties, but we need the lower
1628 // level ids of the contact so add a few fields.
1629 $returnProperties['first_name'] = 1;
1630 $returnProperties['organization_name'] = 1;
1631 $returnProperties['household_name'] = 1;
1632 $returnProperties['contact_type'] = 1;
1633 $returnProperties['contact_sub_type'] = 1;
1634 return list($query, $options) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, $options);
1638 * Given a set of flat profile style field names, create a hierarchy.
1640 * This is for the query to use, create the right sql.
1643 * @param int $contactId
1647 * A hierarchical property tree if appropriate
1649 public static function &makeHierReturnProperties($fields, $contactId = NULL) {
1650 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1652 $returnProperties = array();
1654 $multipleFields = array('website' => 'url');
1655 foreach ($fields as $name => $dontCare) {
1656 if (strpos($name, '-') !== FALSE) {
1657 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $name, 3);
1659 if (!in_array($fieldName, $multipleFields)) {
1660 if ($id == 'Primary') {
1661 $locationTypeName = 1;
1664 $locationTypeName = CRM_Utils_Array
::value($id, $locationTypes);
1665 if (!$locationTypeName) {
1670 if (empty($returnProperties['location'])) {
1671 $returnProperties['location'] = array();
1673 if (empty($returnProperties['location'][$locationTypeName])) {
1674 $returnProperties['location'][$locationTypeName] = array();
1675 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1677 if (in_array($fieldName, array(
1685 $returnProperties['location'][$locationTypeName][$fieldName . '-' . $type] = 1;
1688 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1691 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1692 $returnProperties['location'][$locationTypeName][substr($fieldName, 8)] = 1;
1695 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1699 $returnProperties['website'][$id][$fieldName] = 1;
1703 $returnProperties[$name] = 1;
1707 return $returnProperties;
1711 * Return the primary location type of a contact.
1713 * $params int $contactId contact_id
1714 * $params boolean $isPrimaryExist if true, return primary contact location type otherwise null
1715 * $params boolean $skipDefaultPriamry if true, return primary contact location type otherwise null
1717 * @param int $contactId
1718 * @param bool $skipDefaultPriamry
1719 * @param null $block
1722 * $locationType location_type_id
1724 public static function getPrimaryLocationType($contactId, $skipDefaultPriamry = FALSE, $block = NULL) {
1726 $entityBlock = array('contact_id' => $contactId);
1727 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock);
1728 foreach ($blocks[$block] as $key => $value) {
1729 if (!empty($value['is_primary'])) {
1730 $locationType = CRM_Utils_Array
::value('location_type_id', $value);
1737 IF ( civicrm_email.location_type_id IS NULL,
1738 IF ( civicrm_address.location_type_id IS NULL,
1739 IF ( civicrm_phone.location_type_id IS NULL,
1740 IF ( civicrm_im.location_type_id IS NULL,
1741 IF ( civicrm_openid.location_type_id IS NULL, null, civicrm_openid.location_type_id)
1742 ,civicrm_im.location_type_id)
1743 ,civicrm_phone.location_type_id)
1744 ,civicrm_address.location_type_id)
1745 ,civicrm_email.location_type_id) as locationType
1746 FROM civicrm_contact
1747 LEFT JOIN civicrm_email ON ( civicrm_email.is_primary = 1 AND civicrm_email.contact_id = civicrm_contact.id )
1748 LEFT JOIN civicrm_address ON ( civicrm_address.is_primary = 1 AND civicrm_address.contact_id = civicrm_contact.id)
1749 LEFT JOIN civicrm_phone ON ( civicrm_phone.is_primary = 1 AND civicrm_phone.contact_id = civicrm_contact.id)
1750 LEFT JOIN civicrm_im ON ( civicrm_im.is_primary = 1 AND civicrm_im.contact_id = civicrm_contact.id)
1751 LEFT JOIN civicrm_openid ON ( civicrm_openid.is_primary = 1 AND civicrm_openid.contact_id = civicrm_contact.id)
1752 WHERE civicrm_contact.id = %1 ";
1754 $params = array(1 => array($contactId, 'Integer'));
1756 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1758 $locationType = NULL;
1759 if ($dao->fetch()) {
1760 $locationType = $dao->locationType
;
1763 if (isset($locationType)) {
1764 return $locationType;
1766 elseif ($skipDefaultPriamry) {
1767 // if there is no primary contact location then return null
1771 // if there is no primart contact location, then return default
1772 // location type of the system
1773 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
1774 return $defaultLocationType->id
;
1779 * Get the display name, primary email and location type of a contact.
1782 * Id of the contact.
1785 * Array of display_name, email if found, do_not_email or (null,null,null)
1787 public static function getContactDetails($id) {
1788 // check if the contact type
1789 $contactType = self
::getContactType($id);
1791 $nameFields = ($contactType == 'Individual') ?
"civicrm_contact.first_name, civicrm_contact.last_name, civicrm_contact.display_name" : "civicrm_contact.display_name";
1794 SELECT $nameFields, civicrm_email.email, civicrm_contact.do_not_email, civicrm_email.on_hold, civicrm_contact.is_deceased
1795 FROM civicrm_contact LEFT JOIN civicrm_email ON (civicrm_contact.id = civicrm_email.contact_id)
1796 WHERE civicrm_contact.id = %1
1797 ORDER BY civicrm_email.is_primary DESC";
1798 $params = array(1 => array($id, 'Integer'));
1799 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
1801 if ($dao->fetch()) {
1802 if ($contactType == 'Individual') {
1803 if ($dao->first_name ||
$dao->last_name
) {
1804 $name = "{$dao->first_name} {$dao->last_name}";
1807 $name = $dao->display_name
;
1811 $name = $dao->display_name
;
1813 $email = $dao->email
;
1814 $doNotEmail = $dao->do_not_email ?
TRUE : FALSE;
1815 $onHold = $dao->on_hold ?
TRUE : FALSE;
1816 $isDeceased = $dao->is_deceased ?
TRUE : FALSE;
1817 return array($name, $email, $doNotEmail, $onHold, $isDeceased);
1819 return array(NULL, NULL, NULL, NULL, NULL);
1823 * Add/edit/register contacts through profile.
1825 * @param array $params
1826 * Array of profile fields to be edited/added.
1827 * @param array $fields
1828 * Array of fields from UFGroup.
1829 * @param int $contactID
1830 * Id of the contact to be edited/added.
1831 * @param int $addToGroupID
1832 * Specifies the default group to which contact is added.
1833 * @param int $ufGroupId
1834 * Uf group id (profile id).
1835 * @param string $ctype
1836 * @param bool $visibility
1837 * Basically lets us know where this request is coming from.
1838 * if via a profile from web, we restrict what groups are changed
1841 * contact id created/edited
1843 public static function createProfileContact(
1847 $addToGroupID = NULL,
1852 // add ufGroupID to params array ( CRM-2012 )
1854 $params['uf_group_id'] = $ufGroupId;
1856 self
::addBillingNameFieldsIfOtherwiseNotSet($params);
1858 // If a user has logged in, or accessed via a checksum
1859 // Then deliberately 'blanking' a value in the profile should remove it from their record
1860 $session = CRM_Core_Session
::singleton();
1861 $params['updateBlankLocInfo'] = TRUE;
1862 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0) {
1863 $params['updateBlankLocInfo'] = FALSE;
1868 CRM_Utils_Hook
::pre('edit', 'Profile', $contactID, $params);
1872 CRM_Utils_Hook
::pre('create', 'Profile', NULL, $params);
1875 list($data, $contactDetails) = self
::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
1877 // manage is_opt_out
1878 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
1879 $wasOptOut = CRM_Utils_Array
::value('is_opt_out', $contactDetails, FALSE);
1880 $isOptOut = CRM_Utils_Array
::value('is_opt_out', $params, FALSE);
1881 $data['is_opt_out'] = $isOptOut;
1882 // on change, create new civicrm_subscription_history entry
1883 if (($wasOptOut != $isOptOut) && !empty($contactDetails['contact_id'])) {
1885 'contact_id' => $contactDetails['contact_id'],
1886 'status' => $isOptOut ?
'Removed' : 'Added',
1889 CRM_Contact_BAO_SubscriptionHistory
::create($shParams);
1893 $contact = self
::create($data);
1895 // contact is null if the profile does not have any contact fields
1897 $contactID = $contact->id
;
1900 if (empty($contactID)) {
1901 CRM_Core_Error
::fatal('Cannot proceed without a valid contact id');
1904 // Process group and tag
1905 if (!empty($fields['group'])) {
1907 // this for sure means we are coming in via profile since i added it to fix
1908 // removing contacts from user groups -- lobo
1912 CRM_Contact_BAO_GroupContact
::create($params['group'], $contactID, $visibility, $method);
1915 if (!empty($fields['tag'])) {
1916 CRM_Core_BAO_EntityTag
::create($params['tag'], 'civicrm_contact', $contactID);
1919 //to add profile in default group
1920 if (is_array($addToGroupID)) {
1921 $contactIds = array($contactID);
1922 foreach ($addToGroupID as $groupId) {
1923 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
1926 elseif ($addToGroupID) {
1927 $contactIds = array($contactID);
1928 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $addToGroupID);
1931 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
1934 CRM_Utils_Hook
::post('edit', 'Profile', $contactID, $params);
1937 CRM_Utils_Hook
::post('create', 'Profile', $contactID, $params);
1943 * Format profile contact parameters.
1945 * @param array $params
1947 * @param int $contactID
1948 * @param int $ufGroupId
1949 * @param null $ctype
1950 * @param bool $skipCustom
1954 public static function formatProfileContactParams(
1963 $data = $contactDetails = array();
1965 // get the contact details (hier)
1967 list($details, $options) = self
::getHierContactDetails($contactID, $fields);
1969 $contactDetails = $details[$contactID];
1970 $data['contact_type'] = CRM_Utils_Array
::value('contact_type', $contactDetails);
1971 $data['contact_sub_type'] = CRM_Utils_Array
::value('contact_sub_type', $contactDetails);
1974 //we should get contact type only if contact
1976 $data['contact_type'] = CRM_Core_BAO_UFField
::getProfileType($ufGroupId);
1978 //special case to handle profile with only contact fields
1979 if ($data['contact_type'] == 'Contact') {
1980 $data['contact_type'] = 'Individual';
1982 elseif (CRM_Contact_BAO_ContactType
::isaSubType($data['contact_type'])) {
1983 $data['contact_type'] = CRM_Contact_BAO_ContactType
::getBasicType($data['contact_type']);
1987 $data['contact_type'] = $ctype;
1990 $data['contact_type'] = 'Individual';
1994 //fix contact sub type CRM-5125
1995 if (array_key_exists('contact_sub_type', $params) &&
1996 !empty($params['contact_sub_type'])
1998 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type']);
2000 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
2001 !empty($params['contact_sub_type_hidden'])
2003 // if profile was used, and had any subtype, we obtain it from there
2004 //CRM-13596 - add to existing contact types, rather than overwriting
2005 $data_contact_sub_type_arr = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2006 if (!in_array($params['contact_sub_type_hidden'], $data_contact_sub_type_arr)) {
2007 //CRM-20517 - make sure contact_sub_type gets the correct delimiters
2008 $data['contact_sub_type'] = trim($data['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
);
2009 $data['contact_sub_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. $data['contact_sub_type'] . CRM_Utils_Array
::implodePadded($params['contact_sub_type_hidden']);
2013 if ($ctype == 'Organization') {
2014 $data['organization_name'] = CRM_Utils_Array
::value('organization_name', $contactDetails);
2016 elseif ($ctype == 'Household') {
2017 $data['household_name'] = CRM_Utils_Array
::value('household_name', $contactDetails);
2020 $locationType = array();
2025 $data['contact_id'] = $contactID;
2026 $primaryLocationType = self
::getPrimaryLocationType($contactID);
2029 $defaultLocation = CRM_Core_BAO_LocationType
::getDefault();
2030 $defaultLocationId = $defaultLocation->id
;
2033 $billingLocationTypeId = CRM_Core_BAO_LocationType
::getBilling();
2035 $blocks = array('email', 'phone', 'im', 'openid');
2037 $multiplFields = array('url');
2038 // prevent overwritten of formatted array, reset all block from
2039 // params if it is not in valid format (since import pass valid format)
2040 foreach ($blocks as $blk) {
2041 if (array_key_exists($blk, $params) &&
2042 !is_array($params[$blk])
2044 unset($params[$blk]);
2048 $primaryPhoneLoc = NULL;
2049 $session = CRM_Core_Session
::singleton();
2050 foreach ($params as $key => $value) {
2051 list($fieldName, $locTypeId, $typeId) = CRM_Utils_System
::explode('-', $key, 3);
2053 if ($locTypeId == 'Primary') {
2055 if (in_array($fieldName, $blocks)) {
2056 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, $fieldName);
2059 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, 'address');
2061 $primaryLocationType = $locTypeId;
2064 $locTypeId = $defaultLocationId;
2068 if (is_numeric($locTypeId) &&
2069 !in_array($fieldName, $multiplFields) &&
2070 substr($fieldName, 0, 7) != 'custom_'
2072 $index = $locTypeId;
2074 if (is_numeric($typeId)) {
2075 $index .= '-' . $typeId;
2077 if (!in_array($index, $locationType)) {
2078 $locationType[$count] = $index;
2082 $loc = CRM_Utils_Array
::key($index, $locationType);
2084 $blockName = in_array($fieldName, $blocks) ?
$fieldName : 'address';
2086 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
2088 //set is_billing true, for location type "Billing"
2089 if ($locTypeId == $billingLocationTypeId) {
2090 $data[$blockName][$loc]['is_billing'] = 1;
2094 //get the primary location type
2095 if ($locTypeId == $primaryLocationType) {
2096 $data[$blockName][$loc]['is_primary'] = 1;
2099 elseif ($locTypeId == $defaultLocationId) {
2100 $data[$blockName][$loc]['is_primary'] = 1;
2103 if (in_array($fieldName, array('phone'))) {
2105 $data['phone'][$loc]['phone_type_id'] = $typeId;
2108 $data['phone'][$loc]['phone_type_id'] = '';
2110 $data['phone'][$loc]['phone'] = $value;
2112 //special case to handle primary phone with different phone types
2113 // in this case we make first phone type as primary
2114 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
2115 $primaryPhoneLoc = $loc;
2118 if ($loc != $primaryPhoneLoc) {
2119 unset($data['phone'][$loc]['is_primary']);
2122 elseif ($fieldName == 'phone_ext') {
2123 $data['phone'][$loc]['phone_ext'] = $value;
2125 elseif ($fieldName == 'email') {
2126 $data['email'][$loc]['email'] = $value;
2127 if (empty($contactID)) {
2128 $data['email'][$loc]['is_primary'] = 1;
2131 elseif ($fieldName == 'im') {
2132 if (isset($params[$key . '-provider_id'])) {
2133 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
2135 if (strpos($key, '-provider_id') !== FALSE) {
2136 $data['im'][$loc]['provider_id'] = $params[$key];
2139 $data['im'][$loc]['name'] = $value;
2142 elseif ($fieldName == 'openid') {
2143 $data['openid'][$loc]['openid'] = $value;
2146 if ($fieldName === 'state_province') {
2148 if (is_numeric($value) && ((int ) $value) >= 1000) {
2149 $data['address'][$loc]['state_province_id'] = $value;
2151 elseif (empty($value)) {
2152 $data['address'][$loc]['state_province_id'] = '';
2155 $data['address'][$loc]['state_province'] = $value;
2158 elseif ($fieldName === 'country') {
2160 if (is_numeric($value) && ((int ) $value) >= 1000
2162 $data['address'][$loc]['country_id'] = $value;
2164 elseif (empty($value)) {
2165 $data['address'][$loc]['country_id'] = '';
2168 $data['address'][$loc]['country'] = $value;
2171 elseif ($fieldName === 'county') {
2172 $data['address'][$loc]['county_id'] = $value;
2174 elseif ($fieldName == 'address_name') {
2175 $data['address'][$loc]['name'] = $value;
2177 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2178 $data['address'][$loc][substr($fieldName, 8)] = $value;
2181 $data['address'][$loc][$fieldName] = $value;
2186 if (substr($key, 0, 4) === 'url-') {
2187 $websiteField = explode('-', $key);
2188 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
2189 $data['website'][$websiteField[1]]['url'] = $value;
2191 elseif (in_array($key, self
::$_greetingTypes, TRUE)) {
2192 //save email/postal greeting and addressee values if any, CRM-4575
2193 $data[$key . '_id'] = $value;
2195 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($key))) {
2196 // for autocomplete transfer hidden value instead of label
2197 if ($params[$key] && isset($params[$key . '_id'])) {
2198 $value = $params[$key . '_id'];
2201 // we need to append time with date
2202 if ($params[$key] && isset($params[$key . '_time'])) {
2203 $value .= ' ' . $params[$key . '_time'];
2206 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
2207 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 &&
2208 ($value == '' ||
!isset($value))
2214 if (!empty($params['customRecordValues'])) {
2215 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2216 foreach ($params['customRecordValues'] as $recId => $customFields) {
2217 if (is_array($customFields) && !empty($customFields)) {
2218 foreach ($customFields as $customFieldName) {
2219 if ($customFieldName == $key) {
2229 //CRM-13596 - check for contact_sub_type_hidden first
2230 if (array_key_exists('contact_sub_type_hidden', $params)) {
2231 $type = $params['contact_sub_type_hidden'];
2234 $type = $data['contact_type'];
2235 if (!empty($data['contact_sub_type'])) {
2236 $type = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2240 CRM_Core_BAO_CustomField
::formatCustomField($customFieldId,
2250 elseif ($key == 'edit') {
2254 if ($key == 'location') {
2255 foreach ($value as $locationTypeId => $field) {
2256 foreach ($field as $block => $val) {
2257 if ($block == 'address' && array_key_exists('address_name', $val)) {
2258 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2263 if ($key == 'phone' && isset($params['phone_ext'])) {
2264 $data[$key] = $value;
2265 foreach ($value as $cnt => $phoneBlock) {
2266 if ($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']) {
2267 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array
::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2271 elseif (in_array($key,
2282 ($value == '' ||
!isset($value)) &&
2283 ($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 ||
2284 ($key == 'current_employer' && empty($params['current_employer']))) {
2285 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
2286 // to avoid update with empty values
2290 $data[$key] = $value;
2296 if (!isset($data['contact_type'])) {
2297 $data['contact_type'] = 'Individual';
2300 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2301 $privacy = CRM_Core_SelectValues
::privacy();
2302 foreach ($privacy as $key => $value) {
2303 if (array_key_exists($key, $fields)) {
2304 // do not reset values for existing contacts, if fields are added to a profile
2305 if (array_key_exists($key, $params)) {
2306 $data[$key] = $params[$key];
2307 if (empty($params[$key])) {
2311 elseif (!$contactID) {
2317 return array($data, $contactDetails);
2321 * Find the get contact details.
2323 * This function does not respect ACLs for now, which might need to be rectified at some
2324 * stage based on how its used.
2326 * @param string $mail
2327 * Primary email address of the contact.
2328 * @param string $ctype
2331 * @return object|null
2332 * $dao contact details
2334 public static function matchContactOnEmail($mail, $ctype = NULL) {
2335 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2336 $mail = $strtolower(trim($mail));
2338 SELECT civicrm_contact.id as contact_id,
2339 civicrm_contact.hash as hash,
2340 civicrm_contact.contact_type as contact_type,
2341 civicrm_contact.contact_sub_type as contact_sub_type
2342 FROM civicrm_contact
2343 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2345 if (Civi
::settings()->get('uniq_email_per_site')) {
2346 // try to find a match within a site (multisite).
2347 $groups = CRM_Core_BAO_Domain
::getChildGroupIds();
2348 if (!empty($groups)) {
2350 INNER JOIN civicrm_group_contact gc ON
2351 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2356 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2357 $p = array(1 => array($mail, 'String'));
2360 $query .= " AND civicrm_contact.contact_type = %3";
2361 $p[3] = array($ctype, 'String');
2364 $query .= " ORDER BY civicrm_email.is_primary DESC";
2366 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2368 if ($dao->fetch()) {
2375 * Find the contact details associated with an OpenID.
2377 * @param string $openId
2378 * OpenId of the contact.
2379 * @param string $ctype
2382 * @return object|null
2383 * $dao contact details
2385 public static function matchContactOnOpenId($openId, $ctype = NULL) {
2386 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2387 $openId = $strtolower(trim($openId));
2389 SELECT civicrm_contact.id as contact_id,
2390 civicrm_contact.hash as hash,
2391 civicrm_contact.contact_type as contact_type,
2392 civicrm_contact.contact_sub_type as contact_sub_type
2393 FROM civicrm_contact
2394 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2395 WHERE civicrm_openid.openid = %1";
2396 $p = array(1 => array($openId, 'String'));
2399 $query .= " AND civicrm_contact.contact_type = %3";
2400 $p[3] = array($ctype, 'String');
2403 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2405 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2407 if ($dao->fetch()) {
2414 * Get primary email of the contact.
2416 * @param int $contactID
2420 * Email address if present else null
2422 public static function getPrimaryEmail($contactID) {
2423 // fetch the primary email
2425 SELECT civicrm_email.email as email
2426 FROM civicrm_contact
2427 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2428 WHERE civicrm_email.is_primary = 1
2429 AND civicrm_contact.id = %1";
2430 $p = array(1 => array($contactID, 'Integer'));
2431 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2434 if ($dao->fetch()) {
2435 $email = $dao->email
;
2442 * Function to get primary OpenID of the contact.
2444 * @param int $contactID
2448 * >openid OpenID if present else null
2450 public static function getPrimaryOpenId($contactID) {
2451 // fetch the primary OpenID
2453 SELECT civicrm_openid.openid as openid
2454 FROM civicrm_contact
2455 LEFT JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2456 WHERE civicrm_contact.id = %1
2457 AND civicrm_openid.is_primary = 1";
2458 $p = array(1 => array($contactID, 'Integer'));
2459 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2462 if ($dao->fetch()) {
2463 $openId = $dao->openid
;
2470 * Fetch the object and store the values in the values array.
2472 * @param array $params
2473 * Input parameters to find object.
2474 * @param array $values
2475 * Output values of the object.
2477 * @return CRM_Contact_BAO_Contact|null
2478 * The found object or null
2480 public static function getValues(&$params, &$values) {
2481 $contact = new CRM_Contact_BAO_Contact();
2483 $contact->copyValues($params);
2485 if ($contact->find(TRUE)) {
2487 CRM_Core_DAO
::storeValues($contact, $values);
2490 foreach (self
::$_commPrefs as $name) {
2491 if (isset($contact->$name)) {
2492 $privacy[$name] = $contact->$name;
2496 if (!empty($privacy)) {
2497 $values['privacy'] = $privacy;
2500 // communication Prefferance
2501 $preffComm = $comm = array();
2502 $comm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2503 $contact->preferred_communication_method
2505 foreach ($comm as $value) {
2506 $preffComm[$value] = 1;
2508 $temp = array('preferred_communication_method' => $contact->preferred_communication_method
);
2511 'preferred_communication_method' => array(
2512 'newName' => 'preferred_communication_method_display',
2513 'groupName' => 'preferred_communication_method',
2517 // @todo This can be figured out from metadata & we can avoid the uncached query.
2518 CRM_Core_OptionGroup
::lookupValues($temp, $names, FALSE);
2520 $values['preferred_communication_method'] = $preffComm;
2521 $values['preferred_communication_method_display'] = CRM_Utils_Array
::value('preferred_communication_method_display', $temp);
2523 if ($contact->preferred_mail_format
) {
2524 $preferredMailingFormat = CRM_Core_SelectValues
::pmf();
2525 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format
];
2528 // get preferred languages
2529 if (!empty($contact->preferred_language
)) {
2530 $values['preferred_language'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language
);
2533 // Calculating Year difference
2534 if ($contact->birth_date
) {
2535 $birthDate = CRM_Utils_Date
::customFormat($contact->birth_date
, '%Y%m%d');
2536 if ($birthDate < date('Ymd')) {
2537 $age = CRM_Utils_Date
::calculateAge($birthDate);
2538 $values['age']['y'] = CRM_Utils_Array
::value('years', $age);
2539 $values['age']['m'] = CRM_Utils_Array
::value('months', $age);
2543 $contact->contact_id
= $contact->id
;
2551 * Given the component name and returns the count of participation of contact.
2553 * @param string $component
2554 * Input component name.
2555 * @param int $contactId
2557 * @param string $tableName
2558 * Optional tableName if component is custom group.
2561 * total number in database
2563 public static function getCountComponent($component, $contactId, $tableName = NULL) {
2565 switch ($component) {
2567 return CRM_Core_BAO_EntityTag
::getContactTags($contactId, TRUE);
2570 $result = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
2571 CRM_Contact_BAO_Relationship
::CURRENT
,
2580 return CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, "Added", NULL, TRUE);
2583 if (CRM_Core_BAO_Log
::useLoggingReport()) {
2586 return CRM_Core_BAO_Log
::getContactLogCount($contactId);
2589 return CRM_Core_BAO_Note
::getContactNoteCount($contactId);
2591 case 'contribution':
2592 return CRM_Contribute_BAO_Contribution
::contributionCount($contactId);
2595 return CRM_Member_BAO_Membership
::getContactMembershipCount($contactId, TRUE);
2598 return CRM_Event_BAO_Participant
::getContactParticipantCount($contactId);
2601 return CRM_Pledge_BAO_Pledge
::getContactPledgeCount($contactId);
2604 return CRM_Case_BAO_Case
::caseCount($contactId);
2607 return CRM_Grant_BAO_Grant
::getContactGrantCount($contactId);
2611 'contact_id' => $contactId,
2614 'context' => 'activity',
2616 return CRM_Activity_BAO_Activity
::deprecatedGetActivitiesCount($input);
2619 $params = array('contact_id' => $contactId);
2620 return CRM_Mailing_BAO_Mailing
::getContactMailingsCount($params);
2623 $custom = explode('_', $component);
2624 if ($custom['0'] = 'custom') {
2626 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2628 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2629 return CRM_Core_DAO
::singleValueQuery($queryString);
2635 * Process greetings and cache.
2637 * @param object $contact
2638 * Contact object after save.
2639 * @param bool $useDefaults
2640 * Use default greeting values.
2642 public static function processGreetings(&$contact, $useDefaults = FALSE) {
2644 //retrieve default greetings
2645 $defaultGreetings = CRM_Core_PseudoConstant
::greetingDefaults();
2646 $contactDefaults = $defaultGreetings[$contact->contact_type
];
2649 // The contact object has not always required the
2650 // fields that are required to calculate greetings
2651 // so we need to retrieve it again.
2652 if ($contact->_query
!== FALSE) {
2653 $contact->find(TRUE);
2656 // store object values to an array
2657 $contactDetails = array();
2658 CRM_Core_DAO
::storeValues($contact, $contactDetails);
2659 $contactDetails = array(array($contact->id
=> $contactDetails));
2661 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2662 $updateQueryString = array();
2664 //cache email and postal greeting to greeting display
2665 if ($contact->email_greeting_custom
!= 'null' && $contact->email_greeting_custom
) {
2666 $emailGreetingString = $contact->email_greeting_custom
;
2668 elseif ($contact->email_greeting_id
!= 'null' && $contact->email_greeting_id
) {
2669 // the filter value for Individual contact type is set to 1
2671 'contact_type' => $contact->contact_type
,
2672 'greeting_type' => 'email_greeting',
2675 $emailGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2676 $emailGreetingString = $emailGreeting[$contact->email_greeting_id
];
2677 $updateQueryString[] = " email_greeting_custom = NULL ";
2681 reset($contactDefaults['email_greeting']);
2682 $emailGreetingID = key($contactDefaults['email_greeting']);
2683 $emailGreetingString = $contactDefaults['email_greeting'][$emailGreetingID];
2684 $updateQueryString[] = " email_greeting_id = $emailGreetingID ";
2685 $updateQueryString[] = " email_greeting_custom = NULL ";
2687 elseif ($contact->email_greeting_custom
) {
2688 $updateQueryString[] = " email_greeting_display = NULL ";
2692 if ($emailGreetingString) {
2693 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($emailGreetingString,
2696 'CRM_Contact_BAO_Contact'
2698 $emailGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($emailGreetingString));
2699 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2703 if ($contact->postal_greeting_custom
!= 'null' && $contact->postal_greeting_custom
) {
2704 $postalGreetingString = $contact->postal_greeting_custom
;
2706 elseif ($contact->postal_greeting_id
!= 'null' && $contact->postal_greeting_id
) {
2708 'contact_type' => $contact->contact_type
,
2709 'greeting_type' => 'postal_greeting',
2711 $postalGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2712 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id
];
2713 $updateQueryString[] = " postal_greeting_custom = NULL ";
2717 reset($contactDefaults['postal_greeting']);
2718 $postalGreetingID = key($contactDefaults['postal_greeting']);
2719 $postalGreetingString = $contactDefaults['postal_greeting'][$postalGreetingID];
2720 $updateQueryString[] = " postal_greeting_id = $postalGreetingID ";
2721 $updateQueryString[] = " postal_greeting_custom = NULL ";
2723 elseif ($contact->postal_greeting_custom
) {
2724 $updateQueryString[] = " postal_greeting_display = NULL ";
2728 if ($postalGreetingString) {
2729 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($postalGreetingString,
2732 'CRM_Contact_BAO_Contact'
2734 $postalGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($postalGreetingString));
2735 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2739 if ($contact->addressee_custom
!= 'null' && $contact->addressee_custom
) {
2740 $addresseeString = $contact->addressee_custom
;
2742 elseif ($contact->addressee_id
!= 'null' && $contact->addressee_id
) {
2744 'contact_type' => $contact->contact_type
,
2745 'greeting_type' => 'addressee',
2748 $addressee = CRM_Core_PseudoConstant
::greeting($filter);
2749 $addresseeString = $addressee[$contact->addressee_id
];
2750 $updateQueryString[] = " addressee_custom = NULL ";
2754 reset($contactDefaults['addressee']);
2755 $addresseeID = key($contactDefaults['addressee']);
2756 $addresseeString = $contactDefaults['addressee'][$addresseeID];
2757 $updateQueryString[] = " addressee_id = $addresseeID ";
2758 $updateQueryString[] = " addressee_custom = NULL ";
2760 elseif ($contact->addressee_custom
) {
2761 $updateQueryString[] = " addressee_display = NULL ";
2765 if ($addresseeString) {
2766 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($addresseeString,
2769 'CRM_Contact_BAO_Contact'
2771 $addresseeString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($addresseeString));
2772 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2775 if (!empty($updateQueryString)) {
2776 $updateQueryString = implode(',', $updateQueryString);
2777 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2778 CRM_Core_DAO
::executeQuery($queryString);
2783 * Retrieve loc block ids w/ given condition.
2785 * @param int $contactId
2787 * @param array $criteria
2788 * Key => value pair which should be.
2789 * fulfill by return record ids.
2790 * @param string $condOperator
2791 * Operator use for grouping multiple conditions.
2794 * loc block ids which fulfill condition.
2796 public static function getLocBlockIds($contactId, $criteria = array(), $condOperator = 'AND') {
2797 $locBlockIds = array();
2799 return $locBlockIds;
2802 foreach (array('Email', 'OpenID', 'Phone', 'Address', 'IM') as $block) {
2803 $name = strtolower($block);
2804 $className = "CRM_Core_DAO_$block";
2805 $blockDAO = new $className();
2807 // build the condition.
2808 if (is_array($criteria)) {
2809 $fields = $blockDAO->fields();
2810 $conditions = array();
2811 foreach ($criteria as $field => $value) {
2812 if (array_key_exists($field, $fields)) {
2813 $cond = "( $field = $value )";
2814 // value might be zero or null.
2815 if (!$value ||
strtolower($value) == 'null') {
2816 $cond = "( $field = 0 OR $field IS NULL )";
2818 $conditions[] = $cond;
2821 if (!empty($conditions)) {
2822 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2826 $blockDAO->contact_id
= $contactId;
2828 while ($blockDAO->fetch()) {
2829 $locBlockIds[$name][] = $blockDAO->id
;
2834 return $locBlockIds;
2838 * Build context menu items.
2840 * @param int $contactId
2843 * Array of context menu for logged in user.
2845 public static function contextMenu($contactId = NULL) {
2848 'title' => ts('View Contact'),
2850 'ref' => 'view-contact',
2851 'class' => 'no-popup',
2853 'permissions' => array('view all contacts'),
2856 'title' => ts('Edit Contact'),
2858 'ref' => 'edit-contact',
2859 'class' => 'no-popup',
2861 'permissions' => array('edit all contacts'),
2864 'title' => ts('Delete Contact'),
2866 'ref' => 'delete-contact',
2868 'permissions' => array('access deleted contacts', 'delete contacts'),
2870 'contribution' => array(
2871 'title' => ts('Add Contribution'),
2873 'ref' => 'new-contribution',
2874 'key' => 'contribution',
2875 'tab' => 'contribute',
2876 'component' => 'CiviContribute',
2877 'href' => CRM_Utils_System
::url('civicrm/contact/view/contribution',
2878 'reset=1&action=add&context=contribution'
2880 'permissions' => array(
2881 'access CiviContribute',
2882 'edit contributions',
2885 'participant' => array(
2886 'title' => ts('Register for Event'),
2888 'ref' => 'new-participant',
2889 'key' => 'participant',
2890 'tab' => 'participant',
2891 'component' => 'CiviEvent',
2892 'href' => CRM_Utils_System
::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
2893 'permissions' => array(
2895 'edit event participants',
2898 'activity' => array(
2899 'title' => ts('Record Activity'),
2901 'ref' => 'new-activity',
2902 'key' => 'activity',
2903 'permissions' => array('edit all contacts'),
2906 'title' => ts('Add Pledge'),
2908 'ref' => 'new-pledge',
2911 'href' => CRM_Utils_System
::url('civicrm/contact/view/pledge',
2912 'reset=1&action=add&context=pledge'
2914 'component' => 'CiviPledge',
2915 'permissions' => array(
2916 'access CiviPledge',
2920 'membership' => array(
2921 'title' => ts('Add Membership'),
2923 'ref' => 'new-membership',
2924 'key' => 'membership',
2926 'component' => 'CiviMember',
2927 'href' => CRM_Utils_System
::url('civicrm/contact/view/membership',
2928 'reset=1&action=add&context=membership'
2930 'permissions' => array(
2931 'access CiviMember',
2936 'title' => ts('Add Case'),
2938 'ref' => 'new-case',
2941 'component' => 'CiviCase',
2942 'href' => CRM_Utils_System
::url('civicrm/case/add', 'reset=1&action=add&context=case'),
2943 'permissions' => array('add cases'),
2946 'title' => ts('Add Grant'),
2948 'ref' => 'new-grant',
2951 'component' => 'CiviGrant',
2952 'href' => CRM_Utils_System
::url('civicrm/contact/view/grant',
2953 'reset=1&action=add&context=grant'
2955 'permissions' => array('edit grants'),
2958 'title' => ts('Add Relationship'),
2960 'ref' => 'new-relationship',
2963 'href' => CRM_Utils_System
::url('civicrm/contact/view/rel',
2964 'reset=1&action=add'
2966 'permissions' => array('edit all contacts'),
2969 'title' => ts('Add Note'),
2971 'ref' => 'new-note',
2974 'class' => 'medium-popup',
2975 'href' => CRM_Utils_System
::url('civicrm/contact/view/note',
2976 'reset=1&action=add'
2978 'permissions' => array('edit all contacts'),
2981 'title' => ts('Send an Email'),
2983 'ref' => 'new-email',
2985 'permissions' => array('view all contacts'),
2988 'title' => ts('Add to Group'),
2990 'ref' => 'group-add-contact',
2993 'permissions' => array('edit groups'),
2996 'title' => ts('Tag Contact'),
2998 'ref' => 'tag-contact',
3001 'permissions' => array('edit all contacts'),
3005 $menu['otherActions'] = array(
3007 'title' => ts('Print Summary'),
3008 'description' => ts('Printer-friendly view of this page.'),
3010 'ref' => 'crm-contact-print',
3013 'href' => CRM_Utils_System
::url('civicrm/contact/view/print',
3017 'icon' => 'crm-i fa-print',
3020 'title' => ts('vCard'),
3021 'description' => ts('vCard record for this contact.'),
3023 'ref' => 'crm-contact-vcard',
3026 'href' => CRM_Utils_System
::url('civicrm/contact/view/vcard',
3030 'icon' => 'crm-i fa-list-alt',
3034 if (CRM_Core_Permission
::check('access Contact Dashboard')) {
3035 $menu['otherActions']['dashboard'] = array(
3036 'title' => ts('Contact Dashboard'),
3037 'description' => ts('Contact Dashboard'),
3039 'ref' => 'crm-contact-dashboard',
3040 'key' => 'dashboard',
3041 'tab' => 'dashboard',
3042 'class' => 'dashboard',
3043 // NOTE: As an alternative you can also build url on CMS specific way
3044 // as CRM_Core_Config::singleton()->userSystem->getUserRecordUrl($contactId)
3045 'href' => CRM_Utils_System
::url('civicrm/user', "reset=1&id={$contactId}"),
3046 'icon' => 'crm-i fa-tachometer',
3050 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactId);
3052 $menu['otherActions']['user-record'] = array(
3053 'title' => ts('User Record'),
3054 'description' => ts('User Record'),
3056 'ref' => 'crm-contact-user-record',
3057 'key' => 'user-record',
3058 'tab' => 'user-record',
3059 'class' => 'user-record',
3060 'href' => CRM_Core_Config
::singleton()->userSystem
->getUserRecordUrl($contactId),
3061 'icon' => 'crm-i fa-user',
3064 elseif (CRM_Core_Config
::singleton()->userSystem
->checkPermissionAddUser()) {
3065 $menu['otherActions']['user-add'] = array(
3066 'title' => ts('Create User Record'),
3067 'description' => ts('Create User Record'),
3069 'ref' => 'crm-contact-user-add',
3070 'key' => 'user-add',
3071 'tab' => 'user-add',
3072 'class' => 'user-add',
3073 'href' => CRM_Utils_System
::url('civicrm/contact/view/useradd', 'reset=1&action=add&cid=' . $contactId),
3074 'icon' => 'crm-i fa-user-plus',
3078 CRM_Utils_Hook
::summaryActions($menu, $contactId);
3079 //1. check for component is active.
3080 //2. check for user permissions.
3081 //3. check for acls.
3082 //3. edit and view contact are directly accessible to user.
3084 $aclPermissionedTasks = array(
3089 'group-add-contact',
3093 $corePermission = CRM_Core_Permission
::getPermission();
3095 $contextMenu = array();
3096 foreach ($menu as $key => $values) {
3097 if ($key != 'otherActions') {
3099 // user does not have necessary permissions.
3100 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $values)) {
3103 // build directly accessible action menu.
3104 if (in_array($values['ref'], array(
3108 $contextMenu['primaryActions'][$key] = array(
3109 'title' => $values['title'],
3110 'ref' => $values['ref'],
3111 'class' => CRM_Utils_Array
::value('class', $values),
3112 'key' => $values['key'],
3117 // finally get menu item for -more- action widget.
3118 $contextMenu['moreActions'][$values['weight']] = array(
3119 'title' => $values['title'],
3120 'ref' => $values['ref'],
3121 'href' => CRM_Utils_Array
::value('href', $values),
3122 'tab' => CRM_Utils_Array
::value('tab', $values),
3123 'class' => CRM_Utils_Array
::value('class', $values),
3124 'key' => $values['key'],
3128 foreach ($values as $value) {
3129 // user does not have necessary permissions.
3130 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $value)) {
3134 // finally get menu item for -more- action widget.
3135 $contextMenu['otherActions'][$value['weight']] = array(
3136 'title' => $value['title'],
3137 'ref' => $value['ref'],
3138 'href' => CRM_Utils_Array
::value('href', $value),
3139 'tab' => CRM_Utils_Array
::value('tab', $value),
3140 'class' => CRM_Utils_Array
::value('class', $value),
3141 'icon' => CRM_Utils_Array
::value('icon', $value),
3142 'key' => $value['key'],
3148 ksort($contextMenu['moreActions']);
3149 ksort($contextMenu['otherActions']);
3151 return $contextMenu;
3155 * Check if user has permissions to access items in action menu.
3157 * @param array $aclPermissionedTasks
3158 * Array containing ACL related tasks.
3159 * @param string $corePermission
3160 * The permission of the user (edit or view or null).
3161 * @param array $menuOptions
3162 * Array containing params of the menu (title, href, etc).
3165 * TRUE if user has all permissions, FALSE if otherwise.
3167 public static function checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $menuOptions) {
3168 $componentName = CRM_Utils_Array
::value('component', $menuOptions);
3170 // if component action - make sure component is enable.
3171 if ($componentName && !in_array($componentName, CRM_Core_Config
::singleton()->enableComponents
)) {
3175 // make sure user has all required permissions.
3176 $hasAllPermissions = FALSE;
3178 $permissions = CRM_Utils_Array
::value('permissions', $menuOptions);
3179 if (!is_array($permissions) ||
empty($permissions)) {
3180 $hasAllPermissions = TRUE;
3183 // iterate for required permissions in given permissions array.
3184 if (!$hasAllPermissions) {
3185 $hasPermissions = 0;
3186 foreach ($permissions as $permission) {
3187 if (CRM_Core_Permission
::check($permission)) {
3192 if (count($permissions) == $hasPermissions) {
3193 $hasAllPermissions = TRUE;
3196 // if still user does not have required permissions, check acl.
3197 if (!$hasAllPermissions && $menuOptions['ref'] != 'delete-contact') {
3198 if (in_array($menuOptions['ref'], $aclPermissionedTasks) &&
3199 $corePermission == CRM_Core_Permission
::EDIT
3201 $hasAllPermissions = TRUE;
3203 elseif (in_array($menuOptions['ref'], array(
3206 // grant permissions for these tasks.
3207 $hasAllPermissions = TRUE;
3212 return $hasAllPermissions;
3216 * Retrieve display name of contact that address is shared.
3218 * This is based on $masterAddressId or $contactId .
3220 * @param int $masterAddressId
3222 * @param int $contactId
3225 * @return string|null
3226 * the found display name or null.
3228 public static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3229 $masterDisplayName = NULL;
3231 if (!$masterAddressId && !$contactId) {
3232 return $masterDisplayName;
3235 if ($masterAddressId) {
3237 SELECT display_name from civicrm_contact
3238 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3239 WHERE civicrm_address.id = " . $masterAddressId;
3241 elseif ($contactId) {
3243 SELECT display_name from civicrm_contact cc, civicrm_address add1
3244 LEFT JOIN civicrm_address add2 ON ( add1.master_id = add2.id )
3245 WHERE cc.id = add2.contact_id AND add1.contact_id = " . $contactId;
3248 $masterDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
3249 return $masterDisplayName;
3253 * Get the creation/modification times for a contact.
3255 * @param int $contactId
3258 * Dates - ('created_date' => $, 'modified_date' => $)
3260 public static function getTimestamps($contactId) {
3261 $timestamps = CRM_Core_DAO
::executeQuery(
3262 'SELECT created_date, modified_date
3263 FROM civicrm_contact
3266 1 => array($contactId, 'Integer'),
3269 if ($timestamps->fetch()) {
3271 'created_date' => $timestamps->created_date
,
3272 'modified_date' => $timestamps->modified_date
,
3281 * Get a list of triggers for the contact table.
3283 * @see hook_civicrm_triggerInfo
3284 * @see CRM_Core_DAO::triggerRebuild
3285 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3288 * @param null $tableName
3290 public static function triggerInfo(&$info, $tableName = NULL) {
3291 //during upgrade, first check for valid version and then create triggers
3292 //i.e the columns created_date and modified_date are introduced in 4.3.alpha1 so dont create triggers for older version
3293 if (CRM_Core_Config
::isUpgradeMode()) {
3294 $currentVer = CRM_Core_BAO_Domain
::version(TRUE);
3295 //if current version is less than 4.3.alpha1 dont create below triggers
3296 if (version_compare($currentVer, '4.3.alpha1') < 0) {
3301 // Modifications to these records should update the contact timestamps.
3302 \Civi\Core\SqlTrigger\TimestampTriggers
::create('civicrm_contact', 'Contact')
3303 ->setRelations(array(
3304 array('table' => 'civicrm_address', 'column' => 'contact_id'),
3305 array('table' => 'civicrm_email', 'column' => 'contact_id'),
3306 array('table' => 'civicrm_im', 'column' => 'contact_id'),
3307 array('table' => 'civicrm_phone', 'column' => 'contact_id'),
3308 array('table' => 'civicrm_website', 'column' => 'contact_id'),
3311 ->alterTriggerInfo($info, $tableName);
3313 // Update phone table to populate phone_numeric field
3314 if (!$tableName ||
$tableName == 'civicrm_phone') {
3315 // Define stored sql function needed for phones
3316 $sqlTriggers = Civi
::service('sql_triggers');
3317 $sqlTriggers->enqueueQuery(self
::DROP_STRIP_FUNCTION_43
);
3318 $sqlTriggers->enqueueQuery(self
::CREATE_STRIP_FUNCTION_43
);
3320 'table' => array('civicrm_phone'),
3322 'event' => array('INSERT', 'UPDATE'),
3323 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3329 * Check if contact is being used in civicrm_domain based on $contactId.
3331 * @param int $contactId
3335 * true if present else false.
3337 public static function checkDomainContact($contactId) {
3341 $domainId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3352 * Get options for a given contact field.
3354 * @see CRM_Core_DAO::buildOptions
3356 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3357 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3359 * @param string $fieldName
3360 * @param string $context
3361 * @see CRM_Core_DAO::buildOptionsContext
3362 * @param array $props
3363 * whatever is known about this dao object.
3365 * @return array|bool
3367 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3369 // Special logic for fields whose options depend on context or properties
3370 switch ($fieldName) {
3371 case 'contact_sub_type':
3372 if (!empty($props['contact_type'])) {
3373 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3377 case 'contact_type':
3378 if ($context == 'search') {
3379 // CRM-15495 - EntityRef filters and basic search forms expect this format
3380 // FIXME: Search builder does not
3381 return CRM_Contact_BAO_ContactType
::getSelectElements();
3385 // The contact api supports some related entities so we'll honor that by fetching their options
3388 return CRM_Contact_BAO_GroupContact
::buildOptions('group_id', $context, $props);
3392 $props['entity_table'] = 'civicrm_contact';
3393 return CRM_Core_BAO_EntityTag
::buildOptions('tag_id', $context, $props);
3395 case 'state_province_id':
3396 case 'state_province':
3397 case 'state_province_name':
3402 case 'worldregion_id':
3403 return CRM_Core_BAO_Address
::buildOptions($fieldName, 'get', $props);
3406 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
3410 * Delete a contact-related object that has an 'is_primary' field.
3412 * Ensures that is_primary gets assigned to another object if available
3413 * Also calls pre/post hooks
3415 * @param string $type
3419 public static function deleteObjectWithPrimary($type, $id) {
3420 if (!$id ||
!is_numeric($id)) {
3423 $daoName = "CRM_Core_DAO_$type";
3424 $obj = new $daoName();
3427 if ($obj->fetch()) {
3428 CRM_Utils_Hook
::pre('delete', $type, $id, CRM_Core_DAO
::$_nullArray);
3429 $contactId = $obj->contact_id
;
3435 // is_primary is only relavent if this field belongs to a contact
3437 $dao = new $daoName();
3438 $dao->contact_id
= $contactId;
3439 $dao->is_primary
= 1;
3440 // Pick another record to be primary (if one isn't already)
3441 if (!$dao->find(TRUE)) {
3442 $dao->is_primary
= 0;
3444 if ($dao->fetch()) {
3445 $dao->is_primary
= 1;
3451 CRM_Utils_Hook
::post('delete', $type, $id, $obj);
3459 public function addSelectWhereClause() {
3460 // We always return an array with these keys, even if they are empty,
3461 // because this tells the query builder that we have considered these fields for acls
3463 'id' => (array) CRM_Contact_BAO_Contact_Permission
::cacheSubquery(),
3464 'is_deleted' => CRM_Core_Permission
::check('access deleted contacts') ?
array() : array('!= 1'),
3466 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3471 * Get any existing duplicate contacts based on the input parameters.
3473 * @param array $input
3474 * Input parameters to be matched.
3475 * @param string $contactType
3476 * @param string $rule
3479 * @param $excludedContactIDs
3480 * An array of ids not to be included in the results.
3481 * @param bool $checkPermissions
3482 * @param int $ruleGroupID
3483 * ID of the rule group to be used if an override is desirable.
3487 public static function getDuplicateContacts($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = array(), $checkPermissions = TRUE, $ruleGroupID = NULL) {
3488 $dedupeParams = CRM_Dedupe_Finder
::formatParams($input, $contactType);
3489 $dedupeParams['check_permission'] = $checkPermissions;
3490 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $contactType, $rule, $excludedContactIDs, $ruleGroupID);
3495 * Get the first duplicate contacts based on the input parameters.
3497 * @param array $input
3498 * Input parameters to be matched.
3499 * @param string $contactType
3500 * @param string $rule
3503 * @param $excludedContactIDs
3504 * An array of ids not to be included in the results.
3505 * @param bool $checkPermissions
3506 * @param int $ruleGroupID
3507 * ID of the rule group to be used if an override is desirable.
3511 public static function getFirstDuplicateContact($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = array(), $checkPermissions = TRUE, $ruleGroupID = NULL) {
3512 $ids = self
::getDuplicateContacts($input, $contactType, $rule, $excludedContactIDs, $checkPermissions, $ruleGroupID);
3520 * Check if a field is associated with an entity that has a location type.
3522 * (ie. is an address, phone, email etc field).
3524 * @param string $fieldTitle
3525 * Title of the field (not the name - create a new function for that if required).
3529 public static function isFieldHasLocationType($fieldTitle) {
3530 foreach (CRM_Contact_BAO_Contact
::importableFields() as $key => $field) {
3531 if ($field['title'] === $fieldTitle) {
3532 return CRM_Utils_Array
::value('hasLocationType', $field);