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 $newEmployer = !empty($params['employer_id']) ?
$params['employer_id'] : CRM_Utils_Array
::value('current_employer', $params);
238 // create current employer
241 if (empty($params['contact_id'])) {
244 CRM_Contact_BAO_Contact_Utils
::createCurrentEmployerRelationship($contact->id
, $newEmployer, $employerId, $newContact);
247 //unset if employer id exits
249 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($contact->id
, $employerId);
254 //update cached employee name
255 if ($contact->contact_type
== 'Organization') {
256 CRM_Contact_BAO_Contact_Utils
::updateCurrentEmployer($contact->id
);
263 * Function to create contact
264 * takes an associative array and creates a contact object and all the associated
265 * derived objects (i.e. individual, location, email, phone etc)
267 * This function is invoked from within the web form layer and also from the api layer
269 * @param array $params (reference ) an assoc array of name/value pairs
270 * @param boolean $fixAddress if we need to fix address
271 * @param boolean $invokeHooks if we need to invoke hooks
273 * @param bool $skipDelete
276 * @return object CRM_Contact_BAO_Contact object
280 static function &create(&$params, $fixAddress = TRUE, $invokeHooks = TRUE, $skipDelete = FALSE) {
282 if (empty($params['contact_type']) && empty($params['contact_id'])) {
288 if (!empty($params['contact_id'])) {
289 CRM_Utils_Hook
::pre('edit', $params['contact_type'], $params['contact_id'], $params);
292 CRM_Utils_Hook
::pre('create', $params['contact_type'], NULL, $params);
297 $config = CRM_Core_Config
::singleton();
299 // CRM-6942: set preferred language to the current language if it’s unset (and we’re creating a contact)
300 if (empty($params['contact_id']) && empty($params['preferred_language'])) {
301 $params['preferred_language'] = $config->lcMessages
;
304 // CRM-9739: set greeting & addressee if unset and we’re creating a contact
305 if (empty($params['contact_id'])) {
306 foreach (self
::$_greetingTypes as $greeting) {
307 if (empty($params[$greeting . '_id'])) {
308 if ($defaultGreetingTypeId =
309 CRM_Contact_BAO_Contact_Utils
::defaultGreeting($params['contact_type'], $greeting)
311 $params[$greeting . '_id'] = $defaultGreetingTypeId;
317 $transaction = new CRM_Core_Transaction();
319 $contact = self
::add($params);
321 // not dying here is stupid, since we get into wierd situation and into a bug that
322 // is impossible to figure out for the user or for us
324 CRM_Core_Error
::fatal();
327 $params['contact_id'] = $contact->id
;
329 if (CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
332 // Enabling multisite causes the contact to be added to the domain group
333 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
334 if(!empty($domainGroupID)){
335 if (!empty($params['group']) && is_array($params['group'])) {
336 $params['group'][$domainGroupID] = 1;
339 $params['group'] = array($domainGroupID => 1);
344 if (array_key_exists('group', $params)) {
345 $contactIds = array($params['contact_id']);
346 foreach ($params['group'] as $groupId => $flag) {
348 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
350 elseif ($flag == -1) {
351 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $groupId);
356 //add location Block data
357 $blocks = CRM_Core_BAO_Location
::create($params, $fixAddress);
358 foreach ($blocks as $name => $value) {
359 $contact->$name = $value;
363 CRM_Core_BAO_Website
::create($params['website'], $contact->id
, $skipDelete);
365 //get userID from session
366 $session = CRM_Core_Session
::singleton();
367 $userID = $session->get('userID');
369 if (!empty($params['note'])) {
370 if (is_array($params['note'])) {
371 foreach ($params['note'] as $note) {
372 $contactId = $contact->id
;
373 if (isset($note['contact_id'])) {
374 $contactId = $note['contact_id'];
376 //if logged in user, overwrite contactId
378 $contactId = $userID;
382 'entity_id' => $contact->id
,
383 'entity_table' => 'civicrm_contact',
384 'note' => $note['note'],
385 'subject' => CRM_Utils_Array
::value('subject', $note),
386 'contact_id' => $contactId,
388 CRM_Core_BAO_Note
::add($noteParams, CRM_Core_DAO
::$_nullArray);
392 $contactId = $contact->id
;
393 if (isset($note['contact_id'])) {
394 $contactId = $note['contact_id'];
396 //if logged in user, overwrite contactId
398 $contactId = $userID;
402 'entity_id' => $contact->id
,
403 'entity_table' => 'civicrm_contact',
404 'note' => $params['note'],
405 'subject' => CRM_Utils_Array
::value('subject', $params),
406 'contact_id' => $contactId,
408 CRM_Core_BAO_Note
::add($noteParams, CRM_Core_DAO
::$_nullArray);
413 // update the UF user_unique_id if that has changed
414 CRM_Core_BAO_UFMatch
::updateUFName($contact->id
);
416 if (!empty($params['custom']) &&
417 is_array($params['custom'])
419 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contact', $contact->id
);
422 // make a civicrm_subscription_history entry only on contact create (CRM-777)
423 if (empty($params['contact_id'])) {
424 $subscriptionParams = array(
425 'contact_id' => $contact->id
,
429 CRM_Contact_BAO_SubscriptionHistory
::create($subscriptionParams);
432 $transaction->commit();
434 // CRM-6367: fetch the right label for contact type’s display
435 $contact->contact_type_display
= CRM_Core_DAO
::getFieldValue(
436 'CRM_Contact_DAO_ContactType',
437 $contact->contact_type
,
442 if (!$config->doNotResetCache
) {
443 // Note: doNotResetCache flag is currently set by import contact process and merging,
444 // since resetting and
445 // rebuilding cache could be expensive (for many contacts). We might come out with better
446 // approach in future.
447 CRM_Contact_BAO_Contact_Utils
::clearContactCaches($contact->id
);
452 CRM_Utils_Hook
::post('edit', $params['contact_type'], $contact->id
, $contact);
455 CRM_Utils_Hook
::post('create', $params['contact_type'], $contact->id
, $contact);
459 // process greetings CRM-4575, cache greetings
460 self
::processGreetings($contact);
466 * Get the display name and image of a contact
468 * @param int $id the contactId
472 * @return array the displayName and contactImage for this contact
476 static function getDisplayAndImage($id, $type = FALSE) {
477 //CRM-14276 added the * on the civicrm_contact table so that we have all the contact info available
479 SELECT civicrm_contact.*,
480 civicrm_email.email as email
482 LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
483 AND civicrm_email.is_primary = 1
484 WHERE civicrm_contact.id = " . CRM_Utils_Type
::escape($id, 'Integer');
485 $dao = new CRM_Core_DAO();
488 $image = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
489 $dao->contact_sub_type
: $dao->contact_type
, FALSE, $id
491 $imageUrl = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
492 $dao->contact_sub_type
: $dao->contact_type
, TRUE, $id
495 // use email if display_name is empty
496 if (empty($dao->display_name
)) {
497 $displayName = $dao->email
;
500 $displayName = $dao->display_name
;
503 CRM_Utils_Hook
::alterDisplayName($displayName, $id, $dao);
505 return $type ?
array(
509 $dao->contact_sub_type
,
511 ) : array($displayName, $image, $imageUrl);
517 * @param array $crudLinkSpec with keys:
518 * - action: int, CRM_Core_Action::UPDATE or CRM_Core_Action::VIEW [default: VIEW]
519 * - entity_table: string, eg "civicrm_contact"
521 * @return array|NULL NULL if unavailable, or an array. array has keys:
525 * @see CRM_Utils_System::createDefaultCrudLink
527 public function createDefaultCrudLink($crudLinkSpec) {
528 switch ($crudLinkSpec['action']) {
529 case CRM_Core_Action
::VIEW
:
531 'title' => $this->display_name
,
532 'path' => 'civicrm/contact/view',
538 case CRM_Core_Action
::UPDATE
:
540 'title' => $this->display_name
,
541 'path' => 'civicrm/contact/add',
544 'action' => 'update',
554 * Get the values for pseudoconstants for name->value and reverse.
556 * @param array $defaults (reference) the default values, some of which need to be resolved.
557 * @param boolean $reverse true if we want to resolve the values in the reverse direction (value -> name)
563 static function resolveDefaults(&$defaults, $reverse = FALSE) {
564 // hack for birth_date
565 if (!empty($defaults['birth_date'])) {
566 if (is_array($defaults['birth_date'])) {
567 $defaults['birth_date'] = CRM_Utils_Date
::format($defaults['birth_date'], '-');
571 CRM_Utils_Array
::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id'), $reverse);
572 CRM_Utils_Array
::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'suffix_id'), $reverse);
573 CRM_Utils_Array
::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'), $reverse);
574 CRM_Utils_Array
::lookupValue($defaults, 'communication_style', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'communication_style_id'), $reverse);
576 //lookup value of email/postal greeting, addressee, CRM-4575
577 foreach (self
::$_greetingTypes as $greeting) {
578 $filterCondition = array('contact_type' => CRM_Utils_Array
::value('contact_type', $defaults),
579 'greeting_type' => $greeting,
581 CRM_Utils_Array
::lookupValue($defaults, $greeting,
582 CRM_Core_PseudoConstant
::greeting($filterCondition), $reverse
586 $blocks = array('address', 'im', 'phone');
587 foreach ($blocks as $name) {
588 if (!array_key_exists($name, $defaults) ||
!is_array($defaults[$name])) {
591 foreach ($defaults[$name] as $count => & $values) {
593 //get location type id.
594 CRM_Utils_Array
::lookupValue($values, 'location_type', CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id'), $reverse);
596 if ($name == 'address') {
597 // FIXME: lookupValue doesn't work for vcard_name
598 if (!empty($values['location_type_id'])) {
599 $vcardNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array('labelColumn' => 'vcard_name'));
600 $values['vcard_name'] = $vcardNames[$values['location_type_id']];
603 if (!CRM_Utils_Array
::lookupValue($values,
605 CRM_Core_PseudoConstant
::country(),
610 CRM_Utils_Array
::lookupValue($values,
612 CRM_Core_PseudoConstant
::countryIsoCode(),
618 // if we find a country id above, we need to restrict it to that country
619 // rather than the list of all countries
621 if (!empty($values['country_id'])) {
622 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($values['country_id']);
625 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvince();
627 if (!CRM_Utils_Array
::lookupValue($values,
635 if (!empty($values['country_id'])) {
636 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($values['country_id'], 'abbreviation');
639 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviation();
641 CRM_Utils_Array
::lookupValue($values,
648 if (!empty($values['state_province_id'])) {
649 $countyList = CRM_Core_PseudoConstant
::countyForState($values['state_province_id']);
652 $countyList = CRM_Core_PseudoConstant
::county();
654 CRM_Utils_Array
::lookupValue($values,
662 CRM_Utils_Array
::lookupValue($values,
664 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id'),
669 if ($name == 'phone') {
670 CRM_Utils_Array
::lookupValue($values,
672 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id'),
677 //kill the reference.
684 * Takes a bunch of params that are needed to match certain criteria and
685 * retrieves the relevant objects. Typically the valid params are only
686 * contact_id. We'll tweak this function to be more full featured over a period
687 * of time. This is the inverse function of create. It also stores all the retrieved
688 * values in the default array
690 * @param array $params (reference ) an assoc array of name/value pairs
691 * @param array $defaults (reference ) an assoc array to hold the name / value pairs
692 * in a hierarchical manner
693 * @param boolean $microformat for location in microformat
695 * @return object CRM_Contact_BAO_Contact object
699 static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
700 if (array_key_exists('contact_id', $params)) {
701 $params['id'] = $params['contact_id'];
703 elseif (array_key_exists('id', $params)) {
704 $params['contact_id'] = $params['id'];
707 $contact = self
::getValues($params, $defaults);
709 unset($params['id']);
711 //get the block information for this contact
712 $entityBlock = array('contact_id' => $params['contact_id']);
713 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock, $microformat);
714 $defaults = array_merge($defaults, $blocks);
715 foreach ($blocks as $block => $value) $contact->$block = $value;
717 if (!isset($params['noNotes'])) {
718 $contact->notes
= CRM_Core_BAO_Note
::getValues($params, $defaults);
721 if (!isset($params['noRelationships'])) {
722 $contact->relationship
= CRM_Contact_BAO_Relationship
::getValues($params, $defaults);
725 if (!isset($params['noGroups'])) {
726 $contact->groupContact
= CRM_Contact_BAO_GroupContact
::getValues($params, $defaults);
729 if (!isset($params['noWebsite'])) {
730 $contact->website
= CRM_Core_BAO_Website
::getValues($params, $defaults);
737 * function to get the display name of a contact
739 * @param int $id id of the contact
741 * @return null|string display name of the contact if found
745 static function displayName($id) {
748 $displayName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
755 * Delete a contact and all its associated records
757 * @param int $id id of the contact to delete
758 * @param bool $restore whether to actually restore, not delete
759 * @param bool $skipUndelete whether to force contact delete or not
761 * @return boolean true if contact deleted, false otherwise
765 static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE) {
771 // make sure we have edit permission for this contact
773 if (($skipUndelete && !CRM_Core_Permission
::check('delete contacts')) ||
774 ($restore && !CRM_Core_Permission
::check('access deleted contacts'))
780 // Restrict contact to be delete if contact has financial trxns
782 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent(array($id), $error)) {
786 // make sure this contact_id does not have any membership types
787 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
790 'member_of_contact_id'
792 if ($membershipTypeID) {
796 $contact = new CRM_Contact_DAO_Contact();
798 if (!$contact->find(TRUE)) {
802 $contactType = $contact->contact_type
;
803 $action = ($restore) ?
'restore' : 'delete';
805 CRM_Utils_Hook
::pre($action, $contactType, $id, CRM_Core_DAO
::$_nullArray);
808 self
::contactTrashRestore($contact, TRUE);
809 CRM_Utils_Hook
::post($action, $contactType, $contact->id
, $contact);
814 // currently we only clear employer cache.
815 // we are not deleting inherited membership if any.
816 if ($contact->contact_type
== 'Organization') {
817 CRM_Contact_BAO_Contact_Utils
::clearAllEmployee($id);
820 // start a new transaction
821 $transaction = new CRM_Core_Transaction();
823 if ($skipUndelete or !CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'contact_undelete', NULL)) {
825 //delete billing address if exists.
826 CRM_Contribute_BAO_Contribution
::deleteAddress(NULL, $id);
828 // delete the log entries since we dont have triggers enabled as yet
829 $logDAO = new CRM_Core_DAO_Log();
830 $logDAO->entity_table
= 'civicrm_contact';
831 $logDAO->entity_id
= $id;
834 // delete contact participants CRM-12155
835 CRM_Event_BAO_Participant
::deleteContactParticipant($id);
837 // delete contact contributions CRM-12155
838 CRM_Contribute_BAO_Contribution
::deleteContactContribution($id);
840 // do activity cleanup, CRM-5604
841 CRM_Activity_BAO_Activity
::cleanupActivity($id);
843 // delete all notes related to contact
844 CRM_Core_BAO_Note
::cleanContactNotes($id);
846 // delete cases related to contact
847 $contactCases = CRM_Case_BAO_Case
::retrieveCaseIdsByContactId($id);
848 if (!empty($contactCases)) {
849 foreach ($contactCases as $caseId) {
850 //check if case is associate with other contact or not.
851 $caseContactId = CRM_Case_BAO_Case
::getCaseClients($caseId);
852 if (count($caseContactId) <= 1) {
853 CRM_Case_BAO_Case
::deleteCase($caseId);
861 self
::contactTrashRestore($contact);
864 //delete the contact id from recently view
865 CRM_Utils_Recent
::delContact($id);
867 // reset the group contact cache for this group
868 CRM_Contact_BAO_GroupContactCache
::remove();
870 // delete any dupe cache entry
871 CRM_Core_BAO_PrevNextCache
::deleteItem($id);
873 $transaction->commit();
875 CRM_Utils_Hook
::post('delete', $contactType, $contact->id
, $contact);
877 // also reset the DB_DO global array so we can reuse the memory
878 // http://issues.civicrm.org/jira/browse/CRM-4387
879 CRM_Core_DAO
::freeResult();
885 * function to delete the image of a contact
887 * @param int $id id of the contact
889 * @return boolean true if contact image is deleted
891 public static function deleteContactImage($id) {
896 UPDATE civicrm_contact
899 CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
904 * function to return relative path
905 * @todo make this a method of $config->userSystem (i.e. UF classes) rather than a static function
907 * @param $absolutePath
909 * @internal param String $absPath absolute path
911 * @return String $relativePath Relative url of uploaded image
913 public static function getRelativePath($absolutePath) {
914 $relativePath = NULL;
915 $config = CRM_Core_Config
::singleton();
916 if ($config->userFramework
== 'Joomla') {
917 $userFrameworkBaseURL = trim(str_replace('/administrator/', '', $config->userFrameworkBaseURL
));
918 $customFileUploadDirectory = strstr(str_replace('\\', '/', $absolutePath), '/media');
919 $relativePath = $userFrameworkBaseURL . $customFileUploadDirectory;
921 elseif ($config->userSystem
->is_drupal
== '1') {
922 //ideally we would do a bigger re-factoring & move the getRelativePath onto the UF class
923 $rootPath = $config->userSystem
->cmsRootPath();
924 $baseUrl = $config->userFrameworkBaseURL
;
926 //format url for language negotiation, CRM-7135
927 $baseUrl = CRM_Utils_System
::languageNegotiationURL($baseUrl, FALSE, TRUE);
929 $relativePath = str_replace("{$rootPath}/",
931 str_replace('\\', '/', $absolutePath)
933 } else if ( $config->userFramework
== 'WordPress' ) {
934 $userFrameworkBaseURL = trim( str_replace( '/wp-admin/', '', $config->userFrameworkBaseURL
) );
935 $customFileUploadDirectory = strstr( str_replace('\\', '/', $absolutePath), '/wp-content/' );
936 $relativePath = $userFrameworkBaseURL . $customFileUploadDirectory;
939 return $relativePath;
943 * function to return proportional height and width of the image
945 * @param Integer $imageWidth width of image
947 * @param Integer $imageHeight height of image
949 * @return Array thumb dimension of image
951 public static function getThumbSize($imageWidth, $imageHeight) {
953 if ($imageWidth && $imageHeight) {
954 $imageRatio = $imageWidth / $imageHeight;
959 if ($imageRatio > 1) {
960 $imageThumbWidth = $thumbWidth;
961 $imageThumbHeight = round($thumbWidth / $imageRatio);
964 $imageThumbHeight = $thumbWidth;
965 $imageThumbWidth = round($thumbWidth * $imageRatio);
968 return array($imageThumbWidth, $imageThumbHeight);
972 * function to validate type of contact image
975 * @param String $imageIndex index of image field
977 * @param String $statusMsg status message to be set after operation
979 * @param string $opType
981 * @internal param Array $param array of contact/profile field to be edited/added
983 * @opType String $opType type of operation like fatal, bounce etc
985 * @return boolean true if valid image extension
987 public static function processImageParams(&$params,
988 $imageIndex = 'image_URL',
1002 if (in_array($params[$imageIndex]['type'], $mimeType)) {
1003 $photo = basename($params[$imageIndex]['name']);
1004 $params[$imageIndex] = CRM_Utils_System
::url('civicrm/contact/imagefile', 'photo='.$photo, TRUE);
1008 unset($params[$imageIndex]);
1010 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
1012 if ($opType == 'status') {
1013 CRM_Core_Session
::setStatus($statusMsg, 'Sorry', 'error');
1015 // FIXME: additional support for fatal, bounce etc could be added.
1021 * function to extract contact id from url for deleting contact image
1023 public static function processImage() {
1025 $action = CRM_Utils_Request
::retrieve('action', 'String');
1026 $cid = CRM_Utils_Request
::retrieve('cid', 'Positive');
1027 // retrieve contact id in case of Profile context
1028 $id = CRM_Utils_Request
::retrieve('id', 'Positive');
1029 $cid = $cid ?
$cid : $id;
1030 if ($action & CRM_Core_Action
::DELETE
) {
1031 if (CRM_Utils_Request
::retrieve('confirmed', 'Boolean')) {
1032 CRM_Contact_BAO_Contact
::deleteContactImage($cid);
1033 CRM_Core_Session
::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
1034 $session = CRM_Core_Session
::singleton();
1035 $toUrl = $session->popUserContext();
1036 CRM_Utils_System
::redirect($toUrl);
1042 * Function to set is_delete true or restore deleted contact
1044 * @param int $contact Contact DAO object
1045 * @param boolean $restore true to set the is_delete = 1 else false to restore deleted contact,
1046 * i.e. is_delete = 0
1051 static function contactTrashRestore($contact, $restore = FALSE) {
1052 $op = ($restore ?
'restore' : 'trash');
1054 CRM_Utils_Hook
::pre($op, $contact->contact_type
, $contact->id
, CRM_Core_DAO
::$_nullArray);
1056 $params = array(1 => array($contact->id
, 'Integer'));
1057 $isDelete = ' is_deleted = 1 ';
1059 $isDelete = ' is_deleted = 0 ';
1062 $query = "DELETE FROM civicrm_uf_match WHERE contact_id = %1";
1063 CRM_Core_DAO
::executeQuery($query, $params);
1066 $query = "UPDATE civicrm_contact SET {$isDelete} WHERE id = %1";
1067 CRM_Core_DAO
::executeQuery($query, $params);
1069 CRM_Utils_Hook
::post($op, $contact->contact_type
, $contact->id
, $contact);
1073 * Get contact type for a contact.
1075 * @param int $id - id of the contact whose contact type is needed
1077 * @return string contact_type if $id found else null ""
1084 public static function getContactType($id) {
1085 return CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1089 * Get contact sub type for a contact.
1091 * @param int $id - id of the contact whose contact sub type is needed
1093 * @param null $implodeDelimiter
1095 * @return string contact_sub_type if $id found else null ""
1101 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1102 $subtype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1104 return $implodeDelimiter ?
NULL : array();
1107 $subtype = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($subtype, CRM_Core_DAO
::VALUE_SEPARATOR
));
1109 if ($implodeDelimiter) {
1110 $subtype = implode($implodeDelimiter, $subtype);
1116 * Get pair of contact-type and sub-type for a contact.
1118 * @param int $id - id of the contact whose contact sub/contact type is needed
1127 public static function getContactTypes($id) {
1128 $params = array('id' => $id);
1130 $contact = CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact',
1133 array('contact_type', 'contact_sub_type')
1137 $contactTypes = array();
1138 if ($contact->contact_sub_type
)
1139 $contactTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($contact->contact_sub_type
, CRM_Core_DAO
::VALUE_SEPARATOR
));
1140 array_unshift($contactTypes, $contact->contact_type
);
1142 return $contactTypes;
1145 CRM_Core_Error
::fatal();
1150 * combine all the importable fields from the lower levels object
1152 * The ordering is important, since currently we do not have a weight
1153 * scheme. Adding weight is super important
1155 * @param int|string $contactType contact Type
1156 * @param boolean $status status is used to manipulate first title
1157 * @param boolean $showAll if true returns all fields (includes disabled fields)
1158 * @param boolean $isProfile if its profile mode
1159 * @param boolean $checkPermission if false, do not include permissioning clause (for custom data)
1161 * @param bool $withMultiCustomFields
1163 * @return array array of importable Fields
1167 static function importableFields($contactType = 'Individual',
1171 $checkPermission = TRUE,
1172 $withMultiCustomFields = FALSE
1174 if (empty($contactType)) {
1175 $contactType = 'All';
1178 $cacheKeyString = "importableFields $contactType";
1179 $cacheKeyString .= $status ?
'_1' : '_0';
1180 $cacheKeyString .= $showAll ?
'_1' : '_0';
1181 $cacheKeyString .= $isProfile ?
'_1' : '_0';
1182 $cacheKeyString .= $checkPermission ?
'_1' : '_0';
1184 $fields = CRM_Utils_Array
::value($cacheKeyString, self
::$_importableFields);
1187 // check if we can retrieve from database cache
1188 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1192 $fields = CRM_Contact_DAO_Contact
::import();
1194 // get the fields thar are meant for contact types
1195 if (in_array($contactType, array(
1196 'Individual', 'Household', 'Organization', 'All'))) {
1197 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1200 $locationFields = array_merge(CRM_Core_DAO_Address
::import(),
1201 CRM_Core_DAO_Phone
::import(),
1202 CRM_Core_DAO_Email
::import(),
1203 CRM_Core_DAO_IM
::import(TRUE),
1204 CRM_Core_DAO_OpenID
::import()
1207 $locationFields = array_merge($locationFields,
1208 CRM_Core_BAO_CustomField
::getFieldsForImport('Address',
1216 foreach ($locationFields as $key => $field) {
1217 $locationFields[$key]['hasLocationType'] = TRUE;
1220 $fields = array_merge($fields, $locationFields);
1222 $fields = array_merge($fields, CRM_Contact_DAO_Contact
::import());
1223 $fields = array_merge($fields, CRM_Core_DAO_Note
::import());
1226 $fields = array_merge($fields, CRM_Core_DAO_Website
::import());
1227 $fields['url']['hasWebsiteType'] = TRUE;
1229 if ($contactType != 'All') {
1230 $fields = array_merge($fields,
1231 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType,
1236 $withMultiCustomFields
1239 //unset the fields, which are not related to their
1241 $commonValues = array(
1242 'Individual' => array(
1248 'Household' => array(
1258 'organization_name',
1266 'Organization' => array(
1281 foreach ($commonValues[$contactType] as $value) {
1282 unset($fields[$value]);
1287 'Individual', 'Household', 'Organization') as $type) {
1288 $fields = array_merge($fields,
1289 CRM_Core_BAO_CustomField
::getFieldsForImport($type,
1294 $withMultiCustomFields
1301 $fields = array_merge($fields, array(
1303 'title' => ts('Group(s)'),
1307 'title' => ts('Tag(s)'),
1311 'title' => ts('Note(s)'),
1317 //Sorting fields in alphabetical order(CRM-1507)
1318 $fields = CRM_Utils_Array
::crmArraySortByField($fields, 'title');
1320 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1323 self
::$_importableFields[$cacheKeyString] = $fields;
1327 $fields = array_merge(array('do_not_import' => array('title' => ts('- do not import -'))),
1328 self
::$_importableFields[$cacheKeyString]
1332 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1333 self
::$_importableFields[$cacheKeyString]
1341 * combine all the exportable fields from the lower levels object
1343 * currentlty we are using importable fields as exportable fields
1345 * @param int|string $contactType contact Type
1346 * @param boolean $status true while exporting primary contacts
1347 * @param boolean $export true when used during export
1348 * @param boolean $search true when used during search, might conflict with export param?
1350 * @param bool $withMultiRecord
1352 * @return array array of exportable Fields
1356 static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE) {
1357 if (empty($contactType)) {
1358 $contactType = 'All';
1361 $cacheKeyString = "exportableFields $contactType";
1362 $cacheKeyString .= $export ?
'_1' : '_0';
1363 $cacheKeyString .= $status ?
'_1' : '_0';
1364 $cacheKeyString .= $search ?
'_1' : '_0';
1365 //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
1366 //calculates custom fields takes into account the logged in user & caches that for all users
1367 //as an interim fix we will cache the fields by contact
1368 $cacheKeyString .= '_' . CRM_Core_Session
::getLoggedInContactID();
1370 if (!self
::$_exportableFields ||
!CRM_Utils_Array
::value($cacheKeyString, self
::$_exportableFields)) {
1371 if (!self
::$_exportableFields) {
1372 self
::$_exportableFields = array();
1375 // check if we can retrieve from database cache
1376 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1379 $fields = CRM_Contact_DAO_Contact
::export();
1381 // the fields are meant for contact types
1385 array('Individual', 'Household', 'Organization', 'All')
1388 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1390 // add current employer for individuals
1391 $fields = array_merge($fields, array(
1392 'current_employer' =>
1394 'name' => 'organization_name',
1395 'title' => ts('Current Employer'),
1399 $locationType = array(
1400 'location_type' => array(
1401 'name' => 'location_type',
1402 'where' => 'civicrm_location_type.name',
1403 'title' => ts('Location Type'),
1406 $IMProvider = array(
1407 'im_provider' => array(
1408 'name' => 'im_provider',
1409 'where' => 'civicrm_im.provider_id',
1410 'title' => ts('IM Provider'),
1413 $locationFields = array_merge($locationType,
1414 CRM_Core_DAO_Address
::export(),
1415 CRM_Core_DAO_Phone
::export(),
1416 CRM_Core_DAO_Email
::export(),
1418 CRM_Core_DAO_IM
::export(TRUE),
1419 CRM_Core_DAO_OpenID
::export()
1422 $locationFields = array_merge($locationFields,
1423 CRM_Core_BAO_CustomField
::getFieldsForImport('Address')
1426 foreach ($locationFields as $key => $field) {
1427 $locationFields[$key]['hasLocationType'] = TRUE;
1430 $fields = array_merge($fields, $locationFields);
1433 $fields = array_merge($fields,
1434 CRM_Core_DAO_Worldregion
::export()
1438 $fields = array_merge($fields,
1439 CRM_Contact_DAO_Contact
::export()
1443 $fields = array_merge($fields, CRM_Core_DAO_Website
::export());
1445 if ($contactType != 'All') {
1446 $fields = array_merge($fields,
1447 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType, $status, TRUE, $search, TRUE, $withMultiRecord)
1452 'Individual', 'Household', 'Organization') as $type) {
1453 $fields = array_merge($fields,
1454 CRM_Core_BAO_CustomField
::getFieldsForImport($type, FALSE, FALSE, $search, TRUE, $withMultiRecord)
1461 $fields = array_merge($fields, array(
1463 'title' => ts('Group(s)'),
1467 'title' => ts('Tag(s)'),
1471 'title' => ts('Note(s)'),
1477 $fields = array_merge($fields, array(
1479 'title' => ts('Group(s)'),
1483 'title' => ts('Tag(s)'),
1487 'title' => ts('Note(s)'),
1493 //Sorting fields in alphabetical order(CRM-1507)
1494 foreach ($fields as $k => $v) {
1495 $sortArray[$k] = CRM_Utils_Array
::value('title', $v);
1498 $fields = array_merge($sortArray, $fields);
1499 //unset the field which are not related to their contact type.
1500 if ($contactType != 'All') {
1501 $commonValues = array(
1502 'Individual' => array(
1506 'organization_name',
1507 'email_greeting_custom',
1508 'postal_greeting_custom',
1511 'Household' => array(
1521 'organization_name',
1529 'email_greeting_custom',
1530 'postal_greeting_custom',
1535 'Organization' => array(
1546 'email_greeting_custom',
1547 'postal_greeting_custom',
1557 foreach ($commonValues[$contactType] as $value) {
1558 unset($fields[$value]);
1562 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1564 self
::$_exportableFields[$cacheKeyString] = $fields;
1568 $fields = self
::$_exportableFields[$cacheKeyString];
1571 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1572 self
::$_exportableFields[$cacheKeyString]
1580 * Function to get the all contact details(Hierarchical)
1582 * @param int $contactId contact id
1583 * @param array $fields fields array
1585 * @return $values array contains the contact details
1589 static function getHierContactDetails($contactId, &$fields) {
1590 $params = array(array('contact_id', '=', $contactId, 0, 0));
1593 $returnProperties = self
::makeHierReturnProperties($fields, $contactId);
1595 // we dont know the contents of return properties, but we need the lower level ids of the contact
1596 // so add a few fields
1597 $returnProperties['first_name'] =
1598 $returnProperties['organization_name'] =
1599 $returnProperties['household_name'] =
1600 $returnProperties['contact_type'] =
1601 $returnProperties['contact_sub_type'] = 1;
1602 return list($query, $options) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, $options);
1606 * given a set of flat profile style field names, create a hierarchy
1607 * for query to use and crete the right sql
1610 * @param int $contactId contact id
1612 * @internal param array $properties a flat return properties name value array
1613 * @return array a hierarchical property tree if appropriate
1617 static function &makeHierReturnProperties($fields, $contactId = NULL) {
1618 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1620 $returnProperties = array();
1622 $multipleFields = array('website' => 'url');
1623 foreach ($fields as $name => $dontCare) {
1624 if (strpos($name, '-') !== FALSE) {
1625 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $name, 3);
1627 if (!in_array($fieldName, $multipleFields)) {
1628 if ($id == 'Primary') {
1629 $locationTypeName = 1;
1632 $locationTypeName = CRM_Utils_Array
::value($id, $locationTypes);
1633 if (!$locationTypeName) {
1638 if (empty($returnProperties['location'])) {
1639 $returnProperties['location'] = array();
1641 if (empty($returnProperties['location'][$locationTypeName])) {
1642 $returnProperties['location'][$locationTypeName] = array();
1643 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1645 if (in_array($fieldName, array(
1646 'phone', 'im', 'email', 'openid', 'phone_ext'))) {
1648 $returnProperties['location'][$locationTypeName][$fieldName . '-' . $type] = 1;
1651 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1654 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1655 $returnProperties['location'][$locationTypeName][substr($fieldName, 8)] = 1;
1658 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1662 $returnProperties['website'][$id][$fieldName] = 1;
1666 $returnProperties[$name] = 1;
1670 return $returnProperties;
1674 * Function to return the primary location type of a contact
1676 * $params int $contactId contact_id
1677 * $params boolean $isPrimaryExist if true, return primary contact location type otherwise null
1678 * $params boolean $skipDefaultPriamry if true, return primary contact location type otherwise null
1681 * @param bool $skipDefaultPriamry
1682 * @param null $block
1684 * @return int $locationType location_type_id
1688 static function getPrimaryLocationType($contactId, $skipDefaultPriamry = FALSE, $block = NULL) {
1690 $entityBlock = array('contact_id' => $contactId);
1691 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock);
1692 foreach($blocks[$block] as $key => $value){
1693 if (!empty($value['is_primary'])){
1694 $locationType = CRM_Utils_Array
::value('location_type_id',$value);
1701 IF ( civicrm_email.location_type_id IS NULL,
1702 IF ( civicrm_address.location_type_id IS NULL,
1703 IF ( civicrm_phone.location_type_id IS NULL,
1704 IF ( civicrm_im.location_type_id IS NULL,
1705 IF ( civicrm_openid.location_type_id IS NULL, null, civicrm_openid.location_type_id)
1706 ,civicrm_im.location_type_id)
1707 ,civicrm_phone.location_type_id)
1708 ,civicrm_address.location_type_id)
1709 ,civicrm_email.location_type_id) as locationType
1710 FROM civicrm_contact
1711 LEFT JOIN civicrm_email ON ( civicrm_email.is_primary = 1 AND civicrm_email.contact_id = civicrm_contact.id )
1712 LEFT JOIN civicrm_address ON ( civicrm_address.is_primary = 1 AND civicrm_address.contact_id = civicrm_contact.id)
1713 LEFT JOIN civicrm_phone ON ( civicrm_phone.is_primary = 1 AND civicrm_phone.contact_id = civicrm_contact.id)
1714 LEFT JOIN civicrm_im ON ( civicrm_im.is_primary = 1 AND civicrm_im.contact_id = civicrm_contact.id)
1715 LEFT JOIN civicrm_openid ON ( civicrm_openid.is_primary = 1 AND civicrm_openid.contact_id = civicrm_contact.id)
1716 WHERE civicrm_contact.id = %1 ";
1718 $params = array(1 => array($contactId, 'Integer'));
1720 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1722 $locationType = NULL;
1723 if ($dao->fetch()) {
1724 $locationType = $dao->locationType
;
1727 if (isset($locationType)) {
1728 return $locationType;
1730 elseif ($skipDefaultPriamry) {
1731 // if there is no primary contact location then return null
1735 // if there is no primart contact location, then return default
1736 // location type of the system
1737 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
1738 return $defaultLocationType->id
;
1743 * function to get the display name, primary email and location type of a contact
1745 * @param int $id id of the contact
1747 * @return array of display_name, email if found, do_not_email or (null,null,null)
1751 static function getContactDetails($id) {
1752 // check if the contact type
1753 $contactType = self
::getContactType($id);
1755 $nameFields = ($contactType == 'Individual') ?
"civicrm_contact.first_name, civicrm_contact.last_name, civicrm_contact.display_name" : "civicrm_contact.display_name";
1758 SELECT $nameFields, civicrm_email.email, civicrm_contact.do_not_email, civicrm_email.on_hold, civicrm_contact.is_deceased
1759 FROM civicrm_contact LEFT JOIN civicrm_email ON (civicrm_contact.id = civicrm_email.contact_id)
1760 WHERE civicrm_contact.id = %1
1761 ORDER BY civicrm_email.is_primary DESC";
1762 $params = array(1 => array($id, 'Integer'));
1763 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
1765 if ($dao->fetch()) {
1766 if ($contactType == 'Individual') {
1767 if ($dao->first_name ||
$dao->last_name
) {
1768 $name = "{$dao->first_name} {$dao->last_name}";
1771 $name = $dao->display_name
;
1775 $name = $dao->display_name
;
1777 $email = $dao->email
;
1778 $doNotEmail = $dao->do_not_email ?
TRUE : FALSE;
1779 $onHold = $dao->on_hold ?
TRUE : FALSE;
1780 $isDeceased = $dao->is_deceased ?
TRUE : FALSE;
1781 return array($name, $email, $doNotEmail, $onHold, $isDeceased);
1783 return array(NULL, NULL, NULL, NULL, NULL);
1787 * function to add/edit/register contacts through profile.
1789 * @params array $params Array of profile fields to be edited/added.
1790 * @params int $contactID contact_id of the contact to be edited/added.
1791 * @params array $fields array of fields from UFGroup
1792 * @params int $addToGroupID specifies the default group to which contact is added.
1793 * @params int $ufGroupId uf group id (profile id)
1796 * @param null $contactID
1797 * @param null $addToGroupID
1798 * @param null $ufGroupId
1799 * @param string $ctype contact type
1800 * @param boolean $visibility basically lets us know where this request is coming from
1801 * if via a profile from web, we restrict what groups are changed
1803 * @return int contact id created/edited
1807 static function createProfileContact(
1811 $addToGroupID = NULL,
1816 // add ufGroupID to params array ( CRM-2012 )
1818 $params['uf_group_id'] = $ufGroupId;
1823 CRM_Utils_Hook
::pre('edit', 'Profile', $contactID, $params);
1827 CRM_Utils_Hook
::pre('create', 'Profile', NULL, $params);
1830 list($data, $contactDetails) = self
::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
1832 // manage is_opt_out
1833 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
1834 $wasOptOut = CRM_Utils_Array
::value('is_opt_out', $contactDetails, FALSE);
1835 $isOptOut = CRM_Utils_Array
::value('is_opt_out', $params, FALSE);
1836 $data['is_opt_out'] = $isOptOut;
1837 // on change, create new civicrm_subscription_history entry
1838 if (($wasOptOut != $isOptOut) && !empty($contactDetails['contact_id'])) {
1840 'contact_id' => $contactDetails['contact_id'],
1841 'status' => $isOptOut ?
'Removed' : 'Added',
1844 CRM_Contact_BAO_SubscriptionHistory
::create($shParams);
1848 $contact = self
::create($data);
1850 // contact is null if the profile does not have any contact fields
1852 $contactID = $contact->id
;
1855 if (empty($contactID)) {
1856 CRM_Core_Error
::fatal('Cannot proceed without a valid contact id');
1859 // Process group and tag
1860 if (!empty($fields['group'])) {
1862 // this for sure means we are coming in via profile since i added it to fix
1863 // removing contacts from user groups -- lobo
1867 CRM_Contact_BAO_GroupContact
::create($params['group'], $contactID, $visibility, $method);
1870 if (!empty($fields['tag'])) {
1871 CRM_Core_BAO_EntityTag
::create($params['tag'], 'civicrm_contact', $contactID);
1874 //to add profile in default group
1875 if (is_array($addToGroupID)) {
1876 $contactIds = array($contactID);
1877 foreach ($addToGroupID as $groupId) {
1878 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
1881 elseif ($addToGroupID) {
1882 $contactIds = array($contactID);
1883 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $addToGroupID);
1886 // reset the group contact cache for this group
1887 CRM_Contact_BAO_GroupContactCache
::remove();
1890 CRM_Utils_Hook
::post('edit', 'Profile', $contactID, $params);
1893 CRM_Utils_Hook
::post('create', 'Profile', $contactID, $params);
1901 * @param null $contactID
1902 * @param null $ufGroupId
1903 * @param null $ctype
1904 * @param bool $skipCustom
1908 static function formatProfileContactParams(
1917 $data = $contactDetails = array();
1919 // get the contact details (hier)
1921 list($details, $options) = self
::getHierContactDetails($contactID, $fields);
1923 $contactDetails = $details[$contactID];
1924 $data['contact_type'] = CRM_Utils_Array
::value('contact_type', $contactDetails);
1925 $data['contact_sub_type'] = CRM_Utils_Array
::value('contact_sub_type', $contactDetails);
1928 //we should get contact type only if contact
1930 $data['contact_type'] = CRM_Core_BAO_UFField
::getProfileType($ufGroupId);
1932 //special case to handle profile with only contact fields
1933 if ($data['contact_type'] == 'Contact') {
1934 $data['contact_type'] = 'Individual';
1936 elseif (CRM_Contact_BAO_ContactType
::isaSubType($data['contact_type'])) {
1937 $data['contact_type'] = CRM_Contact_BAO_ContactType
::getBasicType($data['contact_type']);
1941 $data['contact_type'] = $ctype;
1944 $data['contact_type'] = 'Individual';
1948 //fix contact sub type CRM-5125
1949 if (array_key_exists('contact_sub_type', $params) &&
1950 !empty($params['contact_sub_type'])
1952 $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
;
1954 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
1955 !empty($params['contact_sub_type_hidden'])
1957 // if profile was used, and had any subtype, we obtain it from there
1958 $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
;
1961 if ($ctype == 'Organization') {
1962 $data['organization_name'] = CRM_Utils_Array
::value('organization_name', $contactDetails);
1964 elseif ($ctype == 'Household') {
1965 $data['household_name'] = CRM_Utils_Array
::value('household_name', $contactDetails);
1968 $locationType = array();
1973 $data['contact_id'] = $contactID;
1974 $primaryLocationType = self
::getPrimaryLocationType($contactID);
1977 $defaultLocation = CRM_Core_BAO_LocationType
::getDefault();
1978 $defaultLocationId = $defaultLocation->id
;
1981 // get the billing location type
1982 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
1983 $billingLocationTypeId = array_search('Billing', $locationTypes);
1985 $blocks = array('email', 'phone', 'im', 'openid');
1987 $multiplFields = array('url');
1988 // prevent overwritten of formatted array, reset all block from
1989 // params if it is not in valid format (since import pass valid format)
1990 foreach ($blocks as $blk) {
1991 if (array_key_exists($blk, $params) &&
1992 !is_array($params[$blk])
1994 unset($params[$blk]);
1998 $primaryPhoneLoc = NULL;
1999 $session = CRM_Core_Session
::singleton();
2000 foreach ($params as $key => $value) {
2001 $fieldName = $locTypeId = $typeId = NULL;
2002 list($fieldName, $locTypeId, $typeId) = CRM_Utils_System
::explode('-', $key, 3);
2004 //store original location type id
2005 $actualLocTypeId = $locTypeId;
2007 if ($locTypeId == 'Primary') {
2009 if(in_array( $fieldName, $blocks)){
2010 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, $fieldName);
2013 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, 'address');
2015 $primaryLocationType = $locTypeId;
2018 $locTypeId = $defaultLocationId;
2022 if (is_numeric($locTypeId) &&
2023 !in_array($fieldName, $multiplFields) &&
2024 substr($fieldName, 0, 7) != 'custom_'
2026 $index = $locTypeId;
2028 if (is_numeric($typeId)) {
2029 $index .= '-' . $typeId;
2031 if (!in_array($index, $locationType)) {
2032 $locationType[$count] = $index;
2036 $loc = CRM_Utils_Array
::key($index, $locationType);
2038 $blockName = in_array( $fieldName, $blocks) ?
$fieldName : 'address';
2040 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
2042 //set is_billing true, for location type "Billing"
2043 if ($locTypeId == $billingLocationTypeId) {
2044 $data[$blockName][$loc]['is_billing'] = 1;
2048 //get the primary location type
2049 if ($locTypeId == $primaryLocationType) {
2050 $data[$blockName][$loc]['is_primary'] = 1;
2053 elseif ($locTypeId == $defaultLocationId) {
2054 $data[$blockName][$loc]['is_primary'] = 1;
2057 if ( in_array($fieldName, array('phone'))) {
2059 $data['phone'][$loc]['phone_type_id'] = $typeId;
2062 $data['phone'][$loc]['phone_type_id'] = '';
2064 $data['phone'][$loc]['phone'] = $value;
2066 //special case to handle primary phone with different phone types
2067 // in this case we make first phone type as primary
2068 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
2069 $primaryPhoneLoc = $loc;
2072 if ($loc != $primaryPhoneLoc) {
2073 unset($data['phone'][$loc]['is_primary']);
2076 elseif ($fieldName == 'phone_ext') {
2077 $data['phone'][$loc]['phone_ext'] = $value;
2079 elseif ($fieldName == 'email') {
2080 $data['email'][$loc]['email'] = $value;
2082 elseif ($fieldName == 'im') {
2083 if (isset($params[$key . '-provider_id'])) {
2084 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
2086 if (strpos($key, '-provider_id') !== FALSE) {
2087 $data['im'][$loc]['provider_id'] = $params[$key];
2090 $data['im'][$loc]['name'] = $value;
2093 elseif ($fieldName == 'openid') {
2094 $data['openid'][$loc]['openid'] = $value;
2097 if ($fieldName === 'state_province') {
2099 if (is_numeric($value) && ((int ) $value) >= 1000) {
2100 $data['address'][$loc]['state_province_id'] = $value;
2102 elseif (empty($value)) {
2103 $data['address'][$loc]['state_province_id'] = '';
2106 $data['address'][$loc]['state_province'] = $value;
2109 elseif ($fieldName === 'country') {
2111 if (is_numeric($value) && ((int ) $value) >= 1000
2113 $data['address'][$loc]['country_id'] = $value;
2115 elseif (empty($value)) {
2116 $data['address'][$loc]['country_id'] = '';
2119 $data['address'][$loc]['country'] = $value;
2122 elseif ($fieldName === 'county') {
2123 $data['address'][$loc]['county_id'] = $value;
2125 elseif ($fieldName == 'address_name') {
2126 $data['address'][$loc]['name'] = $value;
2128 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2129 $data['address'][$loc][substr($fieldName, 8)] = $value;
2132 $data['address'][$loc][$fieldName] = $value;
2137 if (substr($key, 0, 4) === 'url-') {
2138 $websiteField = explode('-', $key);
2139 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
2140 $data['website'][$websiteField[1]]['url'] = $value;
2142 elseif (in_array($key, self
::$_greetingTypes, TRUE)) {
2143 //save email/postal greeting and addressee values if any, CRM-4575
2144 $data[$key . '_id'] = $value;
2146 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($key))) {
2147 // for autocomplete transfer hidden value instead of label
2148 if ($params[$key] && isset($params[$key . '_id'])) {
2149 $value = $params[$key . '_id'];
2152 // we need to append time with date
2153 if ($params[$key] && isset($params[$key . '_time'])) {
2154 $value .= ' ' . $params[$key . '_time'];
2157 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
2158 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 &&
2159 ($value == '' ||
!isset($value))) {
2164 if (!empty($params['customRecordValues'])) {
2165 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2166 foreach ($params['customRecordValues'] as $recId => $customFields) {
2167 if (is_array($customFields) && !empty($customFields)) {
2168 foreach ($customFields as $customFieldName) {
2169 if ($customFieldName == $key) {
2179 $type = $data['contact_type'];
2180 if (!empty($data['contact_sub_type'])) {
2181 $type = $data['contact_sub_type'];
2182 $type = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($type, CRM_Core_DAO
::VALUE_SEPARATOR
));
2183 // generally a contact even if, has multiple subtypes the parent-type is going to be one only
2184 // and since formatCustomField() would be interested in parent type, lets consider only one subtype
2185 // as the results going to be same.
2189 CRM_Core_BAO_CustomField
::formatCustomField($customFieldId,
2197 elseif ($key == 'edit') {
2201 if ($key == 'location') {
2202 foreach ($value as $locationTypeId => $field) {
2203 foreach ($field as $block => $val) {
2204 if ($block == 'address' && array_key_exists('address_name', $val)) {
2205 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2210 if($key == 'phone' && isset($params['phone_ext'])){
2211 $data[$key] = $value;
2212 foreach($value as $cnt => $phoneBlock){
2213 if($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']){
2214 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array
::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2218 else if (in_array($key,
2227 ($value == '' ||
!isset($value)) &&
2228 ($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0) {
2229 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
2230 // to avoid update with empty values
2234 $data[$key] = $value;
2240 if (!isset($data['contact_type'])) {
2241 $data['contact_type'] = 'Individual';
2244 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2245 $privacy = CRM_Core_SelectValues
::privacy();
2246 foreach ($privacy as $key => $value) {
2247 if (array_key_exists($key, $fields)) {
2248 // do not reset values for existing contacts, if fields are added to a profile
2249 if (array_key_exists($key, $params)) {
2250 $data[$key] = $params[$key];
2251 if (empty($params[$key])) {
2255 elseif (!$contactID) {
2261 return array($data, $contactDetails);
2265 * Function to find the get contact details
2266 * does not respect ACLs for now, which might need to be rectified at some
2267 * stage based on how its used
2269 * @param string $mail primary email address of the contact
2270 * @param string $ctype contact type
2272 * @return object $dao contact details
2275 static function &matchContactOnEmail($mail, $ctype = NULL) {
2276 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2277 $mail = $strtolower(trim($mail));
2279 SELECT civicrm_contact.id as contact_id,
2280 civicrm_contact.hash as hash,
2281 civicrm_contact.contact_type as contact_type,
2282 civicrm_contact.contact_sub_type as contact_sub_type
2283 FROM civicrm_contact
2284 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2287 if (CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
2288 'uniq_email_per_site'
2290 // try to find a match within a site (multisite).
2291 $groups = CRM_Core_BAO_Domain
::getChildGroupIds();
2292 if (!empty($groups)) {
2294 INNER JOIN civicrm_group_contact gc ON
2295 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2300 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2301 $p = array(1 => array($mail, 'String'));
2304 $query .= " AND civicrm_contact.contact_type = %3";
2305 $p[3] = array($ctype, 'String');
2308 $query .= " ORDER BY civicrm_email.is_primary DESC";
2310 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2312 if ($dao->fetch()) {
2315 return CRM_Core_DAO
::$_nullObject;
2319 * Function to find the contact details associated with an OpenID
2321 * @param string $openId openId of the contact
2322 * @param string $ctype contact type
2324 * @return object $dao contact details
2327 static function &matchContactOnOpenId($openId, $ctype = NULL) {
2328 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2329 $openId = $strtolower(trim($openId));
2331 SELECT civicrm_contact.id as contact_id,
2332 civicrm_contact.hash as hash,
2333 civicrm_contact.contact_type as contact_type,
2334 civicrm_contact.contact_sub_type as contact_sub_type
2335 FROM civicrm_contact
2336 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2337 WHERE civicrm_openid.openid = %1";
2338 $p = array(1 => array($openId, 'String'));
2341 $query .= " AND civicrm_contact.contact_type = %3";
2342 $p[3] = array($ctype, 'String');
2345 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2347 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2349 if ($dao->fetch()) {
2352 return CRM_Core_DAO
::$_nullObject;
2356 * Funtion to get primary email of the contact
2358 * @param int $contactID contact id
2360 * @return string $dao->email email address if present else null
2364 public static function getPrimaryEmail($contactID) {
2365 // fetch the primary email
2367 SELECT civicrm_email.email as email
2368 FROM civicrm_contact
2369 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2370 WHERE civicrm_email.is_primary = 1
2371 AND civicrm_contact.id = %1";
2372 $p = array(1 => array($contactID, 'Integer'));
2373 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2376 if ($dao->fetch()) {
2377 $email = $dao->email
;
2384 * Funtion to get primary OpenID of the contact
2386 * @param int $contactID contact id
2388 * @return string $dao->openid OpenID if present else null
2392 public static function getPrimaryOpenId($contactID) {
2393 // fetch the primary OpenID
2395 SELECT civicrm_openid.openid as openid
2396 FROM civicrm_contact
2397 LEFT JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2398 WHERE civicrm_contact.id = %1
2399 AND civicrm_openid.is_primary = 1";
2400 $p = array(1 => array($contactID, 'Integer'));
2401 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2404 if ($dao->fetch()) {
2405 $openId = $dao->openid
;
2412 * Given the list of params in the params array, fetch the object
2413 * and store the values in the values array
2415 * @param array $params input parameters to find object
2416 * @param array $values output values of the object
2418 * @return CRM_Contact_BAO_Contact|null the found object or null
2422 public static function getValues(&$params, &$values) {
2423 $contact = new CRM_Contact_BAO_Contact();
2425 $contact->copyValues($params);
2427 if ($contact->find(TRUE)) {
2429 CRM_Core_DAO
::storeValues($contact, $values);
2432 foreach (self
::$_commPrefs as $name) {
2433 if (isset($contact->$name)) {
2434 $privacy[$name] = $contact->$name;
2438 if (!empty($privacy)) {
2439 $values['privacy'] = $privacy;
2442 // communication Prefferance
2443 $preffComm = $comm = array();
2444 $comm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2445 $contact->preferred_communication_method
2447 foreach ($comm as $value) {
2448 $preffComm[$value] = 1;
2450 $temp = array('preferred_communication_method' => $contact->preferred_communication_method
);
2453 'preferred_communication_method' => array('newName' => 'preferred_communication_method_display',
2454 'groupName' => 'preferred_communication_method',
2457 CRM_Core_OptionGroup
::lookupValues($temp, $names, FALSE);
2459 $values['preferred_communication_method'] = $preffComm;
2460 $values['preferred_communication_method_display'] = CRM_Utils_Array
::value('preferred_communication_method_display', $temp);
2462 $preferredMailingFormat = CRM_Core_SelectValues
::pmf();
2463 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format
];
2465 // get preferred languages
2466 if (!empty($contact->preferred_language
)) {
2467 $values['preferred_language'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language
);
2470 // Calculating Year difference
2471 if ($contact->birth_date
) {
2472 $birthDate = CRM_Utils_Date
::customFormat($contact->birth_date
, '%Y%m%d');
2473 if ($birthDate < date('Ymd')) {
2474 $age = CRM_Utils_Date
::calculateAge($birthDate);
2475 $values['age']['y'] = CRM_Utils_Array
::value('years', $age);
2476 $values['age']['m'] = CRM_Utils_Array
::value('months', $age);
2479 list($values['birth_date']) = CRM_Utils_Date
::setDateDefaults($contact->birth_date
, 'birth');
2480 $values['birth_date_display'] = $contact->birth_date
;
2483 if ($contact->deceased_date
) {
2484 list($values['deceased_date']) = CRM_Utils_Date
::setDateDefaults($contact->deceased_date
, 'birth');
2485 $values['deceased_date_display'] = $contact->deceased_date
;
2488 $contact->contact_id
= $contact->id
;
2496 * Given the component name and returns
2497 * the count of participation of contact
2499 * @param string $component input component name
2500 * @param integer $contactId input contact id
2501 * @param string $tableName optional tableName if component is custom group
2503 * @return total number of count of occurence in database
2507 static function getCountComponent($component, $contactId, $tableName = NULL) {
2509 switch ($component) {
2511 return CRM_Core_BAO_EntityTag
::getContactTags($contactId, TRUE);
2514 return CRM_Contact_BAO_Relationship
::getRelationship($contactId,
2515 CRM_Contact_BAO_Relationship
::CURRENT
,
2520 return CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, "Added", NULL, TRUE);
2523 if (CRM_Core_BAO_Log
::useLoggingReport()) {
2526 return CRM_Core_BAO_Log
::getContactLogCount($contactId);
2529 return CRM_Core_BAO_Note
::getContactNoteCount($contactId);
2531 case 'contribution':
2532 return CRM_Contribute_BAO_Contribution
::contributionCount($contactId);
2535 return CRM_Member_BAO_Membership
::getContactMembershipCount($contactId, TRUE);
2538 return CRM_Event_BAO_Participant
::getContactParticipantCount($contactId);
2541 return CRM_Pledge_BAO_Pledge
::getContactPledgeCount($contactId);
2544 return CRM_Case_BAO_Case
::caseCount($contactId);
2547 return CRM_Grant_BAO_Grant
::getContactGrantCount($contactId);
2551 'contact_id' => $contactId,
2554 'context' => 'activity',
2556 return CRM_Activity_BAO_Activity
::getActivitiesCount($input);
2559 $params = array('contact_id' => $contactId);
2560 return CRM_Mailing_BAO_Mailing
::getContactMailingsCount($params);
2563 $custom = explode('_', $component);
2564 if ($custom['0'] = 'custom') {
2566 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2568 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2569 return CRM_Core_DAO
::singleValueQuery($queryString);
2575 * Function to process greetings and cache
2577 * @param object $contact contact object after save
2578 * @param boolean $useDefaults use default greeting values
2584 static function processGreetings(&$contact, $useDefaults = FALSE) {
2586 //retrieve default greetings
2587 $defaultGreetings = CRM_Core_PseudoConstant
::greetingDefaults();
2588 $contactDefaults = $defaultGreetings[$contact->contact_type
];
2591 // note that contact object not always has required greeting related
2592 // fields that are required to calculate greeting and
2593 // also other fields used in tokens etc,
2594 // hence we need to retrieve it again.
2595 if ( $contact->_query
!== FALSE ) {
2596 $contact->find(TRUE);
2599 // store object values to an array
2600 $contactDetails = array();
2601 CRM_Core_DAO
::storeValues($contact, $contactDetails);
2602 $contactDetails = array(array($contact->id
=> $contactDetails));
2604 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2605 $updateQueryString = array();
2607 //cache email and postal greeting to greeting display
2608 if ($contact->email_greeting_custom
!= 'null' && $contact->email_greeting_custom
) {
2609 $emailGreetingString = $contact->email_greeting_custom
;
2611 elseif ($contact->email_greeting_id
!= 'null' && $contact->email_greeting_id
) {
2612 // the filter value for Individual contact type is set to 1
2614 'contact_type' => $contact->contact_type
,
2615 'greeting_type' => 'email_greeting',
2618 $emailGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2619 $emailGreetingString = $emailGreeting[$contact->email_greeting_id
];
2620 $updateQueryString[] = " email_greeting_custom = NULL ";
2624 reset($contactDefaults['email_greeting']);
2625 $emailGreetingID = key($contactDefaults['email_greeting']);
2626 $emailGreetingString = $contactDefaults['email_greeting'][$emailGreetingID];
2627 $updateQueryString[] = " email_greeting_id = $emailGreetingID ";
2628 $updateQueryString[] = " email_greeting_custom = NULL ";
2630 elseif ($contact->email_greeting_custom
) {
2631 $updateQueryString[] = " email_greeting_display = NULL ";
2635 if ($emailGreetingString) {
2636 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($emailGreetingString,
2639 'CRM_Contact_BAO_Contact'
2641 $emailGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($emailGreetingString));
2642 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2646 if ($contact->postal_greeting_custom
!= 'null' && $contact->postal_greeting_custom
) {
2647 $postalGreetingString = $contact->postal_greeting_custom
;
2649 elseif ($contact->postal_greeting_id
!= 'null' && $contact->postal_greeting_id
) {
2651 'contact_type' => $contact->contact_type
,
2652 'greeting_type' => 'postal_greeting',
2654 $postalGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2655 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id
];
2656 $updateQueryString[] = " postal_greeting_custom = NULL ";
2660 reset($contactDefaults['postal_greeting']);
2661 $postalGreetingID = key($contactDefaults['postal_greeting']);
2662 $postalGreetingString = $contactDefaults['postal_greeting'][$postalGreetingID];
2663 $updateQueryString[] = " postal_greeting_id = $postalGreetingID ";
2664 $updateQueryString[] = " postal_greeting_custom = NULL ";
2666 elseif ($contact->postal_greeting_custom
) {
2667 $updateQueryString[] = " postal_greeting_display = NULL ";
2671 if ($postalGreetingString) {
2672 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($postalGreetingString,
2675 'CRM_Contact_BAO_Contact'
2677 $postalGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($postalGreetingString));
2678 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2682 if ($contact->addressee_custom
!= 'null' && $contact->addressee_custom
) {
2683 $addresseeString = $contact->addressee_custom
;
2685 elseif ($contact->addressee_id
!= 'null' && $contact->addressee_id
) {
2687 'contact_type' => $contact->contact_type
,
2688 'greeting_type' => 'addressee',
2691 $addressee = CRM_Core_PseudoConstant
::greeting($filter);
2692 $addresseeString = $addressee[$contact->addressee_id
];
2693 $updateQueryString[] = " addressee_custom = NULL ";
2697 reset($contactDefaults['addressee']);
2698 $addresseeID = key($contactDefaults['addressee']);
2699 $addresseeString = $contactDefaults['addressee'][$addresseeID];
2700 $updateQueryString[] = " addressee_id = $addresseeID ";
2701 $updateQueryString[] = " addressee_custom = NULL ";
2703 elseif ($contact->addressee_custom
) {
2704 $updateQueryString[] = " addressee_display = NULL ";
2708 if ($addresseeString) {
2709 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($addresseeString,
2712 'CRM_Contact_BAO_Contact'
2714 $addresseeString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($addresseeString));
2715 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2718 if (!empty($updateQueryString)) {
2719 $updateQueryString = implode(',', $updateQueryString);
2720 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2721 CRM_Core_DAO
::executeQuery($queryString);
2726 * Function to retrieve loc block ids w/ given condition.
2728 * @param int $contactId contact id.
2729 * @param array $criteria key => value pair which should be
2730 * fulfill by return record ids.
2731 * @param string $condOperator operator use for grouping multiple conditions.
2733 * @return array $locBlockIds loc block ids which fulfill condition.
2736 static function getLocBlockIds($contactId, $criteria = array(), $condOperator = 'AND') {
2737 $locBlockIds = array();
2739 return $locBlockIds;
2742 foreach (array('Email', 'OpenID', 'Phone', 'Address', 'IM') as $block) {
2743 $name = strtolower($block);
2744 $className = "CRM_Core_DAO_$block";
2745 $blockDAO = new $className();
2747 // build the condition.
2748 if (is_array($criteria)) {
2749 $fields = $blockDAO->fields();
2750 $conditions = array();
2751 foreach ($criteria as $field => $value) {
2752 if (array_key_exists($field, $fields)) {
2753 $cond = "( $field = $value )";
2754 // value might be zero or null.
2755 if (!$value ||
strtolower($value) == 'null') {
2756 $cond = "( $field = 0 OR $field IS NULL )";
2758 $conditions[] = $cond;
2761 if (!empty($conditions)) {
2762 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2766 $blockDAO->contact_id
= $contactId;
2768 while ($blockDAO->fetch()) {
2769 $locBlockIds[$name][] = $blockDAO->id
;
2774 return $locBlockIds;
2778 * Function to build context menu items.
2780 * @param null $contactId
2782 * @return array of context menu for logged in user.
2785 static function contextMenu($contactId = NULL) {
2788 'title' => ts('View Contact'),
2790 'ref' => 'view-contact',
2791 'class' => 'no-popup',
2793 'permissions' => array('view all contacts'),
2796 'title' => ts('Edit Contact'),
2798 'ref' => 'edit-contact',
2799 'class' => 'no-popup',
2801 'permissions' => array('edit all contacts'),
2804 'title' => ts('Delete Contact'),
2806 'ref' => 'delete-contact',
2808 'permissions' => array('access deleted contacts', 'delete contacts'),
2810 'contribution' => array(
2811 'title' => ts('Add Contribution'),
2813 'ref' => 'new-contribution',
2814 'class' => 'huge-popup',
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 'class' => 'huge-popup',
2831 'key' => 'participant',
2832 'tab' => 'participant',
2833 'component' => 'CiviEvent',
2834 'href' => CRM_Utils_System
::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
2835 'permissions' => array(
2837 'edit event participants',
2840 'activity' => array(
2841 'title' => ts('Record Activity'),
2843 'ref' => 'new-activity',
2844 'key' => 'activity',
2845 'permissions' => array('edit all contacts'),
2848 'title' => ts('Add Pledge'),
2850 'ref' => 'new-pledge',
2853 'href' => CRM_Utils_System
::url('civicrm/contact/view/pledge',
2854 'reset=1&action=add&context=pledge'
2856 'component' => 'CiviPledge',
2857 'permissions' => array(
2858 'access CiviPledge',
2862 'membership' => array(
2863 'title' => ts('Add Membership'),
2865 'ref' => 'new-membership',
2866 'class' => 'huge-popup',
2867 'key' => 'membership',
2869 'component' => 'CiviMember',
2870 'href' => CRM_Utils_System
::url('civicrm/contact/view/membership',
2871 'reset=1&action=add&context=membership'
2873 'permissions' => array(
2874 'access CiviMember',
2879 'title' => ts('Add Case'),
2881 'ref' => 'new-case',
2884 'component' => 'CiviCase',
2885 'href' => CRM_Utils_System
::url('civicrm/case/add', 'reset=1&action=add&context=case'),
2886 'permissions' => array('add cases'),
2889 'title' => ts('Add Grant'),
2891 'ref' => 'new-grant',
2894 'component' => 'CiviGrant',
2895 'href' => CRM_Utils_System
::url('civicrm/contact/view/grant',
2896 'reset=1&action=add&context=grant'
2898 'permissions' => array('edit grants'),
2901 'title' => ts('Add Relationship'),
2903 'ref' => 'new-relationship',
2906 'href' => CRM_Utils_System
::url('civicrm/contact/view/rel',
2907 'reset=1&action=add'
2909 'permissions' => array('edit all contacts'),
2912 'title' => ts('Add Note'),
2914 'ref' => 'new-note',
2917 'class' => 'medium-popup',
2918 'href' => CRM_Utils_System
::url('civicrm/contact/view/note',
2919 'reset=1&action=add'
2921 'permissions' => array('edit all contacts'),
2924 'title' => ts('Send an Email'),
2926 'ref' => 'new-email',
2928 'permissions' => array('view all contacts'),
2931 'title' => ts('Add to Group'),
2933 'ref' => 'group-add-contact',
2936 'permissions' => array('edit groups'),
2939 'title' => ts('Tag Contact'),
2941 'ref' => 'tag-contact',
2944 'permissions' => array('edit all contacts'),
2948 CRM_Utils_Hook
::summaryActions($menu, $contactId);
2949 //1. check for component is active.
2950 //2. check for user permissions.
2951 //3. check for acls.
2952 //3. edit and view contact are directly accessible to user.
2954 $aclPermissionedTasks = array(
2955 'view-contact', 'edit-contact', 'new-activity',
2956 'new-email', 'group-add-contact', 'tag-contact', 'delete-contact',
2958 $corePermission = CRM_Core_Permission
::getPermission();
2960 $config = CRM_Core_Config
::singleton();
2962 $contextMenu = array();
2963 foreach ($menu as $key => $values) {
2964 $componentName = CRM_Utils_Array
::value('component', $values);
2966 // if component action - make sure component is enable.
2967 if ($componentName && !in_array($componentName, $config->enableComponents
)) {
2971 // make sure user has all required permissions.
2972 $hasAllPermissions = FALSE;
2974 $permissions = CRM_Utils_Array
::value('permissions', $values);
2975 if (!is_array($permissions) ||
empty($permissions)) {
2976 $hasAllPermissions = TRUE;
2979 // iterate for required permissions in given permissions array.
2980 if (!$hasAllPermissions) {
2981 $hasPermissions = 0;
2982 foreach ($permissions as $permission) {
2983 if (CRM_Core_Permission
::check($permission)) {
2988 if (count($permissions) == $hasPermissions) {
2989 $hasAllPermissions = TRUE;
2992 // if still user does not have required permissions, check acl.
2993 if (!$hasAllPermissions && $values['ref'] != 'delete-contact') {
2994 if (in_array($values['ref'], $aclPermissionedTasks) &&
2995 $corePermission == CRM_Core_Permission
::EDIT
2997 $hasAllPermissions = TRUE;
2999 elseif (in_array($values['ref'], array(
3001 // grant permissions for these tasks.
3002 $hasAllPermissions = TRUE;
3007 // user does not have necessary permissions.
3008 if (!$hasAllPermissions) {
3012 // build directly accessible action menu.
3013 if (in_array($values['ref'], array(
3014 'view-contact', 'edit-contact'))) {
3015 $contextMenu['primaryActions'][$key] = array(
3016 'title' => $values['title'],
3017 'ref' => $values['ref'],
3018 'class' => CRM_Utils_Array
::value('class', $values),
3019 'key' => $values['key'],
3024 // finally get menu item for -more- action widget.
3025 $contextMenu['moreActions'][$values['weight']] = array(
3026 'title' => $values['title'],
3027 'ref' => $values['ref'],
3028 'href' => CRM_Utils_Array
::value('href', $values),
3029 'tab' => CRM_Utils_Array
::value('tab', $values),
3030 'class' => CRM_Utils_Array
::value('class', $values),
3031 'key' => $values['key'],
3035 ksort($contextMenu['moreActions']);
3037 return $contextMenu;
3041 * Function to retrieve display name of contact that address is shared
3042 * based on $masterAddressId or $contactId .
3044 * @param int $masterAddressId master id.
3045 * @param int $contactId contact id.
3047 * @return display name |null the found display name or null.
3051 static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3052 $masterDisplayName = NULL;
3054 if (!$masterAddressId && !$contactId) {
3055 return $masterDisplayName;
3058 if ($masterAddressId) {
3060 SELECT display_name from civicrm_contact
3061 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3062 WHERE civicrm_address.id = " . $masterAddressId;
3064 elseif ($contactId) {
3066 SELECT display_name from civicrm_contact cc, civicrm_address add1
3067 LEFT JOIN civicrm_address add2 ON ( add1.master_id = add2.id )
3068 WHERE cc.id = add2.contact_id AND add1.contact_id = " . $contactId;
3071 $masterDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
3072 return $masterDisplayName;
3076 * Get the creation/modification times for a contact
3080 * @return array('created_date' => $, 'modified_date' => $)
3082 static function getTimestamps($contactId) {
3083 $timestamps = CRM_Core_DAO
::executeQuery(
3084 'SELECT created_date, modified_date
3085 FROM civicrm_contact
3088 1 => array($contactId, 'Integer'),
3091 if ($timestamps->fetch()) {
3093 'created_date' => $timestamps->created_date
,
3094 'modified_date' => $timestamps->modified_date
,
3103 * Get a list of triggers for the contact table
3105 * @see hook_civicrm_triggerInfo
3106 * @see CRM_Core_DAO::triggerRebuild
3107 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3109 static function triggerInfo(&$info, $tableName = NULL) {
3110 //during upgrade, first check for valid version and then create triggers
3111 //i.e the columns created_date and modified_date are introduced in 4.3.alpha1 so dont create triggers for older version
3112 if (CRM_Core_Config
::isUpgradeMode()) {
3113 $currentVer = CRM_Core_BAO_Domain
::version(TRUE);
3114 //if current version is less than 4.3.alpha1 dont create below triggers
3115 if (version_compare($currentVer, '4.3.alpha1') < 0) {
3120 if ($tableName == NULL ||
$tableName == self
::getTableName()) {
3122 'table' => array(self
::getTableName()),
3124 'event' => array('INSERT'),
3125 'sql' => "\nSET NEW.created_date = CURRENT_TIMESTAMP;\n",
3129 // Update timestamp when modifying closely related core tables
3130 $relatedTables = array(
3138 'table' => $relatedTables,
3140 'event' => array('INSERT', 'UPDATE'),
3141 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = NEW.contact_id;\n",
3144 'table' => $relatedTables,
3146 'event' => array('DELETE'),
3147 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = OLD.contact_id;\n",
3150 // Update timestamp when modifying related custom-data tables
3151 $customGroupTables = array();
3152 $customGroupDAO = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity('Contact');
3153 $customGroupDAO->is_multiple
= 0;
3154 $customGroupDAO->find();
3155 while ($customGroupDAO->fetch()) {
3156 $customGroupTables[] = $customGroupDAO->table_name
;
3158 if (!empty($customGroupTables)) {
3160 'table' => $customGroupTables,
3162 'event' => array('INSERT', 'UPDATE'),
3163 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = NEW.entity_id;\n",
3166 'table' => $customGroupTables,
3168 'event' => array('DELETE'),
3169 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = OLD.entity_id;\n",
3173 // Update phone table to populate phone_numeric field
3174 if (!$tableName ||
$tableName == 'civicrm_phone') {
3175 // Define stored sql function needed for phones
3176 CRM_Core_DAO
::executeQuery(self
::DROP_STRIP_FUNCTION_43
);
3177 CRM_Core_DAO
::executeQuery(self
::CREATE_STRIP_FUNCTION_43
);
3179 'table' => array('civicrm_phone'),
3181 'event' => array('INSERT', 'UPDATE'),
3182 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3188 * Function to check if contact is being used in civicrm_domain
3189 * based on $contactId
3191 * @param int $contactId contact id.
3193 * @return true if present else false.
3197 static function checkDomainContact($contactId) {
3200 $domainId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3210 * Get options for a given contact field.
3211 * @see CRM_Core_DAO::buildOptions
3213 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3214 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3216 * @param String $fieldName
3217 * @param String $context : @see CRM_Core_DAO::buildOptionsContext
3218 * @param Array $props : whatever is known about this dao object
3220 * @return Array|bool
3222 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3224 // Special logic for fields whose options depend on context or properties
3225 switch ($fieldName) {
3226 case 'contact_sub_type':
3227 if (!empty($props['contact_type'])) {
3228 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3232 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
3236 * Delete a contact-related object that has an 'is_primary' field
3237 * Ensures that is_primary gets assigned to another object if available
3238 * Also calls pre/post hooks
3240 * @var $type : object type
3241 * @var $id : object id
3244 public static function deleteObjectWithPrimary($type, $id) {
3245 if (!$id ||
!is_numeric($id)) {
3248 $daoName = "CRM_Core_DAO_$type";
3249 $obj = new $daoName();
3252 if ($obj->fetch()) {
3253 CRM_Utils_Hook
::pre('delete', $type, $id, CRM_Core_DAO
::$_nullArray);
3254 $contactId = $obj->contact_id
;
3260 // is_primary is only relavent if this field belongs to a contact
3262 $dao = new $daoName();
3263 $dao->contact_id
= $contactId;
3264 $dao->is_primary
= 1;
3265 // Pick another record to be primary (if one isn't already)
3266 if (!$dao->find(TRUE)) {
3267 $dao->is_primary
= 0;
3269 if ($dao->fetch()) {
3270 $dao->is_primary
= 1;
3276 CRM_Utils_Hook
::post('delete', $type, $id, $obj);