3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
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 * @param bool $skipDelete
280 * Unclear parameter, passed to website create
282 * @todo explain this parameter
285 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
286 * Created or updated contribution object. We are deprecating returning an error in
287 * favour of exceptions
289 public static function &create(&$params, $fixAddress = TRUE, $invokeHooks = TRUE, $skipDelete = FALSE) {
291 if (empty($params['contact_type']) && empty($params['contact_id'])) {
297 if (!empty($params['contact_id'])) {
298 CRM_Utils_Hook
::pre('edit', $params['contact_type'], $params['contact_id'], $params);
301 CRM_Utils_Hook
::pre('create', $params['contact_type'], NULL, $params);
306 $config = CRM_Core_Config
::singleton();
308 // CRM-6942: set preferred language to the current language if it’s unset (and we’re creating a contact).
309 if (empty($params['contact_id']) && empty($params['preferred_language'])) {
310 $params['preferred_language'] = $config->lcMessages
;
313 // CRM-9739: set greeting & addressee if unset and we’re creating a contact.
314 if (empty($params['contact_id'])) {
315 foreach (self
::$_greetingTypes as $greeting) {
316 if (empty($params[$greeting . '_id'])) {
317 if ($defaultGreetingTypeId
318 = CRM_Contact_BAO_Contact_Utils
::defaultGreeting($params['contact_type'], $greeting)
320 $params[$greeting . '_id'] = $defaultGreetingTypeId;
326 $transaction = new CRM_Core_Transaction();
328 $contact = self
::add($params);
330 // Not dying here is stupid, since we get into wierd situation and into a bug that
331 // is impossible to figure out for the user or for us
333 CRM_Core_Error
::fatal();
336 $params['contact_id'] = $contact->id
;
338 if (CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
, 'is_enabled')) {
339 // Enabling multisite causes the contact to be added to the domain group.
340 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
341 if (!empty($domainGroupID)) {
342 if (!empty($params['group']) && is_array($params['group'])) {
343 $params['group'][$domainGroupID] = 1;
346 $params['group'] = array($domainGroupID => 1);
351 if (array_key_exists('group', $params)) {
352 $contactIds = array($params['contact_id']);
353 foreach ($params['group'] as $groupId => $flag) {
355 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
357 elseif ($flag == -1) {
358 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $groupId);
363 // Add location Block data.
364 $blocks = CRM_Core_BAO_Location
::create($params, $fixAddress);
365 foreach ($blocks as $name => $value) {
366 $contact->$name = $value;
370 CRM_Core_BAO_Website
::create($params['website'], $contact->id
, $skipDelete);
372 //get userID from session
373 $session = CRM_Core_Session
::singleton();
374 $userID = $session->get('userID');
376 if (!empty($params['note'])) {
377 if (is_array($params['note'])) {
378 foreach ($params['note'] as $note) {
379 $contactId = $contact->id
;
380 if (isset($note['contact_id'])) {
381 $contactId = $note['contact_id'];
383 //if logged in user, overwrite contactId
385 $contactId = $userID;
389 'entity_id' => $contact->id
,
390 'entity_table' => 'civicrm_contact',
391 'note' => $note['note'],
392 'subject' => CRM_Utils_Array
::value('subject', $note),
393 'contact_id' => $contactId,
395 CRM_Core_BAO_Note
::add($noteParams, CRM_Core_DAO
::$_nullArray);
399 $contactId = $contact->id
;
400 if (isset($note['contact_id'])) {
401 $contactId = $note['contact_id'];
403 //if logged in user, overwrite contactId
405 $contactId = $userID;
409 'entity_id' => $contact->id
,
410 'entity_table' => 'civicrm_contact',
411 'note' => $params['note'],
412 'subject' => CRM_Utils_Array
::value('subject', $params),
413 'contact_id' => $contactId,
415 CRM_Core_BAO_Note
::add($noteParams, CRM_Core_DAO
::$_nullArray);
419 // update the UF user_unique_id if that has changed
420 CRM_Core_BAO_UFMatch
::updateUFName($contact->id
);
422 if (!empty($params['custom']) &&
423 is_array($params['custom'])
425 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contact', $contact->id
);
428 // make a civicrm_subscription_history entry only on contact create (CRM-777)
429 if (empty($params['contact_id'])) {
430 $subscriptionParams = array(
431 'contact_id' => $contact->id
,
435 CRM_Contact_BAO_SubscriptionHistory
::create($subscriptionParams);
438 $transaction->commit();
440 // CRM-6367: fetch the right label for contact type’s display
441 $contact->contact_type_display
= CRM_Core_DAO
::getFieldValue(
442 'CRM_Contact_DAO_ContactType',
443 $contact->contact_type
,
448 if (!$config->doNotResetCache
) {
449 // Note: doNotResetCache flag is currently set by import contact process and merging,
450 // since resetting and
451 // rebuilding cache could be expensive (for many contacts). We might come out with better
452 // approach in future.
453 CRM_Contact_BAO_Contact_Utils
::clearContactCaches($contact->id
);
458 CRM_Utils_Hook
::post('edit', $params['contact_type'], $contact->id
, $contact);
461 CRM_Utils_Hook
::post('create', $params['contact_type'], $contact->id
, $contact);
465 // process greetings CRM-4575, cache greetings
466 self
::processGreetings($contact);
472 * Get the display name and image of a contact.
477 * @param bool $includeTypeInReturnParameters
478 * Should type be part of the returned array?
481 * the displayName and contactImage for this contact
483 public static function getDisplayAndImage($id, $includeTypeInReturnParameters = FALSE) {
484 //CRM-14276 added the * on the civicrm_contact table so that we have all the contact info available
486 SELECT civicrm_contact.*,
487 civicrm_email.email as email
489 LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
490 AND civicrm_email.is_primary = 1
491 WHERE civicrm_contact.id = " . CRM_Utils_Type
::escape($id, 'Integer');
492 $dao = new CRM_Core_DAO();
495 $image = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
496 $dao->contact_sub_type
: $dao->contact_type
, FALSE, $id
498 $imageUrl = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
499 $dao->contact_sub_type
: $dao->contact_type
, TRUE, $id
502 // use email if display_name is empty
503 if (empty($dao->display_name
)) {
504 $displayName = $dao->email
;
507 $displayName = $dao->display_name
;
510 CRM_Utils_Hook
::alterDisplayName($displayName, $id, $dao);
512 return $includeTypeInReturnParameters ?
array(
516 $dao->contact_sub_type
,
518 ) : array($displayName, $image, $imageUrl);
524 * Create last viewed link to recently updated contact.
526 * @param array $crudLinkSpec
527 * - action: int, CRM_Core_Action::UPDATE or CRM_Core_Action::VIEW [default: VIEW]
528 * - entity_table: string, eg "civicrm_contact"
532 * NULL if unavailable, or
533 * [path: string, query: string, title: string]
534 * @see CRM_Utils_System::createDefaultCrudLink
536 public function createDefaultCrudLink($crudLinkSpec) {
537 switch ($crudLinkSpec['action']) {
538 case CRM_Core_Action
::VIEW
:
540 'title' => $this->display_name
,
541 'path' => 'civicrm/contact/view',
549 case CRM_Core_Action
::UPDATE
:
551 'title' => $this->display_name
,
552 'path' => 'civicrm/contact/add',
555 'action' => 'update',
565 * Get the values for pseudoconstants for name->value and reverse.
567 * @param array $defaults
568 * (reference) the default values, some of which need to be resolved.
569 * @param bool $reverse
570 * True if we want to resolve the values in the reverse direction (value -> name).
572 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
573 // Hack for birth_date.
574 if (!empty($defaults['birth_date'])) {
575 if (is_array($defaults['birth_date'])) {
576 $defaults['birth_date'] = CRM_Utils_Date
::format($defaults['birth_date'], '-');
580 CRM_Utils_Array
::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id'), $reverse);
581 CRM_Utils_Array
::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'suffix_id'), $reverse);
582 CRM_Utils_Array
::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'), $reverse);
583 CRM_Utils_Array
::lookupValue($defaults, 'communication_style', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'communication_style_id'), $reverse);
585 //lookup value of email/postal greeting, addressee, CRM-4575
586 foreach (self
::$_greetingTypes as $greeting) {
587 $filterCondition = array(
588 'contact_type' => CRM_Utils_Array
::value('contact_type', $defaults),
589 'greeting_type' => $greeting,
591 CRM_Utils_Array
::lookupValue($defaults, $greeting,
592 CRM_Core_PseudoConstant
::greeting($filterCondition), $reverse
596 $blocks = array('address', 'im', 'phone');
597 foreach ($blocks as $name) {
598 if (!array_key_exists($name, $defaults) ||
!is_array($defaults[$name])) {
601 foreach ($defaults[$name] as $count => & $values) {
603 //get location type id.
604 CRM_Utils_Array
::lookupValue($values, 'location_type', CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id'), $reverse);
606 if ($name == 'address') {
607 // FIXME: lookupValue doesn't work for vcard_name
608 if (!empty($values['location_type_id'])) {
609 $vcardNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array('labelColumn' => 'vcard_name'));
610 $values['vcard_name'] = $vcardNames[$values['location_type_id']];
613 if (!CRM_Utils_Array
::lookupValue($values,
615 CRM_Core_PseudoConstant
::country(),
620 CRM_Utils_Array
::lookupValue($values,
622 CRM_Core_PseudoConstant
::countryIsoCode(),
628 // if we find a country id above, we need to restrict it to that country
629 // rather than the list of all countries
631 if (!empty($values['country_id'])) {
632 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($values['country_id']);
635 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvince();
637 if (!CRM_Utils_Array
::lookupValue($values,
645 if (!empty($values['country_id'])) {
646 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($values['country_id'], 'abbreviation');
649 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviation();
651 CRM_Utils_Array
::lookupValue($values,
658 if (!empty($values['state_province_id'])) {
659 $countyList = CRM_Core_PseudoConstant
::countyForState($values['state_province_id']);
662 $countyList = CRM_Core_PseudoConstant
::county();
664 CRM_Utils_Array
::lookupValue($values,
672 CRM_Utils_Array
::lookupValue($values,
674 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id'),
679 if ($name == 'phone') {
680 CRM_Utils_Array
::lookupValue($values,
682 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id'),
687 // Kill the reference.
694 * Fetch object based on array of properties.
696 * @param array $params
697 * (reference ) an assoc array of name/value pairs.
698 * @param array $defaults
699 * (reference ) an assoc array to hold the name / value pairs.
700 * in a hierarchical manner
701 * @param bool $microformat
702 * For location in microformat.
704 * @return CRM_Contact_BAO_Contact
706 public static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
707 if (array_key_exists('contact_id', $params)) {
708 $params['id'] = $params['contact_id'];
710 elseif (array_key_exists('id', $params)) {
711 $params['contact_id'] = $params['id'];
714 $contact = self
::getValues($params, $defaults);
716 unset($params['id']);
718 //get the block information for this contact
719 $entityBlock = array('contact_id' => $params['contact_id']);
720 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock, $microformat);
721 $defaults = array_merge($defaults, $blocks);
722 foreach ($blocks as $block => $value) {
723 $contact->$block = $value;
726 if (!isset($params['noNotes'])) {
727 $contact->notes
= CRM_Core_BAO_Note
::getValues($params, $defaults);
730 if (!isset($params['noRelationships'])) {
731 $contact->relationship
= CRM_Contact_BAO_Relationship
::getValues($params, $defaults);
734 if (!isset($params['noGroups'])) {
735 $contact->groupContact
= CRM_Contact_BAO_GroupContact
::getValues($params, $defaults);
738 if (!isset($params['noWebsite'])) {
739 $contact->website
= CRM_Core_BAO_Website
::getValues($params, $defaults);
746 * Get the display name of a contact.
751 * @return null|string
752 * display name of the contact if found
754 public static function displayName($id) {
757 $displayName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
764 * Delete a contact and all its associated records.
767 * Id of the contact to delete.
768 * @param bool $restore
769 * Whether to actually restore, not delete.
770 * @param bool $skipUndelete
771 * Whether to force contact delete or not.
774 * Was contact deleted?
776 public static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE) {
781 // If trash is disabled in system settings then we always skip
782 if (!CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'contact_undelete', NULL, 1)) {
783 $skipUndelete = TRUE;
786 // make sure we have edit permission for this contact
788 if (($skipUndelete && !CRM_Core_Permission
::check('delete contacts')) ||
789 ($restore && !CRM_Core_Permission
::check('access deleted contacts'))
795 // Restrict contact to be delete if contact has financial trxns
797 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent(array($id), $error)) {
801 // make sure this contact_id does not have any membership types
802 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
805 'member_of_contact_id'
807 if ($membershipTypeID) {
811 $contact = new CRM_Contact_DAO_Contact();
813 if (!$contact->find(TRUE)) {
817 $contactType = $contact->contact_type
;
820 return self
::contactTrashRestore($contact, TRUE);
823 // currently we only clear employer cache.
824 // we are not deleting inherited membership if any.
825 if ($contact->contact_type
== 'Organization') {
826 CRM_Contact_BAO_Contact_Utils
::clearAllEmployee($id);
829 // start a new transaction
830 $transaction = new CRM_Core_Transaction();
833 CRM_Utils_Hook
::pre('delete', $contactType, $id, CRM_Core_DAO
::$_nullArray);
835 //delete billing address if exists.
836 CRM_Contribute_BAO_Contribution
::deleteAddress(NULL, $id);
838 // delete the log entries since we dont have triggers enabled as yet
839 $logDAO = new CRM_Core_DAO_Log();
840 $logDAO->entity_table
= 'civicrm_contact';
841 $logDAO->entity_id
= $id;
844 // delete contact participants CRM-12155
845 CRM_Event_BAO_Participant
::deleteContactParticipant($id);
847 // delete contact contributions CRM-12155
848 CRM_Contribute_BAO_Contribution
::deleteContactContribution($id);
850 // do activity cleanup, CRM-5604
851 CRM_Activity_BAO_Activity
::cleanupActivity($id);
853 // delete all notes related to contact
854 CRM_Core_BAO_Note
::cleanContactNotes($id);
856 // delete cases related to contact
857 $contactCases = CRM_Case_BAO_Case
::retrieveCaseIdsByContactId($id);
858 if (!empty($contactCases)) {
859 foreach ($contactCases as $caseId) {
860 //check if case is associate with other contact or not.
861 $caseContactId = CRM_Case_BAO_Case
::getCaseClients($caseId);
862 if (count($caseContactId) <= 1) {
863 CRM_Case_BAO_Case
::deleteCase($caseId);
871 self
::contactTrashRestore($contact);
874 //delete the contact id from recently view
875 CRM_Utils_Recent
::delContact($id);
877 // Update the group contact cache
879 CRM_Contact_BAO_GroupContactCache
::remove();
882 CRM_Contact_BAO_GroupContactCache
::removeContact($id);
885 // delete any dupe cache entry
886 CRM_Core_BAO_PrevNextCache
::deleteItem($id);
888 $transaction->commit();
891 CRM_Utils_Hook
::post('delete', $contactType, $contact->id
, $contact);
894 // also reset the DB_DO global array so we can reuse the memory
895 // http://issues.civicrm.org/jira/browse/CRM-4387
896 CRM_Core_DAO
::freeResult();
902 * Delete the image of a contact.
908 * Was contact image deleted?
910 public static function deleteContactImage($id) {
915 UPDATE civicrm_contact
918 CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
923 * Return relative path.
925 * @todo make this a method of $config->userSystem (i.e. UF classes) rather than a static function
927 * @param string $absolutePath
931 * Relative url of uploaded image
933 public static function getRelativePath($absolutePath) {
934 $relativePath = NULL;
935 $config = CRM_Core_Config
::singleton();
936 if ($config->userFramework
== 'Joomla') {
937 $userFrameworkBaseURL = trim(str_replace('/administrator/', '', $config->userFrameworkBaseURL
));
938 $customFileUploadDirectory = strstr(str_replace('\\', '/', $absolutePath), '/media');
939 $relativePath = $userFrameworkBaseURL . $customFileUploadDirectory;
941 elseif ($config->userSystem
->is_drupal
== '1') {
942 //ideally we would do a bigger re-factoring & move the getRelativePath onto the UF class
943 $rootPath = $config->userSystem
->cmsRootPath();
944 $baseUrl = $config->userFrameworkBaseURL
;
946 //format url for language negotiation, CRM-7135
947 $baseUrl = CRM_Utils_System
::languageNegotiationURL($baseUrl, FALSE, TRUE);
949 $relativePath = str_replace("{$rootPath}/",
951 str_replace('\\', '/', $absolutePath)
954 elseif ($config->userFramework
== 'WordPress') {
955 $userFrameworkBaseURL = trim(str_replace('/wp-admin/', '', $config->userFrameworkBaseURL
));
956 $customFileUploadDirectory = strstr(str_replace('\\', '/', $absolutePath), '/wp-content/');
957 $relativePath = $userFrameworkBaseURL . $customFileUploadDirectory;
960 return $relativePath;
964 * Return proportional height and width of the image.
966 * @param int $imageWidth
969 * @param int $imageHeight
973 * Thumb dimension of image
975 public static function getThumbSize($imageWidth, $imageHeight) {
977 if ($imageWidth && $imageHeight) {
978 $imageRatio = $imageWidth / $imageHeight;
983 if ($imageRatio > 1) {
984 $imageThumbWidth = $thumbWidth;
985 $imageThumbHeight = round($thumbWidth / $imageRatio);
988 $imageThumbHeight = $thumbWidth;
989 $imageThumbWidth = round($thumbWidth * $imageRatio);
992 return array($imageThumbWidth, $imageThumbHeight);
996 * Validate type of contact image.
998 * @param array $params
999 * @param string $imageIndex
1000 * Index of image field.
1001 * @param string $statusMsg
1002 * Status message to be set after operation.
1003 * @param string $opType
1004 * Type of operation like fatal, bounce etc.
1007 * true if valid image extension
1009 public static function processImageParams(
1011 $imageIndex = 'image_URL',
1025 if (in_array($params[$imageIndex]['type'], $mimeType)) {
1026 $photo = basename($params[$imageIndex]['name']);
1027 $params[$imageIndex] = CRM_Utils_System
::url('civicrm/contact/imagefile', 'photo=' . $photo, TRUE, NULL, TRUE, TRUE);
1031 unset($params[$imageIndex]);
1033 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
1035 if ($opType == 'status') {
1036 CRM_Core_Session
::setStatus($statusMsg, 'Sorry', 'error');
1038 // FIXME: additional support for fatal, bounce etc could be added.
1044 * Extract contact id from url for deleting contact image.
1046 public static function processImage() {
1048 $action = CRM_Utils_Request
::retrieve('action', 'String');
1049 $cid = CRM_Utils_Request
::retrieve('cid', 'Positive');
1050 // retrieve contact id in case of Profile context
1051 $id = CRM_Utils_Request
::retrieve('id', 'Positive');
1052 $cid = $cid ?
$cid : $id;
1053 if ($action & CRM_Core_Action
::DELETE
) {
1054 if (CRM_Utils_Request
::retrieve('confirmed', 'Boolean')) {
1055 CRM_Contact_BAO_Contact
::deleteContactImage($cid);
1056 CRM_Core_Session
::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
1057 $session = CRM_Core_Session
::singleton();
1058 $toUrl = $session->popUserContext();
1059 CRM_Utils_System
::redirect($toUrl);
1065 * Function to set is_delete true or restore deleted contact.
1067 * @param CRM_Contact_DAO_Contact $contact
1068 * Contact DAO object.
1069 * @param bool $restore
1070 * True to set the is_delete = 1 else false to restore deleted contact,
1071 * i.e. is_delete = 0
1075 public static function contactTrashRestore($contact, $restore = FALSE) {
1076 $updateParams = array(
1077 'id' => $contact->id
,
1078 'is_deleted' => $restore ?
0 : 1,
1081 CRM_Utils_Hook
::pre('update', $contact->contact_type
, $contact->id
, $updateParams);
1083 $params = array(1 => array($contact->id
, 'Integer'));
1085 $query = "DELETE FROM civicrm_uf_match WHERE contact_id = %1";
1086 CRM_Core_DAO
::executeQuery($query, $params);
1089 $contact->copyValues($updateParams);
1092 CRM_Utils_Hook
::post('update', $contact->contact_type
, $contact->id
, $contact);
1098 * Get contact type for a contact.
1101 * Id of the contact whose contact type is needed.
1104 * contact_type if $id found else null ""
1106 public static function getContactType($id) {
1107 return CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1111 * Get contact sub type for a contact.
1114 * Id of the contact whose contact sub type is needed.
1116 * @param string $implodeDelimiter
1119 * contact_sub_type if $id found else null ""
1121 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1122 $subtype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1124 return $implodeDelimiter ?
NULL : array();
1127 $subtype = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($subtype, CRM_Core_DAO
::VALUE_SEPARATOR
));
1129 if ($implodeDelimiter) {
1130 $subtype = implode($implodeDelimiter, $subtype);
1136 * Get pair of contact-type and sub-type for a contact.
1139 * Id of the contact whose contact sub/contact type is needed.
1143 public static function getContactTypes($id) {
1144 $params = array('id' => $id);
1146 $contact = CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact',
1149 array('contact_type', 'contact_sub_type')
1153 $contactTypes = array();
1154 if ($contact->contact_sub_type
) {
1155 $contactTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($contact->contact_sub_type
, CRM_Core_DAO
::VALUE_SEPARATOR
));
1157 array_unshift($contactTypes, $contact->contact_type
);
1159 return $contactTypes;
1162 CRM_Core_Error
::fatal();
1167 * Combine all the importable fields from the lower levels object.
1169 * The ordering is important, since currently we do not have a weight
1170 * scheme. Adding weight is super important
1172 * @param int|string $contactType contact Type
1173 * @param bool $status
1174 * Status is used to manipulate first title.
1175 * @param bool $showAll
1176 * If true returns all fields (includes disabled fields).
1177 * @param bool $isProfile
1178 * If its profile mode.
1179 * @param bool $checkPermission
1180 * If false, do not include permissioning clause (for custom data).
1182 * @param bool $withMultiCustomFields
1185 * array of importable Fields
1187 public static function importableFields(
1188 $contactType = 'Individual',
1192 $checkPermission = TRUE,
1193 $withMultiCustomFields = FALSE
1195 if (empty($contactType)) {
1196 $contactType = 'All';
1199 $cacheKeyString = "importableFields $contactType";
1200 $cacheKeyString .= $status ?
'_1' : '_0';
1201 $cacheKeyString .= $showAll ?
'_1' : '_0';
1202 $cacheKeyString .= $isProfile ?
'_1' : '_0';
1203 $cacheKeyString .= $checkPermission ?
'_1' : '_0';
1205 $fields = CRM_Utils_Array
::value($cacheKeyString, self
::$_importableFields);
1208 // check if we can retrieve from database cache
1209 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1213 $fields = CRM_Contact_DAO_Contact
::import();
1215 // get the fields thar are meant for contact types
1216 if (in_array($contactType, array(
1222 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1225 $locationFields = array_merge(CRM_Core_DAO_Address
::import(),
1226 CRM_Core_DAO_Phone
::import(),
1227 CRM_Core_DAO_Email
::import(),
1228 CRM_Core_DAO_IM
::import(TRUE),
1229 CRM_Core_DAO_OpenID
::import()
1232 $locationFields = array_merge($locationFields,
1233 CRM_Core_BAO_CustomField
::getFieldsForImport('Address',
1241 foreach ($locationFields as $key => $field) {
1242 $locationFields[$key]['hasLocationType'] = TRUE;
1245 $fields = array_merge($fields, $locationFields);
1247 $fields = array_merge($fields, CRM_Contact_DAO_Contact
::import());
1248 $fields = array_merge($fields, CRM_Core_DAO_Note
::import());
1251 $fields = array_merge($fields, CRM_Core_DAO_Website
::import());
1252 $fields['url']['hasWebsiteType'] = TRUE;
1254 if ($contactType != 'All') {
1255 $fields = array_merge($fields,
1256 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType,
1261 $withMultiCustomFields
1264 //unset the fields, which are not related to their
1266 $commonValues = array(
1267 'Individual' => array(
1271 'organization_name',
1273 'Household' => array(
1283 'organization_name',
1291 'Organization' => array(
1306 foreach ($commonValues[$contactType] as $value) {
1307 unset($fields[$value]);
1311 foreach (array('Individual', 'Household', 'Organization') as $type) {
1312 $fields = array_merge($fields,
1313 CRM_Core_BAO_CustomField
::getFieldsForImport($type,
1318 $withMultiCustomFields
1325 $fields = array_merge($fields, array(
1327 'title' => ts('Group(s)'),
1331 'title' => ts('Tag(s)'),
1335 'title' => ts('Note(s)'),
1338 'communication_style_id' => array(
1339 'title' => ts('Communication Style'),
1340 'name' => 'communication_style_id',
1345 //Sorting fields in alphabetical order(CRM-1507)
1346 $fields = CRM_Utils_Array
::crmArraySortByField($fields, 'title');
1348 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1351 self
::$_importableFields[$cacheKeyString] = $fields;
1355 $fields = array_merge(array('do_not_import' => array('title' => ts('- do not import -'))),
1356 self
::$_importableFields[$cacheKeyString]
1360 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1361 self
::$_importableFields[$cacheKeyString]
1369 * Combine all the exportable fields from the lower levels object.
1371 * Currently we are using importable fields as exportable fields
1373 * @param int|string $contactType contact Type
1374 * @param bool $status
1375 * True while exporting primary contacts.
1376 * @param bool $export
1377 * True when used during export.
1378 * @param bool $search
1379 * True when used during search, might conflict with export param?.
1381 * @param bool $withMultiRecord
1384 * array of exportable Fields
1386 public static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE) {
1387 if (empty($contactType)) {
1388 $contactType = 'All';
1391 $cacheKeyString = "exportableFields $contactType";
1392 $cacheKeyString .= $export ?
'_1' : '_0';
1393 $cacheKeyString .= $status ?
'_1' : '_0';
1394 $cacheKeyString .= $search ?
'_1' : '_0';
1395 //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
1396 //calculates custom fields takes into account the logged in user & caches that for all users
1397 //as an interim fix we will cache the fields by contact
1398 $cacheKeyString .= '_' . CRM_Core_Session
::getLoggedInContactID();
1400 if (!self
::$_exportableFields ||
!CRM_Utils_Array
::value($cacheKeyString, self
::$_exportableFields)) {
1401 if (!self
::$_exportableFields) {
1402 self
::$_exportableFields = array();
1405 // check if we can retrieve from database cache
1406 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1409 $fields = CRM_Contact_DAO_Contact
::export();
1411 // The fields are meant for contact types.
1412 if (in_array($contactType, array(
1419 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1421 // add current employer for individuals
1422 $fields = array_merge($fields, array(
1423 'current_employer' =>
1425 'name' => 'organization_name',
1426 'title' => ts('Current Employer'),
1430 $locationType = array(
1431 'location_type' => array(
1432 'name' => 'location_type',
1433 'where' => 'civicrm_location_type.name',
1434 'title' => ts('Location Type'),
1438 $IMProvider = array(
1439 'im_provider' => array(
1440 'name' => 'im_provider',
1441 'where' => 'civicrm_im.provider_id',
1442 'title' => ts('IM Provider'),
1446 $locationFields = array_merge($locationType,
1447 CRM_Core_DAO_Address
::export(),
1448 CRM_Core_DAO_Phone
::export(),
1449 CRM_Core_DAO_Email
::export(),
1451 CRM_Core_DAO_IM
::export(TRUE),
1452 CRM_Core_DAO_OpenID
::export()
1455 $locationFields = array_merge($locationFields,
1456 CRM_Core_BAO_CustomField
::getFieldsForImport('Address')
1459 foreach ($locationFields as $key => $field) {
1460 $locationFields[$key]['hasLocationType'] = TRUE;
1463 $fields = array_merge($fields, $locationFields);
1466 $fields = array_merge($fields,
1467 CRM_Core_DAO_Worldregion
::export()
1470 $fields = array_merge($fields,
1471 CRM_Contact_DAO_Contact
::export()
1475 $fields = array_merge($fields, CRM_Core_DAO_Website
::export());
1477 if ($contactType != 'All') {
1478 $fields = array_merge($fields,
1479 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType, $status, FALSE, $search, TRUE, $withMultiRecord)
1488 $fields = array_merge($fields,
1489 CRM_Core_BAO_CustomField
::getFieldsForImport($type, FALSE, FALSE, $search, TRUE, $withMultiRecord)
1496 $fields = array_merge($fields, array(
1498 'title' => ts('Group(s)'),
1502 'title' => ts('Tag(s)'),
1506 'title' => ts('Note(s)'),
1512 $fields = array_merge($fields, array(
1514 'title' => ts('Group(s)'),
1518 'title' => ts('Tag(s)'),
1522 'title' => ts('Note(s)'),
1528 //Sorting fields in alphabetical order(CRM-1507)
1529 foreach ($fields as $k => $v) {
1530 $sortArray[$k] = CRM_Utils_Array
::value('title', $v);
1533 $fields = array_merge($sortArray, $fields);
1534 //unset the field which are not related to their contact type.
1535 if ($contactType != 'All') {
1536 $commonValues = array(
1537 'Individual' => array(
1541 'organization_name',
1542 'email_greeting_custom',
1543 'postal_greeting_custom',
1546 'Household' => array(
1556 'organization_name',
1564 'email_greeting_custom',
1565 'postal_greeting_custom',
1570 'Organization' => array(
1581 'email_greeting_custom',
1582 'postal_greeting_custom',
1592 foreach ($commonValues[$contactType] as $value) {
1593 unset($fields[$value]);
1597 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1599 self
::$_exportableFields[$cacheKeyString] = $fields;
1603 $fields = self
::$_exportableFields[$cacheKeyString];
1606 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1607 self
::$_exportableFields[$cacheKeyString]
1615 * Get the all contact details (Hierarchical).
1617 * @param int $contactId
1619 * @param array $fields
1625 public static function getHierContactDetails($contactId, &$fields) {
1626 $params = array(array('contact_id', '=', $contactId, 0, 0));
1629 $returnProperties = self
::makeHierReturnProperties($fields, $contactId);
1631 // We don't know the contents of return properties, but we need the lower
1632 // level ids of the contact so add a few fields.
1633 $returnProperties['first_name'] = 1;
1634 $returnProperties['organization_name'] = 1;
1635 $returnProperties['household_name'] = 1;
1636 $returnProperties['contact_type'] = 1;
1637 $returnProperties['contact_sub_type'] = 1;
1638 return list($query, $options) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, $options);
1642 * Given a set of flat profile style field names, create a hierarchy.
1644 * This is for the query to use, create the right sql.
1647 * @param int $contactId
1651 * A hierarchical property tree if appropriate
1653 public static function &makeHierReturnProperties($fields, $contactId = NULL) {
1654 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1656 $returnProperties = array();
1658 $multipleFields = array('website' => 'url');
1659 foreach ($fields as $name => $dontCare) {
1660 if (strpos($name, '-') !== FALSE) {
1661 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $name, 3);
1663 if (!in_array($fieldName, $multipleFields)) {
1664 if ($id == 'Primary') {
1665 $locationTypeName = 1;
1668 $locationTypeName = CRM_Utils_Array
::value($id, $locationTypes);
1669 if (!$locationTypeName) {
1674 if (empty($returnProperties['location'])) {
1675 $returnProperties['location'] = array();
1677 if (empty($returnProperties['location'][$locationTypeName])) {
1678 $returnProperties['location'][$locationTypeName] = array();
1679 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1681 if (in_array($fieldName, array(
1689 $returnProperties['location'][$locationTypeName][$fieldName . '-' . $type] = 1;
1692 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1695 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1696 $returnProperties['location'][$locationTypeName][substr($fieldName, 8)] = 1;
1699 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1703 $returnProperties['website'][$id][$fieldName] = 1;
1707 $returnProperties[$name] = 1;
1711 return $returnProperties;
1715 * Return the primary location type of a contact.
1717 * $params int $contactId contact_id
1718 * $params boolean $isPrimaryExist if true, return primary contact location type otherwise null
1719 * $params boolean $skipDefaultPriamry if true, return primary contact location type otherwise null
1721 * @param int $contactId
1722 * @param bool $skipDefaultPriamry
1723 * @param null $block
1726 * $locationType location_type_id
1728 public static function getPrimaryLocationType($contactId, $skipDefaultPriamry = FALSE, $block = NULL) {
1730 $entityBlock = array('contact_id' => $contactId);
1731 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock);
1732 foreach ($blocks[$block] as $key => $value) {
1733 if (!empty($value['is_primary'])) {
1734 $locationType = CRM_Utils_Array
::value('location_type_id', $value);
1741 IF ( civicrm_email.location_type_id IS NULL,
1742 IF ( civicrm_address.location_type_id IS NULL,
1743 IF ( civicrm_phone.location_type_id IS NULL,
1744 IF ( civicrm_im.location_type_id IS NULL,
1745 IF ( civicrm_openid.location_type_id IS NULL, null, civicrm_openid.location_type_id)
1746 ,civicrm_im.location_type_id)
1747 ,civicrm_phone.location_type_id)
1748 ,civicrm_address.location_type_id)
1749 ,civicrm_email.location_type_id) as locationType
1750 FROM civicrm_contact
1751 LEFT JOIN civicrm_email ON ( civicrm_email.is_primary = 1 AND civicrm_email.contact_id = civicrm_contact.id )
1752 LEFT JOIN civicrm_address ON ( civicrm_address.is_primary = 1 AND civicrm_address.contact_id = civicrm_contact.id)
1753 LEFT JOIN civicrm_phone ON ( civicrm_phone.is_primary = 1 AND civicrm_phone.contact_id = civicrm_contact.id)
1754 LEFT JOIN civicrm_im ON ( civicrm_im.is_primary = 1 AND civicrm_im.contact_id = civicrm_contact.id)
1755 LEFT JOIN civicrm_openid ON ( civicrm_openid.is_primary = 1 AND civicrm_openid.contact_id = civicrm_contact.id)
1756 WHERE civicrm_contact.id = %1 ";
1758 $params = array(1 => array($contactId, 'Integer'));
1760 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1762 $locationType = NULL;
1763 if ($dao->fetch()) {
1764 $locationType = $dao->locationType
;
1767 if (isset($locationType)) {
1768 return $locationType;
1770 elseif ($skipDefaultPriamry) {
1771 // if there is no primary contact location then return null
1775 // if there is no primart contact location, then return default
1776 // location type of the system
1777 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
1778 return $defaultLocationType->id
;
1783 * Get the display name, primary email and location type of a contact.
1786 * Id of the contact.
1789 * Array of display_name, email if found, do_not_email or (null,null,null)
1791 public static function getContactDetails($id) {
1792 // check if the contact type
1793 $contactType = self
::getContactType($id);
1795 $nameFields = ($contactType == 'Individual') ?
"civicrm_contact.first_name, civicrm_contact.last_name, civicrm_contact.display_name" : "civicrm_contact.display_name";
1798 SELECT $nameFields, civicrm_email.email, civicrm_contact.do_not_email, civicrm_email.on_hold, civicrm_contact.is_deceased
1799 FROM civicrm_contact LEFT JOIN civicrm_email ON (civicrm_contact.id = civicrm_email.contact_id)
1800 WHERE civicrm_contact.id = %1
1801 ORDER BY civicrm_email.is_primary DESC";
1802 $params = array(1 => array($id, 'Integer'));
1803 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
1805 if ($dao->fetch()) {
1806 if ($contactType == 'Individual') {
1807 if ($dao->first_name ||
$dao->last_name
) {
1808 $name = "{$dao->first_name} {$dao->last_name}";
1811 $name = $dao->display_name
;
1815 $name = $dao->display_name
;
1817 $email = $dao->email
;
1818 $doNotEmail = $dao->do_not_email ?
TRUE : FALSE;
1819 $onHold = $dao->on_hold ?
TRUE : FALSE;
1820 $isDeceased = $dao->is_deceased ?
TRUE : FALSE;
1821 return array($name, $email, $doNotEmail, $onHold, $isDeceased);
1823 return array(NULL, NULL, NULL, NULL, NULL);
1827 * Add/edit/register contacts through profile.
1829 * @param array $params
1830 * Array of profile fields to be edited/added.
1831 * @param array $fields
1832 * Array of fields from UFGroup.
1833 * @param int $contactID
1834 * Id of the contact to be edited/added.
1835 * @param int $addToGroupID
1836 * Specifies the default group to which contact is added.
1837 * @param int $ufGroupId
1838 * Uf group id (profile id).
1839 * @param string $ctype
1840 * @param bool $visibility
1841 * Basically lets us know where this request is coming from.
1842 * if via a profile from web, we restrict what groups are changed
1845 * contact id created/edited
1847 public static function createProfileContact(
1851 $addToGroupID = NULL,
1856 // add ufGroupID to params array ( CRM-2012 )
1858 $params['uf_group_id'] = $ufGroupId;
1863 CRM_Utils_Hook
::pre('edit', 'Profile', $contactID, $params);
1867 CRM_Utils_Hook
::pre('create', 'Profile', NULL, $params);
1870 list($data, $contactDetails) = self
::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
1872 // manage is_opt_out
1873 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
1874 $wasOptOut = CRM_Utils_Array
::value('is_opt_out', $contactDetails, FALSE);
1875 $isOptOut = CRM_Utils_Array
::value('is_opt_out', $params, FALSE);
1876 $data['is_opt_out'] = $isOptOut;
1877 // on change, create new civicrm_subscription_history entry
1878 if (($wasOptOut != $isOptOut) && !empty($contactDetails['contact_id'])) {
1880 'contact_id' => $contactDetails['contact_id'],
1881 'status' => $isOptOut ?
'Removed' : 'Added',
1884 CRM_Contact_BAO_SubscriptionHistory
::create($shParams);
1888 $contact = self
::create($data);
1890 // contact is null if the profile does not have any contact fields
1892 $contactID = $contact->id
;
1895 if (empty($contactID)) {
1896 CRM_Core_Error
::fatal('Cannot proceed without a valid contact id');
1899 // Process group and tag
1900 if (!empty($fields['group'])) {
1902 // this for sure means we are coming in via profile since i added it to fix
1903 // removing contacts from user groups -- lobo
1907 CRM_Contact_BAO_GroupContact
::create($params['group'], $contactID, $visibility, $method);
1910 if (!empty($fields['tag'])) {
1911 CRM_Core_BAO_EntityTag
::create($params['tag'], 'civicrm_contact', $contactID);
1914 //to add profile in default group
1915 if (is_array($addToGroupID)) {
1916 $contactIds = array($contactID);
1917 foreach ($addToGroupID as $groupId) {
1918 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
1921 elseif ($addToGroupID) {
1922 $contactIds = array($contactID);
1923 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $addToGroupID);
1926 // reset the group contact cache for this group
1927 CRM_Contact_BAO_GroupContactCache
::remove();
1930 CRM_Utils_Hook
::post('edit', 'Profile', $contactID, $params);
1933 CRM_Utils_Hook
::post('create', 'Profile', $contactID, $params);
1939 * Format profile contact parameters.
1941 * @param array $params
1943 * @param int $contactID
1944 * @param int $ufGroupId
1945 * @param null $ctype
1946 * @param bool $skipCustom
1950 public static function formatProfileContactParams(
1959 $data = $contactDetails = array();
1961 // get the contact details (hier)
1963 list($details, $options) = self
::getHierContactDetails($contactID, $fields);
1965 $contactDetails = $details[$contactID];
1966 $data['contact_type'] = CRM_Utils_Array
::value('contact_type', $contactDetails);
1967 $data['contact_sub_type'] = CRM_Utils_Array
::value('contact_sub_type', $contactDetails);
1970 //we should get contact type only if contact
1972 $data['contact_type'] = CRM_Core_BAO_UFField
::getProfileType($ufGroupId);
1974 //special case to handle profile with only contact fields
1975 if ($data['contact_type'] == 'Contact') {
1976 $data['contact_type'] = 'Individual';
1978 elseif (CRM_Contact_BAO_ContactType
::isaSubType($data['contact_type'])) {
1979 $data['contact_type'] = CRM_Contact_BAO_ContactType
::getBasicType($data['contact_type']);
1983 $data['contact_type'] = $ctype;
1986 $data['contact_type'] = 'Individual';
1990 //fix contact sub type CRM-5125
1991 if (array_key_exists('contact_sub_type', $params) &&
1992 !empty($params['contact_sub_type'])
1994 $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
;
1996 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
1997 !empty($params['contact_sub_type_hidden'])
1999 // if profile was used, and had any subtype, we obtain it from there
2000 $data['contact_sub_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, (array) $params['contact_sub_type_hidden']) . CRM_Core_DAO
::VALUE_SEPARATOR
;
2003 if ($ctype == 'Organization') {
2004 $data['organization_name'] = CRM_Utils_Array
::value('organization_name', $contactDetails);
2006 elseif ($ctype == 'Household') {
2007 $data['household_name'] = CRM_Utils_Array
::value('household_name', $contactDetails);
2010 $locationType = array();
2015 $data['contact_id'] = $contactID;
2016 $primaryLocationType = self
::getPrimaryLocationType($contactID);
2019 $defaultLocation = CRM_Core_BAO_LocationType
::getDefault();
2020 $defaultLocationId = $defaultLocation->id
;
2023 // get the billing location type
2024 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
2025 $billingLocationTypeId = array_search('Billing', $locationTypes);
2027 $blocks = array('email', 'phone', 'im', 'openid');
2029 $multiplFields = array('url');
2030 // prevent overwritten of formatted array, reset all block from
2031 // params if it is not in valid format (since import pass valid format)
2032 foreach ($blocks as $blk) {
2033 if (array_key_exists($blk, $params) &&
2034 !is_array($params[$blk])
2036 unset($params[$blk]);
2040 $primaryPhoneLoc = NULL;
2041 $session = CRM_Core_Session
::singleton();
2042 foreach ($params as $key => $value) {
2043 $fieldName = $locTypeId = $typeId = NULL;
2044 list($fieldName, $locTypeId, $typeId) = CRM_Utils_System
::explode('-', $key, 3);
2046 //store original location type id
2047 $actualLocTypeId = $locTypeId;
2049 if ($locTypeId == 'Primary') {
2051 if (in_array($fieldName, $blocks)) {
2052 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, $fieldName);
2055 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, 'address');
2057 $primaryLocationType = $locTypeId;
2060 $locTypeId = $defaultLocationId;
2064 if (is_numeric($locTypeId) &&
2065 !in_array($fieldName, $multiplFields) &&
2066 substr($fieldName, 0, 7) != 'custom_'
2068 $index = $locTypeId;
2070 if (is_numeric($typeId)) {
2071 $index .= '-' . $typeId;
2073 if (!in_array($index, $locationType)) {
2074 $locationType[$count] = $index;
2078 $loc = CRM_Utils_Array
::key($index, $locationType);
2080 $blockName = in_array($fieldName, $blocks) ?
$fieldName : 'address';
2082 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
2084 //set is_billing true, for location type "Billing"
2085 if ($locTypeId == $billingLocationTypeId) {
2086 $data[$blockName][$loc]['is_billing'] = 1;
2090 //get the primary location type
2091 if ($locTypeId == $primaryLocationType) {
2092 $data[$blockName][$loc]['is_primary'] = 1;
2095 elseif ($locTypeId == $defaultLocationId) {
2096 $data[$blockName][$loc]['is_primary'] = 1;
2099 if (in_array($fieldName, array('phone'))) {
2101 $data['phone'][$loc]['phone_type_id'] = $typeId;
2104 $data['phone'][$loc]['phone_type_id'] = '';
2106 $data['phone'][$loc]['phone'] = $value;
2108 //special case to handle primary phone with different phone types
2109 // in this case we make first phone type as primary
2110 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
2111 $primaryPhoneLoc = $loc;
2114 if ($loc != $primaryPhoneLoc) {
2115 unset($data['phone'][$loc]['is_primary']);
2118 elseif ($fieldName == 'phone_ext') {
2119 $data['phone'][$loc]['phone_ext'] = $value;
2121 elseif ($fieldName == 'email') {
2122 $data['email'][$loc]['email'] = $value;
2124 elseif ($fieldName == 'im') {
2125 if (isset($params[$key . '-provider_id'])) {
2126 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
2128 if (strpos($key, '-provider_id') !== FALSE) {
2129 $data['im'][$loc]['provider_id'] = $params[$key];
2132 $data['im'][$loc]['name'] = $value;
2135 elseif ($fieldName == 'openid') {
2136 $data['openid'][$loc]['openid'] = $value;
2139 if ($fieldName === 'state_province') {
2141 if (is_numeric($value) && ((int ) $value) >= 1000) {
2142 $data['address'][$loc]['state_province_id'] = $value;
2144 elseif (empty($value)) {
2145 $data['address'][$loc]['state_province_id'] = '';
2148 $data['address'][$loc]['state_province'] = $value;
2151 elseif ($fieldName === 'country') {
2153 if (is_numeric($value) && ((int ) $value) >= 1000
2155 $data['address'][$loc]['country_id'] = $value;
2157 elseif (empty($value)) {
2158 $data['address'][$loc]['country_id'] = '';
2161 $data['address'][$loc]['country'] = $value;
2164 elseif ($fieldName === 'county') {
2165 $data['address'][$loc]['county_id'] = $value;
2167 elseif ($fieldName == 'address_name') {
2168 $data['address'][$loc]['name'] = $value;
2170 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2171 $data['address'][$loc][substr($fieldName, 8)] = $value;
2174 $data['address'][$loc][$fieldName] = $value;
2179 if (substr($key, 0, 4) === 'url-') {
2180 $websiteField = explode('-', $key);
2181 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
2182 $data['website'][$websiteField[1]]['url'] = $value;
2184 elseif (in_array($key, self
::$_greetingTypes, TRUE)) {
2185 //save email/postal greeting and addressee values if any, CRM-4575
2186 $data[$key . '_id'] = $value;
2188 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($key))) {
2189 // for autocomplete transfer hidden value instead of label
2190 if ($params[$key] && isset($params[$key . '_id'])) {
2191 $value = $params[$key . '_id'];
2194 // we need to append time with date
2195 if ($params[$key] && isset($params[$key . '_time'])) {
2196 $value .= ' ' . $params[$key . '_time'];
2199 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
2200 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 &&
2201 ($value == '' ||
!isset($value))
2207 if (!empty($params['customRecordValues'])) {
2208 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2209 foreach ($params['customRecordValues'] as $recId => $customFields) {
2210 if (is_array($customFields) && !empty($customFields)) {
2211 foreach ($customFields as $customFieldName) {
2212 if ($customFieldName == $key) {
2222 $type = $data['contact_type'];
2223 if (!empty($data['contact_sub_type'])) {
2224 $type = $data['contact_sub_type'];
2225 $type = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($type, CRM_Core_DAO
::VALUE_SEPARATOR
));
2226 // generally a contact even if, has multiple subtypes the parent-type is going to be one only
2227 // and since formatCustomField() would be interested in parent type, lets consider only one subtype
2228 // as the results going to be same.
2232 CRM_Core_BAO_CustomField
::formatCustomField($customFieldId,
2240 elseif ($key == 'edit') {
2244 if ($key == 'location') {
2245 foreach ($value as $locationTypeId => $field) {
2246 foreach ($field as $block => $val) {
2247 if ($block == 'address' && array_key_exists('address_name', $val)) {
2248 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2253 if ($key == 'phone' && isset($params['phone_ext'])) {
2254 $data[$key] = $value;
2255 foreach ($value as $cnt => $phoneBlock) {
2256 if ($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']) {
2257 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array
::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2261 elseif (in_array($key,
2272 ($value == '' ||
!isset($value)) &&
2273 ($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0
2275 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
2276 // to avoid update with empty values
2280 $data[$key] = $value;
2286 if (!isset($data['contact_type'])) {
2287 $data['contact_type'] = 'Individual';
2290 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2291 $privacy = CRM_Core_SelectValues
::privacy();
2292 foreach ($privacy as $key => $value) {
2293 if (array_key_exists($key, $fields)) {
2294 // do not reset values for existing contacts, if fields are added to a profile
2295 if (array_key_exists($key, $params)) {
2296 $data[$key] = $params[$key];
2297 if (empty($params[$key])) {
2301 elseif (!$contactID) {
2307 return array($data, $contactDetails);
2311 * Find the get contact details.
2313 * This function does not respect ACLs for now, which might need to be rectified at some
2314 * stage based on how its used.
2316 * @param string $mail
2317 * Primary email address of the contact.
2318 * @param string $ctype
2322 * $dao contact details
2324 public static function &matchContactOnEmail($mail, $ctype = NULL) {
2325 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2326 $mail = $strtolower(trim($mail));
2328 SELECT civicrm_contact.id as contact_id,
2329 civicrm_contact.hash as hash,
2330 civicrm_contact.contact_type as contact_type,
2331 civicrm_contact.contact_sub_type as contact_sub_type
2332 FROM civicrm_contact
2333 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2335 if (CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
, 'uniq_email_per_site')) {
2336 // try to find a match within a site (multisite).
2337 $groups = CRM_Core_BAO_Domain
::getChildGroupIds();
2338 if (!empty($groups)) {
2340 INNER JOIN civicrm_group_contact gc ON
2341 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2346 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2347 $p = array(1 => array($mail, 'String'));
2350 $query .= " AND civicrm_contact.contact_type = %3";
2351 $p[3] = array($ctype, 'String');
2354 $query .= " ORDER BY civicrm_email.is_primary DESC";
2356 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2358 if ($dao->fetch()) {
2361 return CRM_Core_DAO
::$_nullObject;
2365 * Find the contact details associated with an OpenID.
2367 * @param string $openId
2368 * OpenId of the contact.
2369 * @param string $ctype
2373 * $dao contact details
2375 public static function &matchContactOnOpenId($openId, $ctype = NULL) {
2376 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2377 $openId = $strtolower(trim($openId));
2379 SELECT civicrm_contact.id as contact_id,
2380 civicrm_contact.hash as hash,
2381 civicrm_contact.contact_type as contact_type,
2382 civicrm_contact.contact_sub_type as contact_sub_type
2383 FROM civicrm_contact
2384 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2385 WHERE civicrm_openid.openid = %1";
2386 $p = array(1 => array($openId, 'String'));
2389 $query .= " AND civicrm_contact.contact_type = %3";
2390 $p[3] = array($ctype, 'String');
2393 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2395 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2397 if ($dao->fetch()) {
2400 return CRM_Core_DAO
::$_nullObject;
2404 * Get primary email of the contact.
2406 * @param int $contactID
2410 * Email address if present else null
2412 public static function getPrimaryEmail($contactID) {
2413 // fetch the primary email
2415 SELECT civicrm_email.email as email
2416 FROM civicrm_contact
2417 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2418 WHERE civicrm_email.is_primary = 1
2419 AND civicrm_contact.id = %1";
2420 $p = array(1 => array($contactID, 'Integer'));
2421 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2424 if ($dao->fetch()) {
2425 $email = $dao->email
;
2432 * Function to get primary OpenID of the contact.
2434 * @param int $contactID
2438 * >openid OpenID if present else null
2440 public static function getPrimaryOpenId($contactID) {
2441 // fetch the primary OpenID
2443 SELECT civicrm_openid.openid as openid
2444 FROM civicrm_contact
2445 LEFT JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2446 WHERE civicrm_contact.id = %1
2447 AND civicrm_openid.is_primary = 1";
2448 $p = array(1 => array($contactID, 'Integer'));
2449 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2452 if ($dao->fetch()) {
2453 $openId = $dao->openid
;
2460 * Fetch the object and store the values in the values array.
2462 * @param array $params
2463 * Input parameters to find object.
2464 * @param array $values
2465 * Output values of the object.
2467 * @return CRM_Contact_BAO_Contact|null
2468 * The found object or null
2470 public static function getValues(&$params, &$values) {
2471 $contact = new CRM_Contact_BAO_Contact();
2473 $contact->copyValues($params);
2475 if ($contact->find(TRUE)) {
2477 CRM_Core_DAO
::storeValues($contact, $values);
2480 foreach (self
::$_commPrefs as $name) {
2481 if (isset($contact->$name)) {
2482 $privacy[$name] = $contact->$name;
2486 if (!empty($privacy)) {
2487 $values['privacy'] = $privacy;
2490 // communication Prefferance
2491 $preffComm = $comm = array();
2492 $comm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2493 $contact->preferred_communication_method
2495 foreach ($comm as $value) {
2496 $preffComm[$value] = 1;
2498 $temp = array('preferred_communication_method' => $contact->preferred_communication_method
);
2501 'preferred_communication_method' => array(
2502 'newName' => 'preferred_communication_method_display',
2503 'groupName' => 'preferred_communication_method',
2507 CRM_Core_OptionGroup
::lookupValues($temp, $names, FALSE);
2509 $values['preferred_communication_method'] = $preffComm;
2510 $values['preferred_communication_method_display'] = CRM_Utils_Array
::value('preferred_communication_method_display', $temp);
2512 $preferredMailingFormat = CRM_Core_SelectValues
::pmf();
2513 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format
];
2515 // get preferred languages
2516 if (!empty($contact->preferred_language
)) {
2517 $values['preferred_language'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language
);
2520 // Calculating Year difference
2521 if ($contact->birth_date
) {
2522 $birthDate = CRM_Utils_Date
::customFormat($contact->birth_date
, '%Y%m%d');
2523 if ($birthDate < date('Ymd')) {
2524 $age = CRM_Utils_Date
::calculateAge($birthDate);
2525 $values['age']['y'] = CRM_Utils_Array
::value('years', $age);
2526 $values['age']['m'] = CRM_Utils_Array
::value('months', $age);
2529 list($values['birth_date']) = CRM_Utils_Date
::setDateDefaults($contact->birth_date
, 'birth');
2530 $values['birth_date_display'] = $contact->birth_date
;
2533 if ($contact->deceased_date
) {
2534 list($values['deceased_date']) = CRM_Utils_Date
::setDateDefaults($contact->deceased_date
, 'birth');
2535 $values['deceased_date_display'] = $contact->deceased_date
;
2538 $contact->contact_id
= $contact->id
;
2546 * Given the component name and returns the count of participation of contact.
2548 * @param string $component
2549 * Input component name.
2550 * @param int $contactId
2552 * @param string $tableName
2553 * Optional tableName if component is custom group.
2556 * total number in database
2558 public static function getCountComponent($component, $contactId, $tableName = NULL) {
2560 switch ($component) {
2562 return CRM_Core_BAO_EntityTag
::getContactTags($contactId, TRUE);
2565 $result = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
2566 CRM_Contact_BAO_Relationship
::CURRENT
,
2573 return CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, "Added", NULL, TRUE);
2576 if (CRM_Core_BAO_Log
::useLoggingReport()) {
2579 return CRM_Core_BAO_Log
::getContactLogCount($contactId);
2582 return CRM_Core_BAO_Note
::getContactNoteCount($contactId);
2584 case 'contribution':
2585 return CRM_Contribute_BAO_Contribution
::contributionCount($contactId);
2588 return CRM_Member_BAO_Membership
::getContactMembershipCount($contactId, TRUE);
2591 return CRM_Event_BAO_Participant
::getContactParticipantCount($contactId);
2594 return CRM_Pledge_BAO_Pledge
::getContactPledgeCount($contactId);
2597 return CRM_Case_BAO_Case
::caseCount($contactId);
2600 return CRM_Grant_BAO_Grant
::getContactGrantCount($contactId);
2604 'contact_id' => $contactId,
2607 'context' => 'activity',
2609 return CRM_Activity_BAO_Activity
::getActivitiesCount($input);
2612 $params = array('contact_id' => $contactId);
2613 return CRM_Mailing_BAO_Mailing
::getContactMailingsCount($params);
2616 $custom = explode('_', $component);
2617 if ($custom['0'] = 'custom') {
2619 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2621 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2622 return CRM_Core_DAO
::singleValueQuery($queryString);
2628 * Process greetings and cache.
2630 * @param object $contact
2631 * Contact object after save.
2632 * @param bool $useDefaults
2633 * Use default greeting values.
2635 public static function processGreetings(&$contact, $useDefaults = FALSE) {
2637 //retrieve default greetings
2638 $defaultGreetings = CRM_Core_PseudoConstant
::greetingDefaults();
2639 $contactDefaults = $defaultGreetings[$contact->contact_type
];
2642 // note that contact object not always has required greeting related
2643 // fields that are required to calculate greeting and
2644 // also other fields used in tokens etc,
2645 // hence we need to retrieve it again.
2646 if ($contact->_query
!== FALSE) {
2647 $contact->find(TRUE);
2650 // store object values to an array
2651 $contactDetails = array();
2652 CRM_Core_DAO
::storeValues($contact, $contactDetails);
2653 $contactDetails = array(array($contact->id
=> $contactDetails));
2655 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2656 $updateQueryString = array();
2658 //cache email and postal greeting to greeting display
2659 if ($contact->email_greeting_custom
!= 'null' && $contact->email_greeting_custom
) {
2660 $emailGreetingString = $contact->email_greeting_custom
;
2662 elseif ($contact->email_greeting_id
!= 'null' && $contact->email_greeting_id
) {
2663 // the filter value for Individual contact type is set to 1
2665 'contact_type' => $contact->contact_type
,
2666 'greeting_type' => 'email_greeting',
2669 $emailGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2670 $emailGreetingString = $emailGreeting[$contact->email_greeting_id
];
2671 $updateQueryString[] = " email_greeting_custom = NULL ";
2675 reset($contactDefaults['email_greeting']);
2676 $emailGreetingID = key($contactDefaults['email_greeting']);
2677 $emailGreetingString = $contactDefaults['email_greeting'][$emailGreetingID];
2678 $updateQueryString[] = " email_greeting_id = $emailGreetingID ";
2679 $updateQueryString[] = " email_greeting_custom = NULL ";
2681 elseif ($contact->email_greeting_custom
) {
2682 $updateQueryString[] = " email_greeting_display = NULL ";
2686 if ($emailGreetingString) {
2687 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($emailGreetingString,
2690 'CRM_Contact_BAO_Contact'
2692 $emailGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($emailGreetingString));
2693 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2697 if ($contact->postal_greeting_custom
!= 'null' && $contact->postal_greeting_custom
) {
2698 $postalGreetingString = $contact->postal_greeting_custom
;
2700 elseif ($contact->postal_greeting_id
!= 'null' && $contact->postal_greeting_id
) {
2702 'contact_type' => $contact->contact_type
,
2703 'greeting_type' => 'postal_greeting',
2705 $postalGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2706 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id
];
2707 $updateQueryString[] = " postal_greeting_custom = NULL ";
2711 reset($contactDefaults['postal_greeting']);
2712 $postalGreetingID = key($contactDefaults['postal_greeting']);
2713 $postalGreetingString = $contactDefaults['postal_greeting'][$postalGreetingID];
2714 $updateQueryString[] = " postal_greeting_id = $postalGreetingID ";
2715 $updateQueryString[] = " postal_greeting_custom = NULL ";
2717 elseif ($contact->postal_greeting_custom
) {
2718 $updateQueryString[] = " postal_greeting_display = NULL ";
2722 if ($postalGreetingString) {
2723 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($postalGreetingString,
2726 'CRM_Contact_BAO_Contact'
2728 $postalGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($postalGreetingString));
2729 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2733 if ($contact->addressee_custom
!= 'null' && $contact->addressee_custom
) {
2734 $addresseeString = $contact->addressee_custom
;
2736 elseif ($contact->addressee_id
!= 'null' && $contact->addressee_id
) {
2738 'contact_type' => $contact->contact_type
,
2739 'greeting_type' => 'addressee',
2742 $addressee = CRM_Core_PseudoConstant
::greeting($filter);
2743 $addresseeString = $addressee[$contact->addressee_id
];
2744 $updateQueryString[] = " addressee_custom = NULL ";
2748 reset($contactDefaults['addressee']);
2749 $addresseeID = key($contactDefaults['addressee']);
2750 $addresseeString = $contactDefaults['addressee'][$addresseeID];
2751 $updateQueryString[] = " addressee_id = $addresseeID ";
2752 $updateQueryString[] = " addressee_custom = NULL ";
2754 elseif ($contact->addressee_custom
) {
2755 $updateQueryString[] = " addressee_display = NULL ";
2759 if ($addresseeString) {
2760 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($addresseeString,
2763 'CRM_Contact_BAO_Contact'
2765 $addresseeString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($addresseeString));
2766 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2769 if (!empty($updateQueryString)) {
2770 $updateQueryString = implode(',', $updateQueryString);
2771 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2772 CRM_Core_DAO
::executeQuery($queryString);
2777 * Retrieve loc block ids w/ given condition.
2779 * @param int $contactId
2781 * @param array $criteria
2782 * Key => value pair which should be.
2783 * fulfill by return record ids.
2784 * @param string $condOperator
2785 * Operator use for grouping multiple conditions.
2788 * loc block ids which fulfill condition.
2790 public static function getLocBlockIds($contactId, $criteria = array(), $condOperator = 'AND') {
2791 $locBlockIds = array();
2793 return $locBlockIds;
2796 foreach (array('Email', 'OpenID', 'Phone', 'Address', 'IM') as $block) {
2797 $name = strtolower($block);
2798 $className = "CRM_Core_DAO_$block";
2799 $blockDAO = new $className();
2801 // build the condition.
2802 if (is_array($criteria)) {
2803 $fields = $blockDAO->fields();
2804 $conditions = array();
2805 foreach ($criteria as $field => $value) {
2806 if (array_key_exists($field, $fields)) {
2807 $cond = "( $field = $value )";
2808 // value might be zero or null.
2809 if (!$value ||
strtolower($value) == 'null') {
2810 $cond = "( $field = 0 OR $field IS NULL )";
2812 $conditions[] = $cond;
2815 if (!empty($conditions)) {
2816 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2820 $blockDAO->contact_id
= $contactId;
2822 while ($blockDAO->fetch()) {
2823 $locBlockIds[$name][] = $blockDAO->id
;
2828 return $locBlockIds;
2832 * Build context menu items.
2834 * @param int $contactId
2837 * Array of context menu for logged in user.
2839 public static function contextMenu($contactId = NULL) {
2842 'title' => ts('View Contact'),
2844 'ref' => 'view-contact',
2845 'class' => 'no-popup',
2847 'permissions' => array('view all contacts'),
2850 'title' => ts('Edit Contact'),
2852 'ref' => 'edit-contact',
2853 'class' => 'no-popup',
2855 'permissions' => array('edit all contacts'),
2858 'title' => ts('Delete Contact'),
2860 'ref' => 'delete-contact',
2862 'permissions' => array('access deleted contacts', 'delete contacts'),
2864 'contribution' => array(
2865 'title' => ts('Add Contribution'),
2867 'ref' => 'new-contribution',
2868 'key' => 'contribution',
2869 'tab' => 'contribute',
2870 'component' => 'CiviContribute',
2871 'href' => CRM_Utils_System
::url('civicrm/contact/view/contribution',
2872 'reset=1&action=add&context=contribution'
2874 'permissions' => array(
2875 'access CiviContribute',
2876 'edit contributions',
2879 'participant' => array(
2880 'title' => ts('Register for Event'),
2882 'ref' => 'new-participant',
2883 'key' => 'participant',
2884 'tab' => 'participant',
2885 'component' => 'CiviEvent',
2886 'href' => CRM_Utils_System
::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
2887 'permissions' => array(
2889 'edit event participants',
2892 'activity' => array(
2893 'title' => ts('Record Activity'),
2895 'ref' => 'new-activity',
2896 'key' => 'activity',
2897 'permissions' => array('edit all contacts'),
2900 'title' => ts('Add Pledge'),
2902 'ref' => 'new-pledge',
2905 'href' => CRM_Utils_System
::url('civicrm/contact/view/pledge',
2906 'reset=1&action=add&context=pledge'
2908 'component' => 'CiviPledge',
2909 'permissions' => array(
2910 'access CiviPledge',
2914 'membership' => array(
2915 'title' => ts('Add Membership'),
2917 'ref' => 'new-membership',
2918 'key' => 'membership',
2920 'component' => 'CiviMember',
2921 'href' => CRM_Utils_System
::url('civicrm/contact/view/membership',
2922 'reset=1&action=add&context=membership'
2924 'permissions' => array(
2925 'access CiviMember',
2930 'title' => ts('Add Case'),
2932 'ref' => 'new-case',
2935 'component' => 'CiviCase',
2936 'href' => CRM_Utils_System
::url('civicrm/case/add', 'reset=1&action=add&context=case'),
2937 'permissions' => array('add cases'),
2940 'title' => ts('Add Grant'),
2942 'ref' => 'new-grant',
2945 'component' => 'CiviGrant',
2946 'href' => CRM_Utils_System
::url('civicrm/contact/view/grant',
2947 'reset=1&action=add&context=grant'
2949 'permissions' => array('edit grants'),
2952 'title' => ts('Add Relationship'),
2954 'ref' => 'new-relationship',
2957 'href' => CRM_Utils_System
::url('civicrm/contact/view/rel',
2958 'reset=1&action=add'
2960 'permissions' => array('edit all contacts'),
2963 'title' => ts('Add Note'),
2965 'ref' => 'new-note',
2968 'class' => 'medium-popup',
2969 'href' => CRM_Utils_System
::url('civicrm/contact/view/note',
2970 'reset=1&action=add'
2972 'permissions' => array('edit all contacts'),
2975 'title' => ts('Send an Email'),
2977 'ref' => 'new-email',
2979 'permissions' => array('view all contacts'),
2982 'title' => ts('Add to Group'),
2984 'ref' => 'group-add-contact',
2987 'permissions' => array('edit groups'),
2990 'title' => ts('Tag Contact'),
2992 'ref' => 'tag-contact',
2995 'permissions' => array('edit all contacts'),
2999 CRM_Utils_Hook
::summaryActions($menu, $contactId);
3000 //1. check for component is active.
3001 //2. check for user permissions.
3002 //3. check for acls.
3003 //3. edit and view contact are directly accessible to user.
3005 $aclPermissionedTasks = array(
3010 'group-add-contact',
3014 $corePermission = CRM_Core_Permission
::getPermission();
3016 $config = CRM_Core_Config
::singleton();
3018 $contextMenu = array();
3019 foreach ($menu as $key => $values) {
3020 $componentName = CRM_Utils_Array
::value('component', $values);
3022 // if component action - make sure component is enable.
3023 if ($componentName && !in_array($componentName, $config->enableComponents
)) {
3027 // make sure user has all required permissions.
3028 $hasAllPermissions = FALSE;
3030 $permissions = CRM_Utils_Array
::value('permissions', $values);
3031 if (!is_array($permissions) ||
empty($permissions)) {
3032 $hasAllPermissions = TRUE;
3035 // iterate for required permissions in given permissions array.
3036 if (!$hasAllPermissions) {
3037 $hasPermissions = 0;
3038 foreach ($permissions as $permission) {
3039 if (CRM_Core_Permission
::check($permission)) {
3044 if (count($permissions) == $hasPermissions) {
3045 $hasAllPermissions = TRUE;
3048 // if still user does not have required permissions, check acl.
3049 if (!$hasAllPermissions && $values['ref'] != 'delete-contact') {
3050 if (in_array($values['ref'], $aclPermissionedTasks) &&
3051 $corePermission == CRM_Core_Permission
::EDIT
3053 $hasAllPermissions = TRUE;
3055 elseif (in_array($values['ref'], array(
3058 // grant permissions for these tasks.
3059 $hasAllPermissions = TRUE;
3064 // user does not have necessary permissions.
3065 if (!$hasAllPermissions) {
3069 // build directly accessible action menu.
3070 if (in_array($values['ref'], array(
3074 $contextMenu['primaryActions'][$key] = array(
3075 'title' => $values['title'],
3076 'ref' => $values['ref'],
3077 'class' => CRM_Utils_Array
::value('class', $values),
3078 'key' => $values['key'],
3083 // finally get menu item for -more- action widget.
3084 $contextMenu['moreActions'][$values['weight']] = array(
3085 'title' => $values['title'],
3086 'ref' => $values['ref'],
3087 'href' => CRM_Utils_Array
::value('href', $values),
3088 'tab' => CRM_Utils_Array
::value('tab', $values),
3089 'class' => CRM_Utils_Array
::value('class', $values),
3090 'key' => $values['key'],
3094 ksort($contextMenu['moreActions']);
3096 return $contextMenu;
3100 * Retrieve display name of contact that address is shared.
3102 * This is based on $masterAddressId or $contactId .
3104 * @param int $masterAddressId
3106 * @param int $contactId
3109 * @return string|null
3110 * the found display name or null.
3112 public static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3113 $masterDisplayName = NULL;
3115 if (!$masterAddressId && !$contactId) {
3116 return $masterDisplayName;
3119 if ($masterAddressId) {
3121 SELECT display_name from civicrm_contact
3122 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3123 WHERE civicrm_address.id = " . $masterAddressId;
3125 elseif ($contactId) {
3127 SELECT display_name from civicrm_contact cc, civicrm_address add1
3128 LEFT JOIN civicrm_address add2 ON ( add1.master_id = add2.id )
3129 WHERE cc.id = add2.contact_id AND add1.contact_id = " . $contactId;
3132 $masterDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
3133 return $masterDisplayName;
3137 * Get the creation/modification times for a contact.
3139 * @param int $contactId
3142 * Dates - ('created_date' => $, 'modified_date' => $)
3144 public static function getTimestamps($contactId) {
3145 $timestamps = CRM_Core_DAO
::executeQuery(
3146 'SELECT created_date, modified_date
3147 FROM civicrm_contact
3150 1 => array($contactId, 'Integer'),
3153 if ($timestamps->fetch()) {
3155 'created_date' => $timestamps->created_date
,
3156 'modified_date' => $timestamps->modified_date
,
3165 * Generate triggers to update the timestamp.
3167 * The corresponding civicrm_contact row is updated on insert/update/delete
3168 * to a table that extends civicrm_contact.
3169 * Don't regenerate triggers for all such tables if only asked for one table.
3171 * @param array $info
3172 * Reference to the array where generated trigger information is being stored
3173 * @param string|null $reqTableName
3174 * Name of the table for which triggers are being generated, or NULL if all tables
3175 * @param array $relatedTableNames
3176 * Array of all core or all custom table names extending civicrm_contact
3177 * @param string $contactRefColumn
3178 * 'contact_id' if processing core tables, 'entity_id' if processing custom tables
3180 * @link https://issues.civicrm.org/jira/browse/CRM-15602
3183 public static function generateTimestampTriggers(&$info, $reqTableName, $relatedTableNames, $contactRefColumn) {
3185 $contactRefColumn = CRM_Core_DAO
::escapeString($contactRefColumn);
3186 // If specific related table requested, just process that one
3187 if (in_array($reqTableName, $relatedTableNames)) {
3188 $relatedTableNames = array($reqTableName);
3191 // If no specific table requested (include all related tables),
3192 // or a specific related table requested (as matched above)
3193 if (empty($reqTableName) ||
in_array($reqTableName, $relatedTableNames)) {
3195 'table' => $relatedTableNames,
3197 'event' => array('INSERT', 'UPDATE'),
3198 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = NEW.$contactRefColumn;\n",
3201 'table' => $relatedTableNames,
3203 'event' => array('DELETE'),
3204 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = OLD.$contactRefColumn;\n",
3210 * Get a list of triggers for the contact table.
3212 * @see hook_civicrm_triggerInfo
3213 * @see CRM_Core_DAO::triggerRebuild
3214 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3216 public static function triggerInfo(&$info, $tableName = NULL) {
3217 //during upgrade, first check for valid version and then create triggers
3218 //i.e the columns created_date and modified_date are introduced in 4.3.alpha1 so dont create triggers for older version
3219 if (CRM_Core_Config
::isUpgradeMode()) {
3220 $currentVer = CRM_Core_BAO_Domain
::version(TRUE);
3221 //if current version is less than 4.3.alpha1 dont create below triggers
3222 if (version_compare($currentVer, '4.3.alpha1') < 0) {
3227 // Update timestamp for civicrm_contact itself
3228 if ($tableName == NULL ||
$tableName == self
::getTableName()) {
3230 'table' => array(self
::getTableName()),
3232 'event' => array('INSERT'),
3233 'sql' => "\nSET NEW.created_date = CURRENT_TIMESTAMP;\n",
3237 // Update timestamp when modifying closely related core tables
3238 $relatedTables = array(
3245 self
::generateTimestampTriggers($info, $tableName, $relatedTables, 'contact_id');
3247 // Update timestamp when modifying related custom-data tables
3248 $customGroupTables = array();
3249 $customGroupDAO = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity('Contact');
3250 $customGroupDAO->is_multiple
= 0;
3251 $customGroupDAO->find();
3252 while ($customGroupDAO->fetch()) {
3253 $customGroupTables[] = $customGroupDAO->table_name
;
3255 if (!empty($customGroupTables)) {
3256 self
::generateTimestampTriggers($info, $tableName, $customGroupTables, 'entity_id');
3259 // Update phone table to populate phone_numeric field
3260 if (!$tableName ||
$tableName == 'civicrm_phone') {
3261 // Define stored sql function needed for phones
3262 CRM_Core_DAO
::executeQuery(self
::DROP_STRIP_FUNCTION_43
);
3263 CRM_Core_DAO
::executeQuery(self
::CREATE_STRIP_FUNCTION_43
);
3265 'table' => array('civicrm_phone'),
3267 'event' => array('INSERT', 'UPDATE'),
3268 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3274 * Check if contact is being used in civicrm_domain based on $contactId.
3276 * @param int $contactId
3280 * true if present else false.
3282 public static function checkDomainContact($contactId) {
3286 $domainId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3297 * Get options for a given contact field.
3299 * @see CRM_Core_DAO::buildOptions
3301 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3302 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3304 * @param string $fieldName
3305 * @param string $context
3306 * @see CRM_Core_DAO::buildOptionsContext
3307 * @param array $props
3308 * whatever is known about this dao object.
3310 * @return array|bool
3312 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3314 // Special logic for fields whose options depend on context or properties
3315 switch ($fieldName) {
3316 case 'contact_sub_type':
3317 if (!empty($props['contact_type'])) {
3318 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3322 case 'contact_type':
3323 if ($context == 'search') {
3324 // CRM-15495 - EntityRef filters and basic search forms expect this format
3325 // FIXME: Search builder does not
3326 return CRM_Contact_BAO_ContactType
::getSelectElements();
3330 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
3334 * Delete a contact-related object that has an 'is_primary' field.
3336 * Ensures that is_primary gets assigned to another object if available
3337 * Also calls pre/post hooks
3343 public static function deleteObjectWithPrimary($type, $id) {
3344 if (!$id ||
!is_numeric($id)) {
3347 $daoName = "CRM_Core_DAO_$type";
3348 $obj = new $daoName();
3351 if ($obj->fetch()) {
3352 CRM_Utils_Hook
::pre('delete', $type, $id, CRM_Core_DAO
::$_nullArray);
3353 $contactId = $obj->contact_id
;
3359 // is_primary is only relavent if this field belongs to a contact
3361 $dao = new $daoName();
3362 $dao->contact_id
= $contactId;
3363 $dao->is_primary
= 1;
3364 // Pick another record to be primary (if one isn't already)
3365 if (!$dao->find(TRUE)) {
3366 $dao->is_primary
= 0;
3368 if ($dao->fetch()) {
3369 $dao->is_primary
= 1;
3375 CRM_Utils_Hook
::post('delete', $type, $id, $obj);