3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
34 class CRM_Contact_BAO_Contact
extends CRM_Contact_DAO_Contact
{
37 * SQL function used to format the phone_numeric field via trigger.
38 * @see self::triggerInfo()
40 * Note that this is also used by the 4.3 upgrade script.
41 * @see CRM_Upgrade_Incremental_php_FourThree
43 const DROP_STRIP_FUNCTION_43
= "DROP FUNCTION IF EXISTS civicrm_strip_non_numeric";
44 const CREATE_STRIP_FUNCTION_43
= "
45 CREATE FUNCTION civicrm_strip_non_numeric(input VARCHAR(255) CHARACTER SET utf8)
46 RETURNS VARCHAR(255) CHARACTER SET utf8
50 DECLARE output VARCHAR(255) CHARACTER SET utf8 DEFAULT '';
51 DECLARE iterator INT DEFAULT 1;
52 WHILE iterator < (LENGTH(input) + 1) DO
53 IF SUBSTRING(input, iterator, 1) IN ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') THEN
54 SET output = CONCAT(output, SUBSTRING(input, iterator, 1));
56 SET iterator = iterator + 1;
62 * The types of communication preferences.
66 static $_commPrefs = array(
79 static $_greetingTypes = array(
86 * Static field for all the contact information that we can potentially import.
90 static $_importableFields = array();
93 * Static field for all the contact information that we can potentially export.
97 static $_exportableFields = NULL;
102 public function __construct() {
103 parent
::__construct();
107 * Takes an associative array and creates a contact object.
109 * The function extracts all the params it needs to initialize the create a
110 * contact object. the params array could contain additional unused name/value
113 * @param array $params
114 * (reference) an assoc array of name/value pairs.
116 * @return CRM_Contact_BAO_Contact|CRM_Core_Error|NULL
117 * Created or updated contact object or error object.
118 * (error objects are being phased out in favour of exceptions)
120 public static function add(&$params) {
121 $contact = new CRM_Contact_DAO_Contact();
123 if (empty($params)) {
127 // Fix for validate contact sub type CRM-5143.
128 if (isset($params['contact_sub_type'])) {
129 if (empty($params['contact_sub_type'])) {
130 $params['contact_sub_type'] = 'null';
133 if (!CRM_Contact_BAO_ContactType
::isExtendsContactType($params['contact_sub_type'],
134 $params['contact_type'], TRUE
137 // we'll need to fix tests to handle this
139 CRM_Core_Error
::fatal(ts('The Contact Sub Type does not match the Contact type for this record'));
141 if (is_array($params['contact_sub_type'])) {
142 $params['contact_sub_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $params['contact_sub_type']) . CRM_Core_DAO
::VALUE_SEPARATOR
;
145 $params['contact_sub_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. trim($params['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
152 $params['contact_sub_type'] = 'null';
155 // Fixed contact source.
156 if (isset($params['contact_source'])) {
157 $params['source'] = $params['contact_source'];
160 // Fix for preferred communication method.
161 $prefComm = CRM_Utils_Array
::value('preferred_communication_method', $params);
162 if ($prefComm && is_array($prefComm)) {
163 unset($params['preferred_communication_method']);
166 foreach ($prefComm as $k => $v) {
172 $prefComm = $newPref;
173 if (is_array($prefComm) && !empty($prefComm)) {
174 $prefComm = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, array_keys($prefComm)) . CRM_Core_DAO
::VALUE_SEPARATOR
;
175 $contact->preferred_communication_method
= $prefComm;
178 $contact->preferred_communication_method
= '';
182 $allNull = $contact->copyValues($params);
184 $contact->id
= CRM_Utils_Array
::value('contact_id', $params);
186 if ($contact->contact_type
== 'Individual') {
189 // Format individual fields.
190 CRM_Contact_BAO_Individual
::format($params, $contact);
192 elseif ($contact->contact_type
== 'Household') {
193 if (isset($params['household_name'])) {
195 $contact->display_name
= $contact->sort_name
= CRM_Utils_Array
::value('household_name', $params, '');
198 elseif ($contact->contact_type
== 'Organization') {
199 if (isset($params['organization_name'])) {
201 $contact->display_name
= $contact->sort_name
= CRM_Utils_Array
::value('organization_name', $params, '');
205 $privacy = CRM_Utils_Array
::value('privacy', $params);
207 is_array($privacy) &&
211 foreach (self
::$_commPrefs as $name) {
212 $contact->$name = CRM_Utils_Array
::value($name, $privacy, FALSE);
216 // Since hash was required, make sure we have a 0 value for it (CRM-1063).
217 // @todo - does this mean we can remove this block?
218 // Fixed in 1.5 by making hash optional, only do this in create mode, not update.
219 if ((!array_key_exists('hash', $contact) ||
!$contact->hash
) && !$contact->id
) {
221 $contact->hash
= md5(uniqid(rand(), TRUE));
224 // Even if we don't need $employerId, it's important to call getFieldValue() before
225 // the contact is saved because we want the existing value to be cached.
226 // createCurrentEmployerRelationship() needs the old value not the updated one. CRM-10788
227 $employerId = empty($contact->id
) ?
NULL : CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contact->id
, 'employer_id');
232 CRM_Core_BAO_Log
::register($contact->id
,
238 if ($contact->contact_type
== 'Individual' && (isset($params['current_employer']) ||
isset($params['employer_id']))) {
239 // Create current employer.
240 $newEmployer = !empty($params['employer_id']) ?
$params['employer_id'] : CRM_Utils_Array
::value('current_employer', $params);
243 if (empty($params['contact_id'])) {
247 CRM_Contact_BAO_Contact_Utils
::createCurrentEmployerRelationship($contact->id
, $newEmployer, $employerId, $newContact);
251 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($contact->id
, $employerId);
256 // Update cached employer name.
257 if ($contact->contact_type
== 'Organization') {
258 CRM_Contact_BAO_Contact_Utils
::updateCurrentEmployer($contact->id
);
267 * takes an associative array and creates a contact object and all the associated
268 * derived objects (i.e. individual, location, email, phone etc)
270 * This function is invoked from within the web form layer and also from the api layer
272 * @param array $params
273 * (reference ) an assoc array of name/value pairs.
274 * @param bool $fixAddress
275 * If we need to fix address.
276 * @param bool $invokeHooks
277 * If we need to invoke hooks.
279 * @todo explain this parameter
282 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
283 * Created or updated contribution object. We are deprecating returning an error in
284 * favour of exceptions
286 public static function &create(&$params, $fixAddress = TRUE, $invokeHooks = TRUE) {
288 if (empty($params['contact_type']) && empty($params['contact_id'])) {
294 if (!empty($params['contact_id'])) {
295 CRM_Utils_Hook
::pre('edit', $params['contact_type'], $params['contact_id'], $params);
298 CRM_Utils_Hook
::pre('create', $params['contact_type'], NULL, $params);
303 $config = CRM_Core_Config
::singleton();
305 // CRM-6942: set preferred language to the current language if it’s unset (and we’re creating a contact).
306 if (empty($params['contact_id']) && empty($params['preferred_language'])) {
307 $params['preferred_language'] = $config->lcMessages
;
310 // CRM-9739: set greeting & addressee if unset and we’re creating a contact.
311 if (empty($params['contact_id'])) {
312 foreach (self
::$_greetingTypes as $greeting) {
313 if (empty($params[$greeting . '_id'])) {
314 if ($defaultGreetingTypeId
315 = CRM_Contact_BAO_Contact_Utils
::defaultGreeting($params['contact_type'], $greeting)
317 $params[$greeting . '_id'] = $defaultGreetingTypeId;
323 $transaction = new CRM_Core_Transaction();
325 $contact = self
::add($params);
327 // Not dying here is stupid, since we get into weird situation and into a bug that
328 // is impossible to figure out for the user or for us
330 CRM_Core_Error
::fatal();
333 $params['contact_id'] = $contact->id
;
335 if (CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
, 'is_enabled')) {
336 // Enabling multisite causes the contact to be added to the domain group.
337 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
338 if (!empty($domainGroupID)) {
339 if (!empty($params['group']) && is_array($params['group'])) {
340 $params['group'][$domainGroupID] = 1;
343 $params['group'] = array($domainGroupID => 1);
348 if (array_key_exists('group', $params)) {
349 $contactIds = array($params['contact_id']);
350 foreach ($params['group'] as $groupId => $flag) {
352 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
354 elseif ($flag == -1) {
355 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $groupId);
360 // Add location Block data.
361 $blocks = CRM_Core_BAO_Location
::create($params, $fixAddress);
362 foreach ($blocks as $name => $value) {
363 $contact->$name = $value;
366 // Process website(s) if present in params
367 if (!empty($params['website'])) {
368 CRM_Core_BAO_Website
::create($params, $contact->id
);
371 //get userID from session
372 $session = CRM_Core_Session
::singleton();
373 $userID = $session->get('userID');
375 if (!empty($params['note'])) {
376 if (is_array($params['note'])) {
377 foreach ($params['note'] as $note) {
378 $contactId = $contact->id
;
379 if (isset($note['contact_id'])) {
380 $contactId = $note['contact_id'];
382 //if logged in user, overwrite contactId
384 $contactId = $userID;
388 'entity_id' => $contact->id
,
389 'entity_table' => 'civicrm_contact',
390 'note' => $note['note'],
391 'subject' => CRM_Utils_Array
::value('subject', $note),
392 'contact_id' => $contactId,
394 CRM_Core_BAO_Note
::add($noteParams, CRM_Core_DAO
::$_nullArray);
398 $contactId = $contact->id
;
399 if (isset($note['contact_id'])) {
400 $contactId = $note['contact_id'];
402 //if logged in user, overwrite contactId
404 $contactId = $userID;
408 'entity_id' => $contact->id
,
409 'entity_table' => 'civicrm_contact',
410 'note' => $params['note'],
411 'subject' => CRM_Utils_Array
::value('subject', $params),
412 'contact_id' => $contactId,
414 CRM_Core_BAO_Note
::add($noteParams, CRM_Core_DAO
::$_nullArray);
418 // update the UF user_unique_id if that has changed
419 CRM_Core_BAO_UFMatch
::updateUFName($contact->id
);
421 if (!empty($params['custom']) &&
422 is_array($params['custom'])
424 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contact', $contact->id
);
427 // make a civicrm_subscription_history entry only on contact create (CRM-777)
428 if (empty($params['contact_id'])) {
429 $subscriptionParams = array(
430 'contact_id' => $contact->id
,
434 CRM_Contact_BAO_SubscriptionHistory
::create($subscriptionParams);
437 $transaction->commit();
439 // CRM-6367: fetch the right label for contact type’s display
440 $contact->contact_type_display
= CRM_Core_DAO
::getFieldValue(
441 'CRM_Contact_DAO_ContactType',
442 $contact->contact_type
,
447 if (!$config->doNotResetCache
) {
448 // Note: doNotResetCache flag is currently set by import contact process and merging,
449 // since resetting and
450 // rebuilding cache could be expensive (for many contacts). We might come out with better
451 // approach in future.
452 CRM_Contact_BAO_Contact_Utils
::clearContactCaches($contact->id
);
457 CRM_Utils_Hook
::post('edit', $params['contact_type'], $contact->id
, $contact);
460 CRM_Utils_Hook
::post('create', $params['contact_type'], $contact->id
, $contact);
464 // process greetings CRM-4575, cache greetings
465 self
::processGreetings($contact);
471 * Get the display name and image of a contact.
476 * @param bool $includeTypeInReturnParameters
477 * Should type be part of the returned array?
480 * the displayName and contactImage for this contact
482 public static function getDisplayAndImage($id, $includeTypeInReturnParameters = FALSE) {
483 //CRM-14276 added the * on the civicrm_contact table so that we have all the contact info available
485 SELECT civicrm_contact.*,
486 civicrm_email.email as email
488 LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
489 AND civicrm_email.is_primary = 1
490 WHERE civicrm_contact.id = " . CRM_Utils_Type
::escape($id, 'Integer');
491 $dao = new CRM_Core_DAO();
494 $image = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
495 $dao->contact_sub_type
: $dao->contact_type
, FALSE, $id
497 $imageUrl = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
498 $dao->contact_sub_type
: $dao->contact_type
, TRUE, $id
501 // use email if display_name is empty
502 if (empty($dao->display_name
)) {
503 $displayName = $dao->email
;
506 $displayName = $dao->display_name
;
509 CRM_Utils_Hook
::alterDisplayName($displayName, $id, $dao);
511 return $includeTypeInReturnParameters ?
array(
515 $dao->contact_sub_type
,
517 ) : array($displayName, $image, $imageUrl);
523 * Create last viewed link to recently updated contact.
525 * @param array $crudLinkSpec
526 * - action: int, CRM_Core_Action::UPDATE or CRM_Core_Action::VIEW [default: VIEW]
527 * - entity_table: string, eg "civicrm_contact"
531 * NULL if unavailable, or
532 * [path: string, query: string, title: string]
533 * @see CRM_Utils_System::createDefaultCrudLink
535 public function createDefaultCrudLink($crudLinkSpec) {
536 switch ($crudLinkSpec['action']) {
537 case CRM_Core_Action
::VIEW
:
539 'title' => $this->display_name
,
540 'path' => 'civicrm/contact/view',
548 case CRM_Core_Action
::UPDATE
:
550 'title' => $this->display_name
,
551 'path' => 'civicrm/contact/add',
554 'action' => 'update',
564 * Get the values for pseudoconstants for name->value and reverse.
566 * @param array $defaults
567 * (reference) the default values, some of which need to be resolved.
568 * @param bool $reverse
569 * True if we want to resolve the values in the reverse direction (value -> name).
571 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
572 // Hack for birth_date.
573 if (!empty($defaults['birth_date'])) {
574 if (is_array($defaults['birth_date'])) {
575 $defaults['birth_date'] = CRM_Utils_Date
::format($defaults['birth_date'], '-');
579 CRM_Utils_Array
::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id'), $reverse);
580 CRM_Utils_Array
::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'suffix_id'), $reverse);
581 CRM_Utils_Array
::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'), $reverse);
582 CRM_Utils_Array
::lookupValue($defaults, 'communication_style', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'communication_style_id'), $reverse);
584 //lookup value of email/postal greeting, addressee, CRM-4575
585 foreach (self
::$_greetingTypes as $greeting) {
586 $filterCondition = array(
587 'contact_type' => CRM_Utils_Array
::value('contact_type', $defaults),
588 'greeting_type' => $greeting,
590 CRM_Utils_Array
::lookupValue($defaults, $greeting,
591 CRM_Core_PseudoConstant
::greeting($filterCondition), $reverse
595 $blocks = array('address', 'im', 'phone');
596 foreach ($blocks as $name) {
597 if (!array_key_exists($name, $defaults) ||
!is_array($defaults[$name])) {
600 foreach ($defaults[$name] as $count => & $values) {
602 //get location type id.
603 CRM_Utils_Array
::lookupValue($values, 'location_type', CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id'), $reverse);
605 if ($name == 'address') {
606 // FIXME: lookupValue doesn't work for vcard_name
607 if (!empty($values['location_type_id'])) {
608 $vcardNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array('labelColumn' => 'vcard_name'));
609 $values['vcard_name'] = $vcardNames[$values['location_type_id']];
612 if (!CRM_Utils_Array
::lookupValue($values,
614 CRM_Core_PseudoConstant
::country(),
619 CRM_Utils_Array
::lookupValue($values,
621 CRM_Core_PseudoConstant
::countryIsoCode(),
627 // if we find a country id above, we need to restrict it to that country
628 // rather than the list of all countries
630 if (!empty($values['country_id'])) {
631 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($values['country_id']);
634 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvince();
636 if (!CRM_Utils_Array
::lookupValue($values,
644 if (!empty($values['country_id'])) {
645 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($values['country_id'], 'abbreviation');
648 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviation();
650 CRM_Utils_Array
::lookupValue($values,
657 if (!empty($values['state_province_id'])) {
658 $countyList = CRM_Core_PseudoConstant
::countyForState($values['state_province_id']);
661 $countyList = CRM_Core_PseudoConstant
::county();
663 CRM_Utils_Array
::lookupValue($values,
671 CRM_Utils_Array
::lookupValue($values,
673 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id'),
678 if ($name == 'phone') {
679 CRM_Utils_Array
::lookupValue($values,
681 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id'),
686 // Kill the reference.
693 * Fetch object based on array of properties.
695 * @param array $params
696 * (reference ) an assoc array of name/value pairs.
697 * @param array $defaults
698 * (reference ) an assoc array to hold the name / value pairs.
699 * in a hierarchical manner
700 * @param bool $microformat
701 * For location in microformat.
703 * @return CRM_Contact_BAO_Contact
705 public static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
706 if (array_key_exists('contact_id', $params)) {
707 $params['id'] = $params['contact_id'];
709 elseif (array_key_exists('id', $params)) {
710 $params['contact_id'] = $params['id'];
713 $contact = self
::getValues($params, $defaults);
715 unset($params['id']);
717 //get the block information for this contact
718 $entityBlock = array('contact_id' => $params['contact_id']);
719 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock, $microformat);
720 $defaults = array_merge($defaults, $blocks);
721 foreach ($blocks as $block => $value) {
722 $contact->$block = $value;
725 if (!isset($params['noNotes'])) {
726 $contact->notes
= CRM_Core_BAO_Note
::getValues($params, $defaults);
729 if (!isset($params['noRelationships'])) {
730 $contact->relationship
= CRM_Contact_BAO_Relationship
::getValues($params, $defaults);
733 if (!isset($params['noGroups'])) {
734 $contact->groupContact
= CRM_Contact_BAO_GroupContact
::getValues($params, $defaults);
737 if (!isset($params['noWebsite'])) {
738 $contact->website
= CRM_Core_BAO_Website
::getValues($params, $defaults);
745 * Get the display name of a contact.
750 * @return null|string
751 * display name of the contact if found
753 public static function displayName($id) {
756 $displayName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
763 * Delete a contact and all its associated records.
766 * Id of the contact to delete.
767 * @param bool $restore
768 * Whether to actually restore, not delete.
769 * @param bool $skipUndelete
770 * Whether to force contact delete or not.
773 * Was contact deleted?
775 public static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE) {
780 // If trash is disabled in system settings then we always skip
781 if (!CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'contact_undelete', NULL, 1)) {
782 $skipUndelete = TRUE;
785 // make sure we have edit permission for this contact
787 if (($skipUndelete && !CRM_Core_Permission
::check('delete contacts')) ||
788 ($restore && !CRM_Core_Permission
::check('access deleted contacts'))
794 // Restrict contact to be delete if contact has financial trxns
796 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent(array($id), $error)) {
800 // make sure this contact_id does not have any membership types
801 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
804 'member_of_contact_id'
806 if ($membershipTypeID) {
810 $contact = new CRM_Contact_DAO_Contact();
812 if (!$contact->find(TRUE)) {
816 $contactType = $contact->contact_type
;
817 // currently we only clear employer cache.
818 // we are now deleting inherited membership if any.
819 if ($contact->contact_type
== 'Organization') {
820 $action = $restore ? CRM_Core_Action
::ENABLE
: CRM_Core_Action
::DISABLE
;
821 $relationshipDtls = CRM_Contact_BAO_Relationship
::getRelationship($id);
822 if (!empty($relationshipDtls)) {
823 foreach ($relationshipDtls as $rId => $details) {
824 CRM_Contact_BAO_Relationship
::disableEnableRelationship($rId, $action);
827 CRM_Contact_BAO_Contact_Utils
::clearAllEmployee($id);
831 return self
::contactTrashRestore($contact, TRUE);
834 // start a new transaction
835 $transaction = new CRM_Core_Transaction();
838 CRM_Utils_Hook
::pre('delete', $contactType, $id, CRM_Core_DAO
::$_nullArray);
840 //delete billing address if exists.
841 CRM_Contribute_BAO_Contribution
::deleteAddress(NULL, $id);
843 // delete the log entries since we dont have triggers enabled as yet
844 $logDAO = new CRM_Core_DAO_Log();
845 $logDAO->entity_table
= 'civicrm_contact';
846 $logDAO->entity_id
= $id;
849 // delete contact participants CRM-12155
850 CRM_Event_BAO_Participant
::deleteContactParticipant($id);
852 // delete contact contributions CRM-12155
853 CRM_Contribute_BAO_Contribution
::deleteContactContribution($id);
855 // do activity cleanup, CRM-5604
856 CRM_Activity_BAO_Activity
::cleanupActivity($id);
858 // delete all notes related to contact
859 CRM_Core_BAO_Note
::cleanContactNotes($id);
861 // delete cases related to contact
862 $contactCases = CRM_Case_BAO_Case
::retrieveCaseIdsByContactId($id);
863 if (!empty($contactCases)) {
864 foreach ($contactCases as $caseId) {
865 //check if case is associate with other contact or not.
866 $caseContactId = CRM_Case_BAO_Case
::getCaseClients($caseId);
867 if (count($caseContactId) <= 1) {
868 CRM_Case_BAO_Case
::deleteCase($caseId);
876 self
::contactTrashRestore($contact);
879 //delete the contact id from recently view
880 CRM_Utils_Recent
::delContact($id);
882 // Update the group contact cache
884 CRM_Contact_BAO_GroupContactCache
::remove();
887 CRM_Contact_BAO_GroupContactCache
::removeContact($id);
890 // delete any dupe cache entry
891 CRM_Core_BAO_PrevNextCache
::deleteItem($id);
893 $transaction->commit();
896 CRM_Utils_Hook
::post('delete', $contactType, $contact->id
, $contact);
899 // also reset the DB_DO global array so we can reuse the memory
900 // http://issues.civicrm.org/jira/browse/CRM-4387
901 CRM_Core_DAO
::freeResult();
907 * Delete the image of a contact.
913 * Was contact image deleted?
915 public static function deleteContactImage($id) {
920 UPDATE civicrm_contact
923 CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
928 * Return relative path.
930 * @todo make this a method of $config->userSystem (i.e. UF classes) rather than a static function
932 * @param string $absolutePath
936 * Relative url of uploaded image
938 public static function getRelativePath($absolutePath) {
939 $relativePath = NULL;
940 $config = CRM_Core_Config
::singleton();
941 if ($config->userFramework
== 'Joomla') {
942 $userFrameworkBaseURL = trim(str_replace('/administrator/', '', $config->userFrameworkBaseURL
));
943 $customFileUploadDirectory = strstr(str_replace('\\', '/', $absolutePath), '/media');
944 $relativePath = $userFrameworkBaseURL . $customFileUploadDirectory;
946 elseif ($config->userSystem
->is_drupal
== '1') {
947 //ideally we would do a bigger re-factoring & move the getRelativePath onto the UF class
948 $rootPath = $config->userSystem
->cmsRootPath();
949 $baseUrl = $config->userFrameworkBaseURL
;
951 //format url for language negotiation, CRM-7135
952 $baseUrl = CRM_Utils_System
::languageNegotiationURL($baseUrl, FALSE, TRUE);
954 $relativePath = str_replace("{$rootPath}/",
956 str_replace('\\', '/', $absolutePath)
959 elseif ($config->userFramework
== 'WordPress') {
960 $userFrameworkBaseURL = trim(str_replace('/wp-admin/', '', $config->userFrameworkBaseURL
));
961 $customFileUploadDirectory = strstr(str_replace('\\', '/', $absolutePath), '/wp-content/');
962 $relativePath = $userFrameworkBaseURL . $customFileUploadDirectory;
965 return $relativePath;
969 * Return proportional height and width of the image.
971 * @param int $imageWidth
974 * @param int $imageHeight
978 * Thumb dimension of image
980 public static function getThumbSize($imageWidth, $imageHeight) {
982 if ($imageWidth && $imageHeight) {
983 $imageRatio = $imageWidth / $imageHeight;
988 if ($imageRatio > 1) {
989 $imageThumbWidth = $thumbWidth;
990 $imageThumbHeight = round($thumbWidth / $imageRatio);
993 $imageThumbHeight = $thumbWidth;
994 $imageThumbWidth = round($thumbWidth * $imageRatio);
997 return array($imageThumbWidth, $imageThumbHeight);
1001 * Validate type of contact image.
1003 * @param array $params
1004 * @param string $imageIndex
1005 * Index of image field.
1006 * @param string $statusMsg
1007 * Status message to be set after operation.
1008 * @param string $opType
1009 * Type of operation like fatal, bounce etc.
1012 * true if valid image extension
1014 public static function processImageParams(
1016 $imageIndex = 'image_URL',
1030 if (in_array($params[$imageIndex]['type'], $mimeType)) {
1031 $photo = basename($params[$imageIndex]['name']);
1032 $params[$imageIndex] = CRM_Utils_System
::url('civicrm/contact/imagefile', 'photo=' . $photo, TRUE, NULL, TRUE, TRUE);
1036 unset($params[$imageIndex]);
1038 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
1040 if ($opType == 'status') {
1041 CRM_Core_Session
::setStatus($statusMsg, 'Sorry', 'error');
1043 // FIXME: additional support for fatal, bounce etc could be added.
1049 * Extract contact id from url for deleting contact image.
1051 public static function processImage() {
1053 $action = CRM_Utils_Request
::retrieve('action', 'String');
1054 $cid = CRM_Utils_Request
::retrieve('cid', 'Positive');
1055 // retrieve contact id in case of Profile context
1056 $id = CRM_Utils_Request
::retrieve('id', 'Positive');
1057 $cid = $cid ?
$cid : $id;
1058 if ($action & CRM_Core_Action
::DELETE
) {
1059 if (CRM_Utils_Request
::retrieve('confirmed', 'Boolean')) {
1060 CRM_Contact_BAO_Contact
::deleteContactImage($cid);
1061 CRM_Core_Session
::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
1062 $session = CRM_Core_Session
::singleton();
1063 $toUrl = $session->popUserContext();
1064 CRM_Utils_System
::redirect($toUrl);
1070 * Function to set is_delete true or restore deleted contact.
1072 * @param CRM_Contact_DAO_Contact $contact
1073 * Contact DAO object.
1074 * @param bool $restore
1075 * True to set the is_delete = 1 else false to restore deleted contact,
1076 * i.e. is_delete = 0
1080 public static function contactTrashRestore($contact, $restore = FALSE) {
1081 $updateParams = array(
1082 'id' => $contact->id
,
1083 'is_deleted' => $restore ?
0 : 1,
1086 CRM_Utils_Hook
::pre('update', $contact->contact_type
, $contact->id
, $updateParams);
1088 $params = array(1 => array($contact->id
, 'Integer'));
1090 $query = "DELETE FROM civicrm_uf_match WHERE contact_id = %1";
1091 CRM_Core_DAO
::executeQuery($query, $params);
1094 $contact->copyValues($updateParams);
1097 CRM_Utils_Hook
::post('update', $contact->contact_type
, $contact->id
, $contact);
1103 * Get contact type for a contact.
1106 * Id of the contact whose contact type is needed.
1109 * contact_type if $id found else null ""
1111 public static function getContactType($id) {
1112 return CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1116 * Get contact sub type for a contact.
1119 * Id of the contact whose contact sub type is needed.
1121 * @param string $implodeDelimiter
1124 * contact_sub_type if $id found else null ""
1126 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1127 $subtype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1129 return $implodeDelimiter ?
NULL : array();
1132 $subtype = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($subtype, CRM_Core_DAO
::VALUE_SEPARATOR
));
1134 if ($implodeDelimiter) {
1135 $subtype = implode($implodeDelimiter, $subtype);
1141 * Get pair of contact-type and sub-type for a contact.
1144 * Id of the contact whose contact sub/contact type is needed.
1148 public static function getContactTypes($id) {
1149 $params = array('id' => $id);
1151 $contact = CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact',
1154 array('contact_type', 'contact_sub_type')
1158 $contactTypes = array();
1159 if ($contact->contact_sub_type
) {
1160 $contactTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($contact->contact_sub_type
, CRM_Core_DAO
::VALUE_SEPARATOR
));
1162 array_unshift($contactTypes, $contact->contact_type
);
1164 return $contactTypes;
1167 CRM_Core_Error
::fatal();
1172 * Combine all the importable fields from the lower levels object.
1174 * The ordering is important, since currently we do not have a weight
1175 * scheme. Adding weight is super important
1177 * @param int|string $contactType contact Type
1178 * @param bool $status
1179 * Status is used to manipulate first title.
1180 * @param bool $showAll
1181 * If true returns all fields (includes disabled fields).
1182 * @param bool $isProfile
1183 * If its profile mode.
1184 * @param bool $checkPermission
1185 * If false, do not include permissioning clause (for custom data).
1187 * @param bool $withMultiCustomFields
1190 * array of importable Fields
1192 public static function importableFields(
1193 $contactType = 'Individual',
1197 $checkPermission = TRUE,
1198 $withMultiCustomFields = FALSE
1200 if (empty($contactType)) {
1201 $contactType = 'All';
1204 $cacheKeyString = "importableFields $contactType";
1205 $cacheKeyString .= $status ?
'_1' : '_0';
1206 $cacheKeyString .= $showAll ?
'_1' : '_0';
1207 $cacheKeyString .= $isProfile ?
'_1' : '_0';
1208 $cacheKeyString .= $checkPermission ?
'_1' : '_0';
1210 $fields = CRM_Utils_Array
::value($cacheKeyString, self
::$_importableFields);
1213 // check if we can retrieve from database cache
1214 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1218 $fields = CRM_Contact_DAO_Contact
::import();
1220 // get the fields thar are meant for contact types
1221 if (in_array($contactType, array(
1227 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1230 $locationFields = array_merge(CRM_Core_DAO_Address
::import(),
1231 CRM_Core_DAO_Phone
::import(),
1232 CRM_Core_DAO_Email
::import(),
1233 CRM_Core_DAO_IM
::import(TRUE),
1234 CRM_Core_DAO_OpenID
::import()
1237 $locationFields = array_merge($locationFields,
1238 CRM_Core_BAO_CustomField
::getFieldsForImport('Address',
1246 foreach ($locationFields as $key => $field) {
1247 $locationFields[$key]['hasLocationType'] = TRUE;
1250 $fields = array_merge($fields, $locationFields);
1252 $fields = array_merge($fields, CRM_Contact_DAO_Contact
::import());
1253 $fields = array_merge($fields, CRM_Core_DAO_Note
::import());
1256 $fields = array_merge($fields, CRM_Core_DAO_Website
::import());
1257 $fields['url']['hasWebsiteType'] = TRUE;
1259 if ($contactType != 'All') {
1260 $fields = array_merge($fields,
1261 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType,
1266 $withMultiCustomFields
1269 //unset the fields, which are not related to their
1271 $commonValues = array(
1272 'Individual' => array(
1276 'organization_name',
1278 'Household' => array(
1288 'organization_name',
1296 'Organization' => array(
1311 foreach ($commonValues[$contactType] as $value) {
1312 unset($fields[$value]);
1316 foreach (array('Individual', 'Household', 'Organization') as $type) {
1317 $fields = array_merge($fields,
1318 CRM_Core_BAO_CustomField
::getFieldsForImport($type,
1323 $withMultiCustomFields
1330 $fields = array_merge($fields, array(
1332 'title' => ts('Group(s)'),
1336 'title' => ts('Tag(s)'),
1340 'title' => ts('Note(s)'),
1343 'communication_style_id' => array(
1344 'title' => ts('Communication Style'),
1345 'name' => 'communication_style_id',
1350 //Sorting fields in alphabetical order(CRM-1507)
1351 $fields = CRM_Utils_Array
::crmArraySortByField($fields, 'title');
1353 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1356 self
::$_importableFields[$cacheKeyString] = $fields;
1360 $fields = array_merge(array('do_not_import' => array('title' => ts('- do not import -'))),
1361 self
::$_importableFields[$cacheKeyString]
1365 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1366 self
::$_importableFields[$cacheKeyString]
1374 * Combine all the exportable fields from the lower levels object.
1376 * Currently we are using importable fields as exportable fields
1378 * @param int|string $contactType contact Type
1379 * @param bool $status
1380 * True while exporting primary contacts.
1381 * @param bool $export
1382 * True when used during export.
1383 * @param bool $search
1384 * True when used during search, might conflict with export param?.
1386 * @param bool $withMultiRecord
1389 * array of exportable Fields
1391 public static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE) {
1392 if (empty($contactType)) {
1393 $contactType = 'All';
1396 $cacheKeyString = "exportableFields $contactType";
1397 $cacheKeyString .= $export ?
'_1' : '_0';
1398 $cacheKeyString .= $status ?
'_1' : '_0';
1399 $cacheKeyString .= $search ?
'_1' : '_0';
1400 //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
1401 //calculates custom fields takes into account the logged in user & caches that for all users
1402 //as an interim fix we will cache the fields by contact
1403 $cacheKeyString .= '_' . CRM_Core_Session
::getLoggedInContactID();
1405 if (!self
::$_exportableFields ||
!CRM_Utils_Array
::value($cacheKeyString, self
::$_exportableFields)) {
1406 if (!self
::$_exportableFields) {
1407 self
::$_exportableFields = array();
1410 // check if we can retrieve from database cache
1411 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1414 $fields = CRM_Contact_DAO_Contact
::export();
1416 // The fields are meant for contact types.
1417 if (in_array($contactType, array(
1424 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1426 // add current employer for individuals
1427 $fields = array_merge($fields, array(
1428 'current_employer' =>
1430 'name' => 'organization_name',
1431 'title' => ts('Current Employer'),
1435 $locationType = array(
1436 'location_type' => array(
1437 'name' => 'location_type',
1438 'where' => 'civicrm_location_type.name',
1439 'title' => ts('Location Type'),
1443 $IMProvider = array(
1444 'im_provider' => array(
1445 'name' => 'im_provider',
1446 'where' => 'civicrm_im.provider_id',
1447 'title' => ts('IM Provider'),
1451 $locationFields = array_merge($locationType,
1452 CRM_Core_DAO_Address
::export(),
1453 CRM_Core_DAO_Phone
::export(),
1454 CRM_Core_DAO_Email
::export(),
1456 CRM_Core_DAO_IM
::export(TRUE),
1457 CRM_Core_DAO_OpenID
::export()
1460 $locationFields = array_merge($locationFields,
1461 CRM_Core_BAO_CustomField
::getFieldsForImport('Address')
1464 foreach ($locationFields as $key => $field) {
1465 $locationFields[$key]['hasLocationType'] = TRUE;
1468 $fields = array_merge($fields, $locationFields);
1471 $fields = array_merge($fields,
1472 CRM_Core_DAO_Worldregion
::export()
1475 $fields = array_merge($fields,
1476 CRM_Contact_DAO_Contact
::export()
1480 $fields = array_merge($fields, CRM_Core_DAO_Website
::export());
1482 if ($contactType != 'All') {
1483 $fields = array_merge($fields,
1484 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType, $status, FALSE, $search, TRUE, $withMultiRecord)
1493 $fields = array_merge($fields,
1494 CRM_Core_BAO_CustomField
::getFieldsForImport($type, FALSE, FALSE, $search, TRUE, $withMultiRecord)
1501 $fields = array_merge($fields, array(
1503 'title' => ts('Group(s)'),
1507 'title' => ts('Tag(s)'),
1511 'title' => ts('Note(s)'),
1517 $fields = array_merge($fields, array(
1519 'title' => ts('Group(s)'),
1523 'title' => ts('Tag(s)'),
1527 'title' => ts('Note(s)'),
1533 //Sorting fields in alphabetical order(CRM-1507)
1534 foreach ($fields as $k => $v) {
1535 $sortArray[$k] = CRM_Utils_Array
::value('title', $v);
1538 $fields = array_merge($sortArray, $fields);
1539 //unset the field which are not related to their contact type.
1540 if ($contactType != 'All') {
1541 $commonValues = array(
1542 'Individual' => array(
1546 'organization_name',
1547 'email_greeting_custom',
1548 'postal_greeting_custom',
1551 'Household' => array(
1561 'organization_name',
1569 'email_greeting_custom',
1570 'postal_greeting_custom',
1575 'Organization' => array(
1586 'email_greeting_custom',
1587 'postal_greeting_custom',
1597 foreach ($commonValues[$contactType] as $value) {
1598 unset($fields[$value]);
1602 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1604 self
::$_exportableFields[$cacheKeyString] = $fields;
1608 $fields = self
::$_exportableFields[$cacheKeyString];
1611 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1612 self
::$_exportableFields[$cacheKeyString]
1620 * Get the all contact details (Hierarchical).
1622 * @param int $contactId
1624 * @param array $fields
1630 public static function getHierContactDetails($contactId, &$fields) {
1631 $params = array(array('contact_id', '=', $contactId, 0, 0));
1634 $returnProperties = self
::makeHierReturnProperties($fields, $contactId);
1636 // We don't know the contents of return properties, but we need the lower
1637 // level ids of the contact so add a few fields.
1638 $returnProperties['first_name'] = 1;
1639 $returnProperties['organization_name'] = 1;
1640 $returnProperties['household_name'] = 1;
1641 $returnProperties['contact_type'] = 1;
1642 $returnProperties['contact_sub_type'] = 1;
1643 return list($query, $options) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, $options);
1647 * Given a set of flat profile style field names, create a hierarchy.
1649 * This is for the query to use, create the right sql.
1652 * @param int $contactId
1656 * A hierarchical property tree if appropriate
1658 public static function &makeHierReturnProperties($fields, $contactId = NULL) {
1659 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1661 $returnProperties = array();
1663 $multipleFields = array('website' => 'url');
1664 foreach ($fields as $name => $dontCare) {
1665 if (strpos($name, '-') !== FALSE) {
1666 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $name, 3);
1668 if (!in_array($fieldName, $multipleFields)) {
1669 if ($id == 'Primary') {
1670 $locationTypeName = 1;
1673 $locationTypeName = CRM_Utils_Array
::value($id, $locationTypes);
1674 if (!$locationTypeName) {
1679 if (empty($returnProperties['location'])) {
1680 $returnProperties['location'] = array();
1682 if (empty($returnProperties['location'][$locationTypeName])) {
1683 $returnProperties['location'][$locationTypeName] = array();
1684 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1686 if (in_array($fieldName, array(
1694 $returnProperties['location'][$locationTypeName][$fieldName . '-' . $type] = 1;
1697 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1700 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1701 $returnProperties['location'][$locationTypeName][substr($fieldName, 8)] = 1;
1704 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1708 $returnProperties['website'][$id][$fieldName] = 1;
1712 $returnProperties[$name] = 1;
1716 return $returnProperties;
1720 * Return the primary location type of a contact.
1722 * $params int $contactId contact_id
1723 * $params boolean $isPrimaryExist if true, return primary contact location type otherwise null
1724 * $params boolean $skipDefaultPriamry if true, return primary contact location type otherwise null
1726 * @param int $contactId
1727 * @param bool $skipDefaultPriamry
1728 * @param null $block
1731 * $locationType location_type_id
1733 public static function getPrimaryLocationType($contactId, $skipDefaultPriamry = FALSE, $block = NULL) {
1735 $entityBlock = array('contact_id' => $contactId);
1736 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock);
1737 foreach ($blocks[$block] as $key => $value) {
1738 if (!empty($value['is_primary'])) {
1739 $locationType = CRM_Utils_Array
::value('location_type_id', $value);
1746 IF ( civicrm_email.location_type_id IS NULL,
1747 IF ( civicrm_address.location_type_id IS NULL,
1748 IF ( civicrm_phone.location_type_id IS NULL,
1749 IF ( civicrm_im.location_type_id IS NULL,
1750 IF ( civicrm_openid.location_type_id IS NULL, null, civicrm_openid.location_type_id)
1751 ,civicrm_im.location_type_id)
1752 ,civicrm_phone.location_type_id)
1753 ,civicrm_address.location_type_id)
1754 ,civicrm_email.location_type_id) as locationType
1755 FROM civicrm_contact
1756 LEFT JOIN civicrm_email ON ( civicrm_email.is_primary = 1 AND civicrm_email.contact_id = civicrm_contact.id )
1757 LEFT JOIN civicrm_address ON ( civicrm_address.is_primary = 1 AND civicrm_address.contact_id = civicrm_contact.id)
1758 LEFT JOIN civicrm_phone ON ( civicrm_phone.is_primary = 1 AND civicrm_phone.contact_id = civicrm_contact.id)
1759 LEFT JOIN civicrm_im ON ( civicrm_im.is_primary = 1 AND civicrm_im.contact_id = civicrm_contact.id)
1760 LEFT JOIN civicrm_openid ON ( civicrm_openid.is_primary = 1 AND civicrm_openid.contact_id = civicrm_contact.id)
1761 WHERE civicrm_contact.id = %1 ";
1763 $params = array(1 => array($contactId, 'Integer'));
1765 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1767 $locationType = NULL;
1768 if ($dao->fetch()) {
1769 $locationType = $dao->locationType
;
1772 if (isset($locationType)) {
1773 return $locationType;
1775 elseif ($skipDefaultPriamry) {
1776 // if there is no primary contact location then return null
1780 // if there is no primart contact location, then return default
1781 // location type of the system
1782 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
1783 return $defaultLocationType->id
;
1788 * Get the display name, primary email and location type of a contact.
1791 * Id of the contact.
1794 * Array of display_name, email if found, do_not_email or (null,null,null)
1796 public static function getContactDetails($id) {
1797 // check if the contact type
1798 $contactType = self
::getContactType($id);
1800 $nameFields = ($contactType == 'Individual') ?
"civicrm_contact.first_name, civicrm_contact.last_name, civicrm_contact.display_name" : "civicrm_contact.display_name";
1803 SELECT $nameFields, civicrm_email.email, civicrm_contact.do_not_email, civicrm_email.on_hold, civicrm_contact.is_deceased
1804 FROM civicrm_contact LEFT JOIN civicrm_email ON (civicrm_contact.id = civicrm_email.contact_id)
1805 WHERE civicrm_contact.id = %1
1806 ORDER BY civicrm_email.is_primary DESC";
1807 $params = array(1 => array($id, 'Integer'));
1808 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
1810 if ($dao->fetch()) {
1811 if ($contactType == 'Individual') {
1812 if ($dao->first_name ||
$dao->last_name
) {
1813 $name = "{$dao->first_name} {$dao->last_name}";
1816 $name = $dao->display_name
;
1820 $name = $dao->display_name
;
1822 $email = $dao->email
;
1823 $doNotEmail = $dao->do_not_email ?
TRUE : FALSE;
1824 $onHold = $dao->on_hold ?
TRUE : FALSE;
1825 $isDeceased = $dao->is_deceased ?
TRUE : FALSE;
1826 return array($name, $email, $doNotEmail, $onHold, $isDeceased);
1828 return array(NULL, NULL, NULL, NULL, NULL);
1832 * Add/edit/register contacts through profile.
1834 * @param array $params
1835 * Array of profile fields to be edited/added.
1836 * @param array $fields
1837 * Array of fields from UFGroup.
1838 * @param int $contactID
1839 * Id of the contact to be edited/added.
1840 * @param int $addToGroupID
1841 * Specifies the default group to which contact is added.
1842 * @param int $ufGroupId
1843 * Uf group id (profile id).
1844 * @param string $ctype
1845 * @param bool $visibility
1846 * Basically lets us know where this request is coming from.
1847 * if via a profile from web, we restrict what groups are changed
1850 * contact id created/edited
1852 public static function createProfileContact(
1856 $addToGroupID = NULL,
1861 // add ufGroupID to params array ( CRM-2012 )
1863 $params['uf_group_id'] = $ufGroupId;
1868 // If a user has logged in, or accessed via a checksum
1869 // Then deliberately 'blanking' a value in the profile should remove it from their record
1870 $session = CRM_Core_Session
::singleton();
1871 $params['updateBlankLocInfo'] = TRUE;
1872 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0) {
1873 $params['updateBlankLocInfo'] = FALSE;
1877 CRM_Utils_Hook
::pre('edit', 'Profile', $contactID, $params);
1881 CRM_Utils_Hook
::pre('create', 'Profile', NULL, $params);
1884 list($data, $contactDetails) = self
::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
1886 // manage is_opt_out
1887 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
1888 $wasOptOut = CRM_Utils_Array
::value('is_opt_out', $contactDetails, FALSE);
1889 $isOptOut = CRM_Utils_Array
::value('is_opt_out', $params, FALSE);
1890 $data['is_opt_out'] = $isOptOut;
1891 // on change, create new civicrm_subscription_history entry
1892 if (($wasOptOut != $isOptOut) && !empty($contactDetails['contact_id'])) {
1894 'contact_id' => $contactDetails['contact_id'],
1895 'status' => $isOptOut ?
'Removed' : 'Added',
1898 CRM_Contact_BAO_SubscriptionHistory
::create($shParams);
1902 $contact = self
::create($data);
1904 // contact is null if the profile does not have any contact fields
1906 $contactID = $contact->id
;
1909 if (empty($contactID)) {
1910 CRM_Core_Error
::fatal('Cannot proceed without a valid contact id');
1913 // Process group and tag
1914 if (!empty($fields['group'])) {
1916 // this for sure means we are coming in via profile since i added it to fix
1917 // removing contacts from user groups -- lobo
1921 CRM_Contact_BAO_GroupContact
::create($params['group'], $contactID, $visibility, $method);
1924 if (!empty($fields['tag'])) {
1925 CRM_Core_BAO_EntityTag
::create($params['tag'], 'civicrm_contact', $contactID);
1928 //to add profile in default group
1929 if (is_array($addToGroupID)) {
1930 $contactIds = array($contactID);
1931 foreach ($addToGroupID as $groupId) {
1932 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
1935 elseif ($addToGroupID) {
1936 $contactIds = array($contactID);
1937 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $addToGroupID);
1940 // reset the group contact cache for this group
1941 CRM_Contact_BAO_GroupContactCache
::remove();
1944 CRM_Utils_Hook
::post('edit', 'Profile', $contactID, $params);
1947 CRM_Utils_Hook
::post('create', 'Profile', $contactID, $params);
1953 * Format profile contact parameters.
1955 * @param array $params
1957 * @param int $contactID
1958 * @param int $ufGroupId
1959 * @param null $ctype
1960 * @param bool $skipCustom
1964 public static function formatProfileContactParams(
1973 $data = $contactDetails = array();
1975 // get the contact details (hier)
1977 list($details, $options) = self
::getHierContactDetails($contactID, $fields);
1979 $contactDetails = $details[$contactID];
1980 $data['contact_type'] = CRM_Utils_Array
::value('contact_type', $contactDetails);
1981 $data['contact_sub_type'] = CRM_Utils_Array
::value('contact_sub_type', $contactDetails);
1984 //we should get contact type only if contact
1986 $data['contact_type'] = CRM_Core_BAO_UFField
::getProfileType($ufGroupId);
1988 //special case to handle profile with only contact fields
1989 if ($data['contact_type'] == 'Contact') {
1990 $data['contact_type'] = 'Individual';
1992 elseif (CRM_Contact_BAO_ContactType
::isaSubType($data['contact_type'])) {
1993 $data['contact_type'] = CRM_Contact_BAO_ContactType
::getBasicType($data['contact_type']);
1997 $data['contact_type'] = $ctype;
2000 $data['contact_type'] = 'Individual';
2004 //fix contact sub type CRM-5125
2005 if (array_key_exists('contact_sub_type', $params) &&
2006 !empty($params['contact_sub_type'])
2008 $data['contact_sub_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, (array) $params['contact_sub_type']) . CRM_Core_DAO
::VALUE_SEPARATOR
;
2010 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
2011 !empty($params['contact_sub_type_hidden'])
2013 // if profile was used, and had any subtype, we obtain it from there
2014 //CRM-13596 - add to existing contact types, rather than overwriting
2015 $data_contact_sub_type_arr = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($data['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
));
2016 if (!in_array($params['contact_sub_type_hidden'], $data_contact_sub_type_arr)) {
2017 $data['contact_sub_type'] = $data['contact_sub_type'] . implode(CRM_Core_DAO
::VALUE_SEPARATOR
, (array) $params['contact_sub_type_hidden']) . CRM_Core_DAO
::VALUE_SEPARATOR
;
2021 if ($ctype == 'Organization') {
2022 $data['organization_name'] = CRM_Utils_Array
::value('organization_name', $contactDetails);
2024 elseif ($ctype == 'Household') {
2025 $data['household_name'] = CRM_Utils_Array
::value('household_name', $contactDetails);
2028 $locationType = array();
2033 $data['contact_id'] = $contactID;
2034 $primaryLocationType = self
::getPrimaryLocationType($contactID);
2037 $defaultLocation = CRM_Core_BAO_LocationType
::getDefault();
2038 $defaultLocationId = $defaultLocation->id
;
2041 // get the billing location type
2042 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
2043 $billingLocationTypeId = array_search('Billing', $locationTypes);
2045 $blocks = array('email', 'phone', 'im', 'openid');
2047 $multiplFields = array('url');
2048 // prevent overwritten of formatted array, reset all block from
2049 // params if it is not in valid format (since import pass valid format)
2050 foreach ($blocks as $blk) {
2051 if (array_key_exists($blk, $params) &&
2052 !is_array($params[$blk])
2054 unset($params[$blk]);
2058 $primaryPhoneLoc = NULL;
2059 $session = CRM_Core_Session
::singleton();
2060 foreach ($params as $key => $value) {
2061 $fieldName = $locTypeId = $typeId = NULL;
2062 list($fieldName, $locTypeId, $typeId) = CRM_Utils_System
::explode('-', $key, 3);
2064 //store original location type id
2065 $actualLocTypeId = $locTypeId;
2067 if ($locTypeId == 'Primary') {
2069 if (in_array($fieldName, $blocks)) {
2070 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, $fieldName);
2073 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, 'address');
2075 $primaryLocationType = $locTypeId;
2078 $locTypeId = $defaultLocationId;
2082 if (is_numeric($locTypeId) &&
2083 !in_array($fieldName, $multiplFields) &&
2084 substr($fieldName, 0, 7) != 'custom_'
2086 $index = $locTypeId;
2088 if (is_numeric($typeId)) {
2089 $index .= '-' . $typeId;
2091 if (!in_array($index, $locationType)) {
2092 $locationType[$count] = $index;
2096 $loc = CRM_Utils_Array
::key($index, $locationType);
2098 $blockName = in_array($fieldName, $blocks) ?
$fieldName : 'address';
2100 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
2102 //set is_billing true, for location type "Billing"
2103 if ($locTypeId == $billingLocationTypeId) {
2104 $data[$blockName][$loc]['is_billing'] = 1;
2108 //get the primary location type
2109 if ($locTypeId == $primaryLocationType) {
2110 $data[$blockName][$loc]['is_primary'] = 1;
2113 elseif ($locTypeId == $defaultLocationId) {
2114 $data[$blockName][$loc]['is_primary'] = 1;
2117 if (in_array($fieldName, array('phone'))) {
2119 $data['phone'][$loc]['phone_type_id'] = $typeId;
2122 $data['phone'][$loc]['phone_type_id'] = '';
2124 $data['phone'][$loc]['phone'] = $value;
2126 //special case to handle primary phone with different phone types
2127 // in this case we make first phone type as primary
2128 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
2129 $primaryPhoneLoc = $loc;
2132 if ($loc != $primaryPhoneLoc) {
2133 unset($data['phone'][$loc]['is_primary']);
2136 elseif ($fieldName == 'phone_ext') {
2137 $data['phone'][$loc]['phone_ext'] = $value;
2139 elseif ($fieldName == 'email') {
2140 $data['email'][$loc]['email'] = $value;
2142 elseif ($fieldName == 'im') {
2143 if (isset($params[$key . '-provider_id'])) {
2144 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
2146 if (strpos($key, '-provider_id') !== FALSE) {
2147 $data['im'][$loc]['provider_id'] = $params[$key];
2150 $data['im'][$loc]['name'] = $value;
2153 elseif ($fieldName == 'openid') {
2154 $data['openid'][$loc]['openid'] = $value;
2157 if ($fieldName === 'state_province') {
2159 if (is_numeric($value) && ((int ) $value) >= 1000) {
2160 $data['address'][$loc]['state_province_id'] = $value;
2162 elseif (empty($value)) {
2163 $data['address'][$loc]['state_province_id'] = '';
2166 $data['address'][$loc]['state_province'] = $value;
2169 elseif ($fieldName === 'country') {
2171 if (is_numeric($value) && ((int ) $value) >= 1000
2173 $data['address'][$loc]['country_id'] = $value;
2175 elseif (empty($value)) {
2176 $data['address'][$loc]['country_id'] = '';
2179 $data['address'][$loc]['country'] = $value;
2182 elseif ($fieldName === 'county') {
2183 $data['address'][$loc]['county_id'] = $value;
2185 elseif ($fieldName == 'address_name') {
2186 $data['address'][$loc]['name'] = $value;
2188 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2189 $data['address'][$loc][substr($fieldName, 8)] = $value;
2192 $data['address'][$loc][$fieldName] = $value;
2197 if (substr($key, 0, 4) === 'url-') {
2198 $websiteField = explode('-', $key);
2199 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
2200 $data['website'][$websiteField[1]]['url'] = $value;
2202 elseif (in_array($key, self
::$_greetingTypes, TRUE)) {
2203 //save email/postal greeting and addressee values if any, CRM-4575
2204 $data[$key . '_id'] = $value;
2206 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($key))) {
2207 // for autocomplete transfer hidden value instead of label
2208 if ($params[$key] && isset($params[$key . '_id'])) {
2209 $value = $params[$key . '_id'];
2212 // we need to append time with date
2213 if ($params[$key] && isset($params[$key . '_time'])) {
2214 $value .= ' ' . $params[$key . '_time'];
2217 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
2218 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 &&
2219 ($value == '' ||
!isset($value))
2225 if (!empty($params['customRecordValues'])) {
2226 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2227 foreach ($params['customRecordValues'] as $recId => $customFields) {
2228 if (is_array($customFields) && !empty($customFields)) {
2229 foreach ($customFields as $customFieldName) {
2230 if ($customFieldName == $key) {
2240 //CRM-13596 - check for contact_sub_type_hidden first
2241 if (array_key_exists('contact_sub_type_hidden', $params)) {
2242 $type = $params['contact_sub_type_hidden'];
2245 $type = $data['contact_type'];
2246 if (!empty($data['contact_sub_type'])) {
2247 $type = $data['contact_sub_type'];
2248 $type = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($type, CRM_Core_DAO
::VALUE_SEPARATOR
));
2249 // generally a contact even if, has multiple subtypes the parent-type is going to be one only
2250 // and since formatCustomField() would be interested in parent type, lets consider only one subtype
2251 // as the results going to be same.
2256 CRM_Core_BAO_CustomField
::formatCustomField($customFieldId,
2264 elseif ($key == 'edit') {
2268 if ($key == 'location') {
2269 foreach ($value as $locationTypeId => $field) {
2270 foreach ($field as $block => $val) {
2271 if ($block == 'address' && array_key_exists('address_name', $val)) {
2272 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2277 if ($key == 'phone' && isset($params['phone_ext'])) {
2278 $data[$key] = $value;
2279 foreach ($value as $cnt => $phoneBlock) {
2280 if ($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']) {
2281 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array
::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2285 elseif (in_array($key,
2296 ($value == '' ||
!isset($value)) &&
2297 ($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0
2299 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
2300 // to avoid update with empty values
2304 $data[$key] = $value;
2310 if (!isset($data['contact_type'])) {
2311 $data['contact_type'] = 'Individual';
2314 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2315 $privacy = CRM_Core_SelectValues
::privacy();
2316 foreach ($privacy as $key => $value) {
2317 if (array_key_exists($key, $fields)) {
2318 // do not reset values for existing contacts, if fields are added to a profile
2319 if (array_key_exists($key, $params)) {
2320 $data[$key] = $params[$key];
2321 if (empty($params[$key])) {
2325 elseif (!$contactID) {
2331 return array($data, $contactDetails);
2335 * Find the get contact details.
2337 * This function does not respect ACLs for now, which might need to be rectified at some
2338 * stage based on how its used.
2340 * @param string $mail
2341 * Primary email address of the contact.
2342 * @param string $ctype
2346 * $dao contact details
2348 public static function &matchContactOnEmail($mail, $ctype = NULL) {
2349 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2350 $mail = $strtolower(trim($mail));
2352 SELECT civicrm_contact.id as contact_id,
2353 civicrm_contact.hash as hash,
2354 civicrm_contact.contact_type as contact_type,
2355 civicrm_contact.contact_sub_type as contact_sub_type
2356 FROM civicrm_contact
2357 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2359 if (CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
, 'uniq_email_per_site')) {
2360 // try to find a match within a site (multisite).
2361 $groups = CRM_Core_BAO_Domain
::getChildGroupIds();
2362 if (!empty($groups)) {
2364 INNER JOIN civicrm_group_contact gc ON
2365 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2370 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2371 $p = array(1 => array($mail, 'String'));
2374 $query .= " AND civicrm_contact.contact_type = %3";
2375 $p[3] = array($ctype, 'String');
2378 $query .= " ORDER BY civicrm_email.is_primary DESC";
2380 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2382 if ($dao->fetch()) {
2385 return CRM_Core_DAO
::$_nullObject;
2389 * Find the contact details associated with an OpenID.
2391 * @param string $openId
2392 * OpenId of the contact.
2393 * @param string $ctype
2397 * $dao contact details
2399 public static function &matchContactOnOpenId($openId, $ctype = NULL) {
2400 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2401 $openId = $strtolower(trim($openId));
2403 SELECT civicrm_contact.id as contact_id,
2404 civicrm_contact.hash as hash,
2405 civicrm_contact.contact_type as contact_type,
2406 civicrm_contact.contact_sub_type as contact_sub_type
2407 FROM civicrm_contact
2408 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2409 WHERE civicrm_openid.openid = %1";
2410 $p = array(1 => array($openId, 'String'));
2413 $query .= " AND civicrm_contact.contact_type = %3";
2414 $p[3] = array($ctype, 'String');
2417 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2419 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2421 if ($dao->fetch()) {
2424 return CRM_Core_DAO
::$_nullObject;
2428 * Get primary email of the contact.
2430 * @param int $contactID
2434 * Email address if present else null
2436 public static function getPrimaryEmail($contactID) {
2437 // fetch the primary email
2439 SELECT civicrm_email.email as email
2440 FROM civicrm_contact
2441 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2442 WHERE civicrm_email.is_primary = 1
2443 AND civicrm_contact.id = %1";
2444 $p = array(1 => array($contactID, 'Integer'));
2445 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2448 if ($dao->fetch()) {
2449 $email = $dao->email
;
2456 * Function to get primary OpenID of the contact.
2458 * @param int $contactID
2462 * >openid OpenID if present else null
2464 public static function getPrimaryOpenId($contactID) {
2465 // fetch the primary OpenID
2467 SELECT civicrm_openid.openid as openid
2468 FROM civicrm_contact
2469 LEFT JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2470 WHERE civicrm_contact.id = %1
2471 AND civicrm_openid.is_primary = 1";
2472 $p = array(1 => array($contactID, 'Integer'));
2473 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2476 if ($dao->fetch()) {
2477 $openId = $dao->openid
;
2484 * Fetch the object and store the values in the values array.
2486 * @param array $params
2487 * Input parameters to find object.
2488 * @param array $values
2489 * Output values of the object.
2491 * @return CRM_Contact_BAO_Contact|null
2492 * The found object or null
2494 public static function getValues(&$params, &$values) {
2495 $contact = new CRM_Contact_BAO_Contact();
2497 $contact->copyValues($params);
2499 if ($contact->find(TRUE)) {
2501 CRM_Core_DAO
::storeValues($contact, $values);
2504 foreach (self
::$_commPrefs as $name) {
2505 if (isset($contact->$name)) {
2506 $privacy[$name] = $contact->$name;
2510 if (!empty($privacy)) {
2511 $values['privacy'] = $privacy;
2514 // communication Prefferance
2515 $preffComm = $comm = array();
2516 $comm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2517 $contact->preferred_communication_method
2519 foreach ($comm as $value) {
2520 $preffComm[$value] = 1;
2522 $temp = array('preferred_communication_method' => $contact->preferred_communication_method
);
2525 'preferred_communication_method' => array(
2526 'newName' => 'preferred_communication_method_display',
2527 'groupName' => 'preferred_communication_method',
2531 CRM_Core_OptionGroup
::lookupValues($temp, $names, FALSE);
2533 $values['preferred_communication_method'] = $preffComm;
2534 $values['preferred_communication_method_display'] = CRM_Utils_Array
::value('preferred_communication_method_display', $temp);
2536 $preferredMailingFormat = CRM_Core_SelectValues
::pmf();
2537 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format
];
2539 // get preferred languages
2540 if (!empty($contact->preferred_language
)) {
2541 $values['preferred_language'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language
);
2544 // Calculating Year difference
2545 if ($contact->birth_date
) {
2546 $birthDate = CRM_Utils_Date
::customFormat($contact->birth_date
, '%Y%m%d');
2547 if ($birthDate < date('Ymd')) {
2548 $age = CRM_Utils_Date
::calculateAge($birthDate);
2549 $values['age']['y'] = CRM_Utils_Array
::value('years', $age);
2550 $values['age']['m'] = CRM_Utils_Array
::value('months', $age);
2553 list($values['birth_date']) = CRM_Utils_Date
::setDateDefaults($contact->birth_date
, 'birth');
2554 $values['birth_date_display'] = $contact->birth_date
;
2557 if ($contact->deceased_date
) {
2558 list($values['deceased_date']) = CRM_Utils_Date
::setDateDefaults($contact->deceased_date
, 'birth');
2559 $values['deceased_date_display'] = $contact->deceased_date
;
2562 $contact->contact_id
= $contact->id
;
2570 * Given the component name and returns the count of participation of contact.
2572 * @param string $component
2573 * Input component name.
2574 * @param int $contactId
2576 * @param string $tableName
2577 * Optional tableName if component is custom group.
2580 * total number in database
2582 public static function getCountComponent($component, $contactId, $tableName = NULL) {
2584 switch ($component) {
2586 return CRM_Core_BAO_EntityTag
::getContactTags($contactId, TRUE);
2589 $result = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
2590 CRM_Contact_BAO_Relationship
::CURRENT
,
2597 return CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, "Added", NULL, TRUE);
2600 if (CRM_Core_BAO_Log
::useLoggingReport()) {
2603 return CRM_Core_BAO_Log
::getContactLogCount($contactId);
2606 return CRM_Core_BAO_Note
::getContactNoteCount($contactId);
2608 case 'contribution':
2609 return CRM_Contribute_BAO_Contribution
::contributionCount($contactId);
2612 return CRM_Member_BAO_Membership
::getContactMembershipCount($contactId, TRUE);
2615 return CRM_Event_BAO_Participant
::getContactParticipantCount($contactId);
2618 return CRM_Pledge_BAO_Pledge
::getContactPledgeCount($contactId);
2621 return CRM_Case_BAO_Case
::caseCount($contactId);
2624 return CRM_Grant_BAO_Grant
::getContactGrantCount($contactId);
2628 'contact_id' => $contactId,
2631 'context' => 'activity',
2633 return CRM_Activity_BAO_Activity
::getActivitiesCount($input);
2636 $params = array('contact_id' => $contactId);
2637 return CRM_Mailing_BAO_Mailing
::getContactMailingsCount($params);
2640 $custom = explode('_', $component);
2641 if ($custom['0'] = 'custom') {
2643 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2645 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2646 return CRM_Core_DAO
::singleValueQuery($queryString);
2652 * Process greetings and cache.
2654 * @param object $contact
2655 * Contact object after save.
2656 * @param bool $useDefaults
2657 * Use default greeting values.
2659 public static function processGreetings(&$contact, $useDefaults = FALSE) {
2661 //retrieve default greetings
2662 $defaultGreetings = CRM_Core_PseudoConstant
::greetingDefaults();
2663 $contactDefaults = $defaultGreetings[$contact->contact_type
];
2666 // note that contact object not always has required greeting related
2667 // fields that are required to calculate greeting and
2668 // also other fields used in tokens etc,
2669 // hence we need to retrieve it again.
2670 if ($contact->_query
!== FALSE) {
2671 $contact->find(TRUE);
2674 // store object values to an array
2675 $contactDetails = array();
2676 CRM_Core_DAO
::storeValues($contact, $contactDetails);
2677 $contactDetails = array(array($contact->id
=> $contactDetails));
2679 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2680 $updateQueryString = array();
2682 //cache email and postal greeting to greeting display
2683 if ($contact->email_greeting_custom
!= 'null' && $contact->email_greeting_custom
) {
2684 $emailGreetingString = $contact->email_greeting_custom
;
2686 elseif ($contact->email_greeting_id
!= 'null' && $contact->email_greeting_id
) {
2687 // the filter value for Individual contact type is set to 1
2689 'contact_type' => $contact->contact_type
,
2690 'greeting_type' => 'email_greeting',
2693 $emailGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2694 $emailGreetingString = $emailGreeting[$contact->email_greeting_id
];
2695 $updateQueryString[] = " email_greeting_custom = NULL ";
2699 reset($contactDefaults['email_greeting']);
2700 $emailGreetingID = key($contactDefaults['email_greeting']);
2701 $emailGreetingString = $contactDefaults['email_greeting'][$emailGreetingID];
2702 $updateQueryString[] = " email_greeting_id = $emailGreetingID ";
2703 $updateQueryString[] = " email_greeting_custom = NULL ";
2705 elseif ($contact->email_greeting_custom
) {
2706 $updateQueryString[] = " email_greeting_display = NULL ";
2710 if ($emailGreetingString) {
2711 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($emailGreetingString,
2714 'CRM_Contact_BAO_Contact'
2716 $emailGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($emailGreetingString));
2717 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2721 if ($contact->postal_greeting_custom
!= 'null' && $contact->postal_greeting_custom
) {
2722 $postalGreetingString = $contact->postal_greeting_custom
;
2724 elseif ($contact->postal_greeting_id
!= 'null' && $contact->postal_greeting_id
) {
2726 'contact_type' => $contact->contact_type
,
2727 'greeting_type' => 'postal_greeting',
2729 $postalGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2730 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id
];
2731 $updateQueryString[] = " postal_greeting_custom = NULL ";
2735 reset($contactDefaults['postal_greeting']);
2736 $postalGreetingID = key($contactDefaults['postal_greeting']);
2737 $postalGreetingString = $contactDefaults['postal_greeting'][$postalGreetingID];
2738 $updateQueryString[] = " postal_greeting_id = $postalGreetingID ";
2739 $updateQueryString[] = " postal_greeting_custom = NULL ";
2741 elseif ($contact->postal_greeting_custom
) {
2742 $updateQueryString[] = " postal_greeting_display = NULL ";
2746 if ($postalGreetingString) {
2747 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($postalGreetingString,
2750 'CRM_Contact_BAO_Contact'
2752 $postalGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($postalGreetingString));
2753 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2757 if ($contact->addressee_custom
!= 'null' && $contact->addressee_custom
) {
2758 $addresseeString = $contact->addressee_custom
;
2760 elseif ($contact->addressee_id
!= 'null' && $contact->addressee_id
) {
2762 'contact_type' => $contact->contact_type
,
2763 'greeting_type' => 'addressee',
2766 $addressee = CRM_Core_PseudoConstant
::greeting($filter);
2767 $addresseeString = $addressee[$contact->addressee_id
];
2768 $updateQueryString[] = " addressee_custom = NULL ";
2772 reset($contactDefaults['addressee']);
2773 $addresseeID = key($contactDefaults['addressee']);
2774 $addresseeString = $contactDefaults['addressee'][$addresseeID];
2775 $updateQueryString[] = " addressee_id = $addresseeID ";
2776 $updateQueryString[] = " addressee_custom = NULL ";
2778 elseif ($contact->addressee_custom
) {
2779 $updateQueryString[] = " addressee_display = NULL ";
2783 if ($addresseeString) {
2784 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($addresseeString,
2787 'CRM_Contact_BAO_Contact'
2789 $addresseeString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($addresseeString));
2790 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2793 if (!empty($updateQueryString)) {
2794 $updateQueryString = implode(',', $updateQueryString);
2795 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2796 CRM_Core_DAO
::executeQuery($queryString);
2801 * Retrieve loc block ids w/ given condition.
2803 * @param int $contactId
2805 * @param array $criteria
2806 * Key => value pair which should be.
2807 * fulfill by return record ids.
2808 * @param string $condOperator
2809 * Operator use for grouping multiple conditions.
2812 * loc block ids which fulfill condition.
2814 public static function getLocBlockIds($contactId, $criteria = array(), $condOperator = 'AND') {
2815 $locBlockIds = array();
2817 return $locBlockIds;
2820 foreach (array('Email', 'OpenID', 'Phone', 'Address', 'IM') as $block) {
2821 $name = strtolower($block);
2822 $className = "CRM_Core_DAO_$block";
2823 $blockDAO = new $className();
2825 // build the condition.
2826 if (is_array($criteria)) {
2827 $fields = $blockDAO->fields();
2828 $conditions = array();
2829 foreach ($criteria as $field => $value) {
2830 if (array_key_exists($field, $fields)) {
2831 $cond = "( $field = $value )";
2832 // value might be zero or null.
2833 if (!$value ||
strtolower($value) == 'null') {
2834 $cond = "( $field = 0 OR $field IS NULL )";
2836 $conditions[] = $cond;
2839 if (!empty($conditions)) {
2840 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2844 $blockDAO->contact_id
= $contactId;
2846 while ($blockDAO->fetch()) {
2847 $locBlockIds[$name][] = $blockDAO->id
;
2852 return $locBlockIds;
2856 * Build context menu items.
2858 * @param int $contactId
2861 * Array of context menu for logged in user.
2863 public static function contextMenu($contactId = NULL) {
2866 'title' => ts('View Contact'),
2868 'ref' => 'view-contact',
2869 'class' => 'no-popup',
2871 'permissions' => array('view all contacts'),
2874 'title' => ts('Edit Contact'),
2876 'ref' => 'edit-contact',
2877 'class' => 'no-popup',
2879 'permissions' => array('edit all contacts'),
2882 'title' => ts('Delete Contact'),
2884 'ref' => 'delete-contact',
2886 'permissions' => array('access deleted contacts', 'delete contacts'),
2888 'contribution' => array(
2889 'title' => ts('Add Contribution'),
2891 'ref' => 'new-contribution',
2892 'key' => 'contribution',
2893 'tab' => 'contribute',
2894 'component' => 'CiviContribute',
2895 'href' => CRM_Utils_System
::url('civicrm/contact/view/contribution',
2896 'reset=1&action=add&context=contribution'
2898 'permissions' => array(
2899 'access CiviContribute',
2900 'edit contributions',
2903 'participant' => array(
2904 'title' => ts('Register for Event'),
2906 'ref' => 'new-participant',
2907 'key' => 'participant',
2908 'tab' => 'participant',
2909 'component' => 'CiviEvent',
2910 'href' => CRM_Utils_System
::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
2911 'permissions' => array(
2913 'edit event participants',
2916 'activity' => array(
2917 'title' => ts('Record Activity'),
2919 'ref' => 'new-activity',
2920 'key' => 'activity',
2921 'permissions' => array('edit all contacts'),
2924 'title' => ts('Add Pledge'),
2926 'ref' => 'new-pledge',
2929 'href' => CRM_Utils_System
::url('civicrm/contact/view/pledge',
2930 'reset=1&action=add&context=pledge'
2932 'component' => 'CiviPledge',
2933 'permissions' => array(
2934 'access CiviPledge',
2938 'membership' => array(
2939 'title' => ts('Add Membership'),
2941 'ref' => 'new-membership',
2942 'key' => 'membership',
2944 'component' => 'CiviMember',
2945 'href' => CRM_Utils_System
::url('civicrm/contact/view/membership',
2946 'reset=1&action=add&context=membership'
2948 'permissions' => array(
2949 'access CiviMember',
2954 'title' => ts('Add Case'),
2956 'ref' => 'new-case',
2959 'component' => 'CiviCase',
2960 'href' => CRM_Utils_System
::url('civicrm/case/add', 'reset=1&action=add&context=case'),
2961 'permissions' => array('add cases'),
2964 'title' => ts('Add Grant'),
2966 'ref' => 'new-grant',
2969 'component' => 'CiviGrant',
2970 'href' => CRM_Utils_System
::url('civicrm/contact/view/grant',
2971 'reset=1&action=add&context=grant'
2973 'permissions' => array('edit grants'),
2976 'title' => ts('Add Relationship'),
2978 'ref' => 'new-relationship',
2981 'href' => CRM_Utils_System
::url('civicrm/contact/view/rel',
2982 'reset=1&action=add'
2984 'permissions' => array('edit all contacts'),
2987 'title' => ts('Add Note'),
2989 'ref' => 'new-note',
2992 'class' => 'medium-popup',
2993 'href' => CRM_Utils_System
::url('civicrm/contact/view/note',
2994 'reset=1&action=add'
2996 'permissions' => array('edit all contacts'),
2999 'title' => ts('Send an Email'),
3001 'ref' => 'new-email',
3003 'permissions' => array('view all contacts'),
3006 'title' => ts('Add to Group'),
3008 'ref' => 'group-add-contact',
3011 'permissions' => array('edit groups'),
3014 'title' => ts('Tag Contact'),
3016 'ref' => 'tag-contact',
3019 'permissions' => array('edit all contacts'),
3023 CRM_Utils_Hook
::summaryActions($menu, $contactId);
3024 //1. check for component is active.
3025 //2. check for user permissions.
3026 //3. check for acls.
3027 //3. edit and view contact are directly accessible to user.
3029 $aclPermissionedTasks = array(
3034 'group-add-contact',
3038 $corePermission = CRM_Core_Permission
::getPermission();
3040 $config = CRM_Core_Config
::singleton();
3042 $contextMenu = array();
3043 foreach ($menu as $key => $values) {
3044 $componentName = CRM_Utils_Array
::value('component', $values);
3046 // if component action - make sure component is enable.
3047 if ($componentName && !in_array($componentName, $config->enableComponents
)) {
3051 // make sure user has all required permissions.
3052 $hasAllPermissions = FALSE;
3054 $permissions = CRM_Utils_Array
::value('permissions', $values);
3055 if (!is_array($permissions) ||
empty($permissions)) {
3056 $hasAllPermissions = TRUE;
3059 // iterate for required permissions in given permissions array.
3060 if (!$hasAllPermissions) {
3061 $hasPermissions = 0;
3062 foreach ($permissions as $permission) {
3063 if (CRM_Core_Permission
::check($permission)) {
3068 if (count($permissions) == $hasPermissions) {
3069 $hasAllPermissions = TRUE;
3072 // if still user does not have required permissions, check acl.
3073 if (!$hasAllPermissions && $values['ref'] != 'delete-contact') {
3074 if (in_array($values['ref'], $aclPermissionedTasks) &&
3075 $corePermission == CRM_Core_Permission
::EDIT
3077 $hasAllPermissions = TRUE;
3079 elseif (in_array($values['ref'], array(
3082 // grant permissions for these tasks.
3083 $hasAllPermissions = TRUE;
3088 // user does not have necessary permissions.
3089 if (!$hasAllPermissions) {
3093 // build directly accessible action menu.
3094 if (in_array($values['ref'], array(
3098 $contextMenu['primaryActions'][$key] = array(
3099 'title' => $values['title'],
3100 'ref' => $values['ref'],
3101 'class' => CRM_Utils_Array
::value('class', $values),
3102 'key' => $values['key'],
3107 // finally get menu item for -more- action widget.
3108 $contextMenu['moreActions'][$values['weight']] = array(
3109 'title' => $values['title'],
3110 'ref' => $values['ref'],
3111 'href' => CRM_Utils_Array
::value('href', $values),
3112 'tab' => CRM_Utils_Array
::value('tab', $values),
3113 'class' => CRM_Utils_Array
::value('class', $values),
3114 'key' => $values['key'],
3118 ksort($contextMenu['moreActions']);
3120 return $contextMenu;
3124 * Retrieve display name of contact that address is shared.
3126 * This is based on $masterAddressId or $contactId .
3128 * @param int $masterAddressId
3130 * @param int $contactId
3133 * @return string|null
3134 * the found display name or null.
3136 public static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3137 $masterDisplayName = NULL;
3139 if (!$masterAddressId && !$contactId) {
3140 return $masterDisplayName;
3143 if ($masterAddressId) {
3145 SELECT display_name from civicrm_contact
3146 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3147 WHERE civicrm_address.id = " . $masterAddressId;
3149 elseif ($contactId) {
3151 SELECT display_name from civicrm_contact cc, civicrm_address add1
3152 LEFT JOIN civicrm_address add2 ON ( add1.master_id = add2.id )
3153 WHERE cc.id = add2.contact_id AND add1.contact_id = " . $contactId;
3156 $masterDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
3157 return $masterDisplayName;
3161 * Get the creation/modification times for a contact.
3163 * @param int $contactId
3166 * Dates - ('created_date' => $, 'modified_date' => $)
3168 public static function getTimestamps($contactId) {
3169 $timestamps = CRM_Core_DAO
::executeQuery(
3170 'SELECT created_date, modified_date
3171 FROM civicrm_contact
3174 1 => array($contactId, 'Integer'),
3177 if ($timestamps->fetch()) {
3179 'created_date' => $timestamps->created_date
,
3180 'modified_date' => $timestamps->modified_date
,
3189 * Generate triggers to update the timestamp.
3191 * The corresponding civicrm_contact row is updated on insert/update/delete
3192 * to a table that extends civicrm_contact.
3193 * Don't regenerate triggers for all such tables if only asked for one table.
3195 * @param array $info
3196 * Reference to the array where generated trigger information is being stored
3197 * @param string|null $reqTableName
3198 * Name of the table for which triggers are being generated, or NULL if all tables
3199 * @param array $relatedTableNames
3200 * Array of all core or all custom table names extending civicrm_contact
3201 * @param string $contactRefColumn
3202 * 'contact_id' if processing core tables, 'entity_id' if processing custom tables
3204 * @link https://issues.civicrm.org/jira/browse/CRM-15602
3207 public static function generateTimestampTriggers(&$info, $reqTableName, $relatedTableNames, $contactRefColumn) {
3209 $contactRefColumn = CRM_Core_DAO
::escapeString($contactRefColumn);
3210 // If specific related table requested, just process that one
3211 if (in_array($reqTableName, $relatedTableNames)) {
3212 $relatedTableNames = array($reqTableName);
3215 // If no specific table requested (include all related tables),
3216 // or a specific related table requested (as matched above)
3217 if (empty($reqTableName) ||
in_array($reqTableName, $relatedTableNames)) {
3219 'table' => $relatedTableNames,
3221 'event' => array('INSERT', 'UPDATE'),
3222 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = NEW.$contactRefColumn;\n",
3225 'table' => $relatedTableNames,
3227 'event' => array('DELETE'),
3228 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = OLD.$contactRefColumn;\n",
3234 * Get a list of triggers for the contact table.
3236 * @see hook_civicrm_triggerInfo
3237 * @see CRM_Core_DAO::triggerRebuild
3238 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3241 * @param null $tableName
3243 public static function triggerInfo(&$info, $tableName = NULL) {
3244 //during upgrade, first check for valid version and then create triggers
3245 //i.e the columns created_date and modified_date are introduced in 4.3.alpha1 so dont create triggers for older version
3246 if (CRM_Core_Config
::isUpgradeMode()) {
3247 $currentVer = CRM_Core_BAO_Domain
::version(TRUE);
3248 //if current version is less than 4.3.alpha1 dont create below triggers
3249 if (version_compare($currentVer, '4.3.alpha1') < 0) {
3254 // Update timestamp for civicrm_contact itself
3255 if ($tableName == NULL ||
$tableName == self
::getTableName()) {
3257 'table' => array(self
::getTableName()),
3259 'event' => array('INSERT'),
3260 'sql' => "\nSET NEW.created_date = CURRENT_TIMESTAMP;\n",
3264 // Update timestamp when modifying closely related core tables
3265 $relatedTables = array(
3272 self
::generateTimestampTriggers($info, $tableName, $relatedTables, 'contact_id');
3274 // Update timestamp when modifying related custom-data tables
3275 $customGroupTables = array();
3276 $customGroupDAO = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity('Contact');
3277 $customGroupDAO->is_multiple
= 0;
3278 $customGroupDAO->find();
3279 while ($customGroupDAO->fetch()) {
3280 $customGroupTables[] = $customGroupDAO->table_name
;
3282 if (!empty($customGroupTables)) {
3283 self
::generateTimestampTriggers($info, $tableName, $customGroupTables, 'entity_id');
3286 // Update phone table to populate phone_numeric field
3287 if (!$tableName ||
$tableName == 'civicrm_phone') {
3288 // Define stored sql function needed for phones
3289 CRM_Core_DAO
::executeQuery(self
::DROP_STRIP_FUNCTION_43
);
3290 CRM_Core_DAO
::executeQuery(self
::CREATE_STRIP_FUNCTION_43
);
3292 'table' => array('civicrm_phone'),
3294 'event' => array('INSERT', 'UPDATE'),
3295 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3301 * Check if contact is being used in civicrm_domain based on $contactId.
3303 * @param int $contactId
3307 * true if present else false.
3309 public static function checkDomainContact($contactId) {
3313 $domainId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3324 * Get options for a given contact field.
3326 * @see CRM_Core_DAO::buildOptions
3328 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3329 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3331 * @param string $fieldName
3332 * @param string $context
3333 * @see CRM_Core_DAO::buildOptionsContext
3334 * @param array $props
3335 * whatever is known about this dao object.
3337 * @return array|bool
3339 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3341 // Special logic for fields whose options depend on context or properties
3342 switch ($fieldName) {
3343 case 'contact_sub_type':
3344 if (!empty($props['contact_type'])) {
3345 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3349 case 'contact_type':
3350 if ($context == 'search') {
3351 // CRM-15495 - EntityRef filters and basic search forms expect this format
3352 // FIXME: Search builder does not
3353 return CRM_Contact_BAO_ContactType
::getSelectElements();
3357 // The contact api supports some related entities so we'll honor that by fetching their options
3360 return CRM_Contact_BAO_GroupContact
::buildOptions('group_id', $context, $props);
3364 $props['entity_table'] = 'civicrm_contact';
3365 return CRM_Core_BAO_EntityTag
::buildOptions('tag_id', $context, $props);
3368 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
3372 * Delete a contact-related object that has an 'is_primary' field.
3374 * Ensures that is_primary gets assigned to another object if available
3375 * Also calls pre/post hooks
3381 public static function deleteObjectWithPrimary($type, $id) {
3382 if (!$id ||
!is_numeric($id)) {
3385 $daoName = "CRM_Core_DAO_$type";
3386 $obj = new $daoName();
3389 if ($obj->fetch()) {
3390 CRM_Utils_Hook
::pre('delete', $type, $id, CRM_Core_DAO
::$_nullArray);
3391 $contactId = $obj->contact_id
;
3397 // is_primary is only relavent if this field belongs to a contact
3399 $dao = new $daoName();
3400 $dao->contact_id
= $contactId;
3401 $dao->is_primary
= 1;
3402 // Pick another record to be primary (if one isn't already)
3403 if (!$dao->find(TRUE)) {
3404 $dao->is_primary
= 0;
3406 if ($dao->fetch()) {
3407 $dao->is_primary
= 1;
3413 CRM_Utils_Hook
::post('delete', $type, $id, $obj);