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
35 class CRM_Contact_BAO_Contact
extends CRM_Contact_DAO_Contact
{
38 * SQL function used to format the phone_numeric field via trigger.
39 * @see self::triggerInfo()
41 * Note that this is also used by the 4.3 upgrade script.
42 * @see CRM_Upgrade_Incremental_php_FourThree
44 const DROP_STRIP_FUNCTION_43
= "DROP FUNCTION IF EXISTS civicrm_strip_non_numeric";
45 const CREATE_STRIP_FUNCTION_43
= "
46 CREATE FUNCTION civicrm_strip_non_numeric(input VARCHAR(255) CHARACTER SET utf8)
47 RETURNS VARCHAR(255) CHARACTER SET utf8
51 DECLARE output VARCHAR(255) CHARACTER SET utf8 DEFAULT '';
52 DECLARE iterator INT DEFAULT 1;
53 WHILE iterator < (LENGTH(input) + 1) DO
54 IF SUBSTRING(input, iterator, 1) IN ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') THEN
55 SET output = CONCAT(output, SUBSTRING(input, iterator, 1));
57 SET iterator = iterator + 1;
63 * The types of communication preferences
67 static $_commPrefs = array('do_not_phone', 'do_not_email', 'do_not_mail', 'do_not_sms', 'do_not_trade');
74 static $_greetingTypes = array('addressee', 'email_greeting', 'postal_greeting');
77 * Static field for all the contact information that we can potentially import
82 static $_importableFields = array();
85 * Static field for all the contact information that we can potentially export
90 static $_exportableFields = NULL;
95 * @return \CRM_Contact_DAO_Contact
100 public function __construct() {
101 parent
::__construct();
105 * Takes an associative array and creates a contact object
107 * the function extract all the params it needs to initialize the create a
108 * contact object. the params array could contain additional unused name/value
111 * @param array $params (reference ) an assoc array of name/value pairs
113 * @return CRM_Contact_BAO_Contact object
116 public static function add(&$params) {
117 $contact = new CRM_Contact_DAO_Contact();
119 if (empty($params)) {
123 //fix for validate contact sub type CRM-5143
124 if ( isset( $params['contact_sub_type'] ) ) {
125 if ( empty($params['contact_sub_type']) ) {
126 $params['contact_sub_type'] = 'null';
129 if (!CRM_Contact_BAO_ContactType
::isExtendsContactType($params['contact_sub_type'],
130 $params['contact_type'], TRUE
132 // we'll need to fix tests to handle this
134 CRM_Core_Error
::fatal(ts('The Contact Sub Type does not match the Contact type for this record'));
136 if (is_array($params['contact_sub_type'])) {
137 $params['contact_sub_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $params['contact_sub_type']) . CRM_Core_DAO
::VALUE_SEPARATOR
;
140 $params['contact_sub_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. trim($params['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
147 $params['contact_sub_type'] = 'null';
150 //fixed contact source
151 if (isset($params['contact_source'])) {
152 $params['source'] = $params['contact_source'];
155 //fix for preferred communication method
156 $prefComm = CRM_Utils_Array
::value('preferred_communication_method', $params);
157 if ($prefComm && is_array($prefComm)) {
158 unset($params['preferred_communication_method']);
161 foreach ($prefComm as $k => $v) {
167 $prefComm = $newPref;
168 if (is_array($prefComm) && !empty($prefComm)) {
169 $prefComm = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, array_keys($prefComm)) . CRM_Core_DAO
::VALUE_SEPARATOR
;
170 $contact->preferred_communication_method
= $prefComm;
173 $contact->preferred_communication_method
= '';
177 $allNull = $contact->copyValues($params);
179 $contact->id
= CRM_Utils_Array
::value('contact_id', $params);
181 if ($contact->contact_type
== 'Individual') {
184 //format individual fields
185 CRM_Contact_BAO_Individual
::format($params, $contact);
187 elseif ($contact->contact_type
== 'Household') {
188 if (isset($params['household_name'])) {
190 $contact->display_name
= $contact->sort_name
= CRM_Utils_Array
::value('household_name', $params, '');
193 elseif ($contact->contact_type
== 'Organization') {
194 if (isset($params['organization_name'])) {
196 $contact->display_name
= $contact->sort_name
= CRM_Utils_Array
::value('organization_name', $params, '');
201 $privacy = CRM_Utils_Array
::value('privacy', $params);
203 is_array($privacy) &&
207 foreach (self
::$_commPrefs as $name) {
208 $contact->$name = CRM_Utils_Array
::value($name, $privacy, FALSE);
212 // since hash was required, make sure we have a 0 value for it, CRM-1063
213 // fixed in 1.5 by making hash optional
214 // only do this in create mode, not update
215 if ((!array_key_exists('hash', $contact) ||
!$contact->hash
) && !$contact->id
) {
217 $contact->hash
= md5(uniqid(rand(), TRUE));
220 // Even if we don't need $employerId, it's important to call getFieldValue() before
221 // the contact is saved because we want the existing value to be cached.
222 // createCurrentEmployerRelationship() needs the old value not the updated one. CRM-10788
223 $employerId = empty($contact->id
) ?
NULL : CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contact->id
, 'employer_id');
228 CRM_Core_BAO_Log
::register($contact->id
,
234 if ($contact->contact_type
== 'Individual' && (isset($params['current_employer']) ||
isset($params['employer_id']))) {
235 // create current employer
236 $newEmployer = !empty($params['employer_id']) ?
$params['employer_id'] : CRM_Utils_Array
::value('current_employer', $params);
239 if (empty($params['contact_id'])) {
243 CRM_Contact_BAO_Contact_Utils
::createCurrentEmployerRelationship($contact->id
, $newEmployer, $employerId, $newContact);
246 //unset if employer id exits
248 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($contact->id
, $employerId);
253 //update cached employee name
254 if ($contact->contact_type
== 'Organization') {
255 CRM_Contact_BAO_Contact_Utils
::updateCurrentEmployer($contact->id
);
263 * takes an associative array and creates a contact object and all the associated
264 * derived objects (i.e. individual, location, email, phone etc)
266 * This function is invoked from within the web form layer and also from the api layer
268 * @param array $params (reference ) an assoc array of name/value pairs
269 * @param boolean $fixAddress if we need to fix address
270 * @param boolean $invokeHooks if we need to invoke hooks
272 * @param bool $skipDelete
275 * @return CRM_Contact_BAO_Contact object
278 public static function &create(&$params, $fixAddress = TRUE, $invokeHooks = TRUE, $skipDelete = FALSE) {
280 if (empty($params['contact_type']) && empty($params['contact_id'])) {
286 if (!empty($params['contact_id'])) {
287 CRM_Utils_Hook
::pre('edit', $params['contact_type'], $params['contact_id'], $params);
290 CRM_Utils_Hook
::pre('create', $params['contact_type'], NULL, $params);
295 $config = CRM_Core_Config
::singleton();
297 // CRM-6942: set preferred language to the current language if it’s unset (and we’re creating a contact)
298 if (empty($params['contact_id']) && empty($params['preferred_language'])) {
299 $params['preferred_language'] = $config->lcMessages
;
302 // CRM-9739: set greeting & addressee if unset and we’re creating a contact
303 if (empty($params['contact_id'])) {
304 foreach (self
::$_greetingTypes as $greeting) {
305 if (empty($params[$greeting . '_id'])) {
306 if ($defaultGreetingTypeId =
307 CRM_Contact_BAO_Contact_Utils
::defaultGreeting($params['contact_type'], $greeting)
309 $params[$greeting . '_id'] = $defaultGreetingTypeId;
315 $transaction = new CRM_Core_Transaction();
317 $contact = self
::add($params);
319 // not dying here is stupid, since we get into wierd situation and into a bug that
320 // is impossible to figure out for the user or for us
322 CRM_Core_Error
::fatal();
325 $params['contact_id'] = $contact->id
;
327 if (CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
330 // Enabling multisite causes the contact to be added to the domain group
331 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
332 if(!empty($domainGroupID)){
333 if (!empty($params['group']) && is_array($params['group'])) {
334 $params['group'][$domainGroupID] = 1;
337 $params['group'] = array($domainGroupID => 1);
342 if (array_key_exists('group', $params)) {
343 $contactIds = array($params['contact_id']);
344 foreach ($params['group'] as $groupId => $flag) {
346 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
348 elseif ($flag == -1) {
349 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $groupId);
354 //add location Block data
355 $blocks = CRM_Core_BAO_Location
::create($params, $fixAddress);
356 foreach ($blocks as $name => $value) {
357 $contact->$name = $value;
361 CRM_Core_BAO_Website
::create($params['website'], $contact->id
, $skipDelete);
363 //get userID from session
364 $session = CRM_Core_Session
::singleton();
365 $userID = $session->get('userID');
367 if (!empty($params['note'])) {
368 if (is_array($params['note'])) {
369 foreach ($params['note'] as $note) {
370 $contactId = $contact->id
;
371 if (isset($note['contact_id'])) {
372 $contactId = $note['contact_id'];
374 //if logged in user, overwrite contactId
376 $contactId = $userID;
380 'entity_id' => $contact->id
,
381 'entity_table' => 'civicrm_contact',
382 'note' => $note['note'],
383 'subject' => CRM_Utils_Array
::value('subject', $note),
384 'contact_id' => $contactId,
386 CRM_Core_BAO_Note
::add($noteParams, CRM_Core_DAO
::$_nullArray);
390 $contactId = $contact->id
;
391 if (isset($note['contact_id'])) {
392 $contactId = $note['contact_id'];
394 //if logged in user, overwrite contactId
396 $contactId = $userID;
400 'entity_id' => $contact->id
,
401 'entity_table' => 'civicrm_contact',
402 'note' => $params['note'],
403 'subject' => CRM_Utils_Array
::value('subject', $params),
404 'contact_id' => $contactId,
406 CRM_Core_BAO_Note
::add($noteParams, CRM_Core_DAO
::$_nullArray);
411 // update the UF user_unique_id if that has changed
412 CRM_Core_BAO_UFMatch
::updateUFName($contact->id
);
414 if (!empty($params['custom']) &&
415 is_array($params['custom'])
417 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contact', $contact->id
);
420 // make a civicrm_subscription_history entry only on contact create (CRM-777)
421 if (empty($params['contact_id'])) {
422 $subscriptionParams = array(
423 'contact_id' => $contact->id
,
427 CRM_Contact_BAO_SubscriptionHistory
::create($subscriptionParams);
430 $transaction->commit();
432 // CRM-6367: fetch the right label for contact type’s display
433 $contact->contact_type_display
= CRM_Core_DAO
::getFieldValue(
434 'CRM_Contact_DAO_ContactType',
435 $contact->contact_type
,
440 if (!$config->doNotResetCache
) {
441 // Note: doNotResetCache flag is currently set by import contact process and merging,
442 // since resetting and
443 // rebuilding cache could be expensive (for many contacts). We might come out with better
444 // approach in future.
445 CRM_Contact_BAO_Contact_Utils
::clearContactCaches($contact->id
);
450 CRM_Utils_Hook
::post('edit', $params['contact_type'], $contact->id
, $contact);
453 CRM_Utils_Hook
::post('create', $params['contact_type'], $contact->id
, $contact);
457 // process greetings CRM-4575, cache greetings
458 self
::processGreetings($contact);
464 * Get the display name and image of a contact
466 * @param int $id the contactId
470 * @return array the displayName and contactImage for this contact
473 public static function getDisplayAndImage($id, $type = FALSE) {
474 //CRM-14276 added the * on the civicrm_contact table so that we have all the contact info available
476 SELECT civicrm_contact.*,
477 civicrm_email.email as email
479 LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
480 AND civicrm_email.is_primary = 1
481 WHERE civicrm_contact.id = " . CRM_Utils_Type
::escape($id, 'Integer');
482 $dao = new CRM_Core_DAO();
485 $image = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
486 $dao->contact_sub_type
: $dao->contact_type
, FALSE, $id
488 $imageUrl = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
489 $dao->contact_sub_type
: $dao->contact_type
, TRUE, $id
492 // use email if display_name is empty
493 if (empty($dao->display_name
)) {
494 $displayName = $dao->email
;
497 $displayName = $dao->display_name
;
500 CRM_Utils_Hook
::alterDisplayName($displayName, $id, $dao);
502 return $type ?
array(
506 $dao->contact_sub_type
,
508 ) : array($displayName, $image, $imageUrl);
514 * @param array $crudLinkSpec with keys:
515 * - action: int, CRM_Core_Action::UPDATE or CRM_Core_Action::VIEW [default: VIEW]
516 * - entity_table: string, eg "civicrm_contact"
518 * @return array|NULL NULL if unavailable, or an array. array has keys:
522 * @see CRM_Utils_System::createDefaultCrudLink
524 public function createDefaultCrudLink($crudLinkSpec) {
525 switch ($crudLinkSpec['action']) {
526 case CRM_Core_Action
::VIEW
:
528 'title' => $this->display_name
,
529 'path' => 'civicrm/contact/view',
535 case CRM_Core_Action
::UPDATE
:
537 'title' => $this->display_name
,
538 'path' => 'civicrm/contact/add',
541 'action' => 'update',
550 * Get the values for pseudoconstants for name->value and reverse.
552 * @param array $defaults (reference) the default values, some of which need to be resolved.
553 * @param boolean $reverse true if we want to resolve the values in the reverse direction (value -> name)
558 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
559 // hack for birth_date
560 if (!empty($defaults['birth_date'])) {
561 if (is_array($defaults['birth_date'])) {
562 $defaults['birth_date'] = CRM_Utils_Date
::format($defaults['birth_date'], '-');
566 CRM_Utils_Array
::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id'), $reverse);
567 CRM_Utils_Array
::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'suffix_id'), $reverse);
568 CRM_Utils_Array
::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'), $reverse);
569 CRM_Utils_Array
::lookupValue($defaults, 'communication_style', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'communication_style_id'), $reverse);
571 //lookup value of email/postal greeting, addressee, CRM-4575
572 foreach (self
::$_greetingTypes as $greeting) {
573 $filterCondition = array('contact_type' => CRM_Utils_Array
::value('contact_type', $defaults),
574 'greeting_type' => $greeting,
576 CRM_Utils_Array
::lookupValue($defaults, $greeting,
577 CRM_Core_PseudoConstant
::greeting($filterCondition), $reverse
581 $blocks = array('address', 'im', 'phone');
582 foreach ($blocks as $name) {
583 if (!array_key_exists($name, $defaults) ||
!is_array($defaults[$name])) {
586 foreach ($defaults[$name] as $count => & $values) {
588 //get location type id.
589 CRM_Utils_Array
::lookupValue($values, 'location_type', CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id'), $reverse);
591 if ($name == 'address') {
592 // FIXME: lookupValue doesn't work for vcard_name
593 if (!empty($values['location_type_id'])) {
594 $vcardNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array('labelColumn' => 'vcard_name'));
595 $values['vcard_name'] = $vcardNames[$values['location_type_id']];
598 if (!CRM_Utils_Array
::lookupValue($values,
600 CRM_Core_PseudoConstant
::country(),
605 CRM_Utils_Array
::lookupValue($values,
607 CRM_Core_PseudoConstant
::countryIsoCode(),
613 // if we find a country id above, we need to restrict it to that country
614 // rather than the list of all countries
616 if (!empty($values['country_id'])) {
617 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($values['country_id']);
620 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvince();
622 if (!CRM_Utils_Array
::lookupValue($values,
630 if (!empty($values['country_id'])) {
631 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($values['country_id'], 'abbreviation');
634 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviation();
636 CRM_Utils_Array
::lookupValue($values,
643 if (!empty($values['state_province_id'])) {
644 $countyList = CRM_Core_PseudoConstant
::countyForState($values['state_province_id']);
647 $countyList = CRM_Core_PseudoConstant
::county();
649 CRM_Utils_Array
::lookupValue($values,
657 CRM_Utils_Array
::lookupValue($values,
659 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id'),
664 if ($name == 'phone') {
665 CRM_Utils_Array
::lookupValue($values,
667 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id'),
672 //kill the reference.
679 * Fetch object based on array of properties
681 * @param array $params (reference ) an assoc array of name/value pairs
682 * @param array $defaults (reference ) an assoc array to hold the name / value pairs
683 * in a hierarchical manner
684 * @param boolean $microformat for location in microformat
686 * @return CRM_Contact_BAO_Contact object
689 public static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
690 if (array_key_exists('contact_id', $params)) {
691 $params['id'] = $params['contact_id'];
693 elseif (array_key_exists('id', $params)) {
694 $params['contact_id'] = $params['id'];
697 $contact = self
::getValues($params, $defaults);
699 unset($params['id']);
701 //get the block information for this contact
702 $entityBlock = array('contact_id' => $params['contact_id']);
703 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock, $microformat);
704 $defaults = array_merge($defaults, $blocks);
705 foreach ($blocks as $block => $value) $contact->$block = $value;
707 if (!isset($params['noNotes'])) {
708 $contact->notes
= CRM_Core_BAO_Note
::getValues($params, $defaults);
711 if (!isset($params['noRelationships'])) {
712 $contact->relationship
= CRM_Contact_BAO_Relationship
::getValues($params, $defaults);
715 if (!isset($params['noGroups'])) {
716 $contact->groupContact
= CRM_Contact_BAO_GroupContact
::getValues($params, $defaults);
719 if (!isset($params['noWebsite'])) {
720 $contact->website
= CRM_Core_BAO_Website
::getValues($params, $defaults);
727 * Get the display name of a contact
729 * @param int $id id of the contact
731 * @return null|string display name of the contact if found
734 public static function displayName($id) {
737 $displayName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
744 * Delete a contact and all its associated records
746 * @param int $id id of the contact to delete
747 * @param bool $restore whether to actually restore, not delete
748 * @param bool $skipUndelete whether to force contact delete or not
750 * @return boolean true if contact deleted, false otherwise
753 public static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE) {
759 // make sure we have edit permission for this contact
761 if (($skipUndelete && !CRM_Core_Permission
::check('delete contacts')) ||
762 ($restore && !CRM_Core_Permission
::check('access deleted contacts'))
768 // Restrict contact to be delete if contact has financial trxns
770 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent(array($id), $error)) {
774 // make sure this contact_id does not have any membership types
775 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
778 'member_of_contact_id'
780 if ($membershipTypeID) {
784 $contact = new CRM_Contact_DAO_Contact();
786 if (!$contact->find(TRUE)) {
790 $contactType = $contact->contact_type
;
791 $action = ($restore) ?
'restore' : 'delete';
793 CRM_Utils_Hook
::pre($action, $contactType, $id, CRM_Core_DAO
::$_nullArray);
796 self
::contactTrashRestore($contact, TRUE);
797 CRM_Utils_Hook
::post($action, $contactType, $contact->id
, $contact);
802 // currently we only clear employer cache.
803 // we are not deleting inherited membership if any.
804 if ($contact->contact_type
== 'Organization') {
805 CRM_Contact_BAO_Contact_Utils
::clearAllEmployee($id);
808 // start a new transaction
809 $transaction = new CRM_Core_Transaction();
811 if ($skipUndelete or !CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'contact_undelete', NULL)) {
813 //delete billing address if exists.
814 CRM_Contribute_BAO_Contribution
::deleteAddress(NULL, $id);
816 // delete the log entries since we dont have triggers enabled as yet
817 $logDAO = new CRM_Core_DAO_Log();
818 $logDAO->entity_table
= 'civicrm_contact';
819 $logDAO->entity_id
= $id;
822 // delete contact participants CRM-12155
823 CRM_Event_BAO_Participant
::deleteContactParticipant($id);
825 // delete contact contributions CRM-12155
826 CRM_Contribute_BAO_Contribution
::deleteContactContribution($id);
828 // do activity cleanup, CRM-5604
829 CRM_Activity_BAO_Activity
::cleanupActivity($id);
831 // delete all notes related to contact
832 CRM_Core_BAO_Note
::cleanContactNotes($id);
834 // delete cases related to contact
835 $contactCases = CRM_Case_BAO_Case
::retrieveCaseIdsByContactId($id);
836 if (!empty($contactCases)) {
837 foreach ($contactCases as $caseId) {
838 //check if case is associate with other contact or not.
839 $caseContactId = CRM_Case_BAO_Case
::getCaseClients($caseId);
840 if (count($caseContactId) <= 1) {
841 CRM_Case_BAO_Case
::deleteCase($caseId);
849 self
::contactTrashRestore($contact);
852 //delete the contact id from recently view
853 CRM_Utils_Recent
::delContact($id);
855 // Update the group contact cache
857 CRM_Contact_BAO_GroupContactCache
::remove();
860 CRM_Contact_BAO_GroupContactCache
::removeContact($id);
863 // delete any dupe cache entry
864 CRM_Core_BAO_PrevNextCache
::deleteItem($id);
866 $transaction->commit();
868 CRM_Utils_Hook
::post('delete', $contactType, $contact->id
, $contact);
870 // also reset the DB_DO global array so we can reuse the memory
871 // http://issues.civicrm.org/jira/browse/CRM-4387
872 CRM_Core_DAO
::freeResult();
878 * Delete the image of a contact
880 * @param int $id id of the contact
882 * @return boolean true if contact image is deleted
884 public static function deleteContactImage($id) {
889 UPDATE civicrm_contact
892 CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
897 * Return relative path
898 * @todo make this a method of $config->userSystem (i.e. UF classes) rather than a static function
900 * @param string $absolutePath absolute path
902 * @return String $relativePath Relative url of uploaded image
904 public static function getRelativePath($absolutePath) {
905 $relativePath = NULL;
906 $config = CRM_Core_Config
::singleton();
907 if ($config->userFramework
== 'Joomla') {
908 $userFrameworkBaseURL = trim(str_replace('/administrator/', '', $config->userFrameworkBaseURL
));
909 $customFileUploadDirectory = strstr(str_replace('\\', '/', $absolutePath), '/media');
910 $relativePath = $userFrameworkBaseURL . $customFileUploadDirectory;
912 elseif ($config->userSystem
->is_drupal
== '1') {
913 //ideally we would do a bigger re-factoring & move the getRelativePath onto the UF class
914 $rootPath = $config->userSystem
->cmsRootPath();
915 $baseUrl = $config->userFrameworkBaseURL
;
917 //format url for language negotiation, CRM-7135
918 $baseUrl = CRM_Utils_System
::languageNegotiationURL($baseUrl, FALSE, TRUE);
920 $relativePath = str_replace("{$rootPath}/",
922 str_replace('\\', '/', $absolutePath)
924 } else if ( $config->userFramework
== 'WordPress' ) {
925 $userFrameworkBaseURL = trim( str_replace( '/wp-admin/', '', $config->userFrameworkBaseURL
) );
926 $customFileUploadDirectory = strstr( str_replace('\\', '/', $absolutePath), '/wp-content/' );
927 $relativePath = $userFrameworkBaseURL . $customFileUploadDirectory;
930 return $relativePath;
934 * Return proportional height and width of the image
936 * @param Integer $imageWidth width of image
938 * @param Integer $imageHeight height of image
940 * @return Array thumb dimension of image
942 public static function getThumbSize($imageWidth, $imageHeight) {
944 if ($imageWidth && $imageHeight) {
945 $imageRatio = $imageWidth / $imageHeight;
950 if ($imageRatio > 1) {
951 $imageThumbWidth = $thumbWidth;
952 $imageThumbHeight = round($thumbWidth / $imageRatio);
955 $imageThumbHeight = $thumbWidth;
956 $imageThumbWidth = round($thumbWidth * $imageRatio);
959 return array($imageThumbWidth, $imageThumbHeight);
963 * Validate type of contact image
965 * @param array $params
966 * @param String $imageIndex index of image field
967 * @param String $statusMsg status message to be set after operation
968 * @param string $opType type of operation like fatal, bounce etc
970 * @return boolean true if valid image extension
972 public static function processImageParams(&$params,
973 $imageIndex = 'image_URL',
987 if (in_array($params[$imageIndex]['type'], $mimeType)) {
988 $photo = basename($params[$imageIndex]['name']);
989 $params[$imageIndex] = CRM_Utils_System
::url('civicrm/contact/imagefile', 'photo='.$photo, TRUE, NULL, TRUE, TRUE);
993 unset($params[$imageIndex]);
995 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
997 if ($opType == 'status') {
998 CRM_Core_Session
::setStatus($statusMsg, 'Sorry', 'error');
1000 // FIXME: additional support for fatal, bounce etc could be added.
1006 * Extract contact id from url for deleting contact image
1008 public static function processImage() {
1010 $action = CRM_Utils_Request
::retrieve('action', 'String');
1011 $cid = CRM_Utils_Request
::retrieve('cid', 'Positive');
1012 // retrieve contact id in case of Profile context
1013 $id = CRM_Utils_Request
::retrieve('id', 'Positive');
1014 $cid = $cid ?
$cid : $id;
1015 if ($action & CRM_Core_Action
::DELETE
) {
1016 if (CRM_Utils_Request
::retrieve('confirmed', 'Boolean')) {
1017 CRM_Contact_BAO_Contact
::deleteContactImage($cid);
1018 CRM_Core_Session
::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
1019 $session = CRM_Core_Session
::singleton();
1020 $toUrl = $session->popUserContext();
1021 CRM_Utils_System
::redirect($toUrl);
1027 * Function to set is_delete true or restore deleted contact
1029 * @param int $contact Contact DAO object
1030 * @param boolean $restore true to set the is_delete = 1 else false to restore deleted contact,
1031 * i.e. is_delete = 0
1036 public static function contactTrashRestore($contact, $restore = FALSE) {
1037 $op = ($restore ?
'restore' : 'trash');
1039 CRM_Utils_Hook
::pre($op, $contact->contact_type
, $contact->id
, CRM_Core_DAO
::$_nullArray);
1041 $params = array(1 => array($contact->id
, 'Integer'));
1042 $isDelete = ' is_deleted = 1 ';
1044 $isDelete = ' is_deleted = 0 ';
1047 $query = "DELETE FROM civicrm_uf_match WHERE contact_id = %1";
1048 CRM_Core_DAO
::executeQuery($query, $params);
1051 $query = "UPDATE civicrm_contact SET {$isDelete} WHERE id = %1";
1052 CRM_Core_DAO
::executeQuery($query, $params);
1054 CRM_Utils_Hook
::post($op, $contact->contact_type
, $contact->id
, $contact);
1058 * Get contact type for a contact.
1060 * @param int $id - id of the contact whose contact type is needed
1062 * @return string contact_type if $id found else null ""
1068 public static function getContactType($id) {
1069 return CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1073 * Get contact sub type for a contact.
1075 * @param int $id - id of the contact whose contact sub type is needed
1077 * @param null $implodeDelimiter
1079 * @return string contact_sub_type if $id found else null ""
1084 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1085 $subtype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1087 return $implodeDelimiter ?
NULL : array();
1090 $subtype = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($subtype, CRM_Core_DAO
::VALUE_SEPARATOR
));
1092 if ($implodeDelimiter) {
1093 $subtype = implode($implodeDelimiter, $subtype);
1099 * Get pair of contact-type and sub-type for a contact.
1101 * @param int $id - id of the contact whose contact sub/contact type is needed
1109 public static function getContactTypes($id) {
1110 $params = array('id' => $id);
1112 $contact = CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact',
1115 array('contact_type', 'contact_sub_type')
1119 $contactTypes = array();
1120 if ($contact->contact_sub_type
)
1121 $contactTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($contact->contact_sub_type
, CRM_Core_DAO
::VALUE_SEPARATOR
));
1122 array_unshift($contactTypes, $contact->contact_type
);
1124 return $contactTypes;
1127 CRM_Core_Error
::fatal();
1132 * Combine all the importable fields from the lower levels object
1134 * The ordering is important, since currently we do not have a weight
1135 * scheme. Adding weight is super important
1137 * @param int|string $contactType contact Type
1138 * @param boolean $status status is used to manipulate first title
1139 * @param boolean $showAll if true returns all fields (includes disabled fields)
1140 * @param boolean $isProfile if its profile mode
1141 * @param boolean $checkPermission if false, do not include permissioning clause (for custom data)
1143 * @param bool $withMultiCustomFields
1145 * @return array array of importable Fields
1148 static function importableFields($contactType = 'Individual',
1152 $checkPermission = TRUE,
1153 $withMultiCustomFields = FALSE
1155 if (empty($contactType)) {
1156 $contactType = 'All';
1159 $cacheKeyString = "importableFields $contactType";
1160 $cacheKeyString .= $status ?
'_1' : '_0';
1161 $cacheKeyString .= $showAll ?
'_1' : '_0';
1162 $cacheKeyString .= $isProfile ?
'_1' : '_0';
1163 $cacheKeyString .= $checkPermission ?
'_1' : '_0';
1165 $fields = CRM_Utils_Array
::value($cacheKeyString, self
::$_importableFields);
1168 // check if we can retrieve from database cache
1169 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1173 $fields = CRM_Contact_DAO_Contact
::import();
1175 // get the fields thar are meant for contact types
1176 if (in_array($contactType, array(
1177 'Individual', 'Household', 'Organization', 'All'))) {
1178 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1181 $locationFields = array_merge(CRM_Core_DAO_Address
::import(),
1182 CRM_Core_DAO_Phone
::import(),
1183 CRM_Core_DAO_Email
::import(),
1184 CRM_Core_DAO_IM
::import(TRUE),
1185 CRM_Core_DAO_OpenID
::import()
1188 $locationFields = array_merge($locationFields,
1189 CRM_Core_BAO_CustomField
::getFieldsForImport('Address',
1197 foreach ($locationFields as $key => $field) {
1198 $locationFields[$key]['hasLocationType'] = TRUE;
1201 $fields = array_merge($fields, $locationFields);
1203 $fields = array_merge($fields, CRM_Contact_DAO_Contact
::import());
1204 $fields = array_merge($fields, CRM_Core_DAO_Note
::import());
1207 $fields = array_merge($fields, CRM_Core_DAO_Website
::import());
1208 $fields['url']['hasWebsiteType'] = TRUE;
1210 if ($contactType != 'All') {
1211 $fields = array_merge($fields,
1212 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType,
1217 $withMultiCustomFields
1220 //unset the fields, which are not related to their
1222 $commonValues = array(
1223 'Individual' => array(
1229 'Household' => array(
1239 'organization_name',
1247 'Organization' => array(
1262 foreach ($commonValues[$contactType] as $value) {
1263 unset($fields[$value]);
1268 'Individual', 'Household', 'Organization') as $type) {
1269 $fields = array_merge($fields,
1270 CRM_Core_BAO_CustomField
::getFieldsForImport($type,
1275 $withMultiCustomFields
1282 $fields = array_merge($fields, array(
1284 'title' => ts('Group(s)'),
1288 'title' => ts('Tag(s)'),
1292 'title' => ts('Note(s)'),
1295 'communication_style_id' => array(
1296 'title' => ts('Communication Style'),
1297 'name' => 'communication_style_id',
1302 //Sorting fields in alphabetical order(CRM-1507)
1303 $fields = CRM_Utils_Array
::crmArraySortByField($fields, 'title');
1305 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1308 self
::$_importableFields[$cacheKeyString] = $fields;
1312 $fields = array_merge(array('do_not_import' => array('title' => ts('- do not import -'))),
1313 self
::$_importableFields[$cacheKeyString]
1317 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1318 self
::$_importableFields[$cacheKeyString]
1326 * Combine all the exportable fields from the lower levels object
1328 * currentlty we are using importable fields as exportable fields
1330 * @param int|string $contactType contact Type
1331 * @param boolean $status true while exporting primary contacts
1332 * @param boolean $export true when used during export
1333 * @param boolean $search true when used during search, might conflict with export param?
1335 * @param bool $withMultiRecord
1337 * @return array array of exportable Fields
1340 public static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE) {
1341 if (empty($contactType)) {
1342 $contactType = 'All';
1345 $cacheKeyString = "exportableFields $contactType";
1346 $cacheKeyString .= $export ?
'_1' : '_0';
1347 $cacheKeyString .= $status ?
'_1' : '_0';
1348 $cacheKeyString .= $search ?
'_1' : '_0';
1349 //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
1350 //calculates custom fields takes into account the logged in user & caches that for all users
1351 //as an interim fix we will cache the fields by contact
1352 $cacheKeyString .= '_' . CRM_Core_Session
::getLoggedInContactID();
1354 if (!self
::$_exportableFields ||
!CRM_Utils_Array
::value($cacheKeyString, self
::$_exportableFields)) {
1355 if (!self
::$_exportableFields) {
1356 self
::$_exportableFields = array();
1359 // check if we can retrieve from database cache
1360 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1363 $fields = CRM_Contact_DAO_Contact
::export();
1365 // the fields are meant for contact types
1369 array('Individual', 'Household', 'Organization', 'All')
1372 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1374 // add current employer for individuals
1375 $fields = array_merge($fields, array(
1376 'current_employer' =>
1378 'name' => 'organization_name',
1379 'title' => ts('Current Employer'),
1383 $locationType = array(
1384 'location_type' => array(
1385 'name' => 'location_type',
1386 'where' => 'civicrm_location_type.name',
1387 'title' => ts('Location Type'),
1390 $IMProvider = array(
1391 'im_provider' => array(
1392 'name' => 'im_provider',
1393 'where' => 'civicrm_im.provider_id',
1394 'title' => ts('IM Provider'),
1397 $locationFields = array_merge($locationType,
1398 CRM_Core_DAO_Address
::export(),
1399 CRM_Core_DAO_Phone
::export(),
1400 CRM_Core_DAO_Email
::export(),
1402 CRM_Core_DAO_IM
::export(TRUE),
1403 CRM_Core_DAO_OpenID
::export()
1406 $locationFields = array_merge($locationFields,
1407 CRM_Core_BAO_CustomField
::getFieldsForImport('Address')
1410 foreach ($locationFields as $key => $field) {
1411 $locationFields[$key]['hasLocationType'] = TRUE;
1414 $fields = array_merge($fields, $locationFields);
1417 $fields = array_merge($fields,
1418 CRM_Core_DAO_Worldregion
::export()
1422 $fields = array_merge($fields,
1423 CRM_Contact_DAO_Contact
::export()
1427 $fields = array_merge($fields, CRM_Core_DAO_Website
::export());
1429 if ($contactType != 'All') {
1430 $fields = array_merge($fields,
1431 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType, $status, FALSE, $search, TRUE, $withMultiRecord)
1436 'Individual', 'Household', 'Organization') as $type) {
1437 $fields = array_merge($fields,
1438 CRM_Core_BAO_CustomField
::getFieldsForImport($type, FALSE, FALSE, $search, TRUE, $withMultiRecord)
1445 $fields = array_merge($fields, array(
1447 'title' => ts('Group(s)'),
1451 'title' => ts('Tag(s)'),
1455 'title' => ts('Note(s)'),
1461 $fields = array_merge($fields, array(
1463 'title' => ts('Group(s)'),
1467 'title' => ts('Tag(s)'),
1471 'title' => ts('Note(s)'),
1477 //Sorting fields in alphabetical order(CRM-1507)
1478 foreach ($fields as $k => $v) {
1479 $sortArray[$k] = CRM_Utils_Array
::value('title', $v);
1482 $fields = array_merge($sortArray, $fields);
1483 //unset the field which are not related to their contact type.
1484 if ($contactType != 'All') {
1485 $commonValues = array(
1486 'Individual' => array(
1490 'organization_name',
1491 'email_greeting_custom',
1492 'postal_greeting_custom',
1495 'Household' => array(
1505 'organization_name',
1513 'email_greeting_custom',
1514 'postal_greeting_custom',
1519 'Organization' => array(
1530 'email_greeting_custom',
1531 'postal_greeting_custom',
1541 foreach ($commonValues[$contactType] as $value) {
1542 unset($fields[$value]);
1546 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1548 self
::$_exportableFields[$cacheKeyString] = $fields;
1552 $fields = self
::$_exportableFields[$cacheKeyString];
1555 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1556 self
::$_exportableFields[$cacheKeyString]
1564 * Get the all contact details(Hierarchical)
1566 * @param int $contactId contact id
1567 * @param array $fields fields array
1569 * @return $values array contains the contact details
1572 public static function getHierContactDetails($contactId, &$fields) {
1573 $params = array(array('contact_id', '=', $contactId, 0, 0));
1576 $returnProperties = self
::makeHierReturnProperties($fields, $contactId);
1578 // we dont know the contents of return properties, but we need the lower level ids of the contact
1579 // so add a few fields
1580 $returnProperties['first_name'] =
1581 $returnProperties['organization_name'] =
1582 $returnProperties['household_name'] =
1583 $returnProperties['contact_type'] =
1584 $returnProperties['contact_sub_type'] = 1;
1585 return list($query, $options) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, $options);
1589 * Given a set of flat profile style field names, create a hierarchy
1590 * for query to use and crete the right sql
1593 * @param int $contactId contact id
1595 * @return array a hierarchical property tree if appropriate
1598 public static function &makeHierReturnProperties($fields, $contactId = NULL) {
1599 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1601 $returnProperties = array();
1603 $multipleFields = array('website' => 'url');
1604 foreach ($fields as $name => $dontCare) {
1605 if (strpos($name, '-') !== FALSE) {
1606 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $name, 3);
1608 if (!in_array($fieldName, $multipleFields)) {
1609 if ($id == 'Primary') {
1610 $locationTypeName = 1;
1613 $locationTypeName = CRM_Utils_Array
::value($id, $locationTypes);
1614 if (!$locationTypeName) {
1619 if (empty($returnProperties['location'])) {
1620 $returnProperties['location'] = array();
1622 if (empty($returnProperties['location'][$locationTypeName])) {
1623 $returnProperties['location'][$locationTypeName] = array();
1624 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1626 if (in_array($fieldName, array(
1627 'phone', 'im', 'email', 'openid', 'phone_ext'))) {
1629 $returnProperties['location'][$locationTypeName][$fieldName . '-' . $type] = 1;
1632 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1635 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1636 $returnProperties['location'][$locationTypeName][substr($fieldName, 8)] = 1;
1639 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1643 $returnProperties['website'][$id][$fieldName] = 1;
1647 $returnProperties[$name] = 1;
1651 return $returnProperties;
1655 * Return the primary location type of a contact
1657 * $params int $contactId contact_id
1658 * $params boolean $isPrimaryExist if true, return primary contact location type otherwise null
1659 * $params boolean $skipDefaultPriamry if true, return primary contact location type otherwise null
1661 * @param int $contactId
1662 * @param bool $skipDefaultPriamry
1663 * @param null $block
1665 * @return int $locationType location_type_id
1668 public static function getPrimaryLocationType($contactId, $skipDefaultPriamry = FALSE, $block = NULL) {
1670 $entityBlock = array('contact_id' => $contactId);
1671 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock);
1672 foreach($blocks[$block] as $key => $value){
1673 if (!empty($value['is_primary'])){
1674 $locationType = CRM_Utils_Array
::value('location_type_id',$value);
1681 IF ( civicrm_email.location_type_id IS NULL,
1682 IF ( civicrm_address.location_type_id IS NULL,
1683 IF ( civicrm_phone.location_type_id IS NULL,
1684 IF ( civicrm_im.location_type_id IS NULL,
1685 IF ( civicrm_openid.location_type_id IS NULL, null, civicrm_openid.location_type_id)
1686 ,civicrm_im.location_type_id)
1687 ,civicrm_phone.location_type_id)
1688 ,civicrm_address.location_type_id)
1689 ,civicrm_email.location_type_id) as locationType
1690 FROM civicrm_contact
1691 LEFT JOIN civicrm_email ON ( civicrm_email.is_primary = 1 AND civicrm_email.contact_id = civicrm_contact.id )
1692 LEFT JOIN civicrm_address ON ( civicrm_address.is_primary = 1 AND civicrm_address.contact_id = civicrm_contact.id)
1693 LEFT JOIN civicrm_phone ON ( civicrm_phone.is_primary = 1 AND civicrm_phone.contact_id = civicrm_contact.id)
1694 LEFT JOIN civicrm_im ON ( civicrm_im.is_primary = 1 AND civicrm_im.contact_id = civicrm_contact.id)
1695 LEFT JOIN civicrm_openid ON ( civicrm_openid.is_primary = 1 AND civicrm_openid.contact_id = civicrm_contact.id)
1696 WHERE civicrm_contact.id = %1 ";
1698 $params = array(1 => array($contactId, 'Integer'));
1700 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1702 $locationType = NULL;
1703 if ($dao->fetch()) {
1704 $locationType = $dao->locationType
;
1707 if (isset($locationType)) {
1708 return $locationType;
1710 elseif ($skipDefaultPriamry) {
1711 // if there is no primary contact location then return null
1715 // if there is no primart contact location, then return default
1716 // location type of the system
1717 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
1718 return $defaultLocationType->id
;
1723 * Get the display name, primary email and location type of a contact
1725 * @param int $id id of the contact
1727 * @return array of display_name, email if found, do_not_email or (null,null,null)
1730 public static function getContactDetails($id) {
1731 // check if the contact type
1732 $contactType = self
::getContactType($id);
1734 $nameFields = ($contactType == 'Individual') ?
"civicrm_contact.first_name, civicrm_contact.last_name, civicrm_contact.display_name" : "civicrm_contact.display_name";
1737 SELECT $nameFields, civicrm_email.email, civicrm_contact.do_not_email, civicrm_email.on_hold, civicrm_contact.is_deceased
1738 FROM civicrm_contact LEFT JOIN civicrm_email ON (civicrm_contact.id = civicrm_email.contact_id)
1739 WHERE civicrm_contact.id = %1
1740 ORDER BY civicrm_email.is_primary DESC";
1741 $params = array(1 => array($id, 'Integer'));
1742 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
1744 if ($dao->fetch()) {
1745 if ($contactType == 'Individual') {
1746 if ($dao->first_name ||
$dao->last_name
) {
1747 $name = "{$dao->first_name} {$dao->last_name}";
1750 $name = $dao->display_name
;
1754 $name = $dao->display_name
;
1756 $email = $dao->email
;
1757 $doNotEmail = $dao->do_not_email ?
TRUE : FALSE;
1758 $onHold = $dao->on_hold ?
TRUE : FALSE;
1759 $isDeceased = $dao->is_deceased ?
TRUE : FALSE;
1760 return array($name, $email, $doNotEmail, $onHold, $isDeceased);
1762 return array(NULL, NULL, NULL, NULL, NULL);
1766 * Add/edit/register contacts through profile.
1768 * @param array $params Array of profile fields to be edited/added.
1769 * @param array $fields Array of fields from UFGroup
1770 * @param int $contactID id of the contact to be edited/added.
1771 * @param int $addToGroupID specifies the default group to which contact is added.
1772 * @param int $ufGroupId uf group id (profile id)
1774 * @param boolean $visibility basically lets us know where this request is coming from
1775 * if via a profile from web, we restrict what groups are changed
1777 * @return int contact id created/edited
1780 static function createProfileContact(
1784 $addToGroupID = NULL,
1789 // add ufGroupID to params array ( CRM-2012 )
1791 $params['uf_group_id'] = $ufGroupId;
1796 CRM_Utils_Hook
::pre('edit', 'Profile', $contactID, $params);
1800 CRM_Utils_Hook
::pre('create', 'Profile', NULL, $params);
1803 list($data, $contactDetails) = self
::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
1805 // manage is_opt_out
1806 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
1807 $wasOptOut = CRM_Utils_Array
::value('is_opt_out', $contactDetails, FALSE);
1808 $isOptOut = CRM_Utils_Array
::value('is_opt_out', $params, FALSE);
1809 $data['is_opt_out'] = $isOptOut;
1810 // on change, create new civicrm_subscription_history entry
1811 if (($wasOptOut != $isOptOut) && !empty($contactDetails['contact_id'])) {
1813 'contact_id' => $contactDetails['contact_id'],
1814 'status' => $isOptOut ?
'Removed' : 'Added',
1817 CRM_Contact_BAO_SubscriptionHistory
::create($shParams);
1821 $contact = self
::create($data);
1823 // contact is null if the profile does not have any contact fields
1825 $contactID = $contact->id
;
1828 if (empty($contactID)) {
1829 CRM_Core_Error
::fatal('Cannot proceed without a valid contact id');
1832 // Process group and tag
1833 if (!empty($fields['group'])) {
1835 // this for sure means we are coming in via profile since i added it to fix
1836 // removing contacts from user groups -- lobo
1840 CRM_Contact_BAO_GroupContact
::create($params['group'], $contactID, $visibility, $method);
1843 if (!empty($fields['tag'])) {
1844 CRM_Core_BAO_EntityTag
::create($params['tag'], 'civicrm_contact', $contactID);
1847 //to add profile in default group
1848 if (is_array($addToGroupID)) {
1849 $contactIds = array($contactID);
1850 foreach ($addToGroupID as $groupId) {
1851 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
1854 elseif ($addToGroupID) {
1855 $contactIds = array($contactID);
1856 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $addToGroupID);
1859 // reset the group contact cache for this group
1860 CRM_Contact_BAO_GroupContactCache
::remove();
1863 CRM_Utils_Hook
::post('edit', 'Profile', $contactID, $params);
1866 CRM_Utils_Hook
::post('create', 'Profile', $contactID, $params);
1872 * @param array $params
1874 * @param int $contactID
1875 * @param int $ufGroupId
1876 * @param null $ctype
1877 * @param bool $skipCustom
1881 static function formatProfileContactParams(
1890 $data = $contactDetails = array();
1892 // get the contact details (hier)
1894 list($details, $options) = self
::getHierContactDetails($contactID, $fields);
1896 $contactDetails = $details[$contactID];
1897 $data['contact_type'] = CRM_Utils_Array
::value('contact_type', $contactDetails);
1898 $data['contact_sub_type'] = CRM_Utils_Array
::value('contact_sub_type', $contactDetails);
1901 //we should get contact type only if contact
1903 $data['contact_type'] = CRM_Core_BAO_UFField
::getProfileType($ufGroupId);
1905 //special case to handle profile with only contact fields
1906 if ($data['contact_type'] == 'Contact') {
1907 $data['contact_type'] = 'Individual';
1909 elseif (CRM_Contact_BAO_ContactType
::isaSubType($data['contact_type'])) {
1910 $data['contact_type'] = CRM_Contact_BAO_ContactType
::getBasicType($data['contact_type']);
1914 $data['contact_type'] = $ctype;
1917 $data['contact_type'] = 'Individual';
1921 //fix contact sub type CRM-5125
1922 if (array_key_exists('contact_sub_type', $params) &&
1923 !empty($params['contact_sub_type'])
1925 $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
;
1927 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
1928 !empty($params['contact_sub_type_hidden'])
1930 // if profile was used, and had any subtype, we obtain it from there
1931 $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
;
1934 if ($ctype == 'Organization') {
1935 $data['organization_name'] = CRM_Utils_Array
::value('organization_name', $contactDetails);
1937 elseif ($ctype == 'Household') {
1938 $data['household_name'] = CRM_Utils_Array
::value('household_name', $contactDetails);
1941 $locationType = array();
1946 $data['contact_id'] = $contactID;
1947 $primaryLocationType = self
::getPrimaryLocationType($contactID);
1950 $defaultLocation = CRM_Core_BAO_LocationType
::getDefault();
1951 $defaultLocationId = $defaultLocation->id
;
1954 // get the billing location type
1955 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
1956 $billingLocationTypeId = array_search('Billing', $locationTypes);
1958 $blocks = array('email', 'phone', 'im', 'openid');
1960 $multiplFields = array('url');
1961 // prevent overwritten of formatted array, reset all block from
1962 // params if it is not in valid format (since import pass valid format)
1963 foreach ($blocks as $blk) {
1964 if (array_key_exists($blk, $params) &&
1965 !is_array($params[$blk])
1967 unset($params[$blk]);
1971 $primaryPhoneLoc = NULL;
1972 $session = CRM_Core_Session
::singleton();
1973 foreach ($params as $key => $value) {
1974 $fieldName = $locTypeId = $typeId = NULL;
1975 list($fieldName, $locTypeId, $typeId) = CRM_Utils_System
::explode('-', $key, 3);
1977 //store original location type id
1978 $actualLocTypeId = $locTypeId;
1980 if ($locTypeId == 'Primary') {
1982 if(in_array( $fieldName, $blocks)){
1983 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, $fieldName);
1986 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, 'address');
1988 $primaryLocationType = $locTypeId;
1991 $locTypeId = $defaultLocationId;
1995 if (is_numeric($locTypeId) &&
1996 !in_array($fieldName, $multiplFields) &&
1997 substr($fieldName, 0, 7) != 'custom_'
1999 $index = $locTypeId;
2001 if (is_numeric($typeId)) {
2002 $index .= '-' . $typeId;
2004 if (!in_array($index, $locationType)) {
2005 $locationType[$count] = $index;
2009 $loc = CRM_Utils_Array
::key($index, $locationType);
2011 $blockName = in_array( $fieldName, $blocks) ?
$fieldName : 'address';
2013 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
2015 //set is_billing true, for location type "Billing"
2016 if ($locTypeId == $billingLocationTypeId) {
2017 $data[$blockName][$loc]['is_billing'] = 1;
2021 //get the primary location type
2022 if ($locTypeId == $primaryLocationType) {
2023 $data[$blockName][$loc]['is_primary'] = 1;
2026 elseif ($locTypeId == $defaultLocationId) {
2027 $data[$blockName][$loc]['is_primary'] = 1;
2030 if ( in_array($fieldName, array('phone'))) {
2032 $data['phone'][$loc]['phone_type_id'] = $typeId;
2035 $data['phone'][$loc]['phone_type_id'] = '';
2037 $data['phone'][$loc]['phone'] = $value;
2039 //special case to handle primary phone with different phone types
2040 // in this case we make first phone type as primary
2041 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
2042 $primaryPhoneLoc = $loc;
2045 if ($loc != $primaryPhoneLoc) {
2046 unset($data['phone'][$loc]['is_primary']);
2049 elseif ($fieldName == 'phone_ext') {
2050 $data['phone'][$loc]['phone_ext'] = $value;
2052 elseif ($fieldName == 'email') {
2053 $data['email'][$loc]['email'] = $value;
2055 elseif ($fieldName == 'im') {
2056 if (isset($params[$key . '-provider_id'])) {
2057 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
2059 if (strpos($key, '-provider_id') !== FALSE) {
2060 $data['im'][$loc]['provider_id'] = $params[$key];
2063 $data['im'][$loc]['name'] = $value;
2066 elseif ($fieldName == 'openid') {
2067 $data['openid'][$loc]['openid'] = $value;
2070 if ($fieldName === 'state_province') {
2072 if (is_numeric($value) && ((int ) $value) >= 1000) {
2073 $data['address'][$loc]['state_province_id'] = $value;
2075 elseif (empty($value)) {
2076 $data['address'][$loc]['state_province_id'] = '';
2079 $data['address'][$loc]['state_province'] = $value;
2082 elseif ($fieldName === 'country') {
2084 if (is_numeric($value) && ((int ) $value) >= 1000
2086 $data['address'][$loc]['country_id'] = $value;
2088 elseif (empty($value)) {
2089 $data['address'][$loc]['country_id'] = '';
2092 $data['address'][$loc]['country'] = $value;
2095 elseif ($fieldName === 'county') {
2096 $data['address'][$loc]['county_id'] = $value;
2098 elseif ($fieldName == 'address_name') {
2099 $data['address'][$loc]['name'] = $value;
2101 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2102 $data['address'][$loc][substr($fieldName, 8)] = $value;
2105 $data['address'][$loc][$fieldName] = $value;
2110 if (substr($key, 0, 4) === 'url-') {
2111 $websiteField = explode('-', $key);
2112 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
2113 $data['website'][$websiteField[1]]['url'] = $value;
2115 elseif (in_array($key, self
::$_greetingTypes, TRUE)) {
2116 //save email/postal greeting and addressee values if any, CRM-4575
2117 $data[$key . '_id'] = $value;
2119 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($key))) {
2120 // for autocomplete transfer hidden value instead of label
2121 if ($params[$key] && isset($params[$key . '_id'])) {
2122 $value = $params[$key . '_id'];
2125 // we need to append time with date
2126 if ($params[$key] && isset($params[$key . '_time'])) {
2127 $value .= ' ' . $params[$key . '_time'];
2130 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
2131 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 &&
2132 ($value == '' ||
!isset($value))) {
2137 if (!empty($params['customRecordValues'])) {
2138 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2139 foreach ($params['customRecordValues'] as $recId => $customFields) {
2140 if (is_array($customFields) && !empty($customFields)) {
2141 foreach ($customFields as $customFieldName) {
2142 if ($customFieldName == $key) {
2152 $type = $data['contact_type'];
2153 if (!empty($data['contact_sub_type'])) {
2154 $type = $data['contact_sub_type'];
2155 $type = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($type, CRM_Core_DAO
::VALUE_SEPARATOR
));
2156 // generally a contact even if, has multiple subtypes the parent-type is going to be one only
2157 // and since formatCustomField() would be interested in parent type, lets consider only one subtype
2158 // as the results going to be same.
2162 CRM_Core_BAO_CustomField
::formatCustomField($customFieldId,
2170 elseif ($key == 'edit') {
2174 if ($key == 'location') {
2175 foreach ($value as $locationTypeId => $field) {
2176 foreach ($field as $block => $val) {
2177 if ($block == 'address' && array_key_exists('address_name', $val)) {
2178 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2183 if($key == 'phone' && isset($params['phone_ext'])){
2184 $data[$key] = $value;
2185 foreach($value as $cnt => $phoneBlock){
2186 if($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']){
2187 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array
::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2191 else if (in_array($key,
2200 ($value == '' ||
!isset($value)) &&
2201 ($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0) {
2202 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
2203 // to avoid update with empty values
2207 $data[$key] = $value;
2213 if (!isset($data['contact_type'])) {
2214 $data['contact_type'] = 'Individual';
2217 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2218 $privacy = CRM_Core_SelectValues
::privacy();
2219 foreach ($privacy as $key => $value) {
2220 if (array_key_exists($key, $fields)) {
2221 // do not reset values for existing contacts, if fields are added to a profile
2222 if (array_key_exists($key, $params)) {
2223 $data[$key] = $params[$key];
2224 if (empty($params[$key])) {
2228 elseif (!$contactID) {
2234 return array($data, $contactDetails);
2238 * Find the get contact details
2239 * does not respect ACLs for now, which might need to be rectified at some
2240 * stage based on how its used
2242 * @param string $mail primary email address of the contact
2243 * @param string $ctype contact type
2245 * @return object $dao contact details
2248 public static function &matchContactOnEmail($mail, $ctype = NULL) {
2249 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2250 $mail = $strtolower(trim($mail));
2252 SELECT civicrm_contact.id as contact_id,
2253 civicrm_contact.hash as hash,
2254 civicrm_contact.contact_type as contact_type,
2255 civicrm_contact.contact_sub_type as contact_sub_type
2256 FROM civicrm_contact
2257 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2260 if (CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
2261 'uniq_email_per_site'
2263 // try to find a match within a site (multisite).
2264 $groups = CRM_Core_BAO_Domain
::getChildGroupIds();
2265 if (!empty($groups)) {
2267 INNER JOIN civicrm_group_contact gc ON
2268 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2273 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2274 $p = array(1 => array($mail, 'String'));
2277 $query .= " AND civicrm_contact.contact_type = %3";
2278 $p[3] = array($ctype, 'String');
2281 $query .= " ORDER BY civicrm_email.is_primary DESC";
2283 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2285 if ($dao->fetch()) {
2288 return CRM_Core_DAO
::$_nullObject;
2292 * Find the contact details associated with an OpenID
2294 * @param string $openId openId of the contact
2295 * @param string $ctype contact type
2297 * @return object $dao contact details
2300 public static function &matchContactOnOpenId($openId, $ctype = NULL) {
2301 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2302 $openId = $strtolower(trim($openId));
2304 SELECT civicrm_contact.id as contact_id,
2305 civicrm_contact.hash as hash,
2306 civicrm_contact.contact_type as contact_type,
2307 civicrm_contact.contact_sub_type as contact_sub_type
2308 FROM civicrm_contact
2309 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2310 WHERE civicrm_openid.openid = %1";
2311 $p = array(1 => array($openId, 'String'));
2314 $query .= " AND civicrm_contact.contact_type = %3";
2315 $p[3] = array($ctype, 'String');
2318 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2320 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2322 if ($dao->fetch()) {
2325 return CRM_Core_DAO
::$_nullObject;
2329 * Funtion to get primary email of the contact
2331 * @param int $contactID contact id
2333 * @return string $dao->email email address if present else null
2336 public static function getPrimaryEmail($contactID) {
2337 // fetch the primary email
2339 SELECT civicrm_email.email as email
2340 FROM civicrm_contact
2341 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2342 WHERE civicrm_email.is_primary = 1
2343 AND civicrm_contact.id = %1";
2344 $p = array(1 => array($contactID, 'Integer'));
2345 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2348 if ($dao->fetch()) {
2349 $email = $dao->email
;
2356 * Funtion to get primary OpenID of the contact
2358 * @param int $contactID contact id
2360 * @return string $dao->openid OpenID if present else null
2363 public static function getPrimaryOpenId($contactID) {
2364 // fetch the primary OpenID
2366 SELECT civicrm_openid.openid as openid
2367 FROM civicrm_contact
2368 LEFT JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2369 WHERE civicrm_contact.id = %1
2370 AND civicrm_openid.is_primary = 1";
2371 $p = array(1 => array($contactID, 'Integer'));
2372 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2375 if ($dao->fetch()) {
2376 $openId = $dao->openid
;
2383 * Given the list of params in the params array, fetch the object
2384 * and store the values in the values array
2386 * @param array $params input parameters to find object
2387 * @param array $values output values of the object
2389 * @return CRM_Contact_BAO_Contact|null the found object or null
2392 public static function getValues(&$params, &$values) {
2393 $contact = new CRM_Contact_BAO_Contact();
2395 $contact->copyValues($params);
2397 if ($contact->find(TRUE)) {
2399 CRM_Core_DAO
::storeValues($contact, $values);
2402 foreach (self
::$_commPrefs as $name) {
2403 if (isset($contact->$name)) {
2404 $privacy[$name] = $contact->$name;
2408 if (!empty($privacy)) {
2409 $values['privacy'] = $privacy;
2412 // communication Prefferance
2413 $preffComm = $comm = array();
2414 $comm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2415 $contact->preferred_communication_method
2417 foreach ($comm as $value) {
2418 $preffComm[$value] = 1;
2420 $temp = array('preferred_communication_method' => $contact->preferred_communication_method
);
2423 'preferred_communication_method' => array('newName' => 'preferred_communication_method_display',
2424 'groupName' => 'preferred_communication_method',
2427 CRM_Core_OptionGroup
::lookupValues($temp, $names, FALSE);
2429 $values['preferred_communication_method'] = $preffComm;
2430 $values['preferred_communication_method_display'] = CRM_Utils_Array
::value('preferred_communication_method_display', $temp);
2432 $preferredMailingFormat = CRM_Core_SelectValues
::pmf();
2433 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format
];
2435 // get preferred languages
2436 if (!empty($contact->preferred_language
)) {
2437 $values['preferred_language'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language
);
2440 // Calculating Year difference
2441 if ($contact->birth_date
) {
2442 $birthDate = CRM_Utils_Date
::customFormat($contact->birth_date
, '%Y%m%d');
2443 if ($birthDate < date('Ymd')) {
2444 $age = CRM_Utils_Date
::calculateAge($birthDate);
2445 $values['age']['y'] = CRM_Utils_Array
::value('years', $age);
2446 $values['age']['m'] = CRM_Utils_Array
::value('months', $age);
2449 list($values['birth_date']) = CRM_Utils_Date
::setDateDefaults($contact->birth_date
, 'birth');
2450 $values['birth_date_display'] = $contact->birth_date
;
2453 if ($contact->deceased_date
) {
2454 list($values['deceased_date']) = CRM_Utils_Date
::setDateDefaults($contact->deceased_date
, 'birth');
2455 $values['deceased_date_display'] = $contact->deceased_date
;
2458 $contact->contact_id
= $contact->id
;
2466 * Given the component name and returns
2467 * the count of participation of contact
2469 * @param string $component input component name
2470 * @param integer $contactId input contact id
2471 * @param string $tableName optional tableName if component is custom group
2473 * @return total number of count of occurence in database
2476 public static function getCountComponent($component, $contactId, $tableName = NULL) {
2478 switch ($component) {
2480 return CRM_Core_BAO_EntityTag
::getContactTags($contactId, TRUE);
2483 return CRM_Contact_BAO_Relationship
::getRelationship($contactId,
2484 CRM_Contact_BAO_Relationship
::CURRENT
,
2489 return CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, "Added", NULL, TRUE);
2492 if (CRM_Core_BAO_Log
::useLoggingReport()) {
2495 return CRM_Core_BAO_Log
::getContactLogCount($contactId);
2498 return CRM_Core_BAO_Note
::getContactNoteCount($contactId);
2500 case 'contribution':
2501 return CRM_Contribute_BAO_Contribution
::contributionCount($contactId);
2504 return CRM_Member_BAO_Membership
::getContactMembershipCount($contactId, TRUE);
2507 return CRM_Event_BAO_Participant
::getContactParticipantCount($contactId);
2510 return CRM_Pledge_BAO_Pledge
::getContactPledgeCount($contactId);
2513 return CRM_Case_BAO_Case
::caseCount($contactId);
2516 return CRM_Grant_BAO_Grant
::getContactGrantCount($contactId);
2520 'contact_id' => $contactId,
2523 'context' => 'activity',
2525 return CRM_Activity_BAO_Activity
::getActivitiesCount($input);
2528 $params = array('contact_id' => $contactId);
2529 return CRM_Mailing_BAO_Mailing
::getContactMailingsCount($params);
2532 $custom = explode('_', $component);
2533 if ($custom['0'] = 'custom') {
2535 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2537 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2538 return CRM_Core_DAO
::singleValueQuery($queryString);
2544 * Process greetings and cache
2546 * @param object $contact contact object after save
2547 * @param boolean $useDefaults use default greeting values
2552 public static function processGreetings(&$contact, $useDefaults = FALSE) {
2554 //retrieve default greetings
2555 $defaultGreetings = CRM_Core_PseudoConstant
::greetingDefaults();
2556 $contactDefaults = $defaultGreetings[$contact->contact_type
];
2559 // note that contact object not always has required greeting related
2560 // fields that are required to calculate greeting and
2561 // also other fields used in tokens etc,
2562 // hence we need to retrieve it again.
2563 if ( $contact->_query
!== FALSE ) {
2564 $contact->find(TRUE);
2567 // store object values to an array
2568 $contactDetails = array();
2569 CRM_Core_DAO
::storeValues($contact, $contactDetails);
2570 $contactDetails = array(array($contact->id
=> $contactDetails));
2572 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2573 $updateQueryString = array();
2575 //cache email and postal greeting to greeting display
2576 if ($contact->email_greeting_custom
!= 'null' && $contact->email_greeting_custom
) {
2577 $emailGreetingString = $contact->email_greeting_custom
;
2579 elseif ($contact->email_greeting_id
!= 'null' && $contact->email_greeting_id
) {
2580 // the filter value for Individual contact type is set to 1
2582 'contact_type' => $contact->contact_type
,
2583 'greeting_type' => 'email_greeting',
2586 $emailGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2587 $emailGreetingString = $emailGreeting[$contact->email_greeting_id
];
2588 $updateQueryString[] = " email_greeting_custom = NULL ";
2592 reset($contactDefaults['email_greeting']);
2593 $emailGreetingID = key($contactDefaults['email_greeting']);
2594 $emailGreetingString = $contactDefaults['email_greeting'][$emailGreetingID];
2595 $updateQueryString[] = " email_greeting_id = $emailGreetingID ";
2596 $updateQueryString[] = " email_greeting_custom = NULL ";
2598 elseif ($contact->email_greeting_custom
) {
2599 $updateQueryString[] = " email_greeting_display = NULL ";
2603 if ($emailGreetingString) {
2604 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($emailGreetingString,
2607 'CRM_Contact_BAO_Contact'
2609 $emailGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($emailGreetingString));
2610 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2614 if ($contact->postal_greeting_custom
!= 'null' && $contact->postal_greeting_custom
) {
2615 $postalGreetingString = $contact->postal_greeting_custom
;
2617 elseif ($contact->postal_greeting_id
!= 'null' && $contact->postal_greeting_id
) {
2619 'contact_type' => $contact->contact_type
,
2620 'greeting_type' => 'postal_greeting',
2622 $postalGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2623 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id
];
2624 $updateQueryString[] = " postal_greeting_custom = NULL ";
2628 reset($contactDefaults['postal_greeting']);
2629 $postalGreetingID = key($contactDefaults['postal_greeting']);
2630 $postalGreetingString = $contactDefaults['postal_greeting'][$postalGreetingID];
2631 $updateQueryString[] = " postal_greeting_id = $postalGreetingID ";
2632 $updateQueryString[] = " postal_greeting_custom = NULL ";
2634 elseif ($contact->postal_greeting_custom
) {
2635 $updateQueryString[] = " postal_greeting_display = NULL ";
2639 if ($postalGreetingString) {
2640 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($postalGreetingString,
2643 'CRM_Contact_BAO_Contact'
2645 $postalGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($postalGreetingString));
2646 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2650 if ($contact->addressee_custom
!= 'null' && $contact->addressee_custom
) {
2651 $addresseeString = $contact->addressee_custom
;
2653 elseif ($contact->addressee_id
!= 'null' && $contact->addressee_id
) {
2655 'contact_type' => $contact->contact_type
,
2656 'greeting_type' => 'addressee',
2659 $addressee = CRM_Core_PseudoConstant
::greeting($filter);
2660 $addresseeString = $addressee[$contact->addressee_id
];
2661 $updateQueryString[] = " addressee_custom = NULL ";
2665 reset($contactDefaults['addressee']);
2666 $addresseeID = key($contactDefaults['addressee']);
2667 $addresseeString = $contactDefaults['addressee'][$addresseeID];
2668 $updateQueryString[] = " addressee_id = $addresseeID ";
2669 $updateQueryString[] = " addressee_custom = NULL ";
2671 elseif ($contact->addressee_custom
) {
2672 $updateQueryString[] = " addressee_display = NULL ";
2676 if ($addresseeString) {
2677 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($addresseeString,
2680 'CRM_Contact_BAO_Contact'
2682 $addresseeString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($addresseeString));
2683 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2686 if (!empty($updateQueryString)) {
2687 $updateQueryString = implode(',', $updateQueryString);
2688 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2689 CRM_Core_DAO
::executeQuery($queryString);
2694 * Retrieve loc block ids w/ given condition.
2696 * @param int $contactId contact id.
2697 * @param array $criteria key => value pair which should be
2698 * fulfill by return record ids.
2699 * @param string $condOperator operator use for grouping multiple conditions.
2701 * @return array $locBlockIds loc block ids which fulfill condition.
2704 public static function getLocBlockIds($contactId, $criteria = array(), $condOperator = 'AND') {
2705 $locBlockIds = array();
2707 return $locBlockIds;
2710 foreach (array('Email', 'OpenID', 'Phone', 'Address', 'IM') as $block) {
2711 $name = strtolower($block);
2712 $className = "CRM_Core_DAO_$block";
2713 $blockDAO = new $className();
2715 // build the condition.
2716 if (is_array($criteria)) {
2717 $fields = $blockDAO->fields();
2718 $conditions = array();
2719 foreach ($criteria as $field => $value) {
2720 if (array_key_exists($field, $fields)) {
2721 $cond = "( $field = $value )";
2722 // value might be zero or null.
2723 if (!$value ||
strtolower($value) == 'null') {
2724 $cond = "( $field = 0 OR $field IS NULL )";
2726 $conditions[] = $cond;
2729 if (!empty($conditions)) {
2730 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2734 $blockDAO->contact_id
= $contactId;
2736 while ($blockDAO->fetch()) {
2737 $locBlockIds[$name][] = $blockDAO->id
;
2742 return $locBlockIds;
2746 * Build context menu items.
2748 * @param int $contactId
2750 * @return array of context menu for logged in user.
2753 public static function contextMenu($contactId = NULL) {
2756 'title' => ts('View Contact'),
2758 'ref' => 'view-contact',
2759 'class' => 'no-popup',
2761 'permissions' => array('view all contacts'),
2764 'title' => ts('Edit Contact'),
2766 'ref' => 'edit-contact',
2767 'class' => 'no-popup',
2769 'permissions' => array('edit all contacts'),
2772 'title' => ts('Delete Contact'),
2774 'ref' => 'delete-contact',
2776 'permissions' => array('access deleted contacts', 'delete contacts'),
2778 'contribution' => array(
2779 'title' => ts('Add Contribution'),
2781 'ref' => 'new-contribution',
2782 'key' => 'contribution',
2783 'tab' => 'contribute',
2784 'component' => 'CiviContribute',
2785 'href' => CRM_Utils_System
::url('civicrm/contact/view/contribution',
2786 'reset=1&action=add&context=contribution'
2788 'permissions' => array(
2789 'access CiviContribute',
2790 'edit contributions',
2793 'participant' => array(
2794 'title' => ts('Register for Event'),
2796 'ref' => 'new-participant',
2797 'key' => 'participant',
2798 'tab' => 'participant',
2799 'component' => 'CiviEvent',
2800 'href' => CRM_Utils_System
::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
2801 'permissions' => array(
2803 'edit event participants',
2806 'activity' => array(
2807 'title' => ts('Record Activity'),
2809 'ref' => 'new-activity',
2810 'key' => 'activity',
2811 'permissions' => array('edit all contacts'),
2814 'title' => ts('Add Pledge'),
2816 'ref' => 'new-pledge',
2819 'href' => CRM_Utils_System
::url('civicrm/contact/view/pledge',
2820 'reset=1&action=add&context=pledge'
2822 'component' => 'CiviPledge',
2823 'permissions' => array(
2824 'access CiviPledge',
2828 'membership' => array(
2829 'title' => ts('Add Membership'),
2831 'ref' => 'new-membership',
2832 'key' => 'membership',
2834 'component' => 'CiviMember',
2835 'href' => CRM_Utils_System
::url('civicrm/contact/view/membership',
2836 'reset=1&action=add&context=membership'
2838 'permissions' => array(
2839 'access CiviMember',
2844 'title' => ts('Add Case'),
2846 'ref' => 'new-case',
2849 'component' => 'CiviCase',
2850 'href' => CRM_Utils_System
::url('civicrm/case/add', 'reset=1&action=add&context=case'),
2851 'permissions' => array('add cases'),
2854 'title' => ts('Add Grant'),
2856 'ref' => 'new-grant',
2859 'component' => 'CiviGrant',
2860 'href' => CRM_Utils_System
::url('civicrm/contact/view/grant',
2861 'reset=1&action=add&context=grant'
2863 'permissions' => array('edit grants'),
2866 'title' => ts('Add Relationship'),
2868 'ref' => 'new-relationship',
2871 'href' => CRM_Utils_System
::url('civicrm/contact/view/rel',
2872 'reset=1&action=add'
2874 'permissions' => array('edit all contacts'),
2877 'title' => ts('Add Note'),
2879 'ref' => 'new-note',
2882 'class' => 'medium-popup',
2883 'href' => CRM_Utils_System
::url('civicrm/contact/view/note',
2884 'reset=1&action=add'
2886 'permissions' => array('edit all contacts'),
2889 'title' => ts('Send an Email'),
2891 'ref' => 'new-email',
2893 'permissions' => array('view all contacts'),
2896 'title' => ts('Add to Group'),
2898 'ref' => 'group-add-contact',
2901 'permissions' => array('edit groups'),
2904 'title' => ts('Tag Contact'),
2906 'ref' => 'tag-contact',
2909 'permissions' => array('edit all contacts'),
2913 CRM_Utils_Hook
::summaryActions($menu, $contactId);
2914 //1. check for component is active.
2915 //2. check for user permissions.
2916 //3. check for acls.
2917 //3. edit and view contact are directly accessible to user.
2919 $aclPermissionedTasks = array(
2920 'view-contact', 'edit-contact', 'new-activity',
2921 'new-email', 'group-add-contact', 'tag-contact', 'delete-contact',
2923 $corePermission = CRM_Core_Permission
::getPermission();
2925 $config = CRM_Core_Config
::singleton();
2927 $contextMenu = array();
2928 foreach ($menu as $key => $values) {
2929 $componentName = CRM_Utils_Array
::value('component', $values);
2931 // if component action - make sure component is enable.
2932 if ($componentName && !in_array($componentName, $config->enableComponents
)) {
2936 // make sure user has all required permissions.
2937 $hasAllPermissions = FALSE;
2939 $permissions = CRM_Utils_Array
::value('permissions', $values);
2940 if (!is_array($permissions) ||
empty($permissions)) {
2941 $hasAllPermissions = TRUE;
2944 // iterate for required permissions in given permissions array.
2945 if (!$hasAllPermissions) {
2946 $hasPermissions = 0;
2947 foreach ($permissions as $permission) {
2948 if (CRM_Core_Permission
::check($permission)) {
2953 if (count($permissions) == $hasPermissions) {
2954 $hasAllPermissions = TRUE;
2957 // if still user does not have required permissions, check acl.
2958 if (!$hasAllPermissions && $values['ref'] != 'delete-contact') {
2959 if (in_array($values['ref'], $aclPermissionedTasks) &&
2960 $corePermission == CRM_Core_Permission
::EDIT
2962 $hasAllPermissions = TRUE;
2964 elseif (in_array($values['ref'], array(
2966 // grant permissions for these tasks.
2967 $hasAllPermissions = TRUE;
2972 // user does not have necessary permissions.
2973 if (!$hasAllPermissions) {
2977 // build directly accessible action menu.
2978 if (in_array($values['ref'], array(
2979 'view-contact', 'edit-contact'))) {
2980 $contextMenu['primaryActions'][$key] = array(
2981 'title' => $values['title'],
2982 'ref' => $values['ref'],
2983 'class' => CRM_Utils_Array
::value('class', $values),
2984 'key' => $values['key'],
2989 // finally get menu item for -more- action widget.
2990 $contextMenu['moreActions'][$values['weight']] = array(
2991 'title' => $values['title'],
2992 'ref' => $values['ref'],
2993 'href' => CRM_Utils_Array
::value('href', $values),
2994 'tab' => CRM_Utils_Array
::value('tab', $values),
2995 'class' => CRM_Utils_Array
::value('class', $values),
2996 'key' => $values['key'],
3000 ksort($contextMenu['moreActions']);
3002 return $contextMenu;
3006 * Retrieve display name of contact that address is shared
3007 * based on $masterAddressId or $contactId .
3009 * @param int $masterAddressId master id.
3010 * @param int $contactId contact id.
3012 * @return display name |null the found display name or null.
3015 public static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3016 $masterDisplayName = NULL;
3018 if (!$masterAddressId && !$contactId) {
3019 return $masterDisplayName;
3022 if ($masterAddressId) {
3024 SELECT display_name from civicrm_contact
3025 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3026 WHERE civicrm_address.id = " . $masterAddressId;
3028 elseif ($contactId) {
3030 SELECT display_name from civicrm_contact cc, civicrm_address add1
3031 LEFT JOIN civicrm_address add2 ON ( add1.master_id = add2.id )
3032 WHERE cc.id = add2.contact_id AND add1.contact_id = " . $contactId;
3035 $masterDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
3036 return $masterDisplayName;
3040 * Get the creation/modification times for a contact
3042 * @param int $contactId
3044 * @return array('created_date' => $, 'modified_date' => $)
3046 public static function getTimestamps($contactId) {
3047 $timestamps = CRM_Core_DAO
::executeQuery(
3048 'SELECT created_date, modified_date
3049 FROM civicrm_contact
3052 1 => array($contactId, 'Integer'),
3055 if ($timestamps->fetch()) {
3057 'created_date' => $timestamps->created_date
,
3058 'modified_date' => $timestamps->modified_date
,
3067 * Generate triggers to update the timestamp on the corresponding civicrm_contact row,
3068 * on insert/update/delete to a table that extends civicrm_contact.
3069 * Don't regenerate triggers for all such tables if only asked for one table.
3071 * @param array $info
3072 * Reference to the array where generated trigger information is being stored
3073 * @param string|null $reqTableName
3074 * Name of the table for which triggers are being generated, or NULL if all tables
3075 * @param array $relatedTableNames
3076 * Array of all core or all custom table names extending civicrm_contact
3077 * @param string $contactRefColumn
3078 * 'contact_id' if processing core tables, 'entity_id' if processing custom tables
3081 * @link https://issues.civicrm.org/jira/browse/CRM-15602
3085 public static function generateTimestampTriggers(&$info, $reqTableName, $relatedTableNames, $contactRefColumn) {
3087 $contactRefColumn = CRM_Core_DAO
::escapeString($contactRefColumn);
3088 // If specific related table requested, just process that one
3089 if (in_array($reqTableName, $relatedTableNames)) {
3090 $relatedTableNames = array($reqTableName);
3093 // If no specific table requested (include all related tables),
3094 // or a specific related table requested (as matched above)
3095 if (empty($reqTableName) ||
in_array($reqTableName, $relatedTableNames)) {
3097 'table' => $relatedTableNames,
3099 'event' => array('INSERT', 'UPDATE'),
3100 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = NEW.$contactRefColumn;\n",
3103 'table' => $relatedTableNames,
3105 'event' => array('DELETE'),
3106 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = OLD.$contactRefColumn;\n",
3112 * Get a list of triggers for the contact table
3114 * @see hook_civicrm_triggerInfo
3115 * @see CRM_Core_DAO::triggerRebuild
3116 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3118 public static function triggerInfo(&$info, $tableName = NULL) {
3119 //during upgrade, first check for valid version and then create triggers
3120 //i.e the columns created_date and modified_date are introduced in 4.3.alpha1 so dont create triggers for older version
3121 if (CRM_Core_Config
::isUpgradeMode()) {
3122 $currentVer = CRM_Core_BAO_Domain
::version(TRUE);
3123 //if current version is less than 4.3.alpha1 dont create below triggers
3124 if (version_compare($currentVer, '4.3.alpha1') < 0) {
3129 // Update timestamp for civicrm_contact itself
3130 if ($tableName == NULL ||
$tableName == self
::getTableName()) {
3132 'table' => array(self
::getTableName()),
3134 'event' => array('INSERT'),
3135 'sql' => "\nSET NEW.created_date = CURRENT_TIMESTAMP;\n",
3139 // Update timestamp when modifying closely related core tables
3140 $relatedTables = array(
3147 self
::generateTimestampTriggers($info, $tableName, $relatedTables, 'contact_id');
3149 // Update timestamp when modifying related custom-data tables
3150 $customGroupTables = array();
3151 $customGroupDAO = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity('Contact');
3152 $customGroupDAO->is_multiple
= 0;
3153 $customGroupDAO->find();
3154 while ($customGroupDAO->fetch()) {
3155 $customGroupTables[] = $customGroupDAO->table_name
;
3157 if (!empty($customGroupTables)) {
3158 self
::generateTimestampTriggers($info, $tableName, $customGroupTables, 'entity_id');
3161 // Update phone table to populate phone_numeric field
3162 if (!$tableName ||
$tableName == 'civicrm_phone') {
3163 // Define stored sql function needed for phones
3164 CRM_Core_DAO
::executeQuery(self
::DROP_STRIP_FUNCTION_43
);
3165 CRM_Core_DAO
::executeQuery(self
::CREATE_STRIP_FUNCTION_43
);
3167 'table' => array('civicrm_phone'),
3169 'event' => array('INSERT', 'UPDATE'),
3170 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3176 * Check if contact is being used in civicrm_domain
3177 * based on $contactId
3179 * @param int $contactId contact id.
3181 * @return bool true if present else false.
3184 public static function checkDomainContact($contactId) {
3187 $domainId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3197 * Get options for a given contact field.
3198 * @see CRM_Core_DAO::buildOptions
3200 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3201 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3203 * @param String $fieldName
3204 * @param String $context : @see CRM_Core_DAO::buildOptionsContext
3205 * @param Array $props : whatever is known about this dao object
3207 * @return Array|bool
3209 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3211 // Special logic for fields whose options depend on context or properties
3212 switch ($fieldName) {
3213 case 'contact_sub_type':
3214 if (!empty($props['contact_type'])) {
3215 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3218 case 'contact_type':
3219 if ($context == 'search') {
3220 // CRM-15495 - EntityRef filters and basic search forms expect this format
3221 // FIXME: Search builder does not
3222 return CRM_Contact_BAO_ContactType
::getSelectElements();
3226 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
3230 * Delete a contact-related object that has an 'is_primary' field
3231 * Ensures that is_primary gets assigned to another object if available
3232 * Also calls pre/post hooks
3234 * @var $type : object type
3235 * @var $id : object id
3238 public static function deleteObjectWithPrimary($type, $id) {
3239 if (!$id ||
!is_numeric($id)) {
3242 $daoName = "CRM_Core_DAO_$type";
3243 $obj = new $daoName();
3246 if ($obj->fetch()) {
3247 CRM_Utils_Hook
::pre('delete', $type, $id, CRM_Core_DAO
::$_nullArray);
3248 $contactId = $obj->contact_id
;
3254 // is_primary is only relavent if this field belongs to a contact
3256 $dao = new $daoName();
3257 $dao->contact_id
= $contactId;
3258 $dao->is_primary
= 1;
3259 // Pick another record to be primary (if one isn't already)
3260 if (!$dao->find(TRUE)) {
3261 $dao->is_primary
= 0;
3263 if ($dao->fetch()) {
3264 $dao->is_primary
= 1;
3270 CRM_Utils_Hook
::post('delete', $type, $id, $obj);