3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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;
96 * @return \CRM_Contact_DAO_Contact
101 function __construct() {
102 parent
::__construct();
106 * takes an associative array and creates a contact object
108 * the function extract all the params it needs to initialize the create a
109 * contact object. the params array could contain additional unused name/value
112 * @param array $params (reference ) an assoc array of name/value pairs
114 * @return object CRM_Contact_BAO_Contact object
118 static function add(&$params) {
119 $contact = new CRM_Contact_DAO_Contact();
121 if (empty($params)) {
125 //fix for validate contact sub type CRM-5143
126 if ( isset( $params['contact_sub_type'] ) ) {
127 if ( empty($params['contact_sub_type']) ) {
128 $params['contact_sub_type'] = 'null';
131 if (!CRM_Contact_BAO_ContactType
::isExtendsContactType($params['contact_sub_type'],
132 $params['contact_type'], TRUE
134 // we'll need to fix tests to handle this
136 CRM_Core_Error
::fatal(ts('The Contact Sub Type does not match the Contact type for this record'));
138 if (is_array($params['contact_sub_type'])) {
139 $params['contact_sub_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $params['contact_sub_type']) . CRM_Core_DAO
::VALUE_SEPARATOR
;
142 $params['contact_sub_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. trim($params['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
149 $params['contact_sub_type'] = 'null';
152 //fixed contact source
153 if (isset($params['contact_source'])) {
154 $params['source'] = $params['contact_source'];
157 //fix for preferred communication method
158 $prefComm = CRM_Utils_Array
::value('preferred_communication_method', $params);
159 if ($prefComm && is_array($prefComm)) {
160 unset($params['preferred_communication_method']);
163 foreach ($prefComm as $k => $v) {
169 $prefComm = $newPref;
170 if (is_array($prefComm) && !empty($prefComm)) {
171 $prefComm = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, array_keys($prefComm)) . CRM_Core_DAO
::VALUE_SEPARATOR
;
172 $contact->preferred_communication_method
= $prefComm;
175 $contact->preferred_communication_method
= '';
179 $allNull = $contact->copyValues($params);
181 $contact->id
= CRM_Utils_Array
::value('contact_id', $params);
183 if ($contact->contact_type
== 'Individual') {
186 //format individual fields
187 CRM_Contact_BAO_Individual
::format($params, $contact);
189 elseif ($contact->contact_type
== 'Household') {
190 if (isset($params['household_name'])) {
192 $contact->display_name
= $contact->sort_name
= CRM_Utils_Array
::value('household_name', $params, '');
195 elseif ($contact->contact_type
== 'Organization') {
196 if (isset($params['organization_name'])) {
198 $contact->display_name
= $contact->sort_name
= CRM_Utils_Array
::value('organization_name', $params, '');
203 $privacy = CRM_Utils_Array
::value('privacy', $params);
205 is_array($privacy) &&
209 foreach (self
::$_commPrefs as $name) {
210 $contact->$name = CRM_Utils_Array
::value($name, $privacy, FALSE);
214 // since hash was required, make sure we have a 0 value for it, CRM-1063
215 // fixed in 1.5 by making hash optional
216 // only do this in create mode, not update
217 if ((!array_key_exists('hash', $contact) ||
!$contact->hash
) && !$contact->id
) {
219 $contact->hash
= md5(uniqid(rand(), TRUE));
222 // Even if we don't need $employerId, it's important to call getFieldValue() before
223 // the contact is saved because we want the existing value to be cached.
224 // createCurrentEmployerRelationship() needs the old value not the updated one. CRM-10788
225 $employerId = empty($contact->id
) ?
NULL : CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contact->id
, 'employer_id');
230 CRM_Core_BAO_Log
::register($contact->id
,
236 if ($contact->contact_type
== 'Individual' && (isset($params['current_employer']) ||
isset($params['employer_id']))) {
237 // create current employer
238 $newEmployer = !empty($params['employer_id']) ?
$params['employer_id'] : CRM_Utils_Array
::value('current_employer', $params);
241 if (empty($params['contact_id'])) {
245 CRM_Contact_BAO_Contact_Utils
::createCurrentEmployerRelationship($contact->id
, $newEmployer, $employerId, $newContact);
248 //unset if employer id exits
250 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($contact->id
, $employerId);
255 //update cached employee name
256 if ($contact->contact_type
== 'Organization') {
257 CRM_Contact_BAO_Contact_Utils
::updateCurrentEmployer($contact->id
);
264 * Function to create contact
265 * takes an associative array and creates a contact object and all the associated
266 * derived objects (i.e. individual, location, email, phone etc)
268 * This function is invoked from within the web form layer and also from the api layer
270 * @param array $params (reference ) an assoc array of name/value pairs
271 * @param boolean $fixAddress if we need to fix address
272 * @param boolean $invokeHooks if we need to invoke hooks
274 * @param bool $skipDelete
277 * @return object CRM_Contact_BAO_Contact object
281 static function &create(&$params, $fixAddress = TRUE, $invokeHooks = TRUE, $skipDelete = FALSE) {
283 if (empty($params['contact_type']) && empty($params['contact_id'])) {
289 if (!empty($params['contact_id'])) {
290 CRM_Utils_Hook
::pre('edit', $params['contact_type'], $params['contact_id'], $params);
293 CRM_Utils_Hook
::pre('create', $params['contact_type'], NULL, $params);
298 $config = CRM_Core_Config
::singleton();
300 // CRM-6942: set preferred language to the current language if it’s unset (and we’re creating a contact)
301 if (empty($params['contact_id']) && empty($params['preferred_language'])) {
302 $params['preferred_language'] = $config->lcMessages
;
305 // CRM-9739: set greeting & addressee if unset and we’re creating a contact
306 if (empty($params['contact_id'])) {
307 foreach (self
::$_greetingTypes as $greeting) {
308 if (empty($params[$greeting . '_id'])) {
309 if ($defaultGreetingTypeId =
310 CRM_Contact_BAO_Contact_Utils
::defaultGreeting($params['contact_type'], $greeting)
312 $params[$greeting . '_id'] = $defaultGreetingTypeId;
318 $transaction = new CRM_Core_Transaction();
320 $contact = self
::add($params);
322 // not dying here is stupid, since we get into wierd situation and into a bug that
323 // is impossible to figure out for the user or for us
325 CRM_Core_Error
::fatal();
328 $params['contact_id'] = $contact->id
;
330 if (CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
333 // Enabling multisite causes the contact to be added to the domain group
334 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
335 if(!empty($domainGroupID)){
336 if (!empty($params['group']) && is_array($params['group'])) {
337 $params['group'][$domainGroupID] = 1;
340 $params['group'] = array($domainGroupID => 1);
345 if (array_key_exists('group', $params)) {
346 $contactIds = array($params['contact_id']);
347 foreach ($params['group'] as $groupId => $flag) {
349 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
351 elseif ($flag == -1) {
352 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $groupId);
357 //add location Block data
358 $blocks = CRM_Core_BAO_Location
::create($params, $fixAddress);
359 foreach ($blocks as $name => $value) {
360 $contact->$name = $value;
364 CRM_Core_BAO_Website
::create($params['website'], $contact->id
, $skipDelete);
366 //get userID from session
367 $session = CRM_Core_Session
::singleton();
368 $userID = $session->get('userID');
370 if (!empty($params['note'])) {
371 if (is_array($params['note'])) {
372 foreach ($params['note'] as $note) {
373 $contactId = $contact->id
;
374 if (isset($note['contact_id'])) {
375 $contactId = $note['contact_id'];
377 //if logged in user, overwrite contactId
379 $contactId = $userID;
383 'entity_id' => $contact->id
,
384 'entity_table' => 'civicrm_contact',
385 'note' => $note['note'],
386 'subject' => CRM_Utils_Array
::value('subject', $note),
387 'contact_id' => $contactId,
389 CRM_Core_BAO_Note
::add($noteParams, CRM_Core_DAO
::$_nullArray);
393 $contactId = $contact->id
;
394 if (isset($note['contact_id'])) {
395 $contactId = $note['contact_id'];
397 //if logged in user, overwrite contactId
399 $contactId = $userID;
403 'entity_id' => $contact->id
,
404 'entity_table' => 'civicrm_contact',
405 'note' => $params['note'],
406 'subject' => CRM_Utils_Array
::value('subject', $params),
407 'contact_id' => $contactId,
409 CRM_Core_BAO_Note
::add($noteParams, CRM_Core_DAO
::$_nullArray);
414 // update the UF user_unique_id if that has changed
415 CRM_Core_BAO_UFMatch
::updateUFName($contact->id
);
417 if (!empty($params['custom']) &&
418 is_array($params['custom'])
420 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contact', $contact->id
);
423 // make a civicrm_subscription_history entry only on contact create (CRM-777)
424 if (empty($params['contact_id'])) {
425 $subscriptionParams = array(
426 'contact_id' => $contact->id
,
430 CRM_Contact_BAO_SubscriptionHistory
::create($subscriptionParams);
433 $transaction->commit();
435 // CRM-6367: fetch the right label for contact type’s display
436 $contact->contact_type_display
= CRM_Core_DAO
::getFieldValue(
437 'CRM_Contact_DAO_ContactType',
438 $contact->contact_type
,
443 if (!$config->doNotResetCache
) {
444 // Note: doNotResetCache flag is currently set by import contact process and merging,
445 // since resetting and
446 // rebuilding cache could be expensive (for many contacts). We might come out with better
447 // approach in future.
448 CRM_Contact_BAO_Contact_Utils
::clearContactCaches($contact->id
);
453 CRM_Utils_Hook
::post('edit', $params['contact_type'], $contact->id
, $contact);
456 CRM_Utils_Hook
::post('create', $params['contact_type'], $contact->id
, $contact);
460 // process greetings CRM-4575, cache greetings
461 self
::processGreetings($contact);
467 * Get the display name and image of a contact
469 * @param int $id the contactId
473 * @return array the displayName and contactImage for this contact
477 static function getDisplayAndImage($id, $type = FALSE) {
478 //CRM-14276 added the * on the civicrm_contact table so that we have all the contact info available
480 SELECT civicrm_contact.*,
481 civicrm_email.email as email
483 LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
484 AND civicrm_email.is_primary = 1
485 WHERE civicrm_contact.id = " . CRM_Utils_Type
::escape($id, 'Integer');
486 $dao = new CRM_Core_DAO();
489 $image = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
490 $dao->contact_sub_type
: $dao->contact_type
, FALSE, $id
492 $imageUrl = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
493 $dao->contact_sub_type
: $dao->contact_type
, TRUE, $id
496 // use email if display_name is empty
497 if (empty($dao->display_name
)) {
498 $displayName = $dao->email
;
501 $displayName = $dao->display_name
;
504 CRM_Utils_Hook
::alterDisplayName($displayName, $id, $dao);
506 return $type ?
array(
510 $dao->contact_sub_type
,
512 ) : array($displayName, $image, $imageUrl);
518 * @param array $crudLinkSpec with keys:
519 * - action: int, CRM_Core_Action::UPDATE or CRM_Core_Action::VIEW [default: VIEW]
520 * - entity_table: string, eg "civicrm_contact"
522 * @return array|NULL NULL if unavailable, or an array. array has keys:
526 * @see CRM_Utils_System::createDefaultCrudLink
528 public function createDefaultCrudLink($crudLinkSpec) {
529 switch ($crudLinkSpec['action']) {
530 case CRM_Core_Action
::VIEW
:
532 'title' => $this->display_name
,
533 'path' => 'civicrm/contact/view',
539 case CRM_Core_Action
::UPDATE
:
541 'title' => $this->display_name
,
542 'path' => 'civicrm/contact/add',
545 'action' => 'update',
555 * Get the values for pseudoconstants for name->value and reverse.
557 * @param array $defaults (reference) the default values, some of which need to be resolved.
558 * @param boolean $reverse true if we want to resolve the values in the reverse direction (value -> name)
564 static function resolveDefaults(&$defaults, $reverse = FALSE) {
565 // hack for birth_date
566 if (!empty($defaults['birth_date'])) {
567 if (is_array($defaults['birth_date'])) {
568 $defaults['birth_date'] = CRM_Utils_Date
::format($defaults['birth_date'], '-');
572 CRM_Utils_Array
::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id'), $reverse);
573 CRM_Utils_Array
::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'suffix_id'), $reverse);
574 CRM_Utils_Array
::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'), $reverse);
575 CRM_Utils_Array
::lookupValue($defaults, 'communication_style', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'communication_style_id'), $reverse);
577 //lookup value of email/postal greeting, addressee, CRM-4575
578 foreach (self
::$_greetingTypes as $greeting) {
579 $filterCondition = array('contact_type' => CRM_Utils_Array
::value('contact_type', $defaults),
580 'greeting_type' => $greeting,
582 CRM_Utils_Array
::lookupValue($defaults, $greeting,
583 CRM_Core_PseudoConstant
::greeting($filterCondition), $reverse
587 $blocks = array('address', 'im', 'phone');
588 foreach ($blocks as $name) {
589 if (!array_key_exists($name, $defaults) ||
!is_array($defaults[$name])) {
592 foreach ($defaults[$name] as $count => & $values) {
594 //get location type id.
595 CRM_Utils_Array
::lookupValue($values, 'location_type', CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id'), $reverse);
597 if ($name == 'address') {
598 // FIXME: lookupValue doesn't work for vcard_name
599 if (!empty($values['location_type_id'])) {
600 $vcardNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array('labelColumn' => 'vcard_name'));
601 $values['vcard_name'] = $vcardNames[$values['location_type_id']];
604 if (!CRM_Utils_Array
::lookupValue($values,
606 CRM_Core_PseudoConstant
::country(),
611 CRM_Utils_Array
::lookupValue($values,
613 CRM_Core_PseudoConstant
::countryIsoCode(),
619 // if we find a country id above, we need to restrict it to that country
620 // rather than the list of all countries
622 if (!empty($values['country_id'])) {
623 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($values['country_id']);
626 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvince();
628 if (!CRM_Utils_Array
::lookupValue($values,
636 if (!empty($values['country_id'])) {
637 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($values['country_id'], 'abbreviation');
640 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviation();
642 CRM_Utils_Array
::lookupValue($values,
649 if (!empty($values['state_province_id'])) {
650 $countyList = CRM_Core_PseudoConstant
::countyForState($values['state_province_id']);
653 $countyList = CRM_Core_PseudoConstant
::county();
655 CRM_Utils_Array
::lookupValue($values,
663 CRM_Utils_Array
::lookupValue($values,
665 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id'),
670 if ($name == 'phone') {
671 CRM_Utils_Array
::lookupValue($values,
673 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id'),
678 //kill the reference.
685 * Takes a bunch of params that are needed to match certain criteria and
686 * retrieves the relevant objects. Typically the valid params are only
687 * contact_id. We'll tweak this function to be more full featured over a period
688 * of time. This is the inverse function of create. It also stores all the retrieved
689 * values in the default array
691 * @param array $params (reference ) an assoc array of name/value pairs
692 * @param array $defaults (reference ) an assoc array to hold the name / value pairs
693 * in a hierarchical manner
694 * @param boolean $microformat for location in microformat
696 * @return object CRM_Contact_BAO_Contact object
700 static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
701 if (array_key_exists('contact_id', $params)) {
702 $params['id'] = $params['contact_id'];
704 elseif (array_key_exists('id', $params)) {
705 $params['contact_id'] = $params['id'];
708 $contact = self
::getValues($params, $defaults);
710 unset($params['id']);
712 //get the block information for this contact
713 $entityBlock = array('contact_id' => $params['contact_id']);
714 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock, $microformat);
715 $defaults = array_merge($defaults, $blocks);
716 foreach ($blocks as $block => $value) $contact->$block = $value;
718 if (!isset($params['noNotes'])) {
719 $contact->notes
= CRM_Core_BAO_Note
::getValues($params, $defaults);
722 if (!isset($params['noRelationships'])) {
723 $contact->relationship
= CRM_Contact_BAO_Relationship
::getValues($params, $defaults);
726 if (!isset($params['noGroups'])) {
727 $contact->groupContact
= CRM_Contact_BAO_GroupContact
::getValues($params, $defaults);
730 if (!isset($params['noWebsite'])) {
731 $contact->website
= CRM_Core_BAO_Website
::getValues($params, $defaults);
738 * function to get the display name of a contact
740 * @param int $id id of the contact
742 * @return null|string display name of the contact if found
746 static function displayName($id) {
749 $displayName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
756 * Delete a contact and all its associated records
758 * @param int $id id of the contact to delete
759 * @param bool $restore whether to actually restore, not delete
760 * @param bool $skipUndelete whether to force contact delete or not
762 * @return boolean true if contact deleted, false otherwise
766 static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE) {
772 // make sure we have edit permission for this contact
774 if (($skipUndelete && !CRM_Core_Permission
::check('delete contacts')) ||
775 ($restore && !CRM_Core_Permission
::check('access deleted contacts'))
781 // Restrict contact to be delete if contact has financial trxns
783 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent(array($id), $error)) {
787 // make sure this contact_id does not have any membership types
788 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
791 'member_of_contact_id'
793 if ($membershipTypeID) {
797 $contact = new CRM_Contact_DAO_Contact();
799 if (!$contact->find(TRUE)) {
803 $contactType = $contact->contact_type
;
804 $action = ($restore) ?
'restore' : 'delete';
806 CRM_Utils_Hook
::pre($action, $contactType, $id, CRM_Core_DAO
::$_nullArray);
809 self
::contactTrashRestore($contact, TRUE);
810 CRM_Utils_Hook
::post($action, $contactType, $contact->id
, $contact);
815 // currently we only clear employer cache.
816 // we are not deleting inherited membership if any.
817 if ($contact->contact_type
== 'Organization') {
818 CRM_Contact_BAO_Contact_Utils
::clearAllEmployee($id);
821 // start a new transaction
822 $transaction = new CRM_Core_Transaction();
824 if ($skipUndelete or !CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'contact_undelete', NULL)) {
826 //delete billing address if exists.
827 CRM_Contribute_BAO_Contribution
::deleteAddress(NULL, $id);
829 // delete the log entries since we dont have triggers enabled as yet
830 $logDAO = new CRM_Core_DAO_Log();
831 $logDAO->entity_table
= 'civicrm_contact';
832 $logDAO->entity_id
= $id;
835 // delete contact participants CRM-12155
836 CRM_Event_BAO_Participant
::deleteContactParticipant($id);
838 // delete contact contributions CRM-12155
839 CRM_Contribute_BAO_Contribution
::deleteContactContribution($id);
841 // do activity cleanup, CRM-5604
842 CRM_Activity_BAO_Activity
::cleanupActivity($id);
844 // delete all notes related to contact
845 CRM_Core_BAO_Note
::cleanContactNotes($id);
847 // delete cases related to contact
848 $contactCases = CRM_Case_BAO_Case
::retrieveCaseIdsByContactId($id);
849 if (!empty($contactCases)) {
850 foreach ($contactCases as $caseId) {
851 //check if case is associate with other contact or not.
852 $caseContactId = CRM_Case_BAO_Case
::getCaseClients($caseId);
853 if (count($caseContactId) <= 1) {
854 CRM_Case_BAO_Case
::deleteCase($caseId);
862 self
::contactTrashRestore($contact);
865 //delete the contact id from recently view
866 CRM_Utils_Recent
::delContact($id);
868 // reset the group contact cache for this group
869 CRM_Contact_BAO_GroupContactCache
::remove();
871 // delete any dupe cache entry
872 CRM_Core_BAO_PrevNextCache
::deleteItem($id);
874 $transaction->commit();
876 CRM_Utils_Hook
::post('delete', $contactType, $contact->id
, $contact);
878 // also reset the DB_DO global array so we can reuse the memory
879 // http://issues.civicrm.org/jira/browse/CRM-4387
880 CRM_Core_DAO
::freeResult();
886 * function to delete the image of a contact
888 * @param int $id id of the contact
890 * @return boolean true if contact image is deleted
892 public static function deleteContactImage($id) {
897 UPDATE civicrm_contact
900 CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
905 * function to return relative path
906 * @todo make this a method of $config->userSystem (i.e. UF classes) rather than a static function
908 * @param $absolutePath
910 * @internal param String $absPath absolute path
912 * @return String $relativePath Relative url of uploaded image
914 public static function getRelativePath($absolutePath) {
915 $relativePath = NULL;
916 $config = CRM_Core_Config
::singleton();
917 if ($config->userFramework
== 'Joomla') {
918 $userFrameworkBaseURL = trim(str_replace('/administrator/', '', $config->userFrameworkBaseURL
));
919 $customFileUploadDirectory = strstr(str_replace('\\', '/', $absolutePath), '/media');
920 $relativePath = $userFrameworkBaseURL . $customFileUploadDirectory;
922 elseif ($config->userSystem
->is_drupal
== '1') {
923 //ideally we would do a bigger re-factoring & move the getRelativePath onto the UF class
924 $rootPath = $config->userSystem
->cmsRootPath();
925 $baseUrl = $config->userFrameworkBaseURL
;
927 //format url for language negotiation, CRM-7135
928 $baseUrl = CRM_Utils_System
::languageNegotiationURL($baseUrl, FALSE, TRUE);
930 $relativePath = str_replace("{$rootPath}/",
932 str_replace('\\', '/', $absolutePath)
934 } else if ( $config->userFramework
== 'WordPress' ) {
935 $userFrameworkBaseURL = trim( str_replace( '/wp-admin/', '', $config->userFrameworkBaseURL
) );
936 $customFileUploadDirectory = strstr( str_replace('\\', '/', $absolutePath), '/wp-content/' );
937 $relativePath = $userFrameworkBaseURL . $customFileUploadDirectory;
940 return $relativePath;
944 * function to return proportional height and width of the image
946 * @param Integer $imageWidth width of image
948 * @param Integer $imageHeight height of image
950 * @return Array thumb dimension of image
952 public static function getThumbSize($imageWidth, $imageHeight) {
954 if ($imageWidth && $imageHeight) {
955 $imageRatio = $imageWidth / $imageHeight;
960 if ($imageRatio > 1) {
961 $imageThumbWidth = $thumbWidth;
962 $imageThumbHeight = round($thumbWidth / $imageRatio);
965 $imageThumbHeight = $thumbWidth;
966 $imageThumbWidth = round($thumbWidth * $imageRatio);
969 return array($imageThumbWidth, $imageThumbHeight);
973 * function to validate type of contact image
976 * @param String $imageIndex index of image field
978 * @param String $statusMsg status message to be set after operation
980 * @param string $opType
982 * @internal param Array $param array of contact/profile field to be edited/added
984 * @opType String $opType type of operation like fatal, bounce etc
986 * @return boolean true if valid image extension
988 public static function processImageParams(&$params,
989 $imageIndex = 'image_URL',
1003 if (in_array($params[$imageIndex]['type'], $mimeType)) {
1004 $photo = basename($params[$imageIndex]['name']);
1005 $params[$imageIndex] = CRM_Utils_System
::url('civicrm/contact/imagefile', 'photo='.$photo, TRUE, NULL, TRUE, TRUE);
1009 unset($params[$imageIndex]);
1011 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
1013 if ($opType == 'status') {
1014 CRM_Core_Session
::setStatus($statusMsg, 'Sorry', 'error');
1016 // FIXME: additional support for fatal, bounce etc could be added.
1022 * function to extract contact id from url for deleting contact image
1024 public static function processImage() {
1026 $action = CRM_Utils_Request
::retrieve('action', 'String');
1027 $cid = CRM_Utils_Request
::retrieve('cid', 'Positive');
1028 // retrieve contact id in case of Profile context
1029 $id = CRM_Utils_Request
::retrieve('id', 'Positive');
1030 $cid = $cid ?
$cid : $id;
1031 if ($action & CRM_Core_Action
::DELETE
) {
1032 if (CRM_Utils_Request
::retrieve('confirmed', 'Boolean')) {
1033 CRM_Contact_BAO_Contact
::deleteContactImage($cid);
1034 CRM_Core_Session
::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
1035 $session = CRM_Core_Session
::singleton();
1036 $toUrl = $session->popUserContext();
1037 CRM_Utils_System
::redirect($toUrl);
1043 * Function to set is_delete true or restore deleted contact
1045 * @param int $contact Contact DAO object
1046 * @param boolean $restore true to set the is_delete = 1 else false to restore deleted contact,
1047 * i.e. is_delete = 0
1052 static function contactTrashRestore($contact, $restore = FALSE) {
1053 $op = ($restore ?
'restore' : 'trash');
1055 CRM_Utils_Hook
::pre($op, $contact->contact_type
, $contact->id
, CRM_Core_DAO
::$_nullArray);
1057 $params = array(1 => array($contact->id
, 'Integer'));
1058 $isDelete = ' is_deleted = 1 ';
1060 $isDelete = ' is_deleted = 0 ';
1063 $query = "DELETE FROM civicrm_uf_match WHERE contact_id = %1";
1064 CRM_Core_DAO
::executeQuery($query, $params);
1067 $query = "UPDATE civicrm_contact SET {$isDelete} WHERE id = %1";
1068 CRM_Core_DAO
::executeQuery($query, $params);
1070 CRM_Utils_Hook
::post($op, $contact->contact_type
, $contact->id
, $contact);
1074 * Get contact type for a contact.
1076 * @param int $id - id of the contact whose contact type is needed
1078 * @return string contact_type if $id found else null ""
1085 public static function getContactType($id) {
1086 return CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1090 * Get contact sub type for a contact.
1092 * @param int $id - id of the contact whose contact sub type is needed
1094 * @param null $implodeDelimiter
1096 * @return string contact_sub_type if $id found else null ""
1102 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1103 $subtype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1105 return $implodeDelimiter ?
NULL : array();
1108 $subtype = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($subtype, CRM_Core_DAO
::VALUE_SEPARATOR
));
1110 if ($implodeDelimiter) {
1111 $subtype = implode($implodeDelimiter, $subtype);
1117 * Get pair of contact-type and sub-type for a contact.
1119 * @param int $id - id of the contact whose contact sub/contact type is needed
1128 public static function getContactTypes($id) {
1129 $params = array('id' => $id);
1131 $contact = CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact',
1134 array('contact_type', 'contact_sub_type')
1138 $contactTypes = array();
1139 if ($contact->contact_sub_type
)
1140 $contactTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($contact->contact_sub_type
, CRM_Core_DAO
::VALUE_SEPARATOR
));
1141 array_unshift($contactTypes, $contact->contact_type
);
1143 return $contactTypes;
1146 CRM_Core_Error
::fatal();
1151 * combine all the importable fields from the lower levels object
1153 * The ordering is important, since currently we do not have a weight
1154 * scheme. Adding weight is super important
1156 * @param int|string $contactType contact Type
1157 * @param boolean $status status is used to manipulate first title
1158 * @param boolean $showAll if true returns all fields (includes disabled fields)
1159 * @param boolean $isProfile if its profile mode
1160 * @param boolean $checkPermission if false, do not include permissioning clause (for custom data)
1162 * @param bool $withMultiCustomFields
1164 * @return array array of importable Fields
1168 static function importableFields($contactType = 'Individual',
1172 $checkPermission = TRUE,
1173 $withMultiCustomFields = FALSE
1175 if (empty($contactType)) {
1176 $contactType = 'All';
1179 $cacheKeyString = "importableFields $contactType";
1180 $cacheKeyString .= $status ?
'_1' : '_0';
1181 $cacheKeyString .= $showAll ?
'_1' : '_0';
1182 $cacheKeyString .= $isProfile ?
'_1' : '_0';
1183 $cacheKeyString .= $checkPermission ?
'_1' : '_0';
1185 $fields = CRM_Utils_Array
::value($cacheKeyString, self
::$_importableFields);
1188 // check if we can retrieve from database cache
1189 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1193 $fields = CRM_Contact_DAO_Contact
::import();
1195 // get the fields thar are meant for contact types
1196 if (in_array($contactType, array(
1197 'Individual', 'Household', 'Organization', 'All'))) {
1198 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1201 $locationFields = array_merge(CRM_Core_DAO_Address
::import(),
1202 CRM_Core_DAO_Phone
::import(),
1203 CRM_Core_DAO_Email
::import(),
1204 CRM_Core_DAO_IM
::import(TRUE),
1205 CRM_Core_DAO_OpenID
::import()
1208 $locationFields = array_merge($locationFields,
1209 CRM_Core_BAO_CustomField
::getFieldsForImport('Address',
1217 foreach ($locationFields as $key => $field) {
1218 $locationFields[$key]['hasLocationType'] = TRUE;
1221 $fields = array_merge($fields, $locationFields);
1223 $fields = array_merge($fields, CRM_Contact_DAO_Contact
::import());
1224 $fields = array_merge($fields, CRM_Core_DAO_Note
::import());
1227 $fields = array_merge($fields, CRM_Core_DAO_Website
::import());
1228 $fields['url']['hasWebsiteType'] = TRUE;
1230 if ($contactType != 'All') {
1231 $fields = array_merge($fields,
1232 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType,
1237 $withMultiCustomFields
1240 //unset the fields, which are not related to their
1242 $commonValues = array(
1243 'Individual' => array(
1249 'Household' => array(
1259 'organization_name',
1267 'Organization' => array(
1282 foreach ($commonValues[$contactType] as $value) {
1283 unset($fields[$value]);
1288 'Individual', 'Household', 'Organization') as $type) {
1289 $fields = array_merge($fields,
1290 CRM_Core_BAO_CustomField
::getFieldsForImport($type,
1295 $withMultiCustomFields
1302 $fields = array_merge($fields, array(
1304 'title' => ts('Group(s)'),
1308 'title' => ts('Tag(s)'),
1312 'title' => ts('Note(s)'),
1318 //Sorting fields in alphabetical order(CRM-1507)
1319 $fields = CRM_Utils_Array
::crmArraySortByField($fields, 'title');
1321 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1324 self
::$_importableFields[$cacheKeyString] = $fields;
1328 $fields = array_merge(array('do_not_import' => array('title' => ts('- do not import -'))),
1329 self
::$_importableFields[$cacheKeyString]
1333 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1334 self
::$_importableFields[$cacheKeyString]
1342 * combine all the exportable fields from the lower levels object
1344 * currentlty we are using importable fields as exportable fields
1346 * @param int|string $contactType contact Type
1347 * @param boolean $status true while exporting primary contacts
1348 * @param boolean $export true when used during export
1349 * @param boolean $search true when used during search, might conflict with export param?
1351 * @param bool $withMultiRecord
1353 * @return array array of exportable Fields
1357 static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE) {
1358 if (empty($contactType)) {
1359 $contactType = 'All';
1362 $cacheKeyString = "exportableFields $contactType";
1363 $cacheKeyString .= $export ?
'_1' : '_0';
1364 $cacheKeyString .= $status ?
'_1' : '_0';
1365 $cacheKeyString .= $search ?
'_1' : '_0';
1366 //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
1367 //calculates custom fields takes into account the logged in user & caches that for all users
1368 //as an interim fix we will cache the fields by contact
1369 $cacheKeyString .= '_' . CRM_Core_Session
::getLoggedInContactID();
1371 if (!self
::$_exportableFields ||
!CRM_Utils_Array
::value($cacheKeyString, self
::$_exportableFields)) {
1372 if (!self
::$_exportableFields) {
1373 self
::$_exportableFields = array();
1376 // check if we can retrieve from database cache
1377 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1380 $fields = CRM_Contact_DAO_Contact
::export();
1382 // the fields are meant for contact types
1386 array('Individual', 'Household', 'Organization', 'All')
1389 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1391 // add current employer for individuals
1392 $fields = array_merge($fields, array(
1393 'current_employer' =>
1395 'name' => 'organization_name',
1396 'title' => ts('Current Employer'),
1400 $locationType = array(
1401 'location_type' => array(
1402 'name' => 'location_type',
1403 'where' => 'civicrm_location_type.name',
1404 'title' => ts('Location Type'),
1407 $IMProvider = array(
1408 'im_provider' => array(
1409 'name' => 'im_provider',
1410 'where' => 'civicrm_im.provider_id',
1411 'title' => ts('IM Provider'),
1414 $locationFields = array_merge($locationType,
1415 CRM_Core_DAO_Address
::export(),
1416 CRM_Core_DAO_Phone
::export(),
1417 CRM_Core_DAO_Email
::export(),
1419 CRM_Core_DAO_IM
::export(TRUE),
1420 CRM_Core_DAO_OpenID
::export()
1423 $locationFields = array_merge($locationFields,
1424 CRM_Core_BAO_CustomField
::getFieldsForImport('Address')
1427 foreach ($locationFields as $key => $field) {
1428 $locationFields[$key]['hasLocationType'] = TRUE;
1431 $fields = array_merge($fields, $locationFields);
1434 $fields = array_merge($fields,
1435 CRM_Core_DAO_Worldregion
::export()
1439 $fields = array_merge($fields,
1440 CRM_Contact_DAO_Contact
::export()
1444 $fields = array_merge($fields, CRM_Core_DAO_Website
::export());
1446 if ($contactType != 'All') {
1447 $fields = array_merge($fields,
1448 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType, $status, FALSE, $search, TRUE, $withMultiRecord)
1453 'Individual', 'Household', 'Organization') as $type) {
1454 $fields = array_merge($fields,
1455 CRM_Core_BAO_CustomField
::getFieldsForImport($type, FALSE, FALSE, $search, TRUE, $withMultiRecord)
1462 $fields = array_merge($fields, array(
1464 'title' => ts('Group(s)'),
1468 'title' => ts('Tag(s)'),
1472 'title' => ts('Note(s)'),
1478 $fields = array_merge($fields, array(
1480 'title' => ts('Group(s)'),
1484 'title' => ts('Tag(s)'),
1488 'title' => ts('Note(s)'),
1494 //Sorting fields in alphabetical order(CRM-1507)
1495 foreach ($fields as $k => $v) {
1496 $sortArray[$k] = CRM_Utils_Array
::value('title', $v);
1499 $fields = array_merge($sortArray, $fields);
1500 //unset the field which are not related to their contact type.
1501 if ($contactType != 'All') {
1502 $commonValues = array(
1503 'Individual' => array(
1507 'organization_name',
1508 'email_greeting_custom',
1509 'postal_greeting_custom',
1512 'Household' => array(
1522 'organization_name',
1530 'email_greeting_custom',
1531 'postal_greeting_custom',
1536 'Organization' => array(
1547 'email_greeting_custom',
1548 'postal_greeting_custom',
1558 foreach ($commonValues[$contactType] as $value) {
1559 unset($fields[$value]);
1563 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1565 self
::$_exportableFields[$cacheKeyString] = $fields;
1569 $fields = self
::$_exportableFields[$cacheKeyString];
1572 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1573 self
::$_exportableFields[$cacheKeyString]
1581 * Function to get the all contact details(Hierarchical)
1583 * @param int $contactId contact id
1584 * @param array $fields fields array
1586 * @return $values array contains the contact details
1590 static function getHierContactDetails($contactId, &$fields) {
1591 $params = array(array('contact_id', '=', $contactId, 0, 0));
1594 $returnProperties = self
::makeHierReturnProperties($fields, $contactId);
1596 // we dont know the contents of return properties, but we need the lower level ids of the contact
1597 // so add a few fields
1598 $returnProperties['first_name'] =
1599 $returnProperties['organization_name'] =
1600 $returnProperties['household_name'] =
1601 $returnProperties['contact_type'] =
1602 $returnProperties['contact_sub_type'] = 1;
1603 return list($query, $options) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, $options);
1607 * given a set of flat profile style field names, create a hierarchy
1608 * for query to use and crete the right sql
1611 * @param int $contactId contact id
1613 * @internal param array $properties a flat return properties name value array
1614 * @return array a hierarchical property tree if appropriate
1618 static function &makeHierReturnProperties($fields, $contactId = NULL) {
1619 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1621 $returnProperties = array();
1623 $multipleFields = array('website' => 'url');
1624 foreach ($fields as $name => $dontCare) {
1625 if (strpos($name, '-') !== FALSE) {
1626 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $name, 3);
1628 if (!in_array($fieldName, $multipleFields)) {
1629 if ($id == 'Primary') {
1630 $locationTypeName = 1;
1633 $locationTypeName = CRM_Utils_Array
::value($id, $locationTypes);
1634 if (!$locationTypeName) {
1639 if (empty($returnProperties['location'])) {
1640 $returnProperties['location'] = array();
1642 if (empty($returnProperties['location'][$locationTypeName])) {
1643 $returnProperties['location'][$locationTypeName] = array();
1644 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1646 if (in_array($fieldName, array(
1647 'phone', 'im', 'email', 'openid', 'phone_ext'))) {
1649 $returnProperties['location'][$locationTypeName][$fieldName . '-' . $type] = 1;
1652 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1655 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1656 $returnProperties['location'][$locationTypeName][substr($fieldName, 8)] = 1;
1659 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1663 $returnProperties['website'][$id][$fieldName] = 1;
1667 $returnProperties[$name] = 1;
1671 return $returnProperties;
1675 * Function to return the primary location type of a contact
1677 * $params int $contactId contact_id
1678 * $params boolean $isPrimaryExist if true, return primary contact location type otherwise null
1679 * $params boolean $skipDefaultPriamry if true, return primary contact location type otherwise null
1682 * @param bool $skipDefaultPriamry
1683 * @param null $block
1685 * @return int $locationType location_type_id
1689 static function getPrimaryLocationType($contactId, $skipDefaultPriamry = FALSE, $block = NULL) {
1691 $entityBlock = array('contact_id' => $contactId);
1692 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock);
1693 foreach($blocks[$block] as $key => $value){
1694 if (!empty($value['is_primary'])){
1695 $locationType = CRM_Utils_Array
::value('location_type_id',$value);
1702 IF ( civicrm_email.location_type_id IS NULL,
1703 IF ( civicrm_address.location_type_id IS NULL,
1704 IF ( civicrm_phone.location_type_id IS NULL,
1705 IF ( civicrm_im.location_type_id IS NULL,
1706 IF ( civicrm_openid.location_type_id IS NULL, null, civicrm_openid.location_type_id)
1707 ,civicrm_im.location_type_id)
1708 ,civicrm_phone.location_type_id)
1709 ,civicrm_address.location_type_id)
1710 ,civicrm_email.location_type_id) as locationType
1711 FROM civicrm_contact
1712 LEFT JOIN civicrm_email ON ( civicrm_email.is_primary = 1 AND civicrm_email.contact_id = civicrm_contact.id )
1713 LEFT JOIN civicrm_address ON ( civicrm_address.is_primary = 1 AND civicrm_address.contact_id = civicrm_contact.id)
1714 LEFT JOIN civicrm_phone ON ( civicrm_phone.is_primary = 1 AND civicrm_phone.contact_id = civicrm_contact.id)
1715 LEFT JOIN civicrm_im ON ( civicrm_im.is_primary = 1 AND civicrm_im.contact_id = civicrm_contact.id)
1716 LEFT JOIN civicrm_openid ON ( civicrm_openid.is_primary = 1 AND civicrm_openid.contact_id = civicrm_contact.id)
1717 WHERE civicrm_contact.id = %1 ";
1719 $params = array(1 => array($contactId, 'Integer'));
1721 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1723 $locationType = NULL;
1724 if ($dao->fetch()) {
1725 $locationType = $dao->locationType
;
1728 if (isset($locationType)) {
1729 return $locationType;
1731 elseif ($skipDefaultPriamry) {
1732 // if there is no primary contact location then return null
1736 // if there is no primart contact location, then return default
1737 // location type of the system
1738 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
1739 return $defaultLocationType->id
;
1744 * function to get the display name, primary email and location type of a contact
1746 * @param int $id id of the contact
1748 * @return array of display_name, email if found, do_not_email or (null,null,null)
1752 static function getContactDetails($id) {
1753 // check if the contact type
1754 $contactType = self
::getContactType($id);
1756 $nameFields = ($contactType == 'Individual') ?
"civicrm_contact.first_name, civicrm_contact.last_name, civicrm_contact.display_name" : "civicrm_contact.display_name";
1759 SELECT $nameFields, civicrm_email.email, civicrm_contact.do_not_email, civicrm_email.on_hold, civicrm_contact.is_deceased
1760 FROM civicrm_contact LEFT JOIN civicrm_email ON (civicrm_contact.id = civicrm_email.contact_id)
1761 WHERE civicrm_contact.id = %1
1762 ORDER BY civicrm_email.is_primary DESC";
1763 $params = array(1 => array($id, 'Integer'));
1764 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
1766 if ($dao->fetch()) {
1767 if ($contactType == 'Individual') {
1768 if ($dao->first_name ||
$dao->last_name
) {
1769 $name = "{$dao->first_name} {$dao->last_name}";
1772 $name = $dao->display_name
;
1776 $name = $dao->display_name
;
1778 $email = $dao->email
;
1779 $doNotEmail = $dao->do_not_email ?
TRUE : FALSE;
1780 $onHold = $dao->on_hold ?
TRUE : FALSE;
1781 $isDeceased = $dao->is_deceased ?
TRUE : FALSE;
1782 return array($name, $email, $doNotEmail, $onHold, $isDeceased);
1784 return array(NULL, NULL, NULL, NULL, NULL);
1788 * function to add/edit/register contacts through profile.
1790 * @params array $params Array of profile fields to be edited/added.
1791 * @params int $contactID contact_id of the contact to be edited/added.
1792 * @params array $fields array of fields from UFGroup
1793 * @params int $addToGroupID specifies the default group to which contact is added.
1794 * @params int $ufGroupId uf group id (profile id)
1797 * @param null $contactID
1798 * @param null $addToGroupID
1799 * @param null $ufGroupId
1800 * @param string $ctype contact type
1801 * @param boolean $visibility basically lets us know where this request is coming from
1802 * if via a profile from web, we restrict what groups are changed
1804 * @return int contact id created/edited
1808 static function createProfileContact(
1812 $addToGroupID = NULL,
1817 // add ufGroupID to params array ( CRM-2012 )
1819 $params['uf_group_id'] = $ufGroupId;
1824 CRM_Utils_Hook
::pre('edit', 'Profile', $contactID, $params);
1828 CRM_Utils_Hook
::pre('create', 'Profile', NULL, $params);
1831 list($data, $contactDetails) = self
::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
1833 // manage is_opt_out
1834 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
1835 $wasOptOut = CRM_Utils_Array
::value('is_opt_out', $contactDetails, FALSE);
1836 $isOptOut = CRM_Utils_Array
::value('is_opt_out', $params, FALSE);
1837 $data['is_opt_out'] = $isOptOut;
1838 // on change, create new civicrm_subscription_history entry
1839 if (($wasOptOut != $isOptOut) && !empty($contactDetails['contact_id'])) {
1841 'contact_id' => $contactDetails['contact_id'],
1842 'status' => $isOptOut ?
'Removed' : 'Added',
1845 CRM_Contact_BAO_SubscriptionHistory
::create($shParams);
1849 $contact = self
::create($data);
1851 // contact is null if the profile does not have any contact fields
1853 $contactID = $contact->id
;
1856 if (empty($contactID)) {
1857 CRM_Core_Error
::fatal('Cannot proceed without a valid contact id');
1860 // Process group and tag
1861 if (!empty($fields['group'])) {
1863 // this for sure means we are coming in via profile since i added it to fix
1864 // removing contacts from user groups -- lobo
1868 CRM_Contact_BAO_GroupContact
::create($params['group'], $contactID, $visibility, $method);
1871 if (!empty($fields['tag'])) {
1872 CRM_Core_BAO_EntityTag
::create($params['tag'], 'civicrm_contact', $contactID);
1875 //to add profile in default group
1876 if (is_array($addToGroupID)) {
1877 $contactIds = array($contactID);
1878 foreach ($addToGroupID as $groupId) {
1879 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
1882 elseif ($addToGroupID) {
1883 $contactIds = array($contactID);
1884 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $addToGroupID);
1887 // reset the group contact cache for this group
1888 CRM_Contact_BAO_GroupContactCache
::remove();
1891 CRM_Utils_Hook
::post('edit', 'Profile', $contactID, $params);
1894 CRM_Utils_Hook
::post('create', 'Profile', $contactID, $params);
1902 * @param null $contactID
1903 * @param null $ufGroupId
1904 * @param null $ctype
1905 * @param bool $skipCustom
1909 static function formatProfileContactParams(
1918 $data = $contactDetails = array();
1920 // get the contact details (hier)
1922 list($details, $options) = self
::getHierContactDetails($contactID, $fields);
1924 $contactDetails = $details[$contactID];
1925 $data['contact_type'] = CRM_Utils_Array
::value('contact_type', $contactDetails);
1926 $data['contact_sub_type'] = CRM_Utils_Array
::value('contact_sub_type', $contactDetails);
1929 //we should get contact type only if contact
1931 $data['contact_type'] = CRM_Core_BAO_UFField
::getProfileType($ufGroupId);
1933 //special case to handle profile with only contact fields
1934 if ($data['contact_type'] == 'Contact') {
1935 $data['contact_type'] = 'Individual';
1937 elseif (CRM_Contact_BAO_ContactType
::isaSubType($data['contact_type'])) {
1938 $data['contact_type'] = CRM_Contact_BAO_ContactType
::getBasicType($data['contact_type']);
1942 $data['contact_type'] = $ctype;
1945 $data['contact_type'] = 'Individual';
1949 //fix contact sub type CRM-5125
1950 if (array_key_exists('contact_sub_type', $params) &&
1951 !empty($params['contact_sub_type'])
1953 $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
;
1955 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
1956 !empty($params['contact_sub_type_hidden'])
1958 // if profile was used, and had any subtype, we obtain it from there
1959 $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
;
1962 if ($ctype == 'Organization') {
1963 $data['organization_name'] = CRM_Utils_Array
::value('organization_name', $contactDetails);
1965 elseif ($ctype == 'Household') {
1966 $data['household_name'] = CRM_Utils_Array
::value('household_name', $contactDetails);
1969 $locationType = array();
1974 $data['contact_id'] = $contactID;
1975 $primaryLocationType = self
::getPrimaryLocationType($contactID);
1978 $defaultLocation = CRM_Core_BAO_LocationType
::getDefault();
1979 $defaultLocationId = $defaultLocation->id
;
1982 // get the billing location type
1983 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
1984 $billingLocationTypeId = array_search('Billing', $locationTypes);
1986 $blocks = array('email', 'phone', 'im', 'openid');
1988 $multiplFields = array('url');
1989 // prevent overwritten of formatted array, reset all block from
1990 // params if it is not in valid format (since import pass valid format)
1991 foreach ($blocks as $blk) {
1992 if (array_key_exists($blk, $params) &&
1993 !is_array($params[$blk])
1995 unset($params[$blk]);
1999 $primaryPhoneLoc = NULL;
2000 $session = CRM_Core_Session
::singleton();
2001 foreach ($params as $key => $value) {
2002 $fieldName = $locTypeId = $typeId = NULL;
2003 list($fieldName, $locTypeId, $typeId) = CRM_Utils_System
::explode('-', $key, 3);
2005 //store original location type id
2006 $actualLocTypeId = $locTypeId;
2008 if ($locTypeId == 'Primary') {
2010 if(in_array( $fieldName, $blocks)){
2011 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, $fieldName);
2014 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, 'address');
2016 $primaryLocationType = $locTypeId;
2019 $locTypeId = $defaultLocationId;
2023 if (is_numeric($locTypeId) &&
2024 !in_array($fieldName, $multiplFields) &&
2025 substr($fieldName, 0, 7) != 'custom_'
2027 $index = $locTypeId;
2029 if (is_numeric($typeId)) {
2030 $index .= '-' . $typeId;
2032 if (!in_array($index, $locationType)) {
2033 $locationType[$count] = $index;
2037 $loc = CRM_Utils_Array
::key($index, $locationType);
2039 $blockName = in_array( $fieldName, $blocks) ?
$fieldName : 'address';
2041 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
2043 //set is_billing true, for location type "Billing"
2044 if ($locTypeId == $billingLocationTypeId) {
2045 $data[$blockName][$loc]['is_billing'] = 1;
2049 //get the primary location type
2050 if ($locTypeId == $primaryLocationType) {
2051 $data[$blockName][$loc]['is_primary'] = 1;
2054 elseif ($locTypeId == $defaultLocationId) {
2055 $data[$blockName][$loc]['is_primary'] = 1;
2058 if ( in_array($fieldName, array('phone'))) {
2060 $data['phone'][$loc]['phone_type_id'] = $typeId;
2063 $data['phone'][$loc]['phone_type_id'] = '';
2065 $data['phone'][$loc]['phone'] = $value;
2067 //special case to handle primary phone with different phone types
2068 // in this case we make first phone type as primary
2069 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
2070 $primaryPhoneLoc = $loc;
2073 if ($loc != $primaryPhoneLoc) {
2074 unset($data['phone'][$loc]['is_primary']);
2077 elseif ($fieldName == 'phone_ext') {
2078 $data['phone'][$loc]['phone_ext'] = $value;
2080 elseif ($fieldName == 'email') {
2081 $data['email'][$loc]['email'] = $value;
2083 elseif ($fieldName == 'im') {
2084 if (isset($params[$key . '-provider_id'])) {
2085 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
2087 if (strpos($key, '-provider_id') !== FALSE) {
2088 $data['im'][$loc]['provider_id'] = $params[$key];
2091 $data['im'][$loc]['name'] = $value;
2094 elseif ($fieldName == 'openid') {
2095 $data['openid'][$loc]['openid'] = $value;
2098 if ($fieldName === 'state_province') {
2100 if (is_numeric($value) && ((int ) $value) >= 1000) {
2101 $data['address'][$loc]['state_province_id'] = $value;
2103 elseif (empty($value)) {
2104 $data['address'][$loc]['state_province_id'] = '';
2107 $data['address'][$loc]['state_province'] = $value;
2110 elseif ($fieldName === 'country') {
2112 if (is_numeric($value) && ((int ) $value) >= 1000
2114 $data['address'][$loc]['country_id'] = $value;
2116 elseif (empty($value)) {
2117 $data['address'][$loc]['country_id'] = '';
2120 $data['address'][$loc]['country'] = $value;
2123 elseif ($fieldName === 'county') {
2124 $data['address'][$loc]['county_id'] = $value;
2126 elseif ($fieldName == 'address_name') {
2127 $data['address'][$loc]['name'] = $value;
2129 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2130 $data['address'][$loc][substr($fieldName, 8)] = $value;
2133 $data['address'][$loc][$fieldName] = $value;
2138 if (substr($key, 0, 4) === 'url-') {
2139 $websiteField = explode('-', $key);
2140 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
2141 $data['website'][$websiteField[1]]['url'] = $value;
2143 elseif (in_array($key, self
::$_greetingTypes, TRUE)) {
2144 //save email/postal greeting and addressee values if any, CRM-4575
2145 $data[$key . '_id'] = $value;
2147 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($key))) {
2148 // for autocomplete transfer hidden value instead of label
2149 if ($params[$key] && isset($params[$key . '_id'])) {
2150 $value = $params[$key . '_id'];
2153 // we need to append time with date
2154 if ($params[$key] && isset($params[$key . '_time'])) {
2155 $value .= ' ' . $params[$key . '_time'];
2158 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
2159 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 &&
2160 ($value == '' ||
!isset($value))) {
2165 if (!empty($params['customRecordValues'])) {
2166 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2167 foreach ($params['customRecordValues'] as $recId => $customFields) {
2168 if (is_array($customFields) && !empty($customFields)) {
2169 foreach ($customFields as $customFieldName) {
2170 if ($customFieldName == $key) {
2180 $type = $data['contact_type'];
2181 if (!empty($data['contact_sub_type'])) {
2182 $type = $data['contact_sub_type'];
2183 $type = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($type, CRM_Core_DAO
::VALUE_SEPARATOR
));
2184 // generally a contact even if, has multiple subtypes the parent-type is going to be one only
2185 // and since formatCustomField() would be interested in parent type, lets consider only one subtype
2186 // as the results going to be same.
2190 CRM_Core_BAO_CustomField
::formatCustomField($customFieldId,
2198 elseif ($key == 'edit') {
2202 if ($key == 'location') {
2203 foreach ($value as $locationTypeId => $field) {
2204 foreach ($field as $block => $val) {
2205 if ($block == 'address' && array_key_exists('address_name', $val)) {
2206 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2211 if($key == 'phone' && isset($params['phone_ext'])){
2212 $data[$key] = $value;
2213 foreach($value as $cnt => $phoneBlock){
2214 if($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']){
2215 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array
::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2219 else if (in_array($key,
2228 ($value == '' ||
!isset($value)) &&
2229 ($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0) {
2230 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
2231 // to avoid update with empty values
2235 $data[$key] = $value;
2241 if (!isset($data['contact_type'])) {
2242 $data['contact_type'] = 'Individual';
2245 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2246 $privacy = CRM_Core_SelectValues
::privacy();
2247 foreach ($privacy as $key => $value) {
2248 if (array_key_exists($key, $fields)) {
2249 // do not reset values for existing contacts, if fields are added to a profile
2250 if (array_key_exists($key, $params)) {
2251 $data[$key] = $params[$key];
2252 if (empty($params[$key])) {
2256 elseif (!$contactID) {
2262 return array($data, $contactDetails);
2266 * Function to find the get contact details
2267 * does not respect ACLs for now, which might need to be rectified at some
2268 * stage based on how its used
2270 * @param string $mail primary email address of the contact
2271 * @param string $ctype contact type
2273 * @return object $dao contact details
2276 static function &matchContactOnEmail($mail, $ctype = NULL) {
2277 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2278 $mail = $strtolower(trim($mail));
2280 SELECT civicrm_contact.id as contact_id,
2281 civicrm_contact.hash as hash,
2282 civicrm_contact.contact_type as contact_type,
2283 civicrm_contact.contact_sub_type as contact_sub_type
2284 FROM civicrm_contact
2285 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2288 if (CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
2289 'uniq_email_per_site'
2291 // try to find a match within a site (multisite).
2292 $groups = CRM_Core_BAO_Domain
::getChildGroupIds();
2293 if (!empty($groups)) {
2295 INNER JOIN civicrm_group_contact gc ON
2296 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2301 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2302 $p = array(1 => array($mail, 'String'));
2305 $query .= " AND civicrm_contact.contact_type = %3";
2306 $p[3] = array($ctype, 'String');
2309 $query .= " ORDER BY civicrm_email.is_primary DESC";
2311 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2313 if ($dao->fetch()) {
2316 return CRM_Core_DAO
::$_nullObject;
2320 * Function to find the contact details associated with an OpenID
2322 * @param string $openId openId of the contact
2323 * @param string $ctype contact type
2325 * @return object $dao contact details
2328 static function &matchContactOnOpenId($openId, $ctype = NULL) {
2329 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2330 $openId = $strtolower(trim($openId));
2332 SELECT civicrm_contact.id as contact_id,
2333 civicrm_contact.hash as hash,
2334 civicrm_contact.contact_type as contact_type,
2335 civicrm_contact.contact_sub_type as contact_sub_type
2336 FROM civicrm_contact
2337 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2338 WHERE civicrm_openid.openid = %1";
2339 $p = array(1 => array($openId, 'String'));
2342 $query .= " AND civicrm_contact.contact_type = %3";
2343 $p[3] = array($ctype, 'String');
2346 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2348 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2350 if ($dao->fetch()) {
2353 return CRM_Core_DAO
::$_nullObject;
2357 * Funtion to get primary email of the contact
2359 * @param int $contactID contact id
2361 * @return string $dao->email email address if present else null
2365 public static function getPrimaryEmail($contactID) {
2366 // fetch the primary email
2368 SELECT civicrm_email.email as email
2369 FROM civicrm_contact
2370 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2371 WHERE civicrm_email.is_primary = 1
2372 AND civicrm_contact.id = %1";
2373 $p = array(1 => array($contactID, 'Integer'));
2374 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2377 if ($dao->fetch()) {
2378 $email = $dao->email
;
2385 * Funtion to get primary OpenID of the contact
2387 * @param int $contactID contact id
2389 * @return string $dao->openid OpenID if present else null
2393 public static function getPrimaryOpenId($contactID) {
2394 // fetch the primary OpenID
2396 SELECT civicrm_openid.openid as openid
2397 FROM civicrm_contact
2398 LEFT JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2399 WHERE civicrm_contact.id = %1
2400 AND civicrm_openid.is_primary = 1";
2401 $p = array(1 => array($contactID, 'Integer'));
2402 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2405 if ($dao->fetch()) {
2406 $openId = $dao->openid
;
2413 * Given the list of params in the params array, fetch the object
2414 * and store the values in the values array
2416 * @param array $params input parameters to find object
2417 * @param array $values output values of the object
2419 * @return CRM_Contact_BAO_Contact|null the found object or null
2423 public static function getValues(&$params, &$values) {
2424 $contact = new CRM_Contact_BAO_Contact();
2426 $contact->copyValues($params);
2428 if ($contact->find(TRUE)) {
2430 CRM_Core_DAO
::storeValues($contact, $values);
2433 foreach (self
::$_commPrefs as $name) {
2434 if (isset($contact->$name)) {
2435 $privacy[$name] = $contact->$name;
2439 if (!empty($privacy)) {
2440 $values['privacy'] = $privacy;
2443 // communication Prefferance
2444 $preffComm = $comm = array();
2445 $comm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2446 $contact->preferred_communication_method
2448 foreach ($comm as $value) {
2449 $preffComm[$value] = 1;
2451 $temp = array('preferred_communication_method' => $contact->preferred_communication_method
);
2454 'preferred_communication_method' => array('newName' => 'preferred_communication_method_display',
2455 'groupName' => 'preferred_communication_method',
2458 CRM_Core_OptionGroup
::lookupValues($temp, $names, FALSE);
2460 $values['preferred_communication_method'] = $preffComm;
2461 $values['preferred_communication_method_display'] = CRM_Utils_Array
::value('preferred_communication_method_display', $temp);
2463 $preferredMailingFormat = CRM_Core_SelectValues
::pmf();
2464 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format
];
2466 // get preferred languages
2467 if (!empty($contact->preferred_language
)) {
2468 $values['preferred_language'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language
);
2471 // Calculating Year difference
2472 if ($contact->birth_date
) {
2473 $birthDate = CRM_Utils_Date
::customFormat($contact->birth_date
, '%Y%m%d');
2474 if ($birthDate < date('Ymd')) {
2475 $age = CRM_Utils_Date
::calculateAge($birthDate);
2476 $values['age']['y'] = CRM_Utils_Array
::value('years', $age);
2477 $values['age']['m'] = CRM_Utils_Array
::value('months', $age);
2480 list($values['birth_date']) = CRM_Utils_Date
::setDateDefaults($contact->birth_date
, 'birth');
2481 $values['birth_date_display'] = $contact->birth_date
;
2484 if ($contact->deceased_date
) {
2485 list($values['deceased_date']) = CRM_Utils_Date
::setDateDefaults($contact->deceased_date
, 'birth');
2486 $values['deceased_date_display'] = $contact->deceased_date
;
2489 $contact->contact_id
= $contact->id
;
2497 * Given the component name and returns
2498 * the count of participation of contact
2500 * @param string $component input component name
2501 * @param integer $contactId input contact id
2502 * @param string $tableName optional tableName if component is custom group
2504 * @return total number of count of occurence in database
2508 static function getCountComponent($component, $contactId, $tableName = NULL) {
2510 switch ($component) {
2512 return CRM_Core_BAO_EntityTag
::getContactTags($contactId, TRUE);
2515 return CRM_Contact_BAO_Relationship
::getRelationship($contactId,
2516 CRM_Contact_BAO_Relationship
::CURRENT
,
2521 return CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, "Added", NULL, TRUE);
2524 if (CRM_Core_BAO_Log
::useLoggingReport()) {
2527 return CRM_Core_BAO_Log
::getContactLogCount($contactId);
2530 return CRM_Core_BAO_Note
::getContactNoteCount($contactId);
2532 case 'contribution':
2533 return CRM_Contribute_BAO_Contribution
::contributionCount($contactId);
2536 return CRM_Member_BAO_Membership
::getContactMembershipCount($contactId, TRUE);
2539 return CRM_Event_BAO_Participant
::getContactParticipantCount($contactId);
2542 return CRM_Pledge_BAO_Pledge
::getContactPledgeCount($contactId);
2545 return CRM_Case_BAO_Case
::caseCount($contactId);
2548 return CRM_Grant_BAO_Grant
::getContactGrantCount($contactId);
2552 'contact_id' => $contactId,
2555 'context' => 'activity',
2557 return CRM_Activity_BAO_Activity
::getActivitiesCount($input);
2560 $params = array('contact_id' => $contactId);
2561 return CRM_Mailing_BAO_Mailing
::getContactMailingsCount($params);
2564 $custom = explode('_', $component);
2565 if ($custom['0'] = 'custom') {
2567 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2569 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2570 return CRM_Core_DAO
::singleValueQuery($queryString);
2576 * Function to process greetings and cache
2578 * @param object $contact contact object after save
2579 * @param boolean $useDefaults use default greeting values
2585 static function processGreetings(&$contact, $useDefaults = FALSE) {
2587 //retrieve default greetings
2588 $defaultGreetings = CRM_Core_PseudoConstant
::greetingDefaults();
2589 $contactDefaults = $defaultGreetings[$contact->contact_type
];
2592 // note that contact object not always has required greeting related
2593 // fields that are required to calculate greeting and
2594 // also other fields used in tokens etc,
2595 // hence we need to retrieve it again.
2596 if ( $contact->_query
!== FALSE ) {
2597 $contact->find(TRUE);
2600 // store object values to an array
2601 $contactDetails = array();
2602 CRM_Core_DAO
::storeValues($contact, $contactDetails);
2603 $contactDetails = array(array($contact->id
=> $contactDetails));
2605 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2606 $updateQueryString = array();
2608 //cache email and postal greeting to greeting display
2609 if ($contact->email_greeting_custom
!= 'null' && $contact->email_greeting_custom
) {
2610 $emailGreetingString = $contact->email_greeting_custom
;
2612 elseif ($contact->email_greeting_id
!= 'null' && $contact->email_greeting_id
) {
2613 // the filter value for Individual contact type is set to 1
2615 'contact_type' => $contact->contact_type
,
2616 'greeting_type' => 'email_greeting',
2619 $emailGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2620 $emailGreetingString = $emailGreeting[$contact->email_greeting_id
];
2621 $updateQueryString[] = " email_greeting_custom = NULL ";
2625 reset($contactDefaults['email_greeting']);
2626 $emailGreetingID = key($contactDefaults['email_greeting']);
2627 $emailGreetingString = $contactDefaults['email_greeting'][$emailGreetingID];
2628 $updateQueryString[] = " email_greeting_id = $emailGreetingID ";
2629 $updateQueryString[] = " email_greeting_custom = NULL ";
2631 elseif ($contact->email_greeting_custom
) {
2632 $updateQueryString[] = " email_greeting_display = NULL ";
2636 if ($emailGreetingString) {
2637 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($emailGreetingString,
2640 'CRM_Contact_BAO_Contact'
2642 $emailGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($emailGreetingString));
2643 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2647 if ($contact->postal_greeting_custom
!= 'null' && $contact->postal_greeting_custom
) {
2648 $postalGreetingString = $contact->postal_greeting_custom
;
2650 elseif ($contact->postal_greeting_id
!= 'null' && $contact->postal_greeting_id
) {
2652 'contact_type' => $contact->contact_type
,
2653 'greeting_type' => 'postal_greeting',
2655 $postalGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2656 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id
];
2657 $updateQueryString[] = " postal_greeting_custom = NULL ";
2661 reset($contactDefaults['postal_greeting']);
2662 $postalGreetingID = key($contactDefaults['postal_greeting']);
2663 $postalGreetingString = $contactDefaults['postal_greeting'][$postalGreetingID];
2664 $updateQueryString[] = " postal_greeting_id = $postalGreetingID ";
2665 $updateQueryString[] = " postal_greeting_custom = NULL ";
2667 elseif ($contact->postal_greeting_custom
) {
2668 $updateQueryString[] = " postal_greeting_display = NULL ";
2672 if ($postalGreetingString) {
2673 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($postalGreetingString,
2676 'CRM_Contact_BAO_Contact'
2678 $postalGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($postalGreetingString));
2679 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2683 if ($contact->addressee_custom
!= 'null' && $contact->addressee_custom
) {
2684 $addresseeString = $contact->addressee_custom
;
2686 elseif ($contact->addressee_id
!= 'null' && $contact->addressee_id
) {
2688 'contact_type' => $contact->contact_type
,
2689 'greeting_type' => 'addressee',
2692 $addressee = CRM_Core_PseudoConstant
::greeting($filter);
2693 $addresseeString = $addressee[$contact->addressee_id
];
2694 $updateQueryString[] = " addressee_custom = NULL ";
2698 reset($contactDefaults['addressee']);
2699 $addresseeID = key($contactDefaults['addressee']);
2700 $addresseeString = $contactDefaults['addressee'][$addresseeID];
2701 $updateQueryString[] = " addressee_id = $addresseeID ";
2702 $updateQueryString[] = " addressee_custom = NULL ";
2704 elseif ($contact->addressee_custom
) {
2705 $updateQueryString[] = " addressee_display = NULL ";
2709 if ($addresseeString) {
2710 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($addresseeString,
2713 'CRM_Contact_BAO_Contact'
2715 $addresseeString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($addresseeString));
2716 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2719 if (!empty($updateQueryString)) {
2720 $updateQueryString = implode(',', $updateQueryString);
2721 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2722 CRM_Core_DAO
::executeQuery($queryString);
2727 * Function to retrieve loc block ids w/ given condition.
2729 * @param int $contactId contact id.
2730 * @param array $criteria key => value pair which should be
2731 * fulfill by return record ids.
2732 * @param string $condOperator operator use for grouping multiple conditions.
2734 * @return array $locBlockIds loc block ids which fulfill condition.
2737 static function getLocBlockIds($contactId, $criteria = array(), $condOperator = 'AND') {
2738 $locBlockIds = array();
2740 return $locBlockIds;
2743 foreach (array('Email', 'OpenID', 'Phone', 'Address', 'IM') as $block) {
2744 $name = strtolower($block);
2745 $className = "CRM_Core_DAO_$block";
2746 $blockDAO = new $className();
2748 // build the condition.
2749 if (is_array($criteria)) {
2750 $fields = $blockDAO->fields();
2751 $conditions = array();
2752 foreach ($criteria as $field => $value) {
2753 if (array_key_exists($field, $fields)) {
2754 $cond = "( $field = $value )";
2755 // value might be zero or null.
2756 if (!$value ||
strtolower($value) == 'null') {
2757 $cond = "( $field = 0 OR $field IS NULL )";
2759 $conditions[] = $cond;
2762 if (!empty($conditions)) {
2763 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2767 $blockDAO->contact_id
= $contactId;
2769 while ($blockDAO->fetch()) {
2770 $locBlockIds[$name][] = $blockDAO->id
;
2775 return $locBlockIds;
2779 * Function to build context menu items.
2781 * @param null $contactId
2783 * @return array of context menu for logged in user.
2786 static function contextMenu($contactId = NULL) {
2789 'title' => ts('View Contact'),
2791 'ref' => 'view-contact',
2792 'class' => 'no-popup',
2794 'permissions' => array('view all contacts'),
2797 'title' => ts('Edit Contact'),
2799 'ref' => 'edit-contact',
2800 'class' => 'no-popup',
2802 'permissions' => array('edit all contacts'),
2805 'title' => ts('Delete Contact'),
2807 'ref' => 'delete-contact',
2809 'permissions' => array('access deleted contacts', 'delete contacts'),
2811 'contribution' => array(
2812 'title' => ts('Add Contribution'),
2814 'ref' => 'new-contribution',
2815 'key' => 'contribution',
2816 'tab' => 'contribute',
2817 'component' => 'CiviContribute',
2818 'href' => CRM_Utils_System
::url('civicrm/contact/view/contribution',
2819 'reset=1&action=add&context=contribution'
2821 'permissions' => array(
2822 'access CiviContribute',
2823 'edit contributions',
2826 'participant' => array(
2827 'title' => ts('Register for Event'),
2829 'ref' => 'new-participant',
2830 'key' => 'participant',
2831 'tab' => 'participant',
2832 'component' => 'CiviEvent',
2833 'href' => CRM_Utils_System
::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
2834 'permissions' => array(
2836 'edit event participants',
2839 'activity' => array(
2840 'title' => ts('Record Activity'),
2842 'ref' => 'new-activity',
2843 'key' => 'activity',
2844 'permissions' => array('edit all contacts'),
2847 'title' => ts('Add Pledge'),
2849 'ref' => 'new-pledge',
2852 'href' => CRM_Utils_System
::url('civicrm/contact/view/pledge',
2853 'reset=1&action=add&context=pledge'
2855 'component' => 'CiviPledge',
2856 'permissions' => array(
2857 'access CiviPledge',
2861 'membership' => array(
2862 'title' => ts('Add Membership'),
2864 'ref' => 'new-membership',
2865 'key' => 'membership',
2867 'component' => 'CiviMember',
2868 'href' => CRM_Utils_System
::url('civicrm/contact/view/membership',
2869 'reset=1&action=add&context=membership'
2871 'permissions' => array(
2872 'access CiviMember',
2877 'title' => ts('Add Case'),
2879 'ref' => 'new-case',
2882 'component' => 'CiviCase',
2883 'href' => CRM_Utils_System
::url('civicrm/case/add', 'reset=1&action=add&context=case'),
2884 'permissions' => array('add cases'),
2887 'title' => ts('Add Grant'),
2889 'ref' => 'new-grant',
2892 'component' => 'CiviGrant',
2893 'href' => CRM_Utils_System
::url('civicrm/contact/view/grant',
2894 'reset=1&action=add&context=grant'
2896 'permissions' => array('edit grants'),
2899 'title' => ts('Add Relationship'),
2901 'ref' => 'new-relationship',
2904 'href' => CRM_Utils_System
::url('civicrm/contact/view/rel',
2905 'reset=1&action=add'
2907 'permissions' => array('edit all contacts'),
2910 'title' => ts('Add Note'),
2912 'ref' => 'new-note',
2915 'class' => 'medium-popup',
2916 'href' => CRM_Utils_System
::url('civicrm/contact/view/note',
2917 'reset=1&action=add'
2919 'permissions' => array('edit all contacts'),
2922 'title' => ts('Send an Email'),
2924 'ref' => 'new-email',
2926 'permissions' => array('view all contacts'),
2929 'title' => ts('Add to Group'),
2931 'ref' => 'group-add-contact',
2934 'permissions' => array('edit groups'),
2937 'title' => ts('Tag Contact'),
2939 'ref' => 'tag-contact',
2942 'permissions' => array('edit all contacts'),
2946 CRM_Utils_Hook
::summaryActions($menu, $contactId);
2947 //1. check for component is active.
2948 //2. check for user permissions.
2949 //3. check for acls.
2950 //3. edit and view contact are directly accessible to user.
2952 $aclPermissionedTasks = array(
2953 'view-contact', 'edit-contact', 'new-activity',
2954 'new-email', 'group-add-contact', 'tag-contact', 'delete-contact',
2956 $corePermission = CRM_Core_Permission
::getPermission();
2958 $config = CRM_Core_Config
::singleton();
2960 $contextMenu = array();
2961 foreach ($menu as $key => $values) {
2962 $componentName = CRM_Utils_Array
::value('component', $values);
2964 // if component action - make sure component is enable.
2965 if ($componentName && !in_array($componentName, $config->enableComponents
)) {
2969 // make sure user has all required permissions.
2970 $hasAllPermissions = FALSE;
2972 $permissions = CRM_Utils_Array
::value('permissions', $values);
2973 if (!is_array($permissions) ||
empty($permissions)) {
2974 $hasAllPermissions = TRUE;
2977 // iterate for required permissions in given permissions array.
2978 if (!$hasAllPermissions) {
2979 $hasPermissions = 0;
2980 foreach ($permissions as $permission) {
2981 if (CRM_Core_Permission
::check($permission)) {
2986 if (count($permissions) == $hasPermissions) {
2987 $hasAllPermissions = TRUE;
2990 // if still user does not have required permissions, check acl.
2991 if (!$hasAllPermissions && $values['ref'] != 'delete-contact') {
2992 if (in_array($values['ref'], $aclPermissionedTasks) &&
2993 $corePermission == CRM_Core_Permission
::EDIT
2995 $hasAllPermissions = TRUE;
2997 elseif (in_array($values['ref'], array(
2999 // grant permissions for these tasks.
3000 $hasAllPermissions = TRUE;
3005 // user does not have necessary permissions.
3006 if (!$hasAllPermissions) {
3010 // build directly accessible action menu.
3011 if (in_array($values['ref'], array(
3012 'view-contact', 'edit-contact'))) {
3013 $contextMenu['primaryActions'][$key] = array(
3014 'title' => $values['title'],
3015 'ref' => $values['ref'],
3016 'class' => CRM_Utils_Array
::value('class', $values),
3017 'key' => $values['key'],
3022 // finally get menu item for -more- action widget.
3023 $contextMenu['moreActions'][$values['weight']] = array(
3024 'title' => $values['title'],
3025 'ref' => $values['ref'],
3026 'href' => CRM_Utils_Array
::value('href', $values),
3027 'tab' => CRM_Utils_Array
::value('tab', $values),
3028 'class' => CRM_Utils_Array
::value('class', $values),
3029 'key' => $values['key'],
3033 ksort($contextMenu['moreActions']);
3035 return $contextMenu;
3039 * Function to retrieve display name of contact that address is shared
3040 * based on $masterAddressId or $contactId .
3042 * @param int $masterAddressId master id.
3043 * @param int $contactId contact id.
3045 * @return display name |null the found display name or null.
3049 static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3050 $masterDisplayName = NULL;
3052 if (!$masterAddressId && !$contactId) {
3053 return $masterDisplayName;
3056 if ($masterAddressId) {
3058 SELECT display_name from civicrm_contact
3059 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3060 WHERE civicrm_address.id = " . $masterAddressId;
3062 elseif ($contactId) {
3064 SELECT display_name from civicrm_contact cc, civicrm_address add1
3065 LEFT JOIN civicrm_address add2 ON ( add1.master_id = add2.id )
3066 WHERE cc.id = add2.contact_id AND add1.contact_id = " . $contactId;
3069 $masterDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
3070 return $masterDisplayName;
3074 * Get the creation/modification times for a contact
3078 * @return array('created_date' => $, 'modified_date' => $)
3080 static function getTimestamps($contactId) {
3081 $timestamps = CRM_Core_DAO
::executeQuery(
3082 'SELECT created_date, modified_date
3083 FROM civicrm_contact
3086 1 => array($contactId, 'Integer'),
3089 if ($timestamps->fetch()) {
3091 'created_date' => $timestamps->created_date
,
3092 'modified_date' => $timestamps->modified_date
,
3101 * Generate triggers to update the timestamp on the corresponding civicrm_contact row,
3102 * on insert/update/delete to a table that extends civicrm_contact.
3103 * Don't regenerate triggers for all such tables if only asked for one table.
3105 * @param array $info
3106 * Reference to the array where generated trigger information is being stored
3107 * @param string|null $reqTableName
3108 * Name of the table for which triggers are being generated, or NULL if all tables
3109 * @param array $relatedTableNames
3110 * Array of all core or all custom table names extending civicrm_contact
3111 * @param string $contactRefColumn
3112 * 'contact_id' if processing core tables, 'entity_id' if processing custom tables
3115 * @link https://issues.civicrm.org/jira/browse/CRM-15602
3120 static function generateTimestampTriggers(&$info, $reqTableName, $relatedTableNames, $contactRefColumn) {
3122 $contactRefColumn = CRM_Core_DAO
::escapeString($contactRefColumn);
3123 // If specific related table requested, just process that one
3124 if (in_array($reqTableName, $relatedTableNames)) {
3125 $relatedTableNames = array($reqTableName);
3128 // If no specific table requested (include all related tables),
3129 // or a specific related table requested (as matched above)
3130 if (empty($reqTableName) ||
in_array($reqTableName, $relatedTableNames)) {
3132 'table' => $relatedTableNames,
3134 'event' => array('INSERT', 'UPDATE'),
3135 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = NEW.$contactRefColumn;\n",
3138 'table' => $relatedTableNames,
3140 'event' => array('DELETE'),
3141 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = OLD.$contactRefColumn;\n",
3147 * Get a list of triggers for the contact table
3149 * @see hook_civicrm_triggerInfo
3150 * @see CRM_Core_DAO::triggerRebuild
3151 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3153 static function triggerInfo(&$info, $tableName = NULL) {
3154 //during upgrade, first check for valid version and then create triggers
3155 //i.e the columns created_date and modified_date are introduced in 4.3.alpha1 so dont create triggers for older version
3156 if (CRM_Core_Config
::isUpgradeMode()) {
3157 $currentVer = CRM_Core_BAO_Domain
::version(TRUE);
3158 //if current version is less than 4.3.alpha1 dont create below triggers
3159 if (version_compare($currentVer, '4.3.alpha1') < 0) {
3164 // Update timestamp for civicrm_contact itself
3165 if ($tableName == NULL ||
$tableName == self
::getTableName()) {
3167 'table' => array(self
::getTableName()),
3169 'event' => array('INSERT'),
3170 'sql' => "\nSET NEW.created_date = CURRENT_TIMESTAMP;\n",
3174 // Update timestamp when modifying closely related core tables
3175 $relatedTables = array(
3182 self
::generateTimestampTriggers($info, $tableName, $relatedTables, 'contact_id');
3184 // Update timestamp when modifying related custom-data tables
3185 $customGroupTables = array();
3186 $customGroupDAO = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity('Contact');
3187 $customGroupDAO->is_multiple
= 0;
3188 $customGroupDAO->find();
3189 while ($customGroupDAO->fetch()) {
3190 $customGroupTables[] = $customGroupDAO->table_name
;
3192 if (!empty($customGroupTables)) {
3193 self
::generateTimestampTriggers($info, $tableName, $customGroupTables, 'entity_id');
3196 // Update phone table to populate phone_numeric field
3197 if (!$tableName ||
$tableName == 'civicrm_phone') {
3198 // Define stored sql function needed for phones
3199 CRM_Core_DAO
::executeQuery(self
::DROP_STRIP_FUNCTION_43
);
3200 CRM_Core_DAO
::executeQuery(self
::CREATE_STRIP_FUNCTION_43
);
3202 'table' => array('civicrm_phone'),
3204 'event' => array('INSERT', 'UPDATE'),
3205 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3211 * Function to check if contact is being used in civicrm_domain
3212 * based on $contactId
3214 * @param int $contactId contact id.
3216 * @return bool true if present else false.
3220 static function checkDomainContact($contactId) {
3223 $domainId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3233 * Get options for a given contact field.
3234 * @see CRM_Core_DAO::buildOptions
3236 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3237 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3239 * @param String $fieldName
3240 * @param String $context : @see CRM_Core_DAO::buildOptionsContext
3241 * @param Array $props : whatever is known about this dao object
3243 * @return Array|bool
3245 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3247 // Special logic for fields whose options depend on context or properties
3248 switch ($fieldName) {
3249 case 'contact_sub_type':
3250 if (!empty($props['contact_type'])) {
3251 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3255 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
3259 * Delete a contact-related object that has an 'is_primary' field
3260 * Ensures that is_primary gets assigned to another object if available
3261 * Also calls pre/post hooks
3263 * @var $type : object type
3264 * @var $id : object id
3267 public static function deleteObjectWithPrimary($type, $id) {
3268 if (!$id ||
!is_numeric($id)) {
3271 $daoName = "CRM_Core_DAO_$type";
3272 $obj = new $daoName();
3275 if ($obj->fetch()) {
3276 CRM_Utils_Hook
::pre('delete', $type, $id, CRM_Core_DAO
::$_nullArray);
3277 $contactId = $obj->contact_id
;
3283 // is_primary is only relavent if this field belongs to a contact
3285 $dao = new $daoName();
3286 $dao->contact_id
= $contactId;
3287 $dao->is_primary
= 1;
3288 // Pick another record to be primary (if one isn't already)
3289 if (!$dao->find(TRUE)) {
3290 $dao->is_primary
= 0;
3292 if ($dao->fetch()) {
3293 $dao->is_primary
= 1;
3299 CRM_Utils_Hook
::post('delete', $type, $id, $obj);