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 $userID = CRM_Core_Session
::singleton()->get('userID');
356 if (!empty($params['note'])) {
357 if (is_array($params['note'])) {
358 foreach ($params['note'] as $note) {
359 $contactId = $contact->id
;
360 if (isset($note['contact_id'])) {
361 $contactId = $note['contact_id'];
363 //if logged in user, overwrite contactId
365 $contactId = $userID;
369 'entity_id' => $contact->id
,
370 'entity_table' => 'civicrm_contact',
371 'note' => $note['note'],
372 'subject' => CRM_Utils_Array
::value('subject', $note),
373 'contact_id' => $contactId,
375 CRM_Core_BAO_Note
::add($noteParams, CRM_Core_DAO
::$_nullArray);
379 $contactId = $contact->id
;
380 if (isset($note['contact_id'])) {
381 $contactId = $note['contact_id'];
383 //if logged in user, overwrite contactId
385 $contactId = $userID;
389 'entity_id' => $contact->id
,
390 'entity_table' => 'civicrm_contact',
391 'note' => $params['note'],
392 'subject' => CRM_Utils_Array
::value('subject', $params),
393 'contact_id' => $contactId,
395 CRM_Core_BAO_Note
::add($noteParams, CRM_Core_DAO
::$_nullArray);
399 // update the UF user_unique_id if that has changed
400 CRM_Core_BAO_UFMatch
::updateUFName($contact->id
);
402 if (!empty($params['custom']) &&
403 is_array($params['custom'])
405 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contact', $contact->id
);
408 // make a civicrm_subscription_history entry only on contact create (CRM-777)
409 if (empty($params['contact_id'])) {
410 $subscriptionParams = array(
411 'contact_id' => $contact->id
,
415 CRM_Contact_BAO_SubscriptionHistory
::create($subscriptionParams);
418 $transaction->commit();
420 // CRM-6367: fetch the right label for contact type’s display
421 $contact->contact_type_display
= CRM_Core_DAO
::getFieldValue(
422 'CRM_Contact_DAO_ContactType',
423 $contact->contact_type
,
428 if (!$config->doNotResetCache
) {
429 // Note: doNotResetCache flag is currently set by import contact process and merging,
430 // since resetting and
431 // rebuilding cache could be expensive (for many contacts). We might come out with better
432 // approach in future.
433 CRM_Contact_BAO_Contact_Utils
::clearContactCaches($contact->id
);
438 CRM_Utils_Hook
::post('edit', $params['contact_type'], $contact->id
, $contact);
441 CRM_Utils_Hook
::post('create', $params['contact_type'], $contact->id
, $contact);
445 // process greetings CRM-4575, cache greetings
446 self
::processGreetings($contact);
452 * Get the display name and image of a contact.
457 * @param bool $includeTypeInReturnParameters
458 * Should type be part of the returned array?
461 * the displayName and contactImage for this contact
463 public static function getDisplayAndImage($id, $includeTypeInReturnParameters = FALSE) {
464 //CRM-14276 added the * on the civicrm_contact table so that we have all the contact info available
466 SELECT civicrm_contact.*,
467 civicrm_email.email as email
469 LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
470 AND civicrm_email.is_primary = 1
471 WHERE civicrm_contact.id = " . CRM_Utils_Type
::escape($id, 'Integer');
472 $dao = new CRM_Core_DAO();
475 $image = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
476 $dao->contact_sub_type
: $dao->contact_type
, FALSE, $id
478 $imageUrl = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
479 $dao->contact_sub_type
: $dao->contact_type
, TRUE, $id
482 // use email if display_name is empty
483 if (empty($dao->display_name
)) {
484 $displayName = $dao->email
;
487 $displayName = $dao->display_name
;
490 CRM_Utils_Hook
::alterDisplayName($displayName, $id, $dao);
492 return $includeTypeInReturnParameters ?
array(
496 $dao->contact_sub_type
,
498 ) : array($displayName, $image, $imageUrl);
504 * Add billing fields to the params if appropriate.
506 * If we have ANY name fields then we want to ignore all the billing name fields. However, if we
507 * don't then we should set the name fields to the filling fields AND add the preserveDBName
508 * parameter (which will tell the BAO only to set those fields if none already exist.
510 * We specifically don't want to set first name from billing and last name form an on-page field. Mixing &
511 * matching is best done by hipsters.
513 * @param array $params
515 public static function addBillingNameFieldsIfOtherwiseNotSet(&$params) {
516 $nameFields = array('first_name', 'middle_name', 'last_name', 'nick_name', 'prefix_id', 'suffix_id');
517 foreach ($nameFields as $field) {
518 if (!empty($params[$field])) {
522 // There are only 3 - we can iterate through them twice :-)
523 foreach ($nameFields as $field) {
524 if (!empty($params['billing_' . $field])) {
525 $params[$field] = $params['billing_' . $field];
527 $params['preserveDBName'] = TRUE;
533 * Create last viewed link to recently updated contact.
535 * @param array $crudLinkSpec
536 * - action: int, CRM_Core_Action::UPDATE or CRM_Core_Action::VIEW [default: VIEW]
537 * - entity_table: string, eg "civicrm_contact"
541 * NULL if unavailable, or
542 * [path: string, query: string, title: string]
543 * @see CRM_Utils_System::createDefaultCrudLink
545 public function createDefaultCrudLink($crudLinkSpec) {
546 switch ($crudLinkSpec['action']) {
547 case CRM_Core_Action
::VIEW
:
549 'title' => $this->display_name
,
550 'path' => 'civicrm/contact/view',
558 case CRM_Core_Action
::UPDATE
:
560 'title' => $this->display_name
,
561 'path' => 'civicrm/contact/add',
564 'action' => 'update',
574 * Get the values for pseudoconstants for name->value and reverse.
576 * @param array $defaults
577 * (reference) the default values, some of which need to be resolved.
578 * @param bool $reverse
579 * True if we want to resolve the values in the reverse direction (value -> name).
581 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
582 // Hack for birth_date.
583 if (!empty($defaults['birth_date'])) {
584 if (is_array($defaults['birth_date'])) {
585 $defaults['birth_date'] = CRM_Utils_Date
::format($defaults['birth_date'], '-');
589 CRM_Utils_Array
::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id'), $reverse);
590 CRM_Utils_Array
::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'suffix_id'), $reverse);
591 CRM_Utils_Array
::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'), $reverse);
592 CRM_Utils_Array
::lookupValue($defaults, 'communication_style', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'communication_style_id'), $reverse);
594 //lookup value of email/postal greeting, addressee, CRM-4575
595 foreach (self
::$_greetingTypes as $greeting) {
596 $filterCondition = array(
597 'contact_type' => CRM_Utils_Array
::value('contact_type', $defaults),
598 'greeting_type' => $greeting,
600 CRM_Utils_Array
::lookupValue($defaults, $greeting,
601 CRM_Core_PseudoConstant
::greeting($filterCondition), $reverse
605 $blocks = array('address', 'im', 'phone');
606 foreach ($blocks as $name) {
607 if (!array_key_exists($name, $defaults) ||
!is_array($defaults[$name])) {
610 foreach ($defaults[$name] as $count => & $values) {
612 //get location type id.
613 CRM_Utils_Array
::lookupValue($values, 'location_type', CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id'), $reverse);
615 if ($name == 'address') {
616 // FIXME: lookupValue doesn't work for vcard_name
617 if (!empty($values['location_type_id'])) {
618 $vcardNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array('labelColumn' => 'vcard_name'));
619 $values['vcard_name'] = $vcardNames[$values['location_type_id']];
622 if (!CRM_Utils_Array
::lookupValue($values,
624 CRM_Core_PseudoConstant
::country(),
629 CRM_Utils_Array
::lookupValue($values,
631 CRM_Core_PseudoConstant
::countryIsoCode(),
637 // if we find a country id above, we need to restrict it to that country
638 // rather than the list of all countries
640 if (!empty($values['country_id'])) {
641 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($values['country_id']);
644 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvince();
646 if (!CRM_Utils_Array
::lookupValue($values,
654 if (!empty($values['country_id'])) {
655 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($values['country_id'], 'abbreviation');
658 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviation();
660 CRM_Utils_Array
::lookupValue($values,
667 if (!empty($values['state_province_id'])) {
668 $countyList = CRM_Core_PseudoConstant
::countyForState($values['state_province_id']);
671 $countyList = CRM_Core_PseudoConstant
::county();
673 CRM_Utils_Array
::lookupValue($values,
681 CRM_Utils_Array
::lookupValue($values,
683 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id'),
688 if ($name == 'phone') {
689 CRM_Utils_Array
::lookupValue($values,
691 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id'),
696 // Kill the reference.
703 * Fetch object based on array of properties.
705 * @param array $params
706 * (reference ) an assoc array of name/value pairs.
707 * @param array $defaults
708 * (reference ) an assoc array to hold the name / value pairs.
709 * in a hierarchical manner
710 * @param bool $microformat
711 * For location in microformat.
713 * @return CRM_Contact_BAO_Contact
715 public static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
716 if (array_key_exists('contact_id', $params)) {
717 $params['id'] = $params['contact_id'];
719 elseif (array_key_exists('id', $params)) {
720 $params['contact_id'] = $params['id'];
723 $contact = self
::getValues($params, $defaults);
725 unset($params['id']);
727 //get the block information for this contact
728 $entityBlock = array('contact_id' => $params['contact_id']);
729 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock, $microformat);
730 $defaults = array_merge($defaults, $blocks);
731 foreach ($blocks as $block => $value) {
732 $contact->$block = $value;
735 if (!isset($params['noNotes'])) {
736 $contact->notes
= CRM_Core_BAO_Note
::getValues($params, $defaults);
739 if (!isset($params['noRelationships'])) {
740 $contact->relationship
= CRM_Contact_BAO_Relationship
::getValues($params, $defaults);
743 if (!isset($params['noGroups'])) {
744 $contact->groupContact
= CRM_Contact_BAO_GroupContact
::getValues($params, $defaults);
747 if (!isset($params['noWebsite'])) {
748 $contact->website
= CRM_Core_BAO_Website
::getValues($params, $defaults);
755 * Get the display name of a contact.
760 * @return null|string
761 * display name of the contact if found
763 public static function displayName($id) {
766 $displayName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
773 * Delete a contact and all its associated records.
776 * Id of the contact to delete.
777 * @param bool $restore
778 * Whether to actually restore, not delete.
779 * @param bool $skipUndelete
780 * Whether to force contact delete or not.
781 * @param bool $checkPermissions
784 * Was contact deleted?
786 public static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE, $checkPermissions = TRUE) {
791 // If trash is disabled in system settings then we always skip
792 if (!Civi
::settings()->get('contact_undelete')) {
793 $skipUndelete = TRUE;
796 // make sure we have edit permission for this contact
798 if ($checkPermissions && (($skipUndelete && !CRM_Core_Permission
::check('delete contacts')) ||
799 ($restore && !CRM_Core_Permission
::check('access deleted contacts')))
805 // Restrict contact to be delete if contact has financial trxns
807 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent(array($id), $error)) {
811 // make sure this contact_id does not have any membership types
812 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
815 'member_of_contact_id'
817 if ($membershipTypeID) {
821 $contact = new CRM_Contact_DAO_Contact();
823 if (!$contact->find(TRUE)) {
827 $contactType = $contact->contact_type
;
828 // currently we only clear employer cache.
829 // we are now deleting inherited membership if any.
830 if ($contact->contact_type
== 'Organization') {
831 $action = $restore ? CRM_Core_Action
::ENABLE
: CRM_Core_Action
::DISABLE
;
832 $relationshipDtls = CRM_Contact_BAO_Relationship
::getRelationship($id);
833 if (!empty($relationshipDtls)) {
834 foreach ($relationshipDtls as $rId => $details) {
835 CRM_Contact_BAO_Relationship
::disableEnableRelationship($rId, $action);
838 CRM_Contact_BAO_Contact_Utils
::clearAllEmployee($id);
842 return self
::contactTrashRestore($contact, TRUE);
845 // start a new transaction
846 $transaction = new CRM_Core_Transaction();
849 CRM_Utils_Hook
::pre('delete', $contactType, $id, CRM_Core_DAO
::$_nullArray);
851 //delete billing address if exists.
852 CRM_Contribute_BAO_Contribution
::deleteAddress(NULL, $id);
854 // delete the log entries since we dont have triggers enabled as yet
855 $logDAO = new CRM_Core_DAO_Log();
856 $logDAO->entity_table
= 'civicrm_contact';
857 $logDAO->entity_id
= $id;
860 // delete contact participants CRM-12155
861 CRM_Event_BAO_Participant
::deleteContactParticipant($id);
863 // delete contact contributions CRM-12155
864 CRM_Contribute_BAO_Contribution
::deleteContactContribution($id);
866 // do activity cleanup, CRM-5604
867 CRM_Activity_BAO_Activity
::cleanupActivity($id);
869 // delete all notes related to contact
870 CRM_Core_BAO_Note
::cleanContactNotes($id);
872 // delete cases related to contact
873 $contactCases = CRM_Case_BAO_Case
::retrieveCaseIdsByContactId($id);
874 if (!empty($contactCases)) {
875 foreach ($contactCases as $caseId) {
876 //check if case is associate with other contact or not.
877 $caseContactId = CRM_Case_BAO_Case
::getCaseClients($caseId);
878 if (count($caseContactId) <= 1) {
879 CRM_Case_BAO_Case
::deleteCase($caseId);
887 self
::contactTrashRestore($contact);
890 //delete the contact id from recently view
891 CRM_Utils_Recent
::delContact($id);
892 self
::updateContactCache($id, empty($restore));
894 // delete any dupe cache entry
895 CRM_Core_BAO_PrevNextCache
::deleteItem($id);
897 $transaction->commit();
900 CRM_Utils_Hook
::post('delete', $contactType, $contact->id
, $contact);
903 // also reset the DB_DO global array so we can reuse the memory
904 // http://issues.civicrm.org/jira/browse/CRM-4387
905 CRM_Core_DAO
::freeResult();
911 * Action to update any caches relating to a recently update contact.
913 * I was going to call this from delete as well as from create to ensure the delete is being
914 * done whenever a contact is set to is_deleted=1 BUT I found create is already over-aggressive in
915 * that regard so adding it to delete seems to be enough to remove it from CRM_Contact_BAO_Contact_Permission
916 * where the call involved a subquery that was locking the table.
918 * @param int $contactID
919 * @param bool $isTrashed
921 public static function updateContactCache($contactID, $isTrashed = FALSE) {
924 CRM_Contact_BAO_GroupContactCache
::removeContact($contactID);
925 // This has been moved to here from CRM_Contact_BAO_Contact_Permission as that was causing
926 // a table-locking query. It still seems a bit inadequate as it assumes the acl users can't see deleted
927 // but this should not cause any change as long as contacts are not being trashed outside the
928 // main functions for that.
929 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_acl_contact_cache WHERE contact_id = %1', array(1 => array($contactID, 'Integer')));
932 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
937 * Delete the image of a contact.
943 * Was contact image deleted?
945 public static function deleteContactImage($id) {
950 UPDATE civicrm_contact
953 CRM_Core_DAO
::executeQuery($query);
958 * Return proportional height and width of the image.
960 * @param int $imageWidth
963 * @param int $imageHeight
967 * Thumb dimension of image
969 public static function getThumbSize($imageWidth, $imageHeight) {
971 if ($imageWidth && $imageHeight) {
972 $imageRatio = $imageWidth / $imageHeight;
977 if ($imageRatio > 1) {
978 $imageThumbWidth = $thumbWidth;
979 $imageThumbHeight = round($thumbWidth / $imageRatio);
982 $imageThumbHeight = $thumbWidth;
983 $imageThumbWidth = round($thumbWidth * $imageRatio);
986 return array($imageThumbWidth, $imageThumbHeight);
990 * Validate type of contact image.
992 * @param array $params
993 * @param string $imageIndex
994 * Index of image field.
995 * @param string $statusMsg
996 * Status message to be set after operation.
997 * @param string $opType
998 * Type of operation like fatal, bounce etc.
1001 * true if valid image extension
1003 public static function processImageParams(
1005 $imageIndex = 'image_URL',
1019 if (in_array($params[$imageIndex]['type'], $mimeType)) {
1020 $photo = basename($params[$imageIndex]['name']);
1021 $params[$imageIndex] = CRM_Utils_System
::url('civicrm/contact/imagefile', 'photo=' . $photo, TRUE, NULL, TRUE, TRUE);
1025 unset($params[$imageIndex]);
1027 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
1029 if ($opType == 'status') {
1030 CRM_Core_Session
::setStatus($statusMsg, 'Sorry', 'error');
1032 // FIXME: additional support for fatal, bounce etc could be added.
1038 * Extract contact id from url for deleting contact image.
1040 public static function processImage() {
1042 $action = CRM_Utils_Request
::retrieve('action', 'String');
1043 $cid = CRM_Utils_Request
::retrieve('cid', 'Positive');
1044 // retrieve contact id in case of Profile context
1045 $id = CRM_Utils_Request
::retrieve('id', 'Positive');
1046 $cid = $cid ?
$cid : $id;
1047 if ($action & CRM_Core_Action
::DELETE
) {
1048 if (CRM_Utils_Request
::retrieve('confirmed', 'Boolean')) {
1049 CRM_Contact_BAO_Contact
::deleteContactImage($cid);
1050 CRM_Core_Session
::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
1051 $session = CRM_Core_Session
::singleton();
1052 $toUrl = $session->popUserContext();
1053 CRM_Utils_System
::redirect($toUrl);
1059 * Function to set is_delete true or restore deleted contact.
1061 * @param CRM_Contact_DAO_Contact $contact
1062 * Contact DAO object.
1063 * @param bool $restore
1064 * True to set the is_delete = 1 else false to restore deleted contact,
1065 * i.e. is_delete = 0
1069 public static function contactTrashRestore($contact, $restore = FALSE) {
1070 $updateParams = array(
1071 'id' => $contact->id
,
1072 'is_deleted' => $restore ?
0 : 1,
1075 CRM_Utils_Hook
::pre('update', $contact->contact_type
, $contact->id
, $updateParams);
1077 $params = array(1 => array($contact->id
, 'Integer'));
1079 $query = "DELETE FROM civicrm_uf_match WHERE contact_id = %1";
1080 CRM_Core_DAO
::executeQuery($query, $params);
1083 $contact->copyValues($updateParams);
1086 CRM_Utils_Hook
::post('update', $contact->contact_type
, $contact->id
, $contact);
1092 * Get contact type for a contact.
1095 * Id of the contact whose contact type is needed.
1098 * contact_type if $id found else null ""
1100 public static function getContactType($id) {
1101 return CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1105 * Get contact sub type for a contact.
1108 * Id of the contact whose contact sub type is needed.
1110 * @param string $implodeDelimiter
1113 * contact_sub_type if $id found else null ""
1115 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1116 $subtype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1118 return $implodeDelimiter ?
NULL : array();
1121 $subtype = CRM_Utils_Array
::explodePadded($subtype);
1123 if ($implodeDelimiter) {
1124 $subtype = implode($implodeDelimiter, $subtype);
1130 * Get pair of contact-type and sub-type for a contact.
1133 * Id of the contact whose contact sub/contact type is needed.
1137 public static function getContactTypes($id) {
1138 $params = array('id' => $id);
1140 $contact = CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact',
1143 array('contact_type', 'contact_sub_type')
1147 $contactTypes = array();
1148 if ($contact->contact_sub_type
) {
1149 $contactTypes = CRM_Utils_Array
::explodePadded($contact->contact_sub_type
);
1151 array_unshift($contactTypes, $contact->contact_type
);
1153 return $contactTypes;
1156 CRM_Core_Error
::fatal();
1161 * Combine all the importable fields from the lower levels object.
1163 * The ordering is important, since currently we do not have a weight
1164 * scheme. Adding weight is super important
1166 * @param int|string $contactType contact Type
1167 * @param bool $status
1168 * Status is used to manipulate first title.
1169 * @param bool $showAll
1170 * If true returns all fields (includes disabled fields).
1171 * @param bool $isProfile
1172 * If its profile mode.
1173 * @param bool $checkPermission
1174 * If false, do not include permissioning clause (for custom data).
1176 * @param bool $withMultiCustomFields
1179 * array of importable Fields
1181 public static function importableFields(
1182 $contactType = 'Individual',
1186 $checkPermission = TRUE,
1187 $withMultiCustomFields = FALSE
1189 if (empty($contactType)) {
1190 $contactType = 'All';
1193 $cacheKeyString = "importableFields $contactType";
1194 $cacheKeyString .= $status ?
'_1' : '_0';
1195 $cacheKeyString .= $showAll ?
'_1' : '_0';
1196 $cacheKeyString .= $isProfile ?
'_1' : '_0';
1197 $cacheKeyString .= $checkPermission ?
'_1' : '_0';
1199 $fields = CRM_Utils_Array
::value($cacheKeyString, self
::$_importableFields);
1202 // check if we can retrieve from database cache
1203 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1207 $fields = CRM_Contact_DAO_Contact
::import();
1209 // get the fields thar are meant for contact types
1210 if (in_array($contactType, array(
1216 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1219 $locationFields = array_merge(CRM_Core_DAO_Address
::import(),
1220 CRM_Core_DAO_Phone
::import(),
1221 CRM_Core_DAO_Email
::import(),
1222 CRM_Core_DAO_IM
::import(TRUE),
1223 CRM_Core_DAO_OpenID
::import()
1226 $locationFields = array_merge($locationFields,
1227 CRM_Core_BAO_CustomField
::getFieldsForImport('Address',
1235 foreach ($locationFields as $key => $field) {
1236 $locationFields[$key]['hasLocationType'] = TRUE;
1239 $fields = array_merge($fields, $locationFields);
1241 $fields = array_merge($fields, CRM_Contact_DAO_Contact
::import());
1242 $fields = array_merge($fields, CRM_Core_DAO_Note
::import());
1245 $fields = array_merge($fields, CRM_Core_DAO_Website
::import());
1246 $fields['url']['hasWebsiteType'] = TRUE;
1248 if ($contactType != 'All') {
1249 $fields = array_merge($fields,
1250 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType,
1255 $withMultiCustomFields
1258 //unset the fields, which are not related to their
1260 $commonValues = array(
1261 'Individual' => array(
1265 'organization_name',
1267 'Household' => array(
1277 'organization_name',
1285 'Organization' => array(
1300 foreach ($commonValues[$contactType] as $value) {
1301 unset($fields[$value]);
1305 foreach (array('Individual', 'Household', 'Organization') as $type) {
1306 $fields = array_merge($fields,
1307 CRM_Core_BAO_CustomField
::getFieldsForImport($type,
1312 $withMultiCustomFields
1319 $fields = array_merge($fields, array(
1321 'title' => ts('Group(s)'),
1325 'title' => ts('Tag(s)'),
1329 'title' => ts('Note(s)'),
1332 'communication_style_id' => array(
1333 'title' => ts('Communication Style'),
1334 'name' => 'communication_style_id',
1339 //Sorting fields in alphabetical order(CRM-1507)
1340 $fields = CRM_Utils_Array
::crmArraySortByField($fields, 'title');
1342 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1345 self
::$_importableFields[$cacheKeyString] = $fields;
1349 $fields = array_merge(array('do_not_import' => array('title' => ts('- do not import -'))),
1350 self
::$_importableFields[$cacheKeyString]
1354 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1355 self
::$_importableFields[$cacheKeyString]
1363 * Combine all the exportable fields from the lower levels object.
1365 * Currently we are using importable fields as exportable fields
1367 * @param int|string $contactType contact Type
1368 * @param bool $status
1369 * True while exporting primary contacts.
1370 * @param bool $export
1371 * True when used during export.
1372 * @param bool $search
1373 * True when used during search, might conflict with export param?.
1375 * @param bool $withMultiRecord
1378 * array of exportable Fields
1380 public static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE, $checkPermissions = TRUE) {
1381 if (empty($contactType)) {
1382 $contactType = 'All';
1385 $cacheKeyString = "exportableFields $contactType";
1386 $cacheKeyString .= $export ?
'_1' : '_0';
1387 $cacheKeyString .= $status ?
'_1' : '_0';
1388 $cacheKeyString .= $search ?
'_1' : '_0';
1389 //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
1390 //calculates custom fields takes into account the logged in user & caches that for all users
1391 //as an interim fix we will cache the fields by contact
1392 $cacheKeyString .= '_' . CRM_Core_Session
::getLoggedInContactID();
1394 if (!self
::$_exportableFields ||
!CRM_Utils_Array
::value($cacheKeyString, self
::$_exportableFields)) {
1395 if (!self
::$_exportableFields) {
1396 self
::$_exportableFields = array();
1399 // check if we can retrieve from database cache
1400 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1403 $fields = CRM_Contact_DAO_Contact
::export();
1405 // The fields are meant for contact types.
1406 if (in_array($contactType, array(
1413 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1415 // add current employer for individuals
1416 $fields = array_merge($fields, array(
1417 'current_employer' =>
1419 'name' => 'organization_name',
1420 'title' => ts('Current Employer'),
1424 $locationType = array(
1425 'location_type' => array(
1426 'name' => 'location_type',
1427 'where' => 'civicrm_location_type.name',
1428 'title' => ts('Location Type'),
1432 $IMProvider = array(
1433 'im_provider' => array(
1434 'name' => 'im_provider',
1435 'where' => 'civicrm_im.provider_id',
1436 'title' => ts('IM Provider'),
1440 $locationFields = array_merge($locationType,
1441 CRM_Core_DAO_Address
::export(),
1442 CRM_Core_DAO_Phone
::export(),
1443 CRM_Core_DAO_Email
::export(),
1445 CRM_Core_DAO_IM
::export(TRUE),
1446 CRM_Core_DAO_OpenID
::export()
1449 $locationFields = array_merge($locationFields,
1450 CRM_Core_BAO_CustomField
::getFieldsForImport('Address')
1453 foreach ($locationFields as $key => $field) {
1454 $locationFields[$key]['hasLocationType'] = TRUE;
1457 $fields = array_merge($fields, $locationFields);
1460 $fields = array_merge($fields,
1461 CRM_Core_DAO_Worldregion
::export()
1464 $fields = array_merge($fields,
1465 CRM_Contact_DAO_Contact
::export()
1469 $fields = array_merge($fields, CRM_Core_DAO_Website
::export());
1471 if ($contactType != 'All') {
1472 $fields = array_merge($fields,
1473 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType, $status, FALSE, $search, $checkPermissions, $withMultiRecord)
1482 $fields = array_merge($fields,
1483 CRM_Core_BAO_CustomField
::getFieldsForImport($type, FALSE, FALSE, $search, $checkPermissions, $withMultiRecord)
1487 $fields['current_employer_id']['title'] = ts('Current Employer ID');
1490 $fields = array_merge($fields, array(
1492 'title' => ts('Group(s)'),
1496 'title' => ts('Tag(s)'),
1500 'title' => ts('Note(s)'),
1506 $fields = array_merge($fields, array(
1508 'title' => ts('Group(s)'),
1512 'title' => ts('Tag(s)'),
1516 'title' => ts('Note(s)'),
1522 //Sorting fields in alphabetical order(CRM-1507)
1523 foreach ($fields as $k => $v) {
1524 $sortArray[$k] = CRM_Utils_Array
::value('title', $v);
1527 $fields = array_merge($sortArray, $fields);
1528 //unset the field which are not related to their contact type.
1529 if ($contactType != 'All') {
1530 $commonValues = array(
1531 'Individual' => array(
1535 'organization_name',
1536 'email_greeting_custom',
1537 'postal_greeting_custom',
1540 'Household' => array(
1550 'organization_name',
1558 'email_greeting_custom',
1559 'postal_greeting_custom',
1564 'Organization' => array(
1575 'email_greeting_custom',
1576 'postal_greeting_custom',
1586 foreach ($commonValues[$contactType] as $value) {
1587 unset($fields[$value]);
1591 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1593 self
::$_exportableFields[$cacheKeyString] = $fields;
1597 $fields = self
::$_exportableFields[$cacheKeyString];
1600 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1601 self
::$_exportableFields[$cacheKeyString]
1609 * Get the all contact details (Hierarchical).
1611 * @param int $contactId
1613 * @param array $fields
1619 public static function getHierContactDetails($contactId, &$fields) {
1620 $params = array(array('contact_id', '=', $contactId, 0, 0));
1623 $returnProperties = self
::makeHierReturnProperties($fields, $contactId);
1625 // We don't know the contents of return properties, but we need the lower
1626 // level ids of the contact so add a few fields.
1627 $returnProperties['first_name'] = 1;
1628 $returnProperties['organization_name'] = 1;
1629 $returnProperties['household_name'] = 1;
1630 $returnProperties['contact_type'] = 1;
1631 $returnProperties['contact_sub_type'] = 1;
1632 return list($query, $options) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, $options);
1636 * Given a set of flat profile style field names, create a hierarchy.
1638 * This is for the query to use, create the right sql.
1641 * @param int $contactId
1645 * A hierarchical property tree if appropriate
1647 public static function &makeHierReturnProperties($fields, $contactId = NULL) {
1648 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1650 $returnProperties = array();
1652 $multipleFields = array('website' => 'url');
1653 foreach ($fields as $name => $dontCare) {
1654 if (strpos($name, '-') !== FALSE) {
1655 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $name, 3);
1657 if (!in_array($fieldName, $multipleFields)) {
1658 if ($id == 'Primary') {
1659 $locationTypeName = 1;
1662 $locationTypeName = CRM_Utils_Array
::value($id, $locationTypes);
1663 if (!$locationTypeName) {
1668 if (empty($returnProperties['location'])) {
1669 $returnProperties['location'] = array();
1671 if (empty($returnProperties['location'][$locationTypeName])) {
1672 $returnProperties['location'][$locationTypeName] = array();
1673 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1675 if (in_array($fieldName, array(
1683 $returnProperties['location'][$locationTypeName][$fieldName . '-' . $type] = 1;
1686 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1689 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1690 $returnProperties['location'][$locationTypeName][substr($fieldName, 8)] = 1;
1693 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1697 $returnProperties['website'][$id][$fieldName] = 1;
1701 $returnProperties[$name] = 1;
1705 return $returnProperties;
1709 * Return the primary location type of a contact.
1711 * $params int $contactId contact_id
1712 * $params boolean $isPrimaryExist if true, return primary contact location type otherwise null
1713 * $params boolean $skipDefaultPriamry if true, return primary contact location type otherwise null
1715 * @param int $contactId
1716 * @param bool $skipDefaultPriamry
1717 * @param null $block
1720 * $locationType location_type_id
1722 public static function getPrimaryLocationType($contactId, $skipDefaultPriamry = FALSE, $block = NULL) {
1724 $entityBlock = array('contact_id' => $contactId);
1725 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock);
1726 foreach ($blocks[$block] as $key => $value) {
1727 if (!empty($value['is_primary'])) {
1728 $locationType = CRM_Utils_Array
::value('location_type_id', $value);
1735 IF ( civicrm_email.location_type_id IS NULL,
1736 IF ( civicrm_address.location_type_id IS NULL,
1737 IF ( civicrm_phone.location_type_id IS NULL,
1738 IF ( civicrm_im.location_type_id IS NULL,
1739 IF ( civicrm_openid.location_type_id IS NULL, null, civicrm_openid.location_type_id)
1740 ,civicrm_im.location_type_id)
1741 ,civicrm_phone.location_type_id)
1742 ,civicrm_address.location_type_id)
1743 ,civicrm_email.location_type_id) as locationType
1744 FROM civicrm_contact
1745 LEFT JOIN civicrm_email ON ( civicrm_email.is_primary = 1 AND civicrm_email.contact_id = civicrm_contact.id )
1746 LEFT JOIN civicrm_address ON ( civicrm_address.is_primary = 1 AND civicrm_address.contact_id = civicrm_contact.id)
1747 LEFT JOIN civicrm_phone ON ( civicrm_phone.is_primary = 1 AND civicrm_phone.contact_id = civicrm_contact.id)
1748 LEFT JOIN civicrm_im ON ( civicrm_im.is_primary = 1 AND civicrm_im.contact_id = civicrm_contact.id)
1749 LEFT JOIN civicrm_openid ON ( civicrm_openid.is_primary = 1 AND civicrm_openid.contact_id = civicrm_contact.id)
1750 WHERE civicrm_contact.id = %1 ";
1752 $params = array(1 => array($contactId, 'Integer'));
1754 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1756 $locationType = NULL;
1757 if ($dao->fetch()) {
1758 $locationType = $dao->locationType
;
1761 if (isset($locationType)) {
1762 return $locationType;
1764 elseif ($skipDefaultPriamry) {
1765 // if there is no primary contact location then return null
1769 // if there is no primart contact location, then return default
1770 // location type of the system
1771 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
1772 return $defaultLocationType->id
;
1777 * Get the display name, primary email and location type of a contact.
1780 * Id of the contact.
1783 * Array of display_name, email if found, do_not_email or (null,null,null)
1785 public static function getContactDetails($id) {
1786 // check if the contact type
1787 $contactType = self
::getContactType($id);
1789 $nameFields = ($contactType == 'Individual') ?
"civicrm_contact.first_name, civicrm_contact.last_name, civicrm_contact.display_name" : "civicrm_contact.display_name";
1792 SELECT $nameFields, civicrm_email.email, civicrm_contact.do_not_email, civicrm_email.on_hold, civicrm_contact.is_deceased
1793 FROM civicrm_contact LEFT JOIN civicrm_email ON (civicrm_contact.id = civicrm_email.contact_id)
1794 WHERE civicrm_contact.id = %1
1795 ORDER BY civicrm_email.is_primary DESC";
1796 $params = array(1 => array($id, 'Integer'));
1797 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
1799 if ($dao->fetch()) {
1800 if ($contactType == 'Individual') {
1801 if ($dao->first_name ||
$dao->last_name
) {
1802 $name = "{$dao->first_name} {$dao->last_name}";
1805 $name = $dao->display_name
;
1809 $name = $dao->display_name
;
1811 $email = $dao->email
;
1812 $doNotEmail = $dao->do_not_email ?
TRUE : FALSE;
1813 $onHold = $dao->on_hold ?
TRUE : FALSE;
1814 $isDeceased = $dao->is_deceased ?
TRUE : FALSE;
1815 return array($name, $email, $doNotEmail, $onHold, $isDeceased);
1817 return array(NULL, NULL, NULL, NULL, NULL);
1821 * Add/edit/register contacts through profile.
1823 * @param array $params
1824 * Array of profile fields to be edited/added.
1825 * @param array $fields
1826 * Array of fields from UFGroup.
1827 * @param int $contactID
1828 * Id of the contact to be edited/added.
1829 * @param int $addToGroupID
1830 * Specifies the default group to which contact is added.
1831 * @param int $ufGroupId
1832 * Uf group id (profile id).
1833 * @param string $ctype
1834 * @param bool $visibility
1835 * Basically lets us know where this request is coming from.
1836 * if via a profile from web, we restrict what groups are changed
1839 * contact id created/edited
1841 public static function createProfileContact(
1845 $addToGroupID = NULL,
1850 // add ufGroupID to params array ( CRM-2012 )
1852 $params['uf_group_id'] = $ufGroupId;
1854 self
::addBillingNameFieldsIfOtherwiseNotSet($params);
1856 // If a user has logged in, or accessed via a checksum
1857 // Then deliberately 'blanking' a value in the profile should remove it from their record
1858 $session = CRM_Core_Session
::singleton();
1859 $params['updateBlankLocInfo'] = TRUE;
1860 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0) {
1861 $params['updateBlankLocInfo'] = FALSE;
1866 CRM_Utils_Hook
::pre('edit', 'Profile', $contactID, $params);
1870 CRM_Utils_Hook
::pre('create', 'Profile', NULL, $params);
1873 list($data, $contactDetails) = self
::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
1875 // manage is_opt_out
1876 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
1877 $wasOptOut = CRM_Utils_Array
::value('is_opt_out', $contactDetails, FALSE);
1878 $isOptOut = CRM_Utils_Array
::value('is_opt_out', $params, FALSE);
1879 $data['is_opt_out'] = $isOptOut;
1880 // on change, create new civicrm_subscription_history entry
1881 if (($wasOptOut != $isOptOut) && !empty($contactDetails['contact_id'])) {
1883 'contact_id' => $contactDetails['contact_id'],
1884 'status' => $isOptOut ?
'Removed' : 'Added',
1887 CRM_Contact_BAO_SubscriptionHistory
::create($shParams);
1891 $contact = self
::create($data);
1893 // contact is null if the profile does not have any contact fields
1895 $contactID = $contact->id
;
1898 if (empty($contactID)) {
1899 CRM_Core_Error
::fatal('Cannot proceed without a valid contact id');
1902 // Process group and tag
1903 if (!empty($fields['group'])) {
1905 // this for sure means we are coming in via profile since i added it to fix
1906 // removing contacts from user groups -- lobo
1910 CRM_Contact_BAO_GroupContact
::create($params['group'], $contactID, $visibility, $method);
1913 if (!empty($fields['tag'])) {
1914 CRM_Core_BAO_EntityTag
::create($params['tag'], 'civicrm_contact', $contactID);
1917 //to add profile in default group
1918 if (is_array($addToGroupID)) {
1919 $contactIds = array($contactID);
1920 foreach ($addToGroupID as $groupId) {
1921 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
1924 elseif ($addToGroupID) {
1925 $contactIds = array($contactID);
1926 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $addToGroupID);
1929 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
1932 CRM_Utils_Hook
::post('edit', 'Profile', $contactID, $params);
1935 CRM_Utils_Hook
::post('create', 'Profile', $contactID, $params);
1941 * Format profile contact parameters.
1943 * @param array $params
1945 * @param int $contactID
1946 * @param int $ufGroupId
1947 * @param null $ctype
1948 * @param bool $skipCustom
1952 public static function formatProfileContactParams(
1961 $data = $contactDetails = array();
1963 // get the contact details (hier)
1965 list($details, $options) = self
::getHierContactDetails($contactID, $fields);
1967 $contactDetails = $details[$contactID];
1968 $data['contact_type'] = CRM_Utils_Array
::value('contact_type', $contactDetails);
1969 $data['contact_sub_type'] = CRM_Utils_Array
::value('contact_sub_type', $contactDetails);
1972 //we should get contact type only if contact
1974 $data['contact_type'] = CRM_Core_BAO_UFField
::getProfileType($ufGroupId);
1976 //special case to handle profile with only contact fields
1977 if ($data['contact_type'] == 'Contact') {
1978 $data['contact_type'] = 'Individual';
1980 elseif (CRM_Contact_BAO_ContactType
::isaSubType($data['contact_type'])) {
1981 $data['contact_type'] = CRM_Contact_BAO_ContactType
::getBasicType($data['contact_type']);
1985 $data['contact_type'] = $ctype;
1988 $data['contact_type'] = 'Individual';
1992 //fix contact sub type CRM-5125
1993 if (array_key_exists('contact_sub_type', $params) &&
1994 !empty($params['contact_sub_type'])
1996 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type']);
1998 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
1999 !empty($params['contact_sub_type_hidden'])
2001 // if profile was used, and had any subtype, we obtain it from there
2002 //CRM-13596 - add to existing contact types, rather than overwriting
2003 $data_contact_sub_type_arr = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2004 if (!in_array($params['contact_sub_type_hidden'], $data_contact_sub_type_arr)) {
2005 //CRM-20517 - make sure contact_sub_type gets the correct delimiters
2006 $data['contact_sub_type'] = trim($data['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
);
2007 $data['contact_sub_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. $data['contact_sub_type'] . CRM_Utils_Array
::implodePadded($params['contact_sub_type_hidden']);
2011 if ($ctype == 'Organization') {
2012 $data['organization_name'] = CRM_Utils_Array
::value('organization_name', $contactDetails);
2014 elseif ($ctype == 'Household') {
2015 $data['household_name'] = CRM_Utils_Array
::value('household_name', $contactDetails);
2018 $locationType = array();
2023 $data['contact_id'] = $contactID;
2024 $primaryLocationType = self
::getPrimaryLocationType($contactID);
2027 $defaultLocation = CRM_Core_BAO_LocationType
::getDefault();
2028 $defaultLocationId = $defaultLocation->id
;
2031 $billingLocationTypeId = CRM_Core_BAO_LocationType
::getBilling();
2033 $blocks = array('email', 'phone', 'im', 'openid');
2035 $multiplFields = array('url');
2036 // prevent overwritten of formatted array, reset all block from
2037 // params if it is not in valid format (since import pass valid format)
2038 foreach ($blocks as $blk) {
2039 if (array_key_exists($blk, $params) &&
2040 !is_array($params[$blk])
2042 unset($params[$blk]);
2046 $primaryPhoneLoc = NULL;
2047 $session = CRM_Core_Session
::singleton();
2048 foreach ($params as $key => $value) {
2049 list($fieldName, $locTypeId, $typeId) = CRM_Utils_System
::explode('-', $key, 3);
2051 if ($locTypeId == 'Primary') {
2053 if (in_array($fieldName, $blocks)) {
2054 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, $fieldName);
2057 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, 'address');
2059 $primaryLocationType = $locTypeId;
2062 $locTypeId = $defaultLocationId;
2066 if (is_numeric($locTypeId) &&
2067 !in_array($fieldName, $multiplFields) &&
2068 substr($fieldName, 0, 7) != 'custom_'
2070 $index = $locTypeId;
2072 if (is_numeric($typeId)) {
2073 $index .= '-' . $typeId;
2075 if (!in_array($index, $locationType)) {
2076 $locationType[$count] = $index;
2080 $loc = CRM_Utils_Array
::key($index, $locationType);
2082 $blockName = in_array($fieldName, $blocks) ?
$fieldName : 'address';
2084 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
2086 //set is_billing true, for location type "Billing"
2087 if ($locTypeId == $billingLocationTypeId) {
2088 $data[$blockName][$loc]['is_billing'] = 1;
2092 //get the primary location type
2093 if ($locTypeId == $primaryLocationType) {
2094 $data[$blockName][$loc]['is_primary'] = 1;
2097 elseif ($locTypeId == $defaultLocationId) {
2098 $data[$blockName][$loc]['is_primary'] = 1;
2101 if (in_array($fieldName, array('phone'))) {
2103 $data['phone'][$loc]['phone_type_id'] = $typeId;
2106 $data['phone'][$loc]['phone_type_id'] = '';
2108 $data['phone'][$loc]['phone'] = $value;
2110 //special case to handle primary phone with different phone types
2111 // in this case we make first phone type as primary
2112 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
2113 $primaryPhoneLoc = $loc;
2116 if ($loc != $primaryPhoneLoc) {
2117 unset($data['phone'][$loc]['is_primary']);
2120 elseif ($fieldName == 'phone_ext') {
2121 $data['phone'][$loc]['phone_ext'] = $value;
2123 elseif ($fieldName == 'email') {
2124 $data['email'][$loc]['email'] = $value;
2125 if (empty($contactID)) {
2126 $data['email'][$loc]['is_primary'] = 1;
2129 elseif ($fieldName == 'im') {
2130 if (isset($params[$key . '-provider_id'])) {
2131 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
2133 if (strpos($key, '-provider_id') !== FALSE) {
2134 $data['im'][$loc]['provider_id'] = $params[$key];
2137 $data['im'][$loc]['name'] = $value;
2140 elseif ($fieldName == 'openid') {
2141 $data['openid'][$loc]['openid'] = $value;
2144 if ($fieldName === 'state_province') {
2146 if (is_numeric($value) && ((int ) $value) >= 1000) {
2147 $data['address'][$loc]['state_province_id'] = $value;
2149 elseif (empty($value)) {
2150 $data['address'][$loc]['state_province_id'] = '';
2153 $data['address'][$loc]['state_province'] = $value;
2156 elseif ($fieldName === 'country') {
2158 if (is_numeric($value) && ((int ) $value) >= 1000
2160 $data['address'][$loc]['country_id'] = $value;
2162 elseif (empty($value)) {
2163 $data['address'][$loc]['country_id'] = '';
2166 $data['address'][$loc]['country'] = $value;
2169 elseif ($fieldName === 'county') {
2170 $data['address'][$loc]['county_id'] = $value;
2172 elseif ($fieldName == 'address_name') {
2173 $data['address'][$loc]['name'] = $value;
2175 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2176 $data['address'][$loc][substr($fieldName, 8)] = $value;
2179 $data['address'][$loc][$fieldName] = $value;
2184 if (substr($key, 0, 4) === 'url-') {
2185 $websiteField = explode('-', $key);
2186 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
2187 $data['website'][$websiteField[1]]['url'] = $value;
2189 elseif (in_array($key, self
::$_greetingTypes, TRUE)) {
2190 //save email/postal greeting and addressee values if any, CRM-4575
2191 $data[$key . '_id'] = $value;
2193 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($key))) {
2194 // for autocomplete transfer hidden value instead of label
2195 if ($params[$key] && isset($params[$key . '_id'])) {
2196 $value = $params[$key . '_id'];
2199 // we need to append time with date
2200 if ($params[$key] && isset($params[$key . '_time'])) {
2201 $value .= ' ' . $params[$key . '_time'];
2204 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
2205 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 &&
2206 ($value == '' ||
!isset($value))
2212 if (!empty($params['customRecordValues'])) {
2213 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2214 foreach ($params['customRecordValues'] as $recId => $customFields) {
2215 if (is_array($customFields) && !empty($customFields)) {
2216 foreach ($customFields as $customFieldName) {
2217 if ($customFieldName == $key) {
2227 //CRM-13596 - check for contact_sub_type_hidden first
2228 if (array_key_exists('contact_sub_type_hidden', $params)) {
2229 $type = $params['contact_sub_type_hidden'];
2232 $type = $data['contact_type'];
2233 if (!empty($data['contact_sub_type'])) {
2234 $type = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2238 CRM_Core_BAO_CustomField
::formatCustomField($customFieldId,
2248 elseif ($key == 'edit') {
2252 if ($key == 'location') {
2253 foreach ($value as $locationTypeId => $field) {
2254 foreach ($field as $block => $val) {
2255 if ($block == 'address' && array_key_exists('address_name', $val)) {
2256 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2261 if ($key == 'phone' && isset($params['phone_ext'])) {
2262 $data[$key] = $value;
2263 foreach ($value as $cnt => $phoneBlock) {
2264 if ($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']) {
2265 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array
::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2269 elseif (in_array($key,
2280 ($value == '' ||
!isset($value)) &&
2281 ($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 ||
2282 ($key == 'current_employer' && empty($params['current_employer']))) {
2283 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
2284 // to avoid update with empty values
2288 $data[$key] = $value;
2294 if (!isset($data['contact_type'])) {
2295 $data['contact_type'] = 'Individual';
2298 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2299 $privacy = CRM_Core_SelectValues
::privacy();
2300 foreach ($privacy as $key => $value) {
2301 if (array_key_exists($key, $fields)) {
2302 // do not reset values for existing contacts, if fields are added to a profile
2303 if (array_key_exists($key, $params)) {
2304 $data[$key] = $params[$key];
2305 if (empty($params[$key])) {
2309 elseif (!$contactID) {
2315 return array($data, $contactDetails);
2319 * Find the get contact details.
2321 * This function does not respect ACLs for now, which might need to be rectified at some
2322 * stage based on how its used.
2324 * @param string $mail
2325 * Primary email address of the contact.
2326 * @param string $ctype
2329 * @return object|null
2330 * $dao contact details
2332 public static function matchContactOnEmail($mail, $ctype = NULL) {
2333 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2334 $mail = $strtolower(trim($mail));
2336 SELECT civicrm_contact.id as contact_id,
2337 civicrm_contact.hash as hash,
2338 civicrm_contact.contact_type as contact_type,
2339 civicrm_contact.contact_sub_type as contact_sub_type
2340 FROM civicrm_contact
2341 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2343 if (Civi
::settings()->get('uniq_email_per_site')) {
2344 // try to find a match within a site (multisite).
2345 $groups = CRM_Core_BAO_Domain
::getChildGroupIds();
2346 if (!empty($groups)) {
2348 INNER JOIN civicrm_group_contact gc ON
2349 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2354 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2355 $p = array(1 => array($mail, 'String'));
2358 $query .= " AND civicrm_contact.contact_type = %3";
2359 $p[3] = array($ctype, 'String');
2362 $query .= " ORDER BY civicrm_email.is_primary DESC";
2364 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2366 if ($dao->fetch()) {
2373 * Find the contact details associated with an OpenID.
2375 * @param string $openId
2376 * OpenId of the contact.
2377 * @param string $ctype
2380 * @return object|null
2381 * $dao contact details
2383 public static function matchContactOnOpenId($openId, $ctype = NULL) {
2384 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2385 $openId = $strtolower(trim($openId));
2387 SELECT civicrm_contact.id as contact_id,
2388 civicrm_contact.hash as hash,
2389 civicrm_contact.contact_type as contact_type,
2390 civicrm_contact.contact_sub_type as contact_sub_type
2391 FROM civicrm_contact
2392 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2393 WHERE civicrm_openid.openid = %1";
2394 $p = array(1 => array($openId, 'String'));
2397 $query .= " AND civicrm_contact.contact_type = %3";
2398 $p[3] = array($ctype, 'String');
2401 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2403 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2405 if ($dao->fetch()) {
2412 * Get primary email of the contact.
2414 * @param int $contactID
2418 * Email address if present else null
2420 public static function getPrimaryEmail($contactID) {
2421 // fetch the primary email
2423 SELECT civicrm_email.email as email
2424 FROM civicrm_contact
2425 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2426 WHERE civicrm_email.is_primary = 1
2427 AND civicrm_contact.id = %1";
2428 $p = array(1 => array($contactID, 'Integer'));
2429 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2432 if ($dao->fetch()) {
2433 $email = $dao->email
;
2440 * Function to get primary OpenID of the contact.
2442 * @param int $contactID
2446 * >openid OpenID if present else null
2448 public static function getPrimaryOpenId($contactID) {
2449 // fetch the primary OpenID
2451 SELECT civicrm_openid.openid as openid
2452 FROM civicrm_contact
2453 LEFT JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2454 WHERE civicrm_contact.id = %1
2455 AND civicrm_openid.is_primary = 1";
2456 $p = array(1 => array($contactID, 'Integer'));
2457 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2460 if ($dao->fetch()) {
2461 $openId = $dao->openid
;
2468 * Fetch the object and store the values in the values array.
2470 * @param array $params
2471 * Input parameters to find object.
2472 * @param array $values
2473 * Output values of the object.
2475 * @return CRM_Contact_BAO_Contact|null
2476 * The found object or null
2478 public static function getValues(&$params, &$values) {
2479 $contact = new CRM_Contact_BAO_Contact();
2481 $contact->copyValues($params);
2483 if ($contact->find(TRUE)) {
2485 CRM_Core_DAO
::storeValues($contact, $values);
2488 foreach (self
::$_commPrefs as $name) {
2489 if (isset($contact->$name)) {
2490 $privacy[$name] = $contact->$name;
2494 if (!empty($privacy)) {
2495 $values['privacy'] = $privacy;
2498 // communication Prefferance
2499 $preffComm = $comm = array();
2500 $comm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2501 $contact->preferred_communication_method
2503 foreach ($comm as $value) {
2504 $preffComm[$value] = 1;
2506 $temp = array('preferred_communication_method' => $contact->preferred_communication_method
);
2509 'preferred_communication_method' => array(
2510 'newName' => 'preferred_communication_method_display',
2511 'groupName' => 'preferred_communication_method',
2515 // @todo This can be figured out from metadata & we can avoid the uncached query.
2516 CRM_Core_OptionGroup
::lookupValues($temp, $names, FALSE);
2518 $values['preferred_communication_method'] = $preffComm;
2519 $values['preferred_communication_method_display'] = CRM_Utils_Array
::value('preferred_communication_method_display', $temp);
2521 if ($contact->preferred_mail_format
) {
2522 $preferredMailingFormat = CRM_Core_SelectValues
::pmf();
2523 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format
];
2526 // get preferred languages
2527 if (!empty($contact->preferred_language
)) {
2528 $values['preferred_language'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language
);
2531 // Calculating Year difference
2532 if ($contact->birth_date
) {
2533 $birthDate = CRM_Utils_Date
::customFormat($contact->birth_date
, '%Y%m%d');
2534 if ($birthDate < date('Ymd')) {
2535 $age = CRM_Utils_Date
::calculateAge($birthDate);
2536 $values['age']['y'] = CRM_Utils_Array
::value('years', $age);
2537 $values['age']['m'] = CRM_Utils_Array
::value('months', $age);
2541 $contact->contact_id
= $contact->id
;
2549 * Given the component name and returns the count of participation of contact.
2551 * @param string $component
2552 * Input component name.
2553 * @param int $contactId
2555 * @param string $tableName
2556 * Optional tableName if component is custom group.
2559 * total number in database
2561 public static function getCountComponent($component, $contactId, $tableName = NULL) {
2563 switch ($component) {
2565 return CRM_Core_BAO_EntityTag
::getContactTags($contactId, TRUE);
2568 $result = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
2569 CRM_Contact_BAO_Relationship
::CURRENT
,
2578 return CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, "Added", NULL, TRUE);
2581 if (CRM_Core_BAO_Log
::useLoggingReport()) {
2584 return CRM_Core_BAO_Log
::getContactLogCount($contactId);
2587 return CRM_Core_BAO_Note
::getContactNoteCount($contactId);
2589 case 'contribution':
2590 return CRM_Contribute_BAO_Contribution
::contributionCount($contactId);
2593 return CRM_Member_BAO_Membership
::getContactMembershipCount($contactId, TRUE);
2596 return CRM_Event_BAO_Participant
::getContactParticipantCount($contactId);
2599 return CRM_Pledge_BAO_Pledge
::getContactPledgeCount($contactId);
2602 return CRM_Case_BAO_Case
::caseCount($contactId);
2605 return CRM_Grant_BAO_Grant
::getContactGrantCount($contactId);
2609 'contact_id' => $contactId,
2612 'context' => 'activity',
2614 return CRM_Activity_BAO_Activity
::deprecatedGetActivitiesCount($input);
2617 $params = array('contact_id' => $contactId);
2618 return CRM_Mailing_BAO_Mailing
::getContactMailingsCount($params);
2621 $custom = explode('_', $component);
2622 if ($custom['0'] = 'custom') {
2624 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2626 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2627 return CRM_Core_DAO
::singleValueQuery($queryString);
2633 * Process greetings and cache.
2635 * @param object $contact
2636 * Contact object after save.
2637 * @param bool $useDefaults
2638 * Use default greeting values.
2640 public static function processGreetings(&$contact, $useDefaults = FALSE) {
2642 //retrieve default greetings
2643 $defaultGreetings = CRM_Core_PseudoConstant
::greetingDefaults();
2644 $contactDefaults = $defaultGreetings[$contact->contact_type
];
2647 // The contact object has not always required the
2648 // fields that are required to calculate greetings
2649 // so we need to retrieve it again.
2650 if ($contact->_query
!== FALSE) {
2651 $contact->find(TRUE);
2654 // store object values to an array
2655 $contactDetails = array();
2656 CRM_Core_DAO
::storeValues($contact, $contactDetails);
2657 $contactDetails = array(array($contact->id
=> $contactDetails));
2659 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2660 $updateQueryString = array();
2662 //cache email and postal greeting to greeting display
2663 if ($contact->email_greeting_custom
!= 'null' && $contact->email_greeting_custom
) {
2664 $emailGreetingString = $contact->email_greeting_custom
;
2666 elseif ($contact->email_greeting_id
!= 'null' && $contact->email_greeting_id
) {
2667 // the filter value for Individual contact type is set to 1
2669 'contact_type' => $contact->contact_type
,
2670 'greeting_type' => 'email_greeting',
2673 $emailGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2674 $emailGreetingString = $emailGreeting[$contact->email_greeting_id
];
2675 $updateQueryString[] = " email_greeting_custom = NULL ";
2679 reset($contactDefaults['email_greeting']);
2680 $emailGreetingID = key($contactDefaults['email_greeting']);
2681 $emailGreetingString = $contactDefaults['email_greeting'][$emailGreetingID];
2682 $updateQueryString[] = " email_greeting_id = $emailGreetingID ";
2683 $updateQueryString[] = " email_greeting_custom = NULL ";
2685 elseif ($contact->email_greeting_custom
) {
2686 $updateQueryString[] = " email_greeting_display = NULL ";
2690 if ($emailGreetingString) {
2691 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($emailGreetingString,
2694 'CRM_Contact_BAO_Contact'
2696 $emailGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($emailGreetingString));
2697 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2701 if ($contact->postal_greeting_custom
!= 'null' && $contact->postal_greeting_custom
) {
2702 $postalGreetingString = $contact->postal_greeting_custom
;
2704 elseif ($contact->postal_greeting_id
!= 'null' && $contact->postal_greeting_id
) {
2706 'contact_type' => $contact->contact_type
,
2707 'greeting_type' => 'postal_greeting',
2709 $postalGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2710 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id
];
2711 $updateQueryString[] = " postal_greeting_custom = NULL ";
2715 reset($contactDefaults['postal_greeting']);
2716 $postalGreetingID = key($contactDefaults['postal_greeting']);
2717 $postalGreetingString = $contactDefaults['postal_greeting'][$postalGreetingID];
2718 $updateQueryString[] = " postal_greeting_id = $postalGreetingID ";
2719 $updateQueryString[] = " postal_greeting_custom = NULL ";
2721 elseif ($contact->postal_greeting_custom
) {
2722 $updateQueryString[] = " postal_greeting_display = NULL ";
2726 if ($postalGreetingString) {
2727 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($postalGreetingString,
2730 'CRM_Contact_BAO_Contact'
2732 $postalGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($postalGreetingString));
2733 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2737 if ($contact->addressee_custom
!= 'null' && $contact->addressee_custom
) {
2738 $addresseeString = $contact->addressee_custom
;
2740 elseif ($contact->addressee_id
!= 'null' && $contact->addressee_id
) {
2742 'contact_type' => $contact->contact_type
,
2743 'greeting_type' => 'addressee',
2746 $addressee = CRM_Core_PseudoConstant
::greeting($filter);
2747 $addresseeString = $addressee[$contact->addressee_id
];
2748 $updateQueryString[] = " addressee_custom = NULL ";
2752 reset($contactDefaults['addressee']);
2753 $addresseeID = key($contactDefaults['addressee']);
2754 $addresseeString = $contactDefaults['addressee'][$addresseeID];
2755 $updateQueryString[] = " addressee_id = $addresseeID ";
2756 $updateQueryString[] = " addressee_custom = NULL ";
2758 elseif ($contact->addressee_custom
) {
2759 $updateQueryString[] = " addressee_display = NULL ";
2763 if ($addresseeString) {
2764 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($addresseeString,
2767 'CRM_Contact_BAO_Contact'
2769 $addresseeString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($addresseeString));
2770 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2773 if (!empty($updateQueryString)) {
2774 $updateQueryString = implode(',', $updateQueryString);
2775 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2776 CRM_Core_DAO
::executeQuery($queryString);
2781 * Retrieve loc block ids w/ given condition.
2783 * @param int $contactId
2785 * @param array $criteria
2786 * Key => value pair which should be.
2787 * fulfill by return record ids.
2788 * @param string $condOperator
2789 * Operator use for grouping multiple conditions.
2792 * loc block ids which fulfill condition.
2794 public static function getLocBlockIds($contactId, $criteria = array(), $condOperator = 'AND') {
2795 $locBlockIds = array();
2797 return $locBlockIds;
2800 foreach (array('Email', 'OpenID', 'Phone', 'Address', 'IM') as $block) {
2801 $name = strtolower($block);
2802 $className = "CRM_Core_DAO_$block";
2803 $blockDAO = new $className();
2805 // build the condition.
2806 if (is_array($criteria)) {
2807 $fields = $blockDAO->fields();
2808 $conditions = array();
2809 foreach ($criteria as $field => $value) {
2810 if (array_key_exists($field, $fields)) {
2811 $cond = "( $field = $value )";
2812 // value might be zero or null.
2813 if (!$value ||
strtolower($value) == 'null') {
2814 $cond = "( $field = 0 OR $field IS NULL )";
2816 $conditions[] = $cond;
2819 if (!empty($conditions)) {
2820 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2824 $blockDAO->contact_id
= $contactId;
2826 while ($blockDAO->fetch()) {
2827 $locBlockIds[$name][] = $blockDAO->id
;
2832 return $locBlockIds;
2836 * Build context menu items.
2838 * @param int $contactId
2841 * Array of context menu for logged in user.
2843 public static function contextMenu($contactId = NULL) {
2846 'title' => ts('View Contact'),
2848 'ref' => 'view-contact',
2849 'class' => 'no-popup',
2851 'permissions' => array('view all contacts'),
2854 'title' => ts('Edit Contact'),
2856 'ref' => 'edit-contact',
2857 'class' => 'no-popup',
2859 'permissions' => array('edit all contacts'),
2862 'title' => ts('Delete Contact'),
2864 'ref' => 'delete-contact',
2866 'permissions' => array('access deleted contacts', 'delete contacts'),
2868 'contribution' => array(
2869 'title' => ts('Add Contribution'),
2871 'ref' => 'new-contribution',
2872 'key' => 'contribution',
2873 'tab' => 'contribute',
2874 'component' => 'CiviContribute',
2875 'href' => CRM_Utils_System
::url('civicrm/contact/view/contribution',
2876 'reset=1&action=add&context=contribution'
2878 'permissions' => array(
2879 'access CiviContribute',
2880 'edit contributions',
2883 'participant' => array(
2884 'title' => ts('Register for Event'),
2886 'ref' => 'new-participant',
2887 'key' => 'participant',
2888 'tab' => 'participant',
2889 'component' => 'CiviEvent',
2890 'href' => CRM_Utils_System
::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
2891 'permissions' => array(
2893 'edit event participants',
2896 'activity' => array(
2897 'title' => ts('Record Activity'),
2899 'ref' => 'new-activity',
2900 'key' => 'activity',
2901 'permissions' => array('edit all contacts'),
2904 'title' => ts('Add Pledge'),
2906 'ref' => 'new-pledge',
2909 'href' => CRM_Utils_System
::url('civicrm/contact/view/pledge',
2910 'reset=1&action=add&context=pledge'
2912 'component' => 'CiviPledge',
2913 'permissions' => array(
2914 'access CiviPledge',
2918 'membership' => array(
2919 'title' => ts('Add Membership'),
2921 'ref' => 'new-membership',
2922 'key' => 'membership',
2924 'component' => 'CiviMember',
2925 'href' => CRM_Utils_System
::url('civicrm/contact/view/membership',
2926 'reset=1&action=add&context=membership'
2928 'permissions' => array(
2929 'access CiviMember',
2934 'title' => ts('Add Case'),
2936 'ref' => 'new-case',
2939 'component' => 'CiviCase',
2940 'href' => CRM_Utils_System
::url('civicrm/case/add', 'reset=1&action=add&context=case'),
2941 'permissions' => array('add cases'),
2944 'title' => ts('Add Grant'),
2946 'ref' => 'new-grant',
2949 'component' => 'CiviGrant',
2950 'href' => CRM_Utils_System
::url('civicrm/contact/view/grant',
2951 'reset=1&action=add&context=grant'
2953 'permissions' => array('edit grants'),
2956 'title' => ts('Add Relationship'),
2958 'ref' => 'new-relationship',
2961 'href' => CRM_Utils_System
::url('civicrm/contact/view/rel',
2962 'reset=1&action=add'
2964 'permissions' => array('edit all contacts'),
2967 'title' => ts('Add Note'),
2969 'ref' => 'new-note',
2972 'class' => 'medium-popup',
2973 'href' => CRM_Utils_System
::url('civicrm/contact/view/note',
2974 'reset=1&action=add'
2976 'permissions' => array('edit all contacts'),
2979 'title' => ts('Send an Email'),
2981 'ref' => 'new-email',
2983 'permissions' => array('view all contacts'),
2986 'title' => ts('Add to Group'),
2988 'ref' => 'group-add-contact',
2991 'permissions' => array('edit groups'),
2994 'title' => ts('Tag Contact'),
2996 'ref' => 'tag-contact',
2999 'permissions' => array('edit all contacts'),
3003 $menu['otherActions'] = array(
3005 'title' => ts('Print Summary'),
3006 'description' => ts('Printer-friendly view of this page.'),
3008 'ref' => 'crm-contact-print',
3011 'href' => CRM_Utils_System
::url('civicrm/contact/view/print',
3015 'icon' => 'crm-i fa-print',
3018 'title' => ts('vCard'),
3019 'description' => ts('vCard record for this contact.'),
3021 'ref' => 'crm-contact-vcard',
3024 'href' => CRM_Utils_System
::url('civicrm/contact/view/vcard',
3028 'icon' => 'crm-i fa-list-alt',
3032 if (CRM_Core_Permission
::check('access Contact Dashboard')) {
3033 $menu['otherActions']['dashboard'] = array(
3034 'title' => ts('Contact Dashboard'),
3035 'description' => ts('Contact Dashboard'),
3037 'ref' => 'crm-contact-dashboard',
3038 'key' => 'dashboard',
3039 'tab' => 'dashboard',
3040 'class' => 'dashboard',
3041 // NOTE: As an alternative you can also build url on CMS specific way
3042 // as CRM_Core_Config::singleton()->userSystem->getUserRecordUrl($contactId)
3043 'href' => CRM_Utils_System
::url('civicrm/user', "reset=1&id={$contactId}"),
3044 'icon' => 'crm-i fa-tachometer',
3048 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactId);
3050 $menu['otherActions']['user-record'] = array(
3051 'title' => ts('User Record'),
3052 'description' => ts('User Record'),
3054 'ref' => 'crm-contact-user-record',
3055 'key' => 'user-record',
3056 'tab' => 'user-record',
3057 'class' => 'user-record',
3058 'href' => CRM_Core_Config
::singleton()->userSystem
->getUserRecordUrl($contactId),
3059 'icon' => 'crm-i fa-user',
3062 elseif (CRM_Core_Config
::singleton()->userSystem
->checkPermissionAddUser()) {
3063 $menu['otherActions']['user-add'] = array(
3064 'title' => ts('Create User Record'),
3065 'description' => ts('Create User Record'),
3067 'ref' => 'crm-contact-user-add',
3068 'key' => 'user-add',
3069 'tab' => 'user-add',
3070 'class' => 'user-add',
3071 'href' => CRM_Utils_System
::url('civicrm/contact/view/useradd', 'reset=1&action=add&cid=' . $contactId),
3072 'icon' => 'crm-i fa-user-plus',
3076 CRM_Utils_Hook
::summaryActions($menu, $contactId);
3077 //1. check for component is active.
3078 //2. check for user permissions.
3079 //3. check for acls.
3080 //3. edit and view contact are directly accessible to user.
3082 $aclPermissionedTasks = array(
3087 'group-add-contact',
3091 $corePermission = CRM_Core_Permission
::getPermission();
3093 $contextMenu = array();
3094 foreach ($menu as $key => $values) {
3095 if ($key != 'otherActions') {
3097 // user does not have necessary permissions.
3098 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $values)) {
3101 // build directly accessible action menu.
3102 if (in_array($values['ref'], array(
3106 $contextMenu['primaryActions'][$key] = array(
3107 'title' => $values['title'],
3108 'ref' => $values['ref'],
3109 'class' => CRM_Utils_Array
::value('class', $values),
3110 'key' => $values['key'],
3115 // finally get menu item for -more- action widget.
3116 $contextMenu['moreActions'][$values['weight']] = array(
3117 'title' => $values['title'],
3118 'ref' => $values['ref'],
3119 'href' => CRM_Utils_Array
::value('href', $values),
3120 'tab' => CRM_Utils_Array
::value('tab', $values),
3121 'class' => CRM_Utils_Array
::value('class', $values),
3122 'key' => $values['key'],
3126 foreach ($values as $value) {
3127 // user does not have necessary permissions.
3128 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $value)) {
3132 // finally get menu item for -more- action widget.
3133 $contextMenu['otherActions'][$value['weight']] = array(
3134 'title' => $value['title'],
3135 'ref' => $value['ref'],
3136 'href' => CRM_Utils_Array
::value('href', $value),
3137 'tab' => CRM_Utils_Array
::value('tab', $value),
3138 'class' => CRM_Utils_Array
::value('class', $value),
3139 'icon' => CRM_Utils_Array
::value('icon', $value),
3140 'key' => $value['key'],
3146 ksort($contextMenu['moreActions']);
3147 ksort($contextMenu['otherActions']);
3149 return $contextMenu;
3153 * Check if user has permissions to access items in action menu.
3155 * @param array $aclPermissionedTasks
3156 * Array containing ACL related tasks.
3157 * @param string $corePermission
3158 * The permission of the user (edit or view or null).
3159 * @param array $menuOptions
3160 * Array containing params of the menu (title, href, etc).
3163 * TRUE if user has all permissions, FALSE if otherwise.
3165 public static function checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $menuOptions) {
3166 $componentName = CRM_Utils_Array
::value('component', $menuOptions);
3168 // if component action - make sure component is enable.
3169 if ($componentName && !in_array($componentName, CRM_Core_Config
::singleton()->enableComponents
)) {
3173 // make sure user has all required permissions.
3174 $hasAllPermissions = FALSE;
3176 $permissions = CRM_Utils_Array
::value('permissions', $menuOptions);
3177 if (!is_array($permissions) ||
empty($permissions)) {
3178 $hasAllPermissions = TRUE;
3181 // iterate for required permissions in given permissions array.
3182 if (!$hasAllPermissions) {
3183 $hasPermissions = 0;
3184 foreach ($permissions as $permission) {
3185 if (CRM_Core_Permission
::check($permission)) {
3190 if (count($permissions) == $hasPermissions) {
3191 $hasAllPermissions = TRUE;
3194 // if still user does not have required permissions, check acl.
3195 if (!$hasAllPermissions && $menuOptions['ref'] != 'delete-contact') {
3196 if (in_array($menuOptions['ref'], $aclPermissionedTasks) &&
3197 $corePermission == CRM_Core_Permission
::EDIT
3199 $hasAllPermissions = TRUE;
3201 elseif (in_array($menuOptions['ref'], array(
3204 // grant permissions for these tasks.
3205 $hasAllPermissions = TRUE;
3210 return $hasAllPermissions;
3214 * Retrieve display name of contact that address is shared.
3216 * This is based on $masterAddressId or $contactId .
3218 * @param int $masterAddressId
3220 * @param int $contactId
3223 * @return string|null
3224 * the found display name or null.
3226 public static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3227 $masterDisplayName = NULL;
3229 if (!$masterAddressId && !$contactId) {
3230 return $masterDisplayName;
3233 if ($masterAddressId) {
3235 SELECT display_name from civicrm_contact
3236 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3237 WHERE civicrm_address.id = " . $masterAddressId;
3239 elseif ($contactId) {
3241 SELECT display_name from civicrm_contact cc, civicrm_address add1
3242 LEFT JOIN civicrm_address add2 ON ( add1.master_id = add2.id )
3243 WHERE cc.id = add2.contact_id AND add1.contact_id = " . $contactId;
3246 $masterDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
3247 return $masterDisplayName;
3251 * Get the creation/modification times for a contact.
3253 * @param int $contactId
3256 * Dates - ('created_date' => $, 'modified_date' => $)
3258 public static function getTimestamps($contactId) {
3259 $timestamps = CRM_Core_DAO
::executeQuery(
3260 'SELECT created_date, modified_date
3261 FROM civicrm_contact
3264 1 => array($contactId, 'Integer'),
3267 if ($timestamps->fetch()) {
3269 'created_date' => $timestamps->created_date
,
3270 'modified_date' => $timestamps->modified_date
,
3279 * Get a list of triggers for the contact table.
3281 * @see hook_civicrm_triggerInfo
3282 * @see CRM_Core_DAO::triggerRebuild
3283 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3286 * @param null $tableName
3288 public static function triggerInfo(&$info, $tableName = NULL) {
3289 //during upgrade, first check for valid version and then create triggers
3290 //i.e the columns created_date and modified_date are introduced in 4.3.alpha1 so dont create triggers for older version
3291 if (CRM_Core_Config
::isUpgradeMode()) {
3292 $currentVer = CRM_Core_BAO_Domain
::version(TRUE);
3293 //if current version is less than 4.3.alpha1 dont create below triggers
3294 if (version_compare($currentVer, '4.3.alpha1') < 0) {
3299 // Modifications to these records should update the contact timestamps.
3300 \Civi\Core\SqlTrigger\TimestampTriggers
::create('civicrm_contact', 'Contact')
3301 ->setRelations(array(
3302 array('table' => 'civicrm_address', 'column' => 'contact_id'),
3303 array('table' => 'civicrm_email', 'column' => 'contact_id'),
3304 array('table' => 'civicrm_im', 'column' => 'contact_id'),
3305 array('table' => 'civicrm_phone', 'column' => 'contact_id'),
3306 array('table' => 'civicrm_website', 'column' => 'contact_id'),
3309 ->alterTriggerInfo($info, $tableName);
3311 // Update phone table to populate phone_numeric field
3312 if (!$tableName ||
$tableName == 'civicrm_phone') {
3313 // Define stored sql function needed for phones
3314 $sqlTriggers = Civi
::service('sql_triggers');
3315 $sqlTriggers->enqueueQuery(self
::DROP_STRIP_FUNCTION_43
);
3316 $sqlTriggers->enqueueQuery(self
::CREATE_STRIP_FUNCTION_43
);
3318 'table' => array('civicrm_phone'),
3320 'event' => array('INSERT', 'UPDATE'),
3321 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3327 * Check if contact is being used in civicrm_domain based on $contactId.
3329 * @param int $contactId
3333 * true if present else false.
3335 public static function checkDomainContact($contactId) {
3339 $domainId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3350 * Get options for a given contact field.
3352 * @see CRM_Core_DAO::buildOptions
3354 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3355 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3357 * @param string $fieldName
3358 * @param string $context
3359 * @see CRM_Core_DAO::buildOptionsContext
3360 * @param array $props
3361 * whatever is known about this dao object.
3363 * @return array|bool
3365 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3367 // Special logic for fields whose options depend on context or properties
3368 switch ($fieldName) {
3369 case 'contact_sub_type':
3370 if (!empty($props['contact_type'])) {
3371 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3375 case 'contact_type':
3376 if ($context == 'search') {
3377 // CRM-15495 - EntityRef filters and basic search forms expect this format
3378 // FIXME: Search builder does not
3379 return CRM_Contact_BAO_ContactType
::getSelectElements();
3383 // The contact api supports some related entities so we'll honor that by fetching their options
3386 return CRM_Contact_BAO_GroupContact
::buildOptions('group_id', $context, $props);
3390 $props['entity_table'] = 'civicrm_contact';
3391 return CRM_Core_BAO_EntityTag
::buildOptions('tag_id', $context, $props);
3393 case 'state_province_id':
3394 case 'state_province':
3395 case 'state_province_name':
3400 case 'worldregion_id':
3401 return CRM_Core_BAO_Address
::buildOptions($fieldName, 'get', $props);
3404 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
3408 * Delete a contact-related object that has an 'is_primary' field.
3410 * Ensures that is_primary gets assigned to another object if available
3411 * Also calls pre/post hooks
3413 * @param string $type
3417 public static function deleteObjectWithPrimary($type, $id) {
3418 if (!$id ||
!is_numeric($id)) {
3421 $daoName = "CRM_Core_DAO_$type";
3422 $obj = new $daoName();
3425 if ($obj->fetch()) {
3426 CRM_Utils_Hook
::pre('delete', $type, $id, CRM_Core_DAO
::$_nullArray);
3427 $contactId = $obj->contact_id
;
3433 // is_primary is only relavent if this field belongs to a contact
3435 $dao = new $daoName();
3436 $dao->contact_id
= $contactId;
3437 $dao->is_primary
= 1;
3438 // Pick another record to be primary (if one isn't already)
3439 if (!$dao->find(TRUE)) {
3440 $dao->is_primary
= 0;
3442 if ($dao->fetch()) {
3443 $dao->is_primary
= 1;
3449 CRM_Utils_Hook
::post('delete', $type, $id, $obj);
3457 public function addSelectWhereClause() {
3458 // We always return an array with these keys, even if they are empty,
3459 // because this tells the query builder that we have considered these fields for acls
3461 'id' => (array) CRM_Contact_BAO_Contact_Permission
::cacheSubquery(),
3462 'is_deleted' => CRM_Core_Permission
::check('access deleted contacts') ?
array() : array('!= 1'),
3464 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3469 * Get any existing duplicate contacts based on the input parameters.
3471 * @param array $input
3472 * Input parameters to be matched.
3473 * @param string $contactType
3474 * @param string $rule
3477 * @param $excludedContactIDs
3478 * An array of ids not to be included in the results.
3479 * @param bool $checkPermissions
3480 * @param int $ruleGroupID
3481 * ID of the rule group to be used if an override is desirable.
3485 public static function getDuplicateContacts($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = array(), $checkPermissions = TRUE, $ruleGroupID = NULL) {
3486 $dedupeParams = CRM_Dedupe_Finder
::formatParams($input, $contactType);
3487 $dedupeParams['check_permission'] = $checkPermissions;
3488 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $contactType, $rule, $excludedContactIDs, $ruleGroupID);
3493 * Get the first duplicate contacts based on the input parameters.
3495 * @param array $input
3496 * Input parameters to be matched.
3497 * @param string $contactType
3498 * @param string $rule
3501 * @param $excludedContactIDs
3502 * An array of ids not to be included in the results.
3503 * @param bool $checkPermissions
3504 * @param int $ruleGroupID
3505 * ID of the rule group to be used if an override is desirable.
3509 public static function getFirstDuplicateContact($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = array(), $checkPermissions = TRUE, $ruleGroupID = NULL) {
3510 $ids = self
::getDuplicateContacts($input, $contactType, $rule, $excludedContactIDs, $checkPermissions, $ruleGroupID);
3518 * Check if a field is associated with an entity that has a location type.
3520 * (ie. is an address, phone, email etc field).
3522 * @param string $fieldTitle
3523 * Title of the field (not the name - create a new function for that if required).
3527 public static function isFieldHasLocationType($fieldTitle) {
3528 foreach (CRM_Contact_BAO_Contact
::importableFields() as $key => $field) {
3529 if ($field['title'] === $fieldTitle) {
3530 return CRM_Utils_Array
::value('hasLocationType', $field);