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 // Fix for preferred communication method.
155 $prefComm = CRM_Utils_Array
::value('preferred_communication_method', $params, '');
156 if ($prefComm && is_array($prefComm)) {
157 unset($params['preferred_communication_method']);
159 CRM_Utils_Array
::formatArrayKeys($prefComm);
160 $prefComm = CRM_Utils_Array
::implodePadded($prefComm);
163 $contact->preferred_communication_method
= $prefComm;
165 $allNull = $contact->copyValues($params);
167 $contact->id
= CRM_Utils_Array
::value('contact_id', $params);
169 if ($contact->contact_type
== 'Individual') {
172 // Format individual fields.
173 CRM_Contact_BAO_Individual
::format($params, $contact);
175 elseif ($contact->contact_type
== 'Household') {
176 if (isset($params['household_name'])) {
178 $contact->display_name
= $contact->sort_name
= CRM_Utils_Array
::value('household_name', $params, '');
181 elseif ($contact->contact_type
== 'Organization') {
182 if (isset($params['organization_name'])) {
184 $contact->display_name
= $contact->sort_name
= CRM_Utils_Array
::value('organization_name', $params, '');
188 $privacy = CRM_Utils_Array
::value('privacy', $params);
190 is_array($privacy) &&
194 foreach (self
::$_commPrefs as $name) {
195 $contact->$name = CRM_Utils_Array
::value($name, $privacy, FALSE);
199 // Since hash was required, make sure we have a 0 value for it (CRM-1063).
200 // @todo - does this mean we can remove this block?
201 // Fixed in 1.5 by making hash optional, only do this in create mode, not update.
202 if ((!array_key_exists('hash', $contact) ||
!$contact->hash
) && !$contact->id
) {
204 $contact->hash
= md5(uniqid(rand(), TRUE));
207 // Even if we don't need $employerId, it's important to call getFieldValue() before
208 // the contact is saved because we want the existing value to be cached.
209 // createCurrentEmployerRelationship() needs the old value not the updated one. CRM-10788
210 $employerId = empty($contact->id
) ?
NULL : CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contact->id
, 'employer_id');
215 CRM_Core_BAO_Log
::register($contact->id
,
221 if ($contact->contact_type
== 'Individual' && (isset($params['current_employer']) ||
isset($params['employer_id']))) {
222 // Create current employer.
223 $newEmployer = !empty($params['employer_id']) ?
$params['employer_id'] : CRM_Utils_Array
::value('current_employer', $params);
226 if (empty($params['contact_id'])) {
230 CRM_Contact_BAO_Contact_Utils
::createCurrentEmployerRelationship($contact->id
, $newEmployer, $employerId, $newContact);
234 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($contact->id
, $employerId);
239 // Update cached employer name.
240 if ($contact->contact_type
== 'Organization') {
241 CRM_Contact_BAO_Contact_Utils
::updateCurrentEmployer($contact->id
);
250 * takes an associative array and creates a contact object and all the associated
251 * derived objects (i.e. individual, location, email, phone etc)
253 * This function is invoked from within the web form layer and also from the api layer
255 * @param array $params
256 * (reference ) an assoc array of name/value pairs.
257 * @param bool $fixAddress
258 * If we need to fix address.
259 * @param bool $invokeHooks
260 * If we need to invoke hooks.
262 * @param bool $skipDelete
263 * Unclear parameter, passed to website create
265 * @todo explain this parameter
268 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
269 * Created or updated contribution object. We are deprecating returning an error in
270 * favour of exceptions
272 public static function &create(&$params, $fixAddress = TRUE, $invokeHooks = TRUE, $skipDelete = FALSE) {
274 if (empty($params['contact_type']) && empty($params['contact_id'])) {
280 if (!empty($params['contact_id'])) {
281 CRM_Utils_Hook
::pre('edit', $params['contact_type'], $params['contact_id'], $params);
284 CRM_Utils_Hook
::pre('create', $params['contact_type'], NULL, $params);
289 $config = CRM_Core_Config
::singleton();
291 // CRM-6942: set preferred language to the current language if it’s unset (and we’re creating a contact).
292 if (empty($params['contact_id'])) {
293 // A case could be made for checking isset rather than empty but this is more consistent with previous behaviour.
294 if (empty($params['preferred_language']) && ($language = CRM_Core_I18n
::getContactDefaultLanguage()) != FALSE) {
295 $params['preferred_language'] = $language;
298 // CRM-9739: set greeting & addressee if unset and we’re creating a contact.
299 foreach (self
::$_greetingTypes as $greeting) {
300 if (empty($params[$greeting . '_id'])) {
301 if ($defaultGreetingTypeId
302 = CRM_Contact_BAO_Contact_Utils
::defaultGreeting($params['contact_type'], $greeting)
304 $params[$greeting . '_id'] = $defaultGreetingTypeId;
310 $transaction = new CRM_Core_Transaction();
312 $contact = self
::add($params);
314 // Not dying here is stupid, since we get into weird situation and into a bug that
315 // is impossible to figure out for the user or for us
317 CRM_Core_Error
::fatal();
320 $params['contact_id'] = $contact->id
;
322 if (Civi
::settings()->get('is_enabled')) {
323 // Enabling multisite causes the contact to be added to the domain group.
324 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
325 if (!empty($domainGroupID)) {
326 if (!empty($params['group']) && is_array($params['group'])) {
327 $params['group'][$domainGroupID] = 1;
330 $params['group'] = array($domainGroupID => 1);
335 if (array_key_exists('group', $params)) {
336 $contactIds = array($params['contact_id']);
337 foreach ($params['group'] as $groupId => $flag) {
339 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
341 elseif ($flag == -1) {
342 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $groupId);
347 // Add location Block data.
348 $blocks = CRM_Core_BAO_Location
::create($params, $fixAddress);
349 foreach ($blocks as $name => $value) {
350 $contact->$name = $value;
352 if (!empty($params['updateBlankLocInfo'])) {
357 CRM_Core_BAO_Website
::create($params['website'], $contact->id
, $skipDelete);
359 //get userID from session
360 $session = CRM_Core_Session
::singleton();
361 $userID = $session->get('userID');
363 if (!empty($params['note'])) {
364 if (is_array($params['note'])) {
365 foreach ($params['note'] as $note) {
366 $contactId = $contact->id
;
367 if (isset($note['contact_id'])) {
368 $contactId = $note['contact_id'];
370 //if logged in user, overwrite contactId
372 $contactId = $userID;
376 'entity_id' => $contact->id
,
377 'entity_table' => 'civicrm_contact',
378 'note' => $note['note'],
379 'subject' => CRM_Utils_Array
::value('subject', $note),
380 'contact_id' => $contactId,
382 CRM_Core_BAO_Note
::add($noteParams, CRM_Core_DAO
::$_nullArray);
386 $contactId = $contact->id
;
387 if (isset($note['contact_id'])) {
388 $contactId = $note['contact_id'];
390 //if logged in user, overwrite contactId
392 $contactId = $userID;
396 'entity_id' => $contact->id
,
397 'entity_table' => 'civicrm_contact',
398 'note' => $params['note'],
399 'subject' => CRM_Utils_Array
::value('subject', $params),
400 'contact_id' => $contactId,
402 CRM_Core_BAO_Note
::add($noteParams, CRM_Core_DAO
::$_nullArray);
406 // update the UF user_unique_id if that has changed
407 CRM_Core_BAO_UFMatch
::updateUFName($contact->id
);
409 if (!empty($params['custom']) &&
410 is_array($params['custom'])
412 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contact', $contact->id
);
415 // make a civicrm_subscription_history entry only on contact create (CRM-777)
416 if (empty($params['contact_id'])) {
417 $subscriptionParams = array(
418 'contact_id' => $contact->id
,
422 CRM_Contact_BAO_SubscriptionHistory
::create($subscriptionParams);
425 $transaction->commit();
427 // CRM-6367: fetch the right label for contact type’s display
428 $contact->contact_type_display
= CRM_Core_DAO
::getFieldValue(
429 'CRM_Contact_DAO_ContactType',
430 $contact->contact_type
,
435 if (!$config->doNotResetCache
) {
436 // Note: doNotResetCache flag is currently set by import contact process and merging,
437 // since resetting and
438 // rebuilding cache could be expensive (for many contacts). We might come out with better
439 // approach in future.
440 CRM_Contact_BAO_Contact_Utils
::clearContactCaches($contact->id
);
445 CRM_Utils_Hook
::post('edit', $params['contact_type'], $contact->id
, $contact);
448 CRM_Utils_Hook
::post('create', $params['contact_type'], $contact->id
, $contact);
452 // process greetings CRM-4575, cache greetings
453 self
::processGreetings($contact);
459 * Get the display name and image of a contact.
464 * @param bool $includeTypeInReturnParameters
465 * Should type be part of the returned array?
468 * the displayName and contactImage for this contact
470 public static function getDisplayAndImage($id, $includeTypeInReturnParameters = FALSE) {
471 //CRM-14276 added the * on the civicrm_contact table so that we have all the contact info available
473 SELECT civicrm_contact.*,
474 civicrm_email.email as email
476 LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
477 AND civicrm_email.is_primary = 1
478 WHERE civicrm_contact.id = " . CRM_Utils_Type
::escape($id, 'Integer');
479 $dao = new CRM_Core_DAO();
482 $image = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
483 $dao->contact_sub_type
: $dao->contact_type
, FALSE, $id
485 $imageUrl = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
486 $dao->contact_sub_type
: $dao->contact_type
, TRUE, $id
489 // use email if display_name is empty
490 if (empty($dao->display_name
)) {
491 $displayName = $dao->email
;
494 $displayName = $dao->display_name
;
497 CRM_Utils_Hook
::alterDisplayName($displayName, $id, $dao);
499 return $includeTypeInReturnParameters ?
array(
503 $dao->contact_sub_type
,
505 ) : array($displayName, $image, $imageUrl);
511 * Add billing fields to the params if appropriate.
513 * If we have ANY name fields then we want to ignore all the billing name fields. However, if we
514 * don't then we should set the name fields to the filling fields AND add the preserveDBName
515 * parameter (which will tell the BAO only to set those fields if none already exist.
517 * We specifically don't want to set first name from billing and last name form an on-page field. Mixing &
518 * matching is best done by hipsters.
520 * @param array $params
522 public static function addBillingNameFieldsIfOtherwiseNotSet(&$params) {
523 $nameFields = array('first_name', 'middle_name', 'last_name', 'nick_name', 'prefix_id', 'suffix_id');
524 foreach ($nameFields as $field) {
525 if (!empty($params[$field])) {
529 // There are only 3 - we can iterate through them twice :-)
530 foreach ($nameFields as $field) {
531 if (!empty($params['billing_' . $field])) {
532 $params[$field] = $params['billing_' . $field];
534 $params['preserveDBName'] = TRUE;
540 * Create last viewed link to recently updated contact.
542 * @param array $crudLinkSpec
543 * - action: int, CRM_Core_Action::UPDATE or CRM_Core_Action::VIEW [default: VIEW]
544 * - entity_table: string, eg "civicrm_contact"
548 * NULL if unavailable, or
549 * [path: string, query: string, title: string]
550 * @see CRM_Utils_System::createDefaultCrudLink
552 public function createDefaultCrudLink($crudLinkSpec) {
553 switch ($crudLinkSpec['action']) {
554 case CRM_Core_Action
::VIEW
:
556 'title' => $this->display_name
,
557 'path' => 'civicrm/contact/view',
565 case CRM_Core_Action
::UPDATE
:
567 'title' => $this->display_name
,
568 'path' => 'civicrm/contact/add',
571 'action' => 'update',
581 * Get the values for pseudoconstants for name->value and reverse.
583 * @param array $defaults
584 * (reference) the default values, some of which need to be resolved.
585 * @param bool $reverse
586 * True if we want to resolve the values in the reverse direction (value -> name).
588 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
589 // Hack for birth_date.
590 if (!empty($defaults['birth_date'])) {
591 if (is_array($defaults['birth_date'])) {
592 $defaults['birth_date'] = CRM_Utils_Date
::format($defaults['birth_date'], '-');
596 CRM_Utils_Array
::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id'), $reverse);
597 CRM_Utils_Array
::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'suffix_id'), $reverse);
598 CRM_Utils_Array
::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'), $reverse);
599 CRM_Utils_Array
::lookupValue($defaults, 'communication_style', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'communication_style_id'), $reverse);
601 //lookup value of email/postal greeting, addressee, CRM-4575
602 foreach (self
::$_greetingTypes as $greeting) {
603 $filterCondition = array(
604 'contact_type' => CRM_Utils_Array
::value('contact_type', $defaults),
605 'greeting_type' => $greeting,
607 CRM_Utils_Array
::lookupValue($defaults, $greeting,
608 CRM_Core_PseudoConstant
::greeting($filterCondition), $reverse
612 $blocks = array('address', 'im', 'phone');
613 foreach ($blocks as $name) {
614 if (!array_key_exists($name, $defaults) ||
!is_array($defaults[$name])) {
617 foreach ($defaults[$name] as $count => & $values) {
619 //get location type id.
620 CRM_Utils_Array
::lookupValue($values, 'location_type', CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id'), $reverse);
622 if ($name == 'address') {
623 // FIXME: lookupValue doesn't work for vcard_name
624 if (!empty($values['location_type_id'])) {
625 $vcardNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array('labelColumn' => 'vcard_name'));
626 $values['vcard_name'] = $vcardNames[$values['location_type_id']];
629 if (!CRM_Utils_Array
::lookupValue($values,
631 CRM_Core_PseudoConstant
::country(),
636 CRM_Utils_Array
::lookupValue($values,
638 CRM_Core_PseudoConstant
::countryIsoCode(),
644 // if we find a country id above, we need to restrict it to that country
645 // rather than the list of all countries
647 if (!empty($values['country_id'])) {
648 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($values['country_id']);
651 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvince();
653 if (!CRM_Utils_Array
::lookupValue($values,
661 if (!empty($values['country_id'])) {
662 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($values['country_id'], 'abbreviation');
665 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviation();
667 CRM_Utils_Array
::lookupValue($values,
674 if (!empty($values['state_province_id'])) {
675 $countyList = CRM_Core_PseudoConstant
::countyForState($values['state_province_id']);
678 $countyList = CRM_Core_PseudoConstant
::county();
680 CRM_Utils_Array
::lookupValue($values,
688 CRM_Utils_Array
::lookupValue($values,
690 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id'),
695 if ($name == 'phone') {
696 CRM_Utils_Array
::lookupValue($values,
698 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id'),
703 // Kill the reference.
710 * Fetch object based on array of properties.
712 * @param array $params
713 * (reference ) an assoc array of name/value pairs.
714 * @param array $defaults
715 * (reference ) an assoc array to hold the name / value pairs.
716 * in a hierarchical manner
717 * @param bool $microformat
718 * For location in microformat.
720 * @return CRM_Contact_BAO_Contact
722 public static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
723 if (array_key_exists('contact_id', $params)) {
724 $params['id'] = $params['contact_id'];
726 elseif (array_key_exists('id', $params)) {
727 $params['contact_id'] = $params['id'];
730 $contact = self
::getValues($params, $defaults);
732 unset($params['id']);
734 //get the block information for this contact
735 $entityBlock = array('contact_id' => $params['contact_id']);
736 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock, $microformat);
737 $defaults = array_merge($defaults, $blocks);
738 foreach ($blocks as $block => $value) {
739 $contact->$block = $value;
742 if (!isset($params['noNotes'])) {
743 $contact->notes
= CRM_Core_BAO_Note
::getValues($params, $defaults);
746 if (!isset($params['noRelationships'])) {
747 $contact->relationship
= CRM_Contact_BAO_Relationship
::getValues($params, $defaults);
750 if (!isset($params['noGroups'])) {
751 $contact->groupContact
= CRM_Contact_BAO_GroupContact
::getValues($params, $defaults);
754 if (!isset($params['noWebsite'])) {
755 $contact->website
= CRM_Core_BAO_Website
::getValues($params, $defaults);
762 * Get the display name of a contact.
767 * @return null|string
768 * display name of the contact if found
770 public static function displayName($id) {
773 $displayName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
780 * Delete a contact and all its associated records.
783 * Id of the contact to delete.
784 * @param bool $restore
785 * Whether to actually restore, not delete.
786 * @param bool $skipUndelete
787 * Whether to force contact delete or not.
788 * @param bool $checkPermissions
791 * Was contact deleted?
793 public static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE, $checkPermissions = TRUE) {
798 // If trash is disabled in system settings then we always skip
799 if (!Civi
::settings()->get('contact_undelete')) {
800 $skipUndelete = TRUE;
803 // make sure we have edit permission for this contact
805 if ($checkPermissions && (($skipUndelete && !CRM_Core_Permission
::check('delete contacts')) ||
806 ($restore && !CRM_Core_Permission
::check('access deleted contacts')))
812 // Restrict contact to be delete if contact has financial trxns
814 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent(array($id), $error)) {
818 // make sure this contact_id does not have any membership types
819 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
822 'member_of_contact_id'
824 if ($membershipTypeID) {
828 $contact = new CRM_Contact_DAO_Contact();
830 if (!$contact->find(TRUE)) {
834 $contactType = $contact->contact_type
;
835 // currently we only clear employer cache.
836 // we are now deleting inherited membership if any.
837 if ($contact->contact_type
== 'Organization') {
838 $action = $restore ? CRM_Core_Action
::ENABLE
: CRM_Core_Action
::DISABLE
;
839 $relationshipDtls = CRM_Contact_BAO_Relationship
::getRelationship($id);
840 if (!empty($relationshipDtls)) {
841 foreach ($relationshipDtls as $rId => $details) {
842 CRM_Contact_BAO_Relationship
::disableEnableRelationship($rId, $action);
845 CRM_Contact_BAO_Contact_Utils
::clearAllEmployee($id);
849 return self
::contactTrashRestore($contact, TRUE);
852 // start a new transaction
853 $transaction = new CRM_Core_Transaction();
856 CRM_Utils_Hook
::pre('delete', $contactType, $id, CRM_Core_DAO
::$_nullArray);
858 //delete billing address if exists.
859 CRM_Contribute_BAO_Contribution
::deleteAddress(NULL, $id);
861 // delete the log entries since we dont have triggers enabled as yet
862 $logDAO = new CRM_Core_DAO_Log();
863 $logDAO->entity_table
= 'civicrm_contact';
864 $logDAO->entity_id
= $id;
867 // delete contact participants CRM-12155
868 CRM_Event_BAO_Participant
::deleteContactParticipant($id);
870 // delete contact contributions CRM-12155
871 CRM_Contribute_BAO_Contribution
::deleteContactContribution($id);
873 // do activity cleanup, CRM-5604
874 CRM_Activity_BAO_Activity
::cleanupActivity($id);
876 // delete all notes related to contact
877 CRM_Core_BAO_Note
::cleanContactNotes($id);
879 // delete cases related to contact
880 $contactCases = CRM_Case_BAO_Case
::retrieveCaseIdsByContactId($id);
881 if (!empty($contactCases)) {
882 foreach ($contactCases as $caseId) {
883 //check if case is associate with other contact or not.
884 $caseContactId = CRM_Case_BAO_Case
::getCaseClients($caseId);
885 if (count($caseContactId) <= 1) {
886 CRM_Case_BAO_Case
::deleteCase($caseId);
894 self
::contactTrashRestore($contact);
897 //delete the contact id from recently view
898 CRM_Utils_Recent
::delContact($id);
899 self
::updateContactCache($id, empty($restore));
901 // delete any dupe cache entry
902 CRM_Core_BAO_PrevNextCache
::deleteItem($id);
904 $transaction->commit();
907 CRM_Utils_Hook
::post('delete', $contactType, $contact->id
, $contact);
910 // also reset the DB_DO global array so we can reuse the memory
911 // http://issues.civicrm.org/jira/browse/CRM-4387
912 CRM_Core_DAO
::freeResult();
918 * Action to update any caches relating to a recently update contact.
920 * I was going to call this from delete as well as from create to ensure the delete is being
921 * done whenever a contact is set to is_deleted=1 BUT I found create is already over-aggressive in
922 * that regard so adding it to delete seems to be enough to remove it from CRM_Contact_BAO_Contact_Permission
923 * where the call involved a subquery that was locking the table.
925 * @param int $contactID
926 * @param bool $isTrashed
928 public static function updateContactCache($contactID, $isTrashed = FALSE) {
931 CRM_Contact_BAO_GroupContactCache
::removeContact($contactID);
932 // This has been moved to here from CRM_Contact_BAO_Contact_Permission as that was causing
933 // a table-locking query. It still seems a bit inadequate as it assumes the acl users can't see deleted
934 // but this should not cause any change as long as contacts are not being trashed outside the
935 // main functions for that.
936 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_acl_contact_cache WHERE contact_id = %1', array(1 => array($contactID, 'Integer')));
939 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
944 * Delete the image of a contact.
950 * Was contact image deleted?
952 public static function deleteContactImage($id) {
957 UPDATE civicrm_contact
960 CRM_Core_DAO
::executeQuery($query);
965 * Return proportional height and width of the image.
967 * @param int $imageWidth
970 * @param int $imageHeight
974 * Thumb dimension of image
976 public static function getThumbSize($imageWidth, $imageHeight) {
978 if ($imageWidth && $imageHeight) {
979 $imageRatio = $imageWidth / $imageHeight;
984 if ($imageRatio > 1) {
985 $imageThumbWidth = $thumbWidth;
986 $imageThumbHeight = round($thumbWidth / $imageRatio);
989 $imageThumbHeight = $thumbWidth;
990 $imageThumbWidth = round($thumbWidth * $imageRatio);
993 return array($imageThumbWidth, $imageThumbHeight);
997 * Validate type of contact image.
999 * @param array $params
1000 * @param string $imageIndex
1001 * Index of image field.
1002 * @param string $statusMsg
1003 * Status message to be set after operation.
1004 * @param string $opType
1005 * Type of operation like fatal, bounce etc.
1008 * true if valid image extension
1010 public static function processImageParams(
1012 $imageIndex = 'image_URL',
1026 if (in_array($params[$imageIndex]['type'], $mimeType)) {
1027 $photo = basename($params[$imageIndex]['name']);
1028 $params[$imageIndex] = CRM_Utils_System
::url('civicrm/contact/imagefile', 'photo=' . $photo, TRUE, NULL, TRUE, TRUE);
1032 unset($params[$imageIndex]);
1034 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
1036 if ($opType == 'status') {
1037 CRM_Core_Session
::setStatus($statusMsg, 'Sorry', 'error');
1039 // FIXME: additional support for fatal, bounce etc could be added.
1045 * Extract contact id from url for deleting contact image.
1047 public static function processImage() {
1049 $action = CRM_Utils_Request
::retrieve('action', 'String');
1050 $cid = CRM_Utils_Request
::retrieve('cid', 'Positive');
1051 // retrieve contact id in case of Profile context
1052 $id = CRM_Utils_Request
::retrieve('id', 'Positive');
1053 $cid = $cid ?
$cid : $id;
1054 if ($action & CRM_Core_Action
::DELETE
) {
1055 if (CRM_Utils_Request
::retrieve('confirmed', 'Boolean')) {
1056 CRM_Contact_BAO_Contact
::deleteContactImage($cid);
1057 CRM_Core_Session
::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
1058 $session = CRM_Core_Session
::singleton();
1059 $toUrl = $session->popUserContext();
1060 CRM_Utils_System
::redirect($toUrl);
1066 * Function to set is_delete true or restore deleted contact.
1068 * @param CRM_Contact_DAO_Contact $contact
1069 * Contact DAO object.
1070 * @param bool $restore
1071 * True to set the is_delete = 1 else false to restore deleted contact,
1072 * i.e. is_delete = 0
1076 public static function contactTrashRestore($contact, $restore = FALSE) {
1077 $updateParams = array(
1078 'id' => $contact->id
,
1079 'is_deleted' => $restore ?
0 : 1,
1082 CRM_Utils_Hook
::pre('update', $contact->contact_type
, $contact->id
, $updateParams);
1084 $params = array(1 => array($contact->id
, 'Integer'));
1086 $query = "DELETE FROM civicrm_uf_match WHERE contact_id = %1";
1087 CRM_Core_DAO
::executeQuery($query, $params);
1090 $contact->copyValues($updateParams);
1093 CRM_Utils_Hook
::post('update', $contact->contact_type
, $contact->id
, $contact);
1099 * Get contact type for a contact.
1102 * Id of the contact whose contact type is needed.
1105 * contact_type if $id found else null ""
1107 public static function getContactType($id) {
1108 return CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1112 * Get contact sub type for a contact.
1115 * Id of the contact whose contact sub type is needed.
1117 * @param string $implodeDelimiter
1120 * contact_sub_type if $id found else null ""
1122 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1123 $subtype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1125 return $implodeDelimiter ?
NULL : array();
1128 $subtype = CRM_Utils_Array
::explodePadded($subtype);
1130 if ($implodeDelimiter) {
1131 $subtype = implode($implodeDelimiter, $subtype);
1137 * Get pair of contact-type and sub-type for a contact.
1140 * Id of the contact whose contact sub/contact type is needed.
1144 public static function getContactTypes($id) {
1145 $params = array('id' => $id);
1147 $contact = CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact',
1150 array('contact_type', 'contact_sub_type')
1154 $contactTypes = array();
1155 if ($contact->contact_sub_type
) {
1156 $contactTypes = CRM_Utils_Array
::explodePadded($contact->contact_sub_type
);
1158 array_unshift($contactTypes, $contact->contact_type
);
1160 return $contactTypes;
1163 CRM_Core_Error
::fatal();
1168 * Combine all the importable fields from the lower levels object.
1170 * The ordering is important, since currently we do not have a weight
1171 * scheme. Adding weight is super important
1173 * @param int|string $contactType contact Type
1174 * @param bool $status
1175 * Status is used to manipulate first title.
1176 * @param bool $showAll
1177 * If true returns all fields (includes disabled fields).
1178 * @param bool $isProfile
1179 * If its profile mode.
1180 * @param bool $checkPermission
1181 * If false, do not include permissioning clause (for custom data).
1183 * @param bool $withMultiCustomFields
1186 * array of importable Fields
1188 public static function importableFields(
1189 $contactType = 'Individual',
1193 $checkPermission = TRUE,
1194 $withMultiCustomFields = FALSE
1196 if (empty($contactType)) {
1197 $contactType = 'All';
1200 $cacheKeyString = "importableFields $contactType";
1201 $cacheKeyString .= $status ?
'_1' : '_0';
1202 $cacheKeyString .= $showAll ?
'_1' : '_0';
1203 $cacheKeyString .= $isProfile ?
'_1' : '_0';
1204 $cacheKeyString .= $checkPermission ?
'_1' : '_0';
1206 $fields = CRM_Utils_Array
::value($cacheKeyString, self
::$_importableFields);
1209 // check if we can retrieve from database cache
1210 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1214 $fields = CRM_Contact_DAO_Contact
::import();
1216 // get the fields thar are meant for contact types
1217 if (in_array($contactType, array(
1223 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1226 $locationFields = array_merge(CRM_Core_DAO_Address
::import(),
1227 CRM_Core_DAO_Phone
::import(),
1228 CRM_Core_DAO_Email
::import(),
1229 CRM_Core_DAO_IM
::import(TRUE),
1230 CRM_Core_DAO_OpenID
::import()
1233 $locationFields = array_merge($locationFields,
1234 CRM_Core_BAO_CustomField
::getFieldsForImport('Address',
1242 foreach ($locationFields as $key => $field) {
1243 $locationFields[$key]['hasLocationType'] = TRUE;
1246 $fields = array_merge($fields, $locationFields);
1248 $fields = array_merge($fields, CRM_Contact_DAO_Contact
::import());
1249 $fields = array_merge($fields, CRM_Core_DAO_Note
::import());
1252 $fields = array_merge($fields, CRM_Core_DAO_Website
::import());
1253 $fields['url']['hasWebsiteType'] = TRUE;
1255 if ($contactType != 'All') {
1256 $fields = array_merge($fields,
1257 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType,
1262 $withMultiCustomFields
1265 //unset the fields, which are not related to their
1267 $commonValues = array(
1268 'Individual' => array(
1272 'organization_name',
1274 'Household' => array(
1284 'organization_name',
1292 'Organization' => array(
1307 foreach ($commonValues[$contactType] as $value) {
1308 unset($fields[$value]);
1312 foreach (array('Individual', 'Household', 'Organization') as $type) {
1313 $fields = array_merge($fields,
1314 CRM_Core_BAO_CustomField
::getFieldsForImport($type,
1319 $withMultiCustomFields
1326 $fields = array_merge($fields, array(
1328 'title' => ts('Group(s)'),
1332 'title' => ts('Tag(s)'),
1336 'title' => ts('Note(s)'),
1339 'communication_style_id' => array(
1340 'title' => ts('Communication Style'),
1341 'name' => 'communication_style_id',
1346 //Sorting fields in alphabetical order(CRM-1507)
1347 $fields = CRM_Utils_Array
::crmArraySortByField($fields, 'title');
1349 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1352 self
::$_importableFields[$cacheKeyString] = $fields;
1356 $fields = array_merge(array('do_not_import' => array('title' => ts('- do not import -'))),
1357 self
::$_importableFields[$cacheKeyString]
1361 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1362 self
::$_importableFields[$cacheKeyString]
1370 * Combine all the exportable fields from the lower levels object.
1372 * Currently we are using importable fields as exportable fields
1374 * @param int|string $contactType contact Type
1375 * @param bool $status
1376 * True while exporting primary contacts.
1377 * @param bool $export
1378 * True when used during export.
1379 * @param bool $search
1380 * True when used during search, might conflict with export param?.
1382 * @param bool $withMultiRecord
1385 * array of exportable Fields
1387 public static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE, $checkPermissions = TRUE) {
1388 if (empty($contactType)) {
1389 $contactType = 'All';
1392 $cacheKeyString = "exportableFields $contactType";
1393 $cacheKeyString .= $export ?
'_1' : '_0';
1394 $cacheKeyString .= $status ?
'_1' : '_0';
1395 $cacheKeyString .= $search ?
'_1' : '_0';
1396 //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
1397 //calculates custom fields takes into account the logged in user & caches that for all users
1398 //as an interim fix we will cache the fields by contact
1399 $cacheKeyString .= '_' . CRM_Core_Session
::getLoggedInContactID();
1401 if (!self
::$_exportableFields ||
!CRM_Utils_Array
::value($cacheKeyString, self
::$_exportableFields)) {
1402 if (!self
::$_exportableFields) {
1403 self
::$_exportableFields = array();
1406 // check if we can retrieve from database cache
1407 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1410 $fields = CRM_Contact_DAO_Contact
::export();
1412 // The fields are meant for contact types.
1413 if (in_array($contactType, array(
1420 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1422 // add current employer for individuals
1423 $fields = array_merge($fields, array(
1424 'current_employer' =>
1426 'name' => 'organization_name',
1427 'title' => ts('Current Employer'),
1431 $locationType = array(
1432 'location_type' => array(
1433 'name' => 'location_type',
1434 'where' => 'civicrm_location_type.name',
1435 'title' => ts('Location Type'),
1439 $IMProvider = array(
1440 'im_provider' => array(
1441 'name' => 'im_provider',
1442 'where' => 'civicrm_im.provider_id',
1443 'title' => ts('IM Provider'),
1447 $locationFields = array_merge($locationType,
1448 CRM_Core_DAO_Address
::export(),
1449 CRM_Core_DAO_Phone
::export(),
1450 CRM_Core_DAO_Email
::export(),
1452 CRM_Core_DAO_IM
::export(TRUE),
1453 CRM_Core_DAO_OpenID
::export()
1456 $locationFields = array_merge($locationFields,
1457 CRM_Core_BAO_CustomField
::getFieldsForImport('Address')
1460 foreach ($locationFields as $key => $field) {
1461 $locationFields[$key]['hasLocationType'] = TRUE;
1464 $fields = array_merge($fields, $locationFields);
1467 $fields = array_merge($fields,
1468 CRM_Core_DAO_Worldregion
::export()
1471 $fields = array_merge($fields,
1472 CRM_Contact_DAO_Contact
::export()
1476 $fields = array_merge($fields, CRM_Core_DAO_Website
::export());
1478 if ($contactType != 'All') {
1479 $fields = array_merge($fields,
1480 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType, $status, FALSE, $search, $checkPermissions, $withMultiRecord)
1489 $fields = array_merge($fields,
1490 CRM_Core_BAO_CustomField
::getFieldsForImport($type, FALSE, FALSE, $search, $checkPermissions, $withMultiRecord)
1494 $fields['current_employer_id']['title'] = ts('Current Employer ID');
1497 $fields = array_merge($fields, array(
1499 'title' => ts('Group(s)'),
1503 'title' => ts('Tag(s)'),
1507 'title' => ts('Note(s)'),
1513 $fields = array_merge($fields, array(
1515 'title' => ts('Group(s)'),
1519 'title' => ts('Tag(s)'),
1523 'title' => ts('Note(s)'),
1529 //Sorting fields in alphabetical order(CRM-1507)
1530 foreach ($fields as $k => $v) {
1531 $sortArray[$k] = CRM_Utils_Array
::value('title', $v);
1534 $fields = array_merge($sortArray, $fields);
1535 //unset the field which are not related to their contact type.
1536 if ($contactType != 'All') {
1537 $commonValues = array(
1538 'Individual' => array(
1542 'organization_name',
1543 'email_greeting_custom',
1544 'postal_greeting_custom',
1547 'Household' => array(
1557 'organization_name',
1565 'email_greeting_custom',
1566 'postal_greeting_custom',
1571 'Organization' => array(
1582 'email_greeting_custom',
1583 'postal_greeting_custom',
1593 foreach ($commonValues[$contactType] as $value) {
1594 unset($fields[$value]);
1598 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1600 self
::$_exportableFields[$cacheKeyString] = $fields;
1604 $fields = self
::$_exportableFields[$cacheKeyString];
1607 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1608 self
::$_exportableFields[$cacheKeyString]
1616 * Get the all contact details (Hierarchical).
1618 * @param int $contactId
1620 * @param array $fields
1626 public static function getHierContactDetails($contactId, &$fields) {
1627 $params = array(array('contact_id', '=', $contactId, 0, 0));
1630 $returnProperties = self
::makeHierReturnProperties($fields, $contactId);
1632 // We don't know the contents of return properties, but we need the lower
1633 // level ids of the contact so add a few fields.
1634 $returnProperties['first_name'] = 1;
1635 $returnProperties['organization_name'] = 1;
1636 $returnProperties['household_name'] = 1;
1637 $returnProperties['contact_type'] = 1;
1638 $returnProperties['contact_sub_type'] = 1;
1639 return list($query, $options) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, $options);
1643 * Given a set of flat profile style field names, create a hierarchy.
1645 * This is for the query to use, create the right sql.
1648 * @param int $contactId
1652 * A hierarchical property tree if appropriate
1654 public static function &makeHierReturnProperties($fields, $contactId = NULL) {
1655 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1657 $returnProperties = array();
1659 $multipleFields = array('website' => 'url');
1660 foreach ($fields as $name => $dontCare) {
1661 if (strpos($name, '-') !== FALSE) {
1662 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $name, 3);
1664 if (!in_array($fieldName, $multipleFields)) {
1665 if ($id == 'Primary') {
1666 $locationTypeName = 1;
1669 $locationTypeName = CRM_Utils_Array
::value($id, $locationTypes);
1670 if (!$locationTypeName) {
1675 if (empty($returnProperties['location'])) {
1676 $returnProperties['location'] = array();
1678 if (empty($returnProperties['location'][$locationTypeName])) {
1679 $returnProperties['location'][$locationTypeName] = array();
1680 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1682 if (in_array($fieldName, array(
1690 $returnProperties['location'][$locationTypeName][$fieldName . '-' . $type] = 1;
1693 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1696 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1697 $returnProperties['location'][$locationTypeName][substr($fieldName, 8)] = 1;
1700 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1704 $returnProperties['website'][$id][$fieldName] = 1;
1708 $returnProperties[$name] = 1;
1712 return $returnProperties;
1716 * Return the primary location type of a contact.
1718 * $params int $contactId contact_id
1719 * $params boolean $isPrimaryExist if true, return primary contact location type otherwise null
1720 * $params boolean $skipDefaultPriamry if true, return primary contact location type otherwise null
1722 * @param int $contactId
1723 * @param bool $skipDefaultPriamry
1724 * @param null $block
1727 * $locationType location_type_id
1729 public static function getPrimaryLocationType($contactId, $skipDefaultPriamry = FALSE, $block = NULL) {
1731 $entityBlock = array('contact_id' => $contactId);
1732 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock);
1733 foreach ($blocks[$block] as $key => $value) {
1734 if (!empty($value['is_primary'])) {
1735 $locationType = CRM_Utils_Array
::value('location_type_id', $value);
1742 IF ( civicrm_email.location_type_id IS NULL,
1743 IF ( civicrm_address.location_type_id IS NULL,
1744 IF ( civicrm_phone.location_type_id IS NULL,
1745 IF ( civicrm_im.location_type_id IS NULL,
1746 IF ( civicrm_openid.location_type_id IS NULL, null, civicrm_openid.location_type_id)
1747 ,civicrm_im.location_type_id)
1748 ,civicrm_phone.location_type_id)
1749 ,civicrm_address.location_type_id)
1750 ,civicrm_email.location_type_id) as locationType
1751 FROM civicrm_contact
1752 LEFT JOIN civicrm_email ON ( civicrm_email.is_primary = 1 AND civicrm_email.contact_id = civicrm_contact.id )
1753 LEFT JOIN civicrm_address ON ( civicrm_address.is_primary = 1 AND civicrm_address.contact_id = civicrm_contact.id)
1754 LEFT JOIN civicrm_phone ON ( civicrm_phone.is_primary = 1 AND civicrm_phone.contact_id = civicrm_contact.id)
1755 LEFT JOIN civicrm_im ON ( civicrm_im.is_primary = 1 AND civicrm_im.contact_id = civicrm_contact.id)
1756 LEFT JOIN civicrm_openid ON ( civicrm_openid.is_primary = 1 AND civicrm_openid.contact_id = civicrm_contact.id)
1757 WHERE civicrm_contact.id = %1 ";
1759 $params = array(1 => array($contactId, 'Integer'));
1761 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1763 $locationType = NULL;
1764 if ($dao->fetch()) {
1765 $locationType = $dao->locationType
;
1768 if (isset($locationType)) {
1769 return $locationType;
1771 elseif ($skipDefaultPriamry) {
1772 // if there is no primary contact location then return null
1776 // if there is no primart contact location, then return default
1777 // location type of the system
1778 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
1779 return $defaultLocationType->id
;
1784 * Get the display name, primary email and location type of a contact.
1787 * Id of the contact.
1790 * Array of display_name, email if found, do_not_email or (null,null,null)
1792 public static function getContactDetails($id) {
1793 // check if the contact type
1794 $contactType = self
::getContactType($id);
1796 $nameFields = ($contactType == 'Individual') ?
"civicrm_contact.first_name, civicrm_contact.last_name, civicrm_contact.display_name" : "civicrm_contact.display_name";
1799 SELECT $nameFields, civicrm_email.email, civicrm_contact.do_not_email, civicrm_email.on_hold, civicrm_contact.is_deceased
1800 FROM civicrm_contact LEFT JOIN civicrm_email ON (civicrm_contact.id = civicrm_email.contact_id)
1801 WHERE civicrm_contact.id = %1
1802 ORDER BY civicrm_email.is_primary DESC";
1803 $params = array(1 => array($id, 'Integer'));
1804 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
1806 if ($dao->fetch()) {
1807 if ($contactType == 'Individual') {
1808 if ($dao->first_name ||
$dao->last_name
) {
1809 $name = "{$dao->first_name} {$dao->last_name}";
1812 $name = $dao->display_name
;
1816 $name = $dao->display_name
;
1818 $email = $dao->email
;
1819 $doNotEmail = $dao->do_not_email ?
TRUE : FALSE;
1820 $onHold = $dao->on_hold ?
TRUE : FALSE;
1821 $isDeceased = $dao->is_deceased ?
TRUE : FALSE;
1822 return array($name, $email, $doNotEmail, $onHold, $isDeceased);
1824 return array(NULL, NULL, NULL, NULL, NULL);
1828 * Add/edit/register contacts through profile.
1830 * @param array $params
1831 * Array of profile fields to be edited/added.
1832 * @param array $fields
1833 * Array of fields from UFGroup.
1834 * @param int $contactID
1835 * Id of the contact to be edited/added.
1836 * @param int $addToGroupID
1837 * Specifies the default group to which contact is added.
1838 * @param int $ufGroupId
1839 * Uf group id (profile id).
1840 * @param string $ctype
1841 * @param bool $visibility
1842 * Basically lets us know where this request is coming from.
1843 * if via a profile from web, we restrict what groups are changed
1846 * contact id created/edited
1848 public static function createProfileContact(
1852 $addToGroupID = NULL,
1857 // add ufGroupID to params array ( CRM-2012 )
1859 $params['uf_group_id'] = $ufGroupId;
1861 self
::addBillingNameFieldsIfOtherwiseNotSet($params);
1863 // If a user has logged in, or accessed via a checksum
1864 // Then deliberately 'blanking' a value in the profile should remove it from their record
1865 $session = CRM_Core_Session
::singleton();
1866 $params['updateBlankLocInfo'] = TRUE;
1867 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0) {
1868 $params['updateBlankLocInfo'] = FALSE;
1873 CRM_Utils_Hook
::pre('edit', 'Profile', $contactID, $params);
1877 CRM_Utils_Hook
::pre('create', 'Profile', NULL, $params);
1880 list($data, $contactDetails) = self
::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
1882 // manage is_opt_out
1883 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
1884 $wasOptOut = CRM_Utils_Array
::value('is_opt_out', $contactDetails, FALSE);
1885 $isOptOut = CRM_Utils_Array
::value('is_opt_out', $params, FALSE);
1886 $data['is_opt_out'] = $isOptOut;
1887 // on change, create new civicrm_subscription_history entry
1888 if (($wasOptOut != $isOptOut) && !empty($contactDetails['contact_id'])) {
1890 'contact_id' => $contactDetails['contact_id'],
1891 'status' => $isOptOut ?
'Removed' : 'Added',
1894 CRM_Contact_BAO_SubscriptionHistory
::create($shParams);
1898 $contact = self
::create($data);
1900 // contact is null if the profile does not have any contact fields
1902 $contactID = $contact->id
;
1905 if (empty($contactID)) {
1906 CRM_Core_Error
::fatal('Cannot proceed without a valid contact id');
1909 // Process group and tag
1910 if (!empty($fields['group'])) {
1912 // this for sure means we are coming in via profile since i added it to fix
1913 // removing contacts from user groups -- lobo
1917 CRM_Contact_BAO_GroupContact
::create($params['group'], $contactID, $visibility, $method);
1920 if (!empty($fields['tag'])) {
1921 CRM_Core_BAO_EntityTag
::create($params['tag'], 'civicrm_contact', $contactID);
1924 //to add profile in default group
1925 if (is_array($addToGroupID)) {
1926 $contactIds = array($contactID);
1927 foreach ($addToGroupID as $groupId) {
1928 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
1931 elseif ($addToGroupID) {
1932 $contactIds = array($contactID);
1933 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $addToGroupID);
1936 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
1939 CRM_Utils_Hook
::post('edit', 'Profile', $contactID, $params);
1942 CRM_Utils_Hook
::post('create', 'Profile', $contactID, $params);
1948 * Format profile contact parameters.
1950 * @param array $params
1952 * @param int $contactID
1953 * @param int $ufGroupId
1954 * @param null $ctype
1955 * @param bool $skipCustom
1959 public static function formatProfileContactParams(
1968 $data = $contactDetails = array();
1970 // get the contact details (hier)
1972 list($details, $options) = self
::getHierContactDetails($contactID, $fields);
1974 $contactDetails = $details[$contactID];
1975 $data['contact_type'] = CRM_Utils_Array
::value('contact_type', $contactDetails);
1976 $data['contact_sub_type'] = CRM_Utils_Array
::value('contact_sub_type', $contactDetails);
1979 //we should get contact type only if contact
1981 $data['contact_type'] = CRM_Core_BAO_UFField
::getProfileType($ufGroupId);
1983 //special case to handle profile with only contact fields
1984 if ($data['contact_type'] == 'Contact') {
1985 $data['contact_type'] = 'Individual';
1987 elseif (CRM_Contact_BAO_ContactType
::isaSubType($data['contact_type'])) {
1988 $data['contact_type'] = CRM_Contact_BAO_ContactType
::getBasicType($data['contact_type']);
1992 $data['contact_type'] = $ctype;
1995 $data['contact_type'] = 'Individual';
1999 //fix contact sub type CRM-5125
2000 if (array_key_exists('contact_sub_type', $params) &&
2001 !empty($params['contact_sub_type'])
2003 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type']);
2005 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
2006 !empty($params['contact_sub_type_hidden'])
2008 // if profile was used, and had any subtype, we obtain it from there
2009 //CRM-13596 - add to existing contact types, rather than overwriting
2010 $data_contact_sub_type_arr = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2011 if (!in_array($params['contact_sub_type_hidden'], $data_contact_sub_type_arr)) {
2012 $data['contact_sub_type'] .= CRM_Utils_Array
::implodePadded($params['contact_sub_type_hidden']);
2016 if ($ctype == 'Organization') {
2017 $data['organization_name'] = CRM_Utils_Array
::value('organization_name', $contactDetails);
2019 elseif ($ctype == 'Household') {
2020 $data['household_name'] = CRM_Utils_Array
::value('household_name', $contactDetails);
2023 $locationType = array();
2028 $data['contact_id'] = $contactID;
2029 $primaryLocationType = self
::getPrimaryLocationType($contactID);
2032 $defaultLocation = CRM_Core_BAO_LocationType
::getDefault();
2033 $defaultLocationId = $defaultLocation->id
;
2036 $billingLocationTypeId = CRM_Core_BAO_LocationType
::getBilling();
2038 $blocks = array('email', 'phone', 'im', 'openid');
2040 $multiplFields = array('url');
2041 // prevent overwritten of formatted array, reset all block from
2042 // params if it is not in valid format (since import pass valid format)
2043 foreach ($blocks as $blk) {
2044 if (array_key_exists($blk, $params) &&
2045 !is_array($params[$blk])
2047 unset($params[$blk]);
2051 $primaryPhoneLoc = NULL;
2052 $session = CRM_Core_Session
::singleton();
2053 foreach ($params as $key => $value) {
2054 list($fieldName, $locTypeId, $typeId) = CRM_Utils_System
::explode('-', $key, 3);
2056 if ($locTypeId == 'Primary') {
2058 if (in_array($fieldName, $blocks)) {
2059 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, $fieldName);
2062 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, 'address');
2064 $primaryLocationType = $locTypeId;
2067 $locTypeId = $defaultLocationId;
2071 if (is_numeric($locTypeId) &&
2072 !in_array($fieldName, $multiplFields) &&
2073 substr($fieldName, 0, 7) != 'custom_'
2075 $index = $locTypeId;
2077 if (is_numeric($typeId)) {
2078 $index .= '-' . $typeId;
2080 if (!in_array($index, $locationType)) {
2081 $locationType[$count] = $index;
2085 $loc = CRM_Utils_Array
::key($index, $locationType);
2087 $blockName = in_array($fieldName, $blocks) ?
$fieldName : 'address';
2089 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
2091 //set is_billing true, for location type "Billing"
2092 if ($locTypeId == $billingLocationTypeId) {
2093 $data[$blockName][$loc]['is_billing'] = 1;
2097 //get the primary location type
2098 if ($locTypeId == $primaryLocationType) {
2099 $data[$blockName][$loc]['is_primary'] = 1;
2102 elseif ($locTypeId == $defaultLocationId) {
2103 $data[$blockName][$loc]['is_primary'] = 1;
2106 if (in_array($fieldName, array('phone'))) {
2108 $data['phone'][$loc]['phone_type_id'] = $typeId;
2111 $data['phone'][$loc]['phone_type_id'] = '';
2113 $data['phone'][$loc]['phone'] = $value;
2115 //special case to handle primary phone with different phone types
2116 // in this case we make first phone type as primary
2117 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
2118 $primaryPhoneLoc = $loc;
2121 if ($loc != $primaryPhoneLoc) {
2122 unset($data['phone'][$loc]['is_primary']);
2125 elseif ($fieldName == 'phone_ext') {
2126 $data['phone'][$loc]['phone_ext'] = $value;
2128 elseif ($fieldName == 'email') {
2129 $data['email'][$loc]['email'] = $value;
2130 if (empty($contactID)) {
2131 $data['email'][$loc]['is_primary'] = 1;
2134 elseif ($fieldName == 'im') {
2135 if (isset($params[$key . '-provider_id'])) {
2136 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
2138 if (strpos($key, '-provider_id') !== FALSE) {
2139 $data['im'][$loc]['provider_id'] = $params[$key];
2142 $data['im'][$loc]['name'] = $value;
2145 elseif ($fieldName == 'openid') {
2146 $data['openid'][$loc]['openid'] = $value;
2149 if ($fieldName === 'state_province') {
2151 if (is_numeric($value) && ((int ) $value) >= 1000) {
2152 $data['address'][$loc]['state_province_id'] = $value;
2154 elseif (empty($value)) {
2155 $data['address'][$loc]['state_province_id'] = '';
2158 $data['address'][$loc]['state_province'] = $value;
2161 elseif ($fieldName === 'country') {
2163 if (is_numeric($value) && ((int ) $value) >= 1000
2165 $data['address'][$loc]['country_id'] = $value;
2167 elseif (empty($value)) {
2168 $data['address'][$loc]['country_id'] = '';
2171 $data['address'][$loc]['country'] = $value;
2174 elseif ($fieldName === 'county') {
2175 $data['address'][$loc]['county_id'] = $value;
2177 elseif ($fieldName == 'address_name') {
2178 $data['address'][$loc]['name'] = $value;
2180 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2181 $data['address'][$loc][substr($fieldName, 8)] = $value;
2184 $data['address'][$loc][$fieldName] = $value;
2189 if (substr($key, 0, 4) === 'url-') {
2190 $websiteField = explode('-', $key);
2191 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
2192 $data['website'][$websiteField[1]]['url'] = $value;
2194 elseif (in_array($key, self
::$_greetingTypes, TRUE)) {
2195 //save email/postal greeting and addressee values if any, CRM-4575
2196 $data[$key . '_id'] = $value;
2198 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($key))) {
2199 // for autocomplete transfer hidden value instead of label
2200 if ($params[$key] && isset($params[$key . '_id'])) {
2201 $value = $params[$key . '_id'];
2204 // we need to append time with date
2205 if ($params[$key] && isset($params[$key . '_time'])) {
2206 $value .= ' ' . $params[$key . '_time'];
2209 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
2210 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 &&
2211 ($value == '' ||
!isset($value))
2217 if (!empty($params['customRecordValues'])) {
2218 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2219 foreach ($params['customRecordValues'] as $recId => $customFields) {
2220 if (is_array($customFields) && !empty($customFields)) {
2221 foreach ($customFields as $customFieldName) {
2222 if ($customFieldName == $key) {
2232 //CRM-13596 - check for contact_sub_type_hidden first
2233 if (array_key_exists('contact_sub_type_hidden', $params)) {
2234 $type = $params['contact_sub_type_hidden'];
2237 $type = $data['contact_type'];
2238 if (!empty($data['contact_sub_type'])) {
2239 $type = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2243 CRM_Core_BAO_CustomField
::formatCustomField($customFieldId,
2253 elseif ($key == 'edit') {
2257 if ($key == 'location') {
2258 foreach ($value as $locationTypeId => $field) {
2259 foreach ($field as $block => $val) {
2260 if ($block == 'address' && array_key_exists('address_name', $val)) {
2261 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2266 if ($key == 'phone' && isset($params['phone_ext'])) {
2267 $data[$key] = $value;
2268 foreach ($value as $cnt => $phoneBlock) {
2269 if ($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']) {
2270 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array
::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2274 elseif (in_array($key,
2285 ($value == '' ||
!isset($value)) &&
2286 ($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 ||
2287 ($key == 'current_employer' && empty($params['current_employer']))) {
2288 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
2289 // to avoid update with empty values
2293 $data[$key] = $value;
2299 if (!isset($data['contact_type'])) {
2300 $data['contact_type'] = 'Individual';
2303 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2304 $privacy = CRM_Core_SelectValues
::privacy();
2305 foreach ($privacy as $key => $value) {
2306 if (array_key_exists($key, $fields)) {
2307 // do not reset values for existing contacts, if fields are added to a profile
2308 if (array_key_exists($key, $params)) {
2309 $data[$key] = $params[$key];
2310 if (empty($params[$key])) {
2314 elseif (!$contactID) {
2320 return array($data, $contactDetails);
2324 * Find the get contact details.
2326 * This function does not respect ACLs for now, which might need to be rectified at some
2327 * stage based on how its used.
2329 * @param string $mail
2330 * Primary email address of the contact.
2331 * @param string $ctype
2334 * @return object|null
2335 * $dao contact details
2337 public static function matchContactOnEmail($mail, $ctype = NULL) {
2338 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2339 $mail = $strtolower(trim($mail));
2341 SELECT civicrm_contact.id as contact_id,
2342 civicrm_contact.hash as hash,
2343 civicrm_contact.contact_type as contact_type,
2344 civicrm_contact.contact_sub_type as contact_sub_type
2345 FROM civicrm_contact
2346 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2348 if (Civi
::settings()->get('uniq_email_per_site')) {
2349 // try to find a match within a site (multisite).
2350 $groups = CRM_Core_BAO_Domain
::getChildGroupIds();
2351 if (!empty($groups)) {
2353 INNER JOIN civicrm_group_contact gc ON
2354 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2359 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2360 $p = array(1 => array($mail, 'String'));
2363 $query .= " AND civicrm_contact.contact_type = %3";
2364 $p[3] = array($ctype, 'String');
2367 $query .= " ORDER BY civicrm_email.is_primary DESC";
2369 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2371 if ($dao->fetch()) {
2378 * Find the contact details associated with an OpenID.
2380 * @param string $openId
2381 * OpenId of the contact.
2382 * @param string $ctype
2385 * @return object|null
2386 * $dao contact details
2388 public static function matchContactOnOpenId($openId, $ctype = NULL) {
2389 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2390 $openId = $strtolower(trim($openId));
2392 SELECT civicrm_contact.id as contact_id,
2393 civicrm_contact.hash as hash,
2394 civicrm_contact.contact_type as contact_type,
2395 civicrm_contact.contact_sub_type as contact_sub_type
2396 FROM civicrm_contact
2397 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2398 WHERE civicrm_openid.openid = %1";
2399 $p = array(1 => array($openId, 'String'));
2402 $query .= " AND civicrm_contact.contact_type = %3";
2403 $p[3] = array($ctype, 'String');
2406 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2408 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2410 if ($dao->fetch()) {
2417 * Get primary email of the contact.
2419 * @param int $contactID
2423 * Email address if present else null
2425 public static function getPrimaryEmail($contactID) {
2426 // fetch the primary email
2428 SELECT civicrm_email.email as email
2429 FROM civicrm_contact
2430 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2431 WHERE civicrm_email.is_primary = 1
2432 AND civicrm_contact.id = %1";
2433 $p = array(1 => array($contactID, 'Integer'));
2434 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2437 if ($dao->fetch()) {
2438 $email = $dao->email
;
2445 * Function to get primary OpenID of the contact.
2447 * @param int $contactID
2451 * >openid OpenID if present else null
2453 public static function getPrimaryOpenId($contactID) {
2454 // fetch the primary OpenID
2456 SELECT civicrm_openid.openid as openid
2457 FROM civicrm_contact
2458 LEFT JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2459 WHERE civicrm_contact.id = %1
2460 AND civicrm_openid.is_primary = 1";
2461 $p = array(1 => array($contactID, 'Integer'));
2462 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2465 if ($dao->fetch()) {
2466 $openId = $dao->openid
;
2473 * Fetch the object and store the values in the values array.
2475 * @param array $params
2476 * Input parameters to find object.
2477 * @param array $values
2478 * Output values of the object.
2480 * @return CRM_Contact_BAO_Contact|null
2481 * The found object or null
2483 public static function getValues(&$params, &$values) {
2484 $contact = new CRM_Contact_BAO_Contact();
2486 $contact->copyValues($params);
2488 if ($contact->find(TRUE)) {
2490 CRM_Core_DAO
::storeValues($contact, $values);
2493 foreach (self
::$_commPrefs as $name) {
2494 if (isset($contact->$name)) {
2495 $privacy[$name] = $contact->$name;
2499 if (!empty($privacy)) {
2500 $values['privacy'] = $privacy;
2503 // communication Prefferance
2504 $preffComm = $comm = array();
2505 $comm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2506 $contact->preferred_communication_method
2508 foreach ($comm as $value) {
2509 $preffComm[$value] = 1;
2511 $temp = array('preferred_communication_method' => $contact->preferred_communication_method
);
2514 'preferred_communication_method' => array(
2515 'newName' => 'preferred_communication_method_display',
2516 'groupName' => 'preferred_communication_method',
2520 // @todo This can be figured out from metadata & we can avoid the uncached query.
2521 CRM_Core_OptionGroup
::lookupValues($temp, $names, FALSE);
2523 $values['preferred_communication_method'] = $preffComm;
2524 $values['preferred_communication_method_display'] = CRM_Utils_Array
::value('preferred_communication_method_display', $temp);
2526 if ($contact->preferred_mail_format
) {
2527 $preferredMailingFormat = CRM_Core_SelectValues
::pmf();
2528 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format
];
2531 // get preferred languages
2532 if (!empty($contact->preferred_language
)) {
2533 $values['preferred_language'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language
);
2536 // Calculating Year difference
2537 if ($contact->birth_date
) {
2538 $birthDate = CRM_Utils_Date
::customFormat($contact->birth_date
, '%Y%m%d');
2539 if ($birthDate < date('Ymd')) {
2540 $age = CRM_Utils_Date
::calculateAge($birthDate);
2541 $values['age']['y'] = CRM_Utils_Array
::value('years', $age);
2542 $values['age']['m'] = CRM_Utils_Array
::value('months', $age);
2546 $contact->contact_id
= $contact->id
;
2554 * Given the component name and returns the count of participation of contact.
2556 * @param string $component
2557 * Input component name.
2558 * @param int $contactId
2560 * @param string $tableName
2561 * Optional tableName if component is custom group.
2564 * total number in database
2566 public static function getCountComponent($component, $contactId, $tableName = NULL) {
2568 switch ($component) {
2570 return CRM_Core_BAO_EntityTag
::getContactTags($contactId, TRUE);
2573 $result = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
2574 CRM_Contact_BAO_Relationship
::CURRENT
,
2579 return count($result);
2583 return CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, "Added", NULL, TRUE);
2586 if (CRM_Core_BAO_Log
::useLoggingReport()) {
2589 return CRM_Core_BAO_Log
::getContactLogCount($contactId);
2592 return CRM_Core_BAO_Note
::getContactNoteCount($contactId);
2594 case 'contribution':
2595 return CRM_Contribute_BAO_Contribution
::contributionCount($contactId);
2598 return CRM_Member_BAO_Membership
::getContactMembershipCount($contactId, TRUE);
2601 return CRM_Event_BAO_Participant
::getContactParticipantCount($contactId);
2604 return CRM_Pledge_BAO_Pledge
::getContactPledgeCount($contactId);
2607 return CRM_Case_BAO_Case
::caseCount($contactId);
2610 return CRM_Grant_BAO_Grant
::getContactGrantCount($contactId);
2614 'contact_id' => $contactId,
2617 'context' => 'activity',
2619 return CRM_Activity_BAO_Activity
::getActivitiesCount($input);
2622 $params = array('contact_id' => $contactId);
2623 return CRM_Mailing_BAO_Mailing
::getContactMailingsCount($params);
2626 $custom = explode('_', $component);
2627 if ($custom['0'] = 'custom') {
2629 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2631 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2632 return CRM_Core_DAO
::singleValueQuery($queryString);
2638 * Process greetings and cache.
2640 * @param object $contact
2641 * Contact object after save.
2642 * @param bool $useDefaults
2643 * Use default greeting values.
2645 public static function processGreetings(&$contact, $useDefaults = FALSE) {
2647 //retrieve default greetings
2648 $defaultGreetings = CRM_Core_PseudoConstant
::greetingDefaults();
2649 $contactDefaults = $defaultGreetings[$contact->contact_type
];
2652 // note that contact object not always has required greeting related
2653 // fields that are required to calculate greeting and
2654 // also other fields used in tokens etc,
2655 // hence we need to retrieve it again.
2656 if ($contact->_query
!== FALSE) {
2657 $contact->find(TRUE);
2660 // store object values to an array
2661 $contactDetails = array();
2662 CRM_Core_DAO
::storeValues($contact, $contactDetails);
2663 $contactDetails = array(array($contact->id
=> $contactDetails));
2665 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2666 $updateQueryString = array();
2668 //cache email and postal greeting to greeting display
2669 if ($contact->email_greeting_custom
!= 'null' && $contact->email_greeting_custom
) {
2670 $emailGreetingString = $contact->email_greeting_custom
;
2672 elseif ($contact->email_greeting_id
!= 'null' && $contact->email_greeting_id
) {
2673 // the filter value for Individual contact type is set to 1
2675 'contact_type' => $contact->contact_type
,
2676 'greeting_type' => 'email_greeting',
2679 $emailGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2680 $emailGreetingString = $emailGreeting[$contact->email_greeting_id
];
2681 $updateQueryString[] = " email_greeting_custom = NULL ";
2685 reset($contactDefaults['email_greeting']);
2686 $emailGreetingID = key($contactDefaults['email_greeting']);
2687 $emailGreetingString = $contactDefaults['email_greeting'][$emailGreetingID];
2688 $updateQueryString[] = " email_greeting_id = $emailGreetingID ";
2689 $updateQueryString[] = " email_greeting_custom = NULL ";
2691 elseif ($contact->email_greeting_custom
) {
2692 $updateQueryString[] = " email_greeting_display = NULL ";
2696 if ($emailGreetingString) {
2697 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($emailGreetingString,
2700 'CRM_Contact_BAO_Contact'
2702 $emailGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($emailGreetingString));
2703 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2707 if ($contact->postal_greeting_custom
!= 'null' && $contact->postal_greeting_custom
) {
2708 $postalGreetingString = $contact->postal_greeting_custom
;
2710 elseif ($contact->postal_greeting_id
!= 'null' && $contact->postal_greeting_id
) {
2712 'contact_type' => $contact->contact_type
,
2713 'greeting_type' => 'postal_greeting',
2715 $postalGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2716 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id
];
2717 $updateQueryString[] = " postal_greeting_custom = NULL ";
2721 reset($contactDefaults['postal_greeting']);
2722 $postalGreetingID = key($contactDefaults['postal_greeting']);
2723 $postalGreetingString = $contactDefaults['postal_greeting'][$postalGreetingID];
2724 $updateQueryString[] = " postal_greeting_id = $postalGreetingID ";
2725 $updateQueryString[] = " postal_greeting_custom = NULL ";
2727 elseif ($contact->postal_greeting_custom
) {
2728 $updateQueryString[] = " postal_greeting_display = NULL ";
2732 if ($postalGreetingString) {
2733 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($postalGreetingString,
2736 'CRM_Contact_BAO_Contact'
2738 $postalGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($postalGreetingString));
2739 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2743 if ($contact->addressee_custom
!= 'null' && $contact->addressee_custom
) {
2744 $addresseeString = $contact->addressee_custom
;
2746 elseif ($contact->addressee_id
!= 'null' && $contact->addressee_id
) {
2748 'contact_type' => $contact->contact_type
,
2749 'greeting_type' => 'addressee',
2752 $addressee = CRM_Core_PseudoConstant
::greeting($filter);
2753 $addresseeString = $addressee[$contact->addressee_id
];
2754 $updateQueryString[] = " addressee_custom = NULL ";
2758 reset($contactDefaults['addressee']);
2759 $addresseeID = key($contactDefaults['addressee']);
2760 $addresseeString = $contactDefaults['addressee'][$addresseeID];
2761 $updateQueryString[] = " addressee_id = $addresseeID ";
2762 $updateQueryString[] = " addressee_custom = NULL ";
2764 elseif ($contact->addressee_custom
) {
2765 $updateQueryString[] = " addressee_display = NULL ";
2769 if ($addresseeString) {
2770 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($addresseeString,
2773 'CRM_Contact_BAO_Contact'
2775 $addresseeString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($addresseeString));
2776 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2779 if (!empty($updateQueryString)) {
2780 $updateQueryString = implode(',', $updateQueryString);
2781 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2782 CRM_Core_DAO
::executeQuery($queryString);
2787 * Retrieve loc block ids w/ given condition.
2789 * @param int $contactId
2791 * @param array $criteria
2792 * Key => value pair which should be.
2793 * fulfill by return record ids.
2794 * @param string $condOperator
2795 * Operator use for grouping multiple conditions.
2798 * loc block ids which fulfill condition.
2800 public static function getLocBlockIds($contactId, $criteria = array(), $condOperator = 'AND') {
2801 $locBlockIds = array();
2803 return $locBlockIds;
2806 foreach (array('Email', 'OpenID', 'Phone', 'Address', 'IM') as $block) {
2807 $name = strtolower($block);
2808 $className = "CRM_Core_DAO_$block";
2809 $blockDAO = new $className();
2811 // build the condition.
2812 if (is_array($criteria)) {
2813 $fields = $blockDAO->fields();
2814 $conditions = array();
2815 foreach ($criteria as $field => $value) {
2816 if (array_key_exists($field, $fields)) {
2817 $cond = "( $field = $value )";
2818 // value might be zero or null.
2819 if (!$value ||
strtolower($value) == 'null') {
2820 $cond = "( $field = 0 OR $field IS NULL )";
2822 $conditions[] = $cond;
2825 if (!empty($conditions)) {
2826 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2830 $blockDAO->contact_id
= $contactId;
2832 while ($blockDAO->fetch()) {
2833 $locBlockIds[$name][] = $blockDAO->id
;
2838 return $locBlockIds;
2842 * Build context menu items.
2844 * @param int $contactId
2847 * Array of context menu for logged in user.
2849 public static function contextMenu($contactId = NULL) {
2852 'title' => ts('View Contact'),
2854 'ref' => 'view-contact',
2855 'class' => 'no-popup',
2857 'permissions' => array('view all contacts'),
2860 'title' => ts('Edit Contact'),
2862 'ref' => 'edit-contact',
2863 'class' => 'no-popup',
2865 'permissions' => array('edit all contacts'),
2868 'title' => ts('Delete Contact'),
2870 'ref' => 'delete-contact',
2872 'permissions' => array('access deleted contacts', 'delete contacts'),
2874 'contribution' => array(
2875 'title' => ts('Add Contribution'),
2877 'ref' => 'new-contribution',
2878 'key' => 'contribution',
2879 'tab' => 'contribute',
2880 'component' => 'CiviContribute',
2881 'href' => CRM_Utils_System
::url('civicrm/contact/view/contribution',
2882 'reset=1&action=add&context=contribution'
2884 'permissions' => array(
2885 'access CiviContribute',
2886 'edit contributions',
2889 'participant' => array(
2890 'title' => ts('Register for Event'),
2892 'ref' => 'new-participant',
2893 'key' => 'participant',
2894 'tab' => 'participant',
2895 'component' => 'CiviEvent',
2896 'href' => CRM_Utils_System
::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
2897 'permissions' => array(
2899 'edit event participants',
2902 'activity' => array(
2903 'title' => ts('Record Activity'),
2905 'ref' => 'new-activity',
2906 'key' => 'activity',
2907 'permissions' => array('edit all contacts'),
2910 'title' => ts('Add Pledge'),
2912 'ref' => 'new-pledge',
2915 'href' => CRM_Utils_System
::url('civicrm/contact/view/pledge',
2916 'reset=1&action=add&context=pledge'
2918 'component' => 'CiviPledge',
2919 'permissions' => array(
2920 'access CiviPledge',
2924 'membership' => array(
2925 'title' => ts('Add Membership'),
2927 'ref' => 'new-membership',
2928 'key' => 'membership',
2930 'component' => 'CiviMember',
2931 'href' => CRM_Utils_System
::url('civicrm/contact/view/membership',
2932 'reset=1&action=add&context=membership'
2934 'permissions' => array(
2935 'access CiviMember',
2940 'title' => ts('Add Case'),
2942 'ref' => 'new-case',
2945 'component' => 'CiviCase',
2946 'href' => CRM_Utils_System
::url('civicrm/case/add', 'reset=1&action=add&context=case'),
2947 'permissions' => array('add cases'),
2950 'title' => ts('Add Grant'),
2952 'ref' => 'new-grant',
2955 'component' => 'CiviGrant',
2956 'href' => CRM_Utils_System
::url('civicrm/contact/view/grant',
2957 'reset=1&action=add&context=grant'
2959 'permissions' => array('edit grants'),
2962 'title' => ts('Add Relationship'),
2964 'ref' => 'new-relationship',
2967 'href' => CRM_Utils_System
::url('civicrm/contact/view/rel',
2968 'reset=1&action=add'
2970 'permissions' => array('edit all contacts'),
2973 'title' => ts('Add Note'),
2975 'ref' => 'new-note',
2978 'class' => 'medium-popup',
2979 'href' => CRM_Utils_System
::url('civicrm/contact/view/note',
2980 'reset=1&action=add'
2982 'permissions' => array('edit all contacts'),
2985 'title' => ts('Send an Email'),
2987 'ref' => 'new-email',
2989 'permissions' => array('view all contacts'),
2992 'title' => ts('Add to Group'),
2994 'ref' => 'group-add-contact',
2997 'permissions' => array('edit groups'),
3000 'title' => ts('Tag Contact'),
3002 'ref' => 'tag-contact',
3005 'permissions' => array('edit all contacts'),
3009 CRM_Utils_Hook
::summaryActions($menu, $contactId);
3010 //1. check for component is active.
3011 //2. check for user permissions.
3012 //3. check for acls.
3013 //3. edit and view contact are directly accessible to user.
3015 $aclPermissionedTasks = array(
3020 'group-add-contact',
3024 $corePermission = CRM_Core_Permission
::getPermission();
3026 $config = CRM_Core_Config
::singleton();
3028 $contextMenu = array();
3029 foreach ($menu as $key => $values) {
3030 $componentName = CRM_Utils_Array
::value('component', $values);
3032 // if component action - make sure component is enable.
3033 if ($componentName && !in_array($componentName, $config->enableComponents
)) {
3037 // make sure user has all required permissions.
3038 $hasAllPermissions = FALSE;
3040 $permissions = CRM_Utils_Array
::value('permissions', $values);
3041 if (!is_array($permissions) ||
empty($permissions)) {
3042 $hasAllPermissions = TRUE;
3045 // iterate for required permissions in given permissions array.
3046 if (!$hasAllPermissions) {
3047 $hasPermissions = 0;
3048 foreach ($permissions as $permission) {
3049 if (CRM_Core_Permission
::check($permission)) {
3054 if (count($permissions) == $hasPermissions) {
3055 $hasAllPermissions = TRUE;
3058 // if still user does not have required permissions, check acl.
3059 if (!$hasAllPermissions && $values['ref'] != 'delete-contact') {
3060 if (in_array($values['ref'], $aclPermissionedTasks) &&
3061 $corePermission == CRM_Core_Permission
::EDIT
3063 $hasAllPermissions = TRUE;
3065 elseif (in_array($values['ref'], array(
3068 // grant permissions for these tasks.
3069 $hasAllPermissions = TRUE;
3074 // user does not have necessary permissions.
3075 if (!$hasAllPermissions) {
3079 // build directly accessible action menu.
3080 if (in_array($values['ref'], array(
3084 $contextMenu['primaryActions'][$key] = array(
3085 'title' => $values['title'],
3086 'ref' => $values['ref'],
3087 'class' => CRM_Utils_Array
::value('class', $values),
3088 'key' => $values['key'],
3093 // finally get menu item for -more- action widget.
3094 $contextMenu['moreActions'][$values['weight']] = array(
3095 'title' => $values['title'],
3096 'ref' => $values['ref'],
3097 'href' => CRM_Utils_Array
::value('href', $values),
3098 'tab' => CRM_Utils_Array
::value('tab', $values),
3099 'class' => CRM_Utils_Array
::value('class', $values),
3100 'key' => $values['key'],
3104 ksort($contextMenu['moreActions']);
3106 return $contextMenu;
3110 * Retrieve display name of contact that address is shared.
3112 * This is based on $masterAddressId or $contactId .
3114 * @param int $masterAddressId
3116 * @param int $contactId
3119 * @return string|null
3120 * the found display name or null.
3122 public static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3123 $masterDisplayName = NULL;
3125 if (!$masterAddressId && !$contactId) {
3126 return $masterDisplayName;
3129 if ($masterAddressId) {
3131 SELECT display_name from civicrm_contact
3132 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3133 WHERE civicrm_address.id = " . $masterAddressId;
3135 elseif ($contactId) {
3137 SELECT display_name from civicrm_contact cc, civicrm_address add1
3138 LEFT JOIN civicrm_address add2 ON ( add1.master_id = add2.id )
3139 WHERE cc.id = add2.contact_id AND add1.contact_id = " . $contactId;
3142 $masterDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
3143 return $masterDisplayName;
3147 * Get the creation/modification times for a contact.
3149 * @param int $contactId
3152 * Dates - ('created_date' => $, 'modified_date' => $)
3154 public static function getTimestamps($contactId) {
3155 $timestamps = CRM_Core_DAO
::executeQuery(
3156 'SELECT created_date, modified_date
3157 FROM civicrm_contact
3160 1 => array($contactId, 'Integer'),
3163 if ($timestamps->fetch()) {
3165 'created_date' => $timestamps->created_date
,
3166 'modified_date' => $timestamps->modified_date
,
3175 * Generate triggers to update the timestamp.
3177 * The corresponding civicrm_contact row is updated on insert/update/delete
3178 * to a table that extends civicrm_contact.
3179 * Don't regenerate triggers for all such tables if only asked for one table.
3181 * @param array $info
3182 * Reference to the array where generated trigger information is being stored
3183 * @param string|null $reqTableName
3184 * Name of the table for which triggers are being generated, or NULL if all tables
3185 * @param array $relatedTableNames
3186 * Array of all core or all custom table names extending civicrm_contact
3187 * @param string $contactRefColumn
3188 * 'contact_id' if processing core tables, 'entity_id' if processing custom tables
3190 * @link https://issues.civicrm.org/jira/browse/CRM-15602
3193 public static function generateTimestampTriggers(&$info, $reqTableName, $relatedTableNames, $contactRefColumn) {
3195 $contactRefColumn = CRM_Core_DAO
::escapeString($contactRefColumn);
3196 // If specific related table requested, just process that one
3197 if (in_array($reqTableName, $relatedTableNames)) {
3198 $relatedTableNames = array($reqTableName);
3201 // If no specific table requested (include all related tables),
3202 // or a specific related table requested (as matched above)
3203 if (empty($reqTableName) ||
in_array($reqTableName, $relatedTableNames)) {
3205 'table' => $relatedTableNames,
3207 'event' => array('INSERT', 'UPDATE'),
3208 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = NEW.$contactRefColumn;\n",
3211 'table' => $relatedTableNames,
3213 'event' => array('DELETE'),
3214 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = OLD.$contactRefColumn;\n",
3220 * Get a list of triggers for the contact table.
3222 * @see hook_civicrm_triggerInfo
3223 * @see CRM_Core_DAO::triggerRebuild
3224 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3227 * @param null $tableName
3229 public static function triggerInfo(&$info, $tableName = NULL) {
3230 //during upgrade, first check for valid version and then create triggers
3231 //i.e the columns created_date and modified_date are introduced in 4.3.alpha1 so dont create triggers for older version
3232 if (CRM_Core_Config
::isUpgradeMode()) {
3233 $currentVer = CRM_Core_BAO_Domain
::version(TRUE);
3234 //if current version is less than 4.3.alpha1 dont create below triggers
3235 if (version_compare($currentVer, '4.3.alpha1') < 0) {
3240 // Update timestamp for civicrm_contact itself
3241 if ($tableName == NULL ||
$tableName == self
::getTableName()) {
3243 'table' => array(self
::getTableName()),
3245 'event' => array('INSERT'),
3246 'sql' => "\nSET NEW.created_date = CURRENT_TIMESTAMP;\n",
3250 // Update timestamp when modifying closely related core tables
3251 $relatedTables = array(
3258 self
::generateTimestampTriggers($info, $tableName, $relatedTables, 'contact_id');
3260 // Update timestamp when modifying related custom-data tables
3261 $customGroupTables = array();
3262 $customGroupDAO = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity('Contact');
3263 $customGroupDAO->is_multiple
= 0;
3264 $customGroupDAO->find();
3265 while ($customGroupDAO->fetch()) {
3266 $customGroupTables[] = $customGroupDAO->table_name
;
3268 if (!empty($customGroupTables)) {
3269 self
::generateTimestampTriggers($info, $tableName, $customGroupTables, 'entity_id');
3272 // Update phone table to populate phone_numeric field
3273 if (!$tableName ||
$tableName == 'civicrm_phone') {
3274 // Define stored sql function needed for phones
3275 $sqlTriggers = Civi
::service('sql_triggers');
3276 $sqlTriggers->enqueueQuery(self
::DROP_STRIP_FUNCTION_43
);
3277 $sqlTriggers->enqueueQuery(self
::CREATE_STRIP_FUNCTION_43
);
3279 'table' => array('civicrm_phone'),
3281 'event' => array('INSERT', 'UPDATE'),
3282 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3288 * Check if contact is being used in civicrm_domain based on $contactId.
3290 * @param int $contactId
3294 * true if present else false.
3296 public static function checkDomainContact($contactId) {
3300 $domainId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3311 * Get options for a given contact field.
3313 * @see CRM_Core_DAO::buildOptions
3315 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3316 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3318 * @param string $fieldName
3319 * @param string $context
3320 * @see CRM_Core_DAO::buildOptionsContext
3321 * @param array $props
3322 * whatever is known about this dao object.
3324 * @return array|bool
3326 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3328 // Special logic for fields whose options depend on context or properties
3329 switch ($fieldName) {
3330 case 'contact_sub_type':
3331 if (!empty($props['contact_type'])) {
3332 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3336 case 'contact_type':
3337 if ($context == 'search') {
3338 // CRM-15495 - EntityRef filters and basic search forms expect this format
3339 // FIXME: Search builder does not
3340 return CRM_Contact_BAO_ContactType
::getSelectElements();
3344 // The contact api supports some related entities so we'll honor that by fetching their options
3347 return CRM_Contact_BAO_GroupContact
::buildOptions('group_id', $context, $props);
3351 $props['entity_table'] = 'civicrm_contact';
3352 return CRM_Core_BAO_EntityTag
::buildOptions('tag_id', $context, $props);
3354 case 'state_province_id':
3355 case 'state_province':
3356 case 'state_province_name':
3361 case 'worldregion_id':
3362 return CRM_Core_BAO_Address
::buildOptions($fieldName, 'get', $props);
3365 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
3369 * Delete a contact-related object that has an 'is_primary' field.
3371 * Ensures that is_primary gets assigned to another object if available
3372 * Also calls pre/post hooks
3374 * @param string $type
3378 public static function deleteObjectWithPrimary($type, $id) {
3379 if (!$id ||
!is_numeric($id)) {
3382 $daoName = "CRM_Core_DAO_$type";
3383 $obj = new $daoName();
3386 if ($obj->fetch()) {
3387 CRM_Utils_Hook
::pre('delete', $type, $id, CRM_Core_DAO
::$_nullArray);
3388 $contactId = $obj->contact_id
;
3394 // is_primary is only relavent if this field belongs to a contact
3396 $dao = new $daoName();
3397 $dao->contact_id
= $contactId;
3398 $dao->is_primary
= 1;
3399 // Pick another record to be primary (if one isn't already)
3400 if (!$dao->find(TRUE)) {
3401 $dao->is_primary
= 0;
3403 if ($dao->fetch()) {
3404 $dao->is_primary
= 1;
3410 CRM_Utils_Hook
::post('delete', $type, $id, $obj);
3418 public function addSelectWhereClause() {
3419 // We always return an array with these keys, even if they are empty,
3420 // because this tells the query builder that we have considered these fields for acls
3422 'id' => (array) CRM_Contact_BAO_Contact_Permission
::cacheSubquery(),
3423 'is_deleted' => CRM_Core_Permission
::check('access deleted contacts') ?
array() : array('!= 1'),
3425 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3430 * Get any existing duplicate contacts based on the input parameters.
3432 * @param array $input
3433 * Input parameters to be matched.
3434 * @param string $contactType
3435 * @param string $rule
3438 * @param $excludedContactIDs
3439 * An array of ids not to be included in the results.
3440 * @param bool $checkPermissions
3441 * @param int $ruleGroupID
3442 * ID of the rule group to be used if an override is desirable.
3446 public static function getDuplicateContacts($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = array(), $checkPermissions = TRUE, $ruleGroupID = NULL) {
3447 $dedupeParams = CRM_Dedupe_Finder
::formatParams($input, $contactType);
3448 $dedupeParams['check_permission'] = $checkPermissions;
3449 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $contactType, $rule, $excludedContactIDs, $ruleGroupID);
3454 * Get the first duplicate contacts based on the input parameters.
3456 * @param array $input
3457 * Input parameters to be matched.
3458 * @param string $contactType
3459 * @param string $rule
3462 * @param $excludedContactIDs
3463 * An array of ids not to be included in the results.
3464 * @param bool $checkPermissions
3465 * @param int $ruleGroupID
3466 * ID of the rule group to be used if an override is desirable.
3470 public static function getFirstDuplicateContact($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = array(), $checkPermissions = TRUE, $ruleGroupID = NULL) {
3471 $ids = self
::getDuplicateContacts($input, $contactType, $rule, $excludedContactIDs, $checkPermissions, $ruleGroupID);