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 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
);
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 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',
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 * Fetch object based on array of properties
686 * @param array $params (reference ) an assoc array of name/value pairs
687 * @param array $defaults (reference ) an assoc array to hold the name / value pairs
688 * in a hierarchical manner
689 * @param boolean $microformat for location in microformat
691 * @return CRM_Contact_BAO_Contact object
695 static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
696 if (array_key_exists('contact_id', $params)) {
697 $params['id'] = $params['contact_id'];
699 elseif (array_key_exists('id', $params)) {
700 $params['contact_id'] = $params['id'];
703 $contact = self
::getValues($params, $defaults);
705 unset($params['id']);
707 //get the block information for this contact
708 $entityBlock = array('contact_id' => $params['contact_id']);
709 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock, $microformat);
710 $defaults = array_merge($defaults, $blocks);
711 foreach ($blocks as $block => $value) $contact->$block = $value;
713 if (!isset($params['noNotes'])) {
714 $contact->notes
= CRM_Core_BAO_Note
::getValues($params, $defaults);
717 if (!isset($params['noRelationships'])) {
718 $contact->relationship
= CRM_Contact_BAO_Relationship
::getValues($params, $defaults);
721 if (!isset($params['noGroups'])) {
722 $contact->groupContact
= CRM_Contact_BAO_GroupContact
::getValues($params, $defaults);
725 if (!isset($params['noWebsite'])) {
726 $contact->website
= CRM_Core_BAO_Website
::getValues($params, $defaults);
733 * Get the display name of a contact
735 * @param int $id id of the contact
737 * @return null|string display name of the contact if found
741 static function displayName($id) {
744 $displayName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
751 * Delete a contact and all its associated records
753 * @param int $id id of the contact to delete
754 * @param bool $restore whether to actually restore, not delete
755 * @param bool $skipUndelete whether to force contact delete or not
757 * @return boolean true if contact deleted, false otherwise
761 static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE) {
767 // make sure we have edit permission for this contact
769 if (($skipUndelete && !CRM_Core_Permission
::check('delete contacts')) ||
770 ($restore && !CRM_Core_Permission
::check('access deleted contacts'))
776 // Restrict contact to be delete if contact has financial trxns
778 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent(array($id), $error)) {
782 // make sure this contact_id does not have any membership types
783 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
786 'member_of_contact_id'
788 if ($membershipTypeID) {
792 $contact = new CRM_Contact_DAO_Contact();
794 if (!$contact->find(TRUE)) {
798 $contactType = $contact->contact_type
;
799 $action = ($restore) ?
'restore' : 'delete';
801 CRM_Utils_Hook
::pre($action, $contactType, $id, CRM_Core_DAO
::$_nullArray);
804 self
::contactTrashRestore($contact, TRUE);
805 CRM_Utils_Hook
::post($action, $contactType, $contact->id
, $contact);
810 // currently we only clear employer cache.
811 // we are not deleting inherited membership if any.
812 if ($contact->contact_type
== 'Organization') {
813 CRM_Contact_BAO_Contact_Utils
::clearAllEmployee($id);
816 // start a new transaction
817 $transaction = new CRM_Core_Transaction();
819 if ($skipUndelete or !CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'contact_undelete', NULL)) {
821 //delete billing address if exists.
822 CRM_Contribute_BAO_Contribution
::deleteAddress(NULL, $id);
824 // delete the log entries since we dont have triggers enabled as yet
825 $logDAO = new CRM_Core_DAO_Log();
826 $logDAO->entity_table
= 'civicrm_contact';
827 $logDAO->entity_id
= $id;
830 // delete contact participants CRM-12155
831 CRM_Event_BAO_Participant
::deleteContactParticipant($id);
833 // delete contact contributions CRM-12155
834 CRM_Contribute_BAO_Contribution
::deleteContactContribution($id);
836 // do activity cleanup, CRM-5604
837 CRM_Activity_BAO_Activity
::cleanupActivity($id);
839 // delete all notes related to contact
840 CRM_Core_BAO_Note
::cleanContactNotes($id);
842 // delete cases related to contact
843 $contactCases = CRM_Case_BAO_Case
::retrieveCaseIdsByContactId($id);
844 if (!empty($contactCases)) {
845 foreach ($contactCases as $caseId) {
846 //check if case is associate with other contact or not.
847 $caseContactId = CRM_Case_BAO_Case
::getCaseClients($caseId);
848 if (count($caseContactId) <= 1) {
849 CRM_Case_BAO_Case
::deleteCase($caseId);
857 self
::contactTrashRestore($contact);
860 //delete the contact id from recently view
861 CRM_Utils_Recent
::delContact($id);
863 // Update the group contact cache
865 CRM_Contact_BAO_GroupContactCache
::remove();
868 CRM_Contact_BAO_GroupContactCache
::removeContact($id);
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 * 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 * Return relative path
906 * @todo make this a method of $config->userSystem (i.e. UF classes) rather than a static function
908 * @param string $absolutePath absolute path
910 * @return String $relativePath Relative url of uploaded image
912 public static function getRelativePath($absolutePath) {
913 $relativePath = NULL;
914 $config = CRM_Core_Config
::singleton();
915 if ($config->userFramework
== 'Joomla') {
916 $userFrameworkBaseURL = trim(str_replace('/administrator/', '', $config->userFrameworkBaseURL
));
917 $customFileUploadDirectory = strstr(str_replace('\\', '/', $absolutePath), '/media');
918 $relativePath = $userFrameworkBaseURL . $customFileUploadDirectory;
920 elseif ($config->userSystem
->is_drupal
== '1') {
921 //ideally we would do a bigger re-factoring & move the getRelativePath onto the UF class
922 $rootPath = $config->userSystem
->cmsRootPath();
923 $baseUrl = $config->userFrameworkBaseURL
;
925 //format url for language negotiation, CRM-7135
926 $baseUrl = CRM_Utils_System
::languageNegotiationURL($baseUrl, FALSE, TRUE);
928 $relativePath = str_replace("{$rootPath}/",
930 str_replace('\\', '/', $absolutePath)
932 } else if ( $config->userFramework
== 'WordPress' ) {
933 $userFrameworkBaseURL = trim( str_replace( '/wp-admin/', '', $config->userFrameworkBaseURL
) );
934 $customFileUploadDirectory = strstr( str_replace('\\', '/', $absolutePath), '/wp-content/' );
935 $relativePath = $userFrameworkBaseURL . $customFileUploadDirectory;
938 return $relativePath;
942 * Return proportional height and width of the image
944 * @param Integer $imageWidth width of image
946 * @param Integer $imageHeight height of image
948 * @return Array thumb dimension of image
950 public static function getThumbSize($imageWidth, $imageHeight) {
952 if ($imageWidth && $imageHeight) {
953 $imageRatio = $imageWidth / $imageHeight;
958 if ($imageRatio > 1) {
959 $imageThumbWidth = $thumbWidth;
960 $imageThumbHeight = round($thumbWidth / $imageRatio);
963 $imageThumbHeight = $thumbWidth;
964 $imageThumbWidth = round($thumbWidth * $imageRatio);
967 return array($imageThumbWidth, $imageThumbHeight);
971 * Validate type of contact image
973 * @param array $params
974 * @param String $imageIndex index of image field
975 * @param String $statusMsg status message to be set after operation
976 * @param string $opType type of operation like fatal, bounce etc
978 * @return boolean true if valid image extension
980 public static function processImageParams(&$params,
981 $imageIndex = 'image_URL',
995 if (in_array($params[$imageIndex]['type'], $mimeType)) {
996 $photo = basename($params[$imageIndex]['name']);
997 $params[$imageIndex] = CRM_Utils_System
::url('civicrm/contact/imagefile', 'photo='.$photo, TRUE, NULL, TRUE, TRUE);
1001 unset($params[$imageIndex]);
1003 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
1005 if ($opType == 'status') {
1006 CRM_Core_Session
::setStatus($statusMsg, 'Sorry', 'error');
1008 // FIXME: additional support for fatal, bounce etc could be added.
1014 * Extract contact id from url for deleting contact image
1016 public static function processImage() {
1018 $action = CRM_Utils_Request
::retrieve('action', 'String');
1019 $cid = CRM_Utils_Request
::retrieve('cid', 'Positive');
1020 // retrieve contact id in case of Profile context
1021 $id = CRM_Utils_Request
::retrieve('id', 'Positive');
1022 $cid = $cid ?
$cid : $id;
1023 if ($action & CRM_Core_Action
::DELETE
) {
1024 if (CRM_Utils_Request
::retrieve('confirmed', 'Boolean')) {
1025 CRM_Contact_BAO_Contact
::deleteContactImage($cid);
1026 CRM_Core_Session
::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
1027 $session = CRM_Core_Session
::singleton();
1028 $toUrl = $session->popUserContext();
1029 CRM_Utils_System
::redirect($toUrl);
1035 * Function to set is_delete true or restore deleted contact
1037 * @param int $contact Contact DAO object
1038 * @param boolean $restore true to set the is_delete = 1 else false to restore deleted contact,
1039 * i.e. is_delete = 0
1044 static function contactTrashRestore($contact, $restore = FALSE) {
1045 $op = ($restore ?
'restore' : 'trash');
1047 CRM_Utils_Hook
::pre($op, $contact->contact_type
, $contact->id
, CRM_Core_DAO
::$_nullArray);
1049 $params = array(1 => array($contact->id
, 'Integer'));
1050 $isDelete = ' is_deleted = 1 ';
1052 $isDelete = ' is_deleted = 0 ';
1055 $query = "DELETE FROM civicrm_uf_match WHERE contact_id = %1";
1056 CRM_Core_DAO
::executeQuery($query, $params);
1059 $query = "UPDATE civicrm_contact SET {$isDelete} WHERE id = %1";
1060 CRM_Core_DAO
::executeQuery($query, $params);
1062 CRM_Utils_Hook
::post($op, $contact->contact_type
, $contact->id
, $contact);
1066 * Get contact type for a contact.
1068 * @param int $id - id of the contact whose contact type is needed
1070 * @return string contact_type if $id found else null ""
1077 public static function getContactType($id) {
1078 return CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1082 * Get contact sub type for a contact.
1084 * @param int $id - id of the contact whose contact sub type is needed
1086 * @param null $implodeDelimiter
1088 * @return string contact_sub_type if $id found else null ""
1094 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1095 $subtype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1097 return $implodeDelimiter ?
NULL : array();
1100 $subtype = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($subtype, CRM_Core_DAO
::VALUE_SEPARATOR
));
1102 if ($implodeDelimiter) {
1103 $subtype = implode($implodeDelimiter, $subtype);
1109 * Get pair of contact-type and sub-type for a contact.
1111 * @param int $id - id of the contact whose contact sub/contact type is needed
1120 public static function getContactTypes($id) {
1121 $params = array('id' => $id);
1123 $contact = CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact',
1126 array('contact_type', 'contact_sub_type')
1130 $contactTypes = array();
1131 if ($contact->contact_sub_type
)
1132 $contactTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($contact->contact_sub_type
, CRM_Core_DAO
::VALUE_SEPARATOR
));
1133 array_unshift($contactTypes, $contact->contact_type
);
1135 return $contactTypes;
1138 CRM_Core_Error
::fatal();
1143 * Combine all the importable fields from the lower levels object
1145 * The ordering is important, since currently we do not have a weight
1146 * scheme. Adding weight is super important
1148 * @param int|string $contactType contact Type
1149 * @param boolean $status status is used to manipulate first title
1150 * @param boolean $showAll if true returns all fields (includes disabled fields)
1151 * @param boolean $isProfile if its profile mode
1152 * @param boolean $checkPermission if false, do not include permissioning clause (for custom data)
1154 * @param bool $withMultiCustomFields
1156 * @return array array of importable Fields
1160 static function importableFields($contactType = 'Individual',
1164 $checkPermission = TRUE,
1165 $withMultiCustomFields = FALSE
1167 if (empty($contactType)) {
1168 $contactType = 'All';
1171 $cacheKeyString = "importableFields $contactType";
1172 $cacheKeyString .= $status ?
'_1' : '_0';
1173 $cacheKeyString .= $showAll ?
'_1' : '_0';
1174 $cacheKeyString .= $isProfile ?
'_1' : '_0';
1175 $cacheKeyString .= $checkPermission ?
'_1' : '_0';
1177 $fields = CRM_Utils_Array
::value($cacheKeyString, self
::$_importableFields);
1180 // check if we can retrieve from database cache
1181 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1185 $fields = CRM_Contact_DAO_Contact
::import();
1187 // get the fields thar are meant for contact types
1188 if (in_array($contactType, array(
1189 'Individual', 'Household', 'Organization', 'All'))) {
1190 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1193 $locationFields = array_merge(CRM_Core_DAO_Address
::import(),
1194 CRM_Core_DAO_Phone
::import(),
1195 CRM_Core_DAO_Email
::import(),
1196 CRM_Core_DAO_IM
::import(TRUE),
1197 CRM_Core_DAO_OpenID
::import()
1200 $locationFields = array_merge($locationFields,
1201 CRM_Core_BAO_CustomField
::getFieldsForImport('Address',
1209 foreach ($locationFields as $key => $field) {
1210 $locationFields[$key]['hasLocationType'] = TRUE;
1213 $fields = array_merge($fields, $locationFields);
1215 $fields = array_merge($fields, CRM_Contact_DAO_Contact
::import());
1216 $fields = array_merge($fields, CRM_Core_DAO_Note
::import());
1219 $fields = array_merge($fields, CRM_Core_DAO_Website
::import());
1220 $fields['url']['hasWebsiteType'] = TRUE;
1222 if ($contactType != 'All') {
1223 $fields = array_merge($fields,
1224 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType,
1229 $withMultiCustomFields
1232 //unset the fields, which are not related to their
1234 $commonValues = array(
1235 'Individual' => array(
1241 'Household' => array(
1251 'organization_name',
1259 'Organization' => array(
1274 foreach ($commonValues[$contactType] as $value) {
1275 unset($fields[$value]);
1280 'Individual', 'Household', 'Organization') as $type) {
1281 $fields = array_merge($fields,
1282 CRM_Core_BAO_CustomField
::getFieldsForImport($type,
1287 $withMultiCustomFields
1294 $fields = array_merge($fields, array(
1296 'title' => ts('Group(s)'),
1300 'title' => ts('Tag(s)'),
1304 'title' => ts('Note(s)'),
1307 'communication_style_id' => array(
1308 'title' => ts('Communication Style'),
1309 'name' => 'communication_style_id',
1314 //Sorting fields in alphabetical order(CRM-1507)
1315 $fields = CRM_Utils_Array
::crmArraySortByField($fields, 'title');
1317 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1320 self
::$_importableFields[$cacheKeyString] = $fields;
1324 $fields = array_merge(array('do_not_import' => array('title' => ts('- do not import -'))),
1325 self
::$_importableFields[$cacheKeyString]
1329 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1330 self
::$_importableFields[$cacheKeyString]
1338 * Combine all the exportable fields from the lower levels object
1340 * currentlty we are using importable fields as exportable fields
1342 * @param int|string $contactType contact Type
1343 * @param boolean $status true while exporting primary contacts
1344 * @param boolean $export true when used during export
1345 * @param boolean $search true when used during search, might conflict with export param?
1347 * @param bool $withMultiRecord
1349 * @return array array of exportable Fields
1353 static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE) {
1354 if (empty($contactType)) {
1355 $contactType = 'All';
1358 $cacheKeyString = "exportableFields $contactType";
1359 $cacheKeyString .= $export ?
'_1' : '_0';
1360 $cacheKeyString .= $status ?
'_1' : '_0';
1361 $cacheKeyString .= $search ?
'_1' : '_0';
1362 //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
1363 //calculates custom fields takes into account the logged in user & caches that for all users
1364 //as an interim fix we will cache the fields by contact
1365 $cacheKeyString .= '_' . CRM_Core_Session
::getLoggedInContactID();
1367 if (!self
::$_exportableFields ||
!CRM_Utils_Array
::value($cacheKeyString, self
::$_exportableFields)) {
1368 if (!self
::$_exportableFields) {
1369 self
::$_exportableFields = array();
1372 // check if we can retrieve from database cache
1373 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1376 $fields = CRM_Contact_DAO_Contact
::export();
1378 // the fields are meant for contact types
1382 array('Individual', 'Household', 'Organization', 'All')
1385 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1387 // add current employer for individuals
1388 $fields = array_merge($fields, array(
1389 'current_employer' =>
1391 'name' => 'organization_name',
1392 'title' => ts('Current Employer'),
1396 $locationType = array(
1397 'location_type' => array(
1398 'name' => 'location_type',
1399 'where' => 'civicrm_location_type.name',
1400 'title' => ts('Location Type'),
1403 $IMProvider = array(
1404 'im_provider' => array(
1405 'name' => 'im_provider',
1406 'where' => 'civicrm_im.provider_id',
1407 'title' => ts('IM Provider'),
1410 $locationFields = array_merge($locationType,
1411 CRM_Core_DAO_Address
::export(),
1412 CRM_Core_DAO_Phone
::export(),
1413 CRM_Core_DAO_Email
::export(),
1415 CRM_Core_DAO_IM
::export(TRUE),
1416 CRM_Core_DAO_OpenID
::export()
1419 $locationFields = array_merge($locationFields,
1420 CRM_Core_BAO_CustomField
::getFieldsForImport('Address')
1423 foreach ($locationFields as $key => $field) {
1424 $locationFields[$key]['hasLocationType'] = TRUE;
1427 $fields = array_merge($fields, $locationFields);
1430 $fields = array_merge($fields,
1431 CRM_Core_DAO_Worldregion
::export()
1435 $fields = array_merge($fields,
1436 CRM_Contact_DAO_Contact
::export()
1440 $fields = array_merge($fields, CRM_Core_DAO_Website
::export());
1442 if ($contactType != 'All') {
1443 $fields = array_merge($fields,
1444 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType, $status, FALSE, $search, TRUE, $withMultiRecord)
1449 'Individual', 'Household', 'Organization') as $type) {
1450 $fields = array_merge($fields,
1451 CRM_Core_BAO_CustomField
::getFieldsForImport($type, FALSE, FALSE, $search, TRUE, $withMultiRecord)
1458 $fields = array_merge($fields, array(
1460 'title' => ts('Group(s)'),
1464 'title' => ts('Tag(s)'),
1468 'title' => ts('Note(s)'),
1474 $fields = array_merge($fields, array(
1476 'title' => ts('Group(s)'),
1480 'title' => ts('Tag(s)'),
1484 'title' => ts('Note(s)'),
1490 //Sorting fields in alphabetical order(CRM-1507)
1491 foreach ($fields as $k => $v) {
1492 $sortArray[$k] = CRM_Utils_Array
::value('title', $v);
1495 $fields = array_merge($sortArray, $fields);
1496 //unset the field which are not related to their contact type.
1497 if ($contactType != 'All') {
1498 $commonValues = array(
1499 'Individual' => array(
1503 'organization_name',
1504 'email_greeting_custom',
1505 'postal_greeting_custom',
1508 'Household' => array(
1518 'organization_name',
1526 'email_greeting_custom',
1527 'postal_greeting_custom',
1532 'Organization' => array(
1543 'email_greeting_custom',
1544 'postal_greeting_custom',
1554 foreach ($commonValues[$contactType] as $value) {
1555 unset($fields[$value]);
1559 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1561 self
::$_exportableFields[$cacheKeyString] = $fields;
1565 $fields = self
::$_exportableFields[$cacheKeyString];
1568 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1569 self
::$_exportableFields[$cacheKeyString]
1577 * Get the all contact details(Hierarchical)
1579 * @param int $contactId contact id
1580 * @param array $fields fields array
1582 * @return $values array contains the contact details
1586 static function getHierContactDetails($contactId, &$fields) {
1587 $params = array(array('contact_id', '=', $contactId, 0, 0));
1590 $returnProperties = self
::makeHierReturnProperties($fields, $contactId);
1592 // we dont know the contents of return properties, but we need the lower level ids of the contact
1593 // so add a few fields
1594 $returnProperties['first_name'] =
1595 $returnProperties['organization_name'] =
1596 $returnProperties['household_name'] =
1597 $returnProperties['contact_type'] =
1598 $returnProperties['contact_sub_type'] = 1;
1599 return list($query, $options) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, $options);
1603 * Given a set of flat profile style field names, create a hierarchy
1604 * for query to use and crete the right sql
1607 * @param int $contactId contact id
1609 * @return array a hierarchical property tree if appropriate
1613 static function &makeHierReturnProperties($fields, $contactId = NULL) {
1614 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1616 $returnProperties = array();
1618 $multipleFields = array('website' => 'url');
1619 foreach ($fields as $name => $dontCare) {
1620 if (strpos($name, '-') !== FALSE) {
1621 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $name, 3);
1623 if (!in_array($fieldName, $multipleFields)) {
1624 if ($id == 'Primary') {
1625 $locationTypeName = 1;
1628 $locationTypeName = CRM_Utils_Array
::value($id, $locationTypes);
1629 if (!$locationTypeName) {
1634 if (empty($returnProperties['location'])) {
1635 $returnProperties['location'] = array();
1637 if (empty($returnProperties['location'][$locationTypeName])) {
1638 $returnProperties['location'][$locationTypeName] = array();
1639 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1641 if (in_array($fieldName, array(
1642 'phone', 'im', 'email', 'openid', 'phone_ext'))) {
1644 $returnProperties['location'][$locationTypeName][$fieldName . '-' . $type] = 1;
1647 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1650 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1651 $returnProperties['location'][$locationTypeName][substr($fieldName, 8)] = 1;
1654 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1658 $returnProperties['website'][$id][$fieldName] = 1;
1662 $returnProperties[$name] = 1;
1666 return $returnProperties;
1670 * Return the primary location type of a contact
1672 * $params int $contactId contact_id
1673 * $params boolean $isPrimaryExist if true, return primary contact location type otherwise null
1674 * $params boolean $skipDefaultPriamry if true, return primary contact location type otherwise null
1676 * @param int $contactId
1677 * @param bool $skipDefaultPriamry
1678 * @param null $block
1680 * @return int $locationType location_type_id
1684 static function getPrimaryLocationType($contactId, $skipDefaultPriamry = FALSE, $block = NULL) {
1686 $entityBlock = array('contact_id' => $contactId);
1687 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock);
1688 foreach($blocks[$block] as $key => $value){
1689 if (!empty($value['is_primary'])){
1690 $locationType = CRM_Utils_Array
::value('location_type_id',$value);
1697 IF ( civicrm_email.location_type_id IS NULL,
1698 IF ( civicrm_address.location_type_id IS NULL,
1699 IF ( civicrm_phone.location_type_id IS NULL,
1700 IF ( civicrm_im.location_type_id IS NULL,
1701 IF ( civicrm_openid.location_type_id IS NULL, null, civicrm_openid.location_type_id)
1702 ,civicrm_im.location_type_id)
1703 ,civicrm_phone.location_type_id)
1704 ,civicrm_address.location_type_id)
1705 ,civicrm_email.location_type_id) as locationType
1706 FROM civicrm_contact
1707 LEFT JOIN civicrm_email ON ( civicrm_email.is_primary = 1 AND civicrm_email.contact_id = civicrm_contact.id )
1708 LEFT JOIN civicrm_address ON ( civicrm_address.is_primary = 1 AND civicrm_address.contact_id = civicrm_contact.id)
1709 LEFT JOIN civicrm_phone ON ( civicrm_phone.is_primary = 1 AND civicrm_phone.contact_id = civicrm_contact.id)
1710 LEFT JOIN civicrm_im ON ( civicrm_im.is_primary = 1 AND civicrm_im.contact_id = civicrm_contact.id)
1711 LEFT JOIN civicrm_openid ON ( civicrm_openid.is_primary = 1 AND civicrm_openid.contact_id = civicrm_contact.id)
1712 WHERE civicrm_contact.id = %1 ";
1714 $params = array(1 => array($contactId, 'Integer'));
1716 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1718 $locationType = NULL;
1719 if ($dao->fetch()) {
1720 $locationType = $dao->locationType
;
1723 if (isset($locationType)) {
1724 return $locationType;
1726 elseif ($skipDefaultPriamry) {
1727 // if there is no primary contact location then return null
1731 // if there is no primart contact location, then return default
1732 // location type of the system
1733 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
1734 return $defaultLocationType->id
;
1739 * Get the display name, primary email and location type of a contact
1741 * @param int $id id of the contact
1743 * @return array of display_name, email if found, do_not_email or (null,null,null)
1747 static function getContactDetails($id) {
1748 // check if the contact type
1749 $contactType = self
::getContactType($id);
1751 $nameFields = ($contactType == 'Individual') ?
"civicrm_contact.first_name, civicrm_contact.last_name, civicrm_contact.display_name" : "civicrm_contact.display_name";
1754 SELECT $nameFields, civicrm_email.email, civicrm_contact.do_not_email, civicrm_email.on_hold, civicrm_contact.is_deceased
1755 FROM civicrm_contact LEFT JOIN civicrm_email ON (civicrm_contact.id = civicrm_email.contact_id)
1756 WHERE civicrm_contact.id = %1
1757 ORDER BY civicrm_email.is_primary DESC";
1758 $params = array(1 => array($id, 'Integer'));
1759 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
1761 if ($dao->fetch()) {
1762 if ($contactType == 'Individual') {
1763 if ($dao->first_name ||
$dao->last_name
) {
1764 $name = "{$dao->first_name} {$dao->last_name}";
1767 $name = $dao->display_name
;
1771 $name = $dao->display_name
;
1773 $email = $dao->email
;
1774 $doNotEmail = $dao->do_not_email ?
TRUE : FALSE;
1775 $onHold = $dao->on_hold ?
TRUE : FALSE;
1776 $isDeceased = $dao->is_deceased ?
TRUE : FALSE;
1777 return array($name, $email, $doNotEmail, $onHold, $isDeceased);
1779 return array(NULL, NULL, NULL, NULL, NULL);
1783 * Add/edit/register contacts through profile.
1785 * @param array $params Array of profile fields to be edited/added.
1786 * @param array $fields Array of fields from UFGroup
1787 * @param int $contactID id of the contact to be edited/added.
1788 * @param int $addToGroupID specifies the default group to which contact is added.
1789 * @param int $ufGroupId uf group id (profile id)
1791 * @param boolean $visibility basically lets us know where this request is coming from
1792 * if via a profile from web, we restrict what groups are changed
1794 * @return int contact id created/edited
1798 static function createProfileContact(
1802 $addToGroupID = NULL,
1807 // add ufGroupID to params array ( CRM-2012 )
1809 $params['uf_group_id'] = $ufGroupId;
1814 CRM_Utils_Hook
::pre('edit', 'Profile', $contactID, $params);
1818 CRM_Utils_Hook
::pre('create', 'Profile', NULL, $params);
1821 list($data, $contactDetails) = self
::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
1823 // manage is_opt_out
1824 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
1825 $wasOptOut = CRM_Utils_Array
::value('is_opt_out', $contactDetails, FALSE);
1826 $isOptOut = CRM_Utils_Array
::value('is_opt_out', $params, FALSE);
1827 $data['is_opt_out'] = $isOptOut;
1828 // on change, create new civicrm_subscription_history entry
1829 if (($wasOptOut != $isOptOut) && !empty($contactDetails['contact_id'])) {
1831 'contact_id' => $contactDetails['contact_id'],
1832 'status' => $isOptOut ?
'Removed' : 'Added',
1835 CRM_Contact_BAO_SubscriptionHistory
::create($shParams);
1839 $contact = self
::create($data);
1841 // contact is null if the profile does not have any contact fields
1843 $contactID = $contact->id
;
1846 if (empty($contactID)) {
1847 CRM_Core_Error
::fatal('Cannot proceed without a valid contact id');
1850 // Process group and tag
1851 if (!empty($fields['group'])) {
1853 // this for sure means we are coming in via profile since i added it to fix
1854 // removing contacts from user groups -- lobo
1858 CRM_Contact_BAO_GroupContact
::create($params['group'], $contactID, $visibility, $method);
1861 if (!empty($fields['tag'])) {
1862 CRM_Core_BAO_EntityTag
::create($params['tag'], 'civicrm_contact', $contactID);
1865 //to add profile in default group
1866 if (is_array($addToGroupID)) {
1867 $contactIds = array($contactID);
1868 foreach ($addToGroupID as $groupId) {
1869 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
1872 elseif ($addToGroupID) {
1873 $contactIds = array($contactID);
1874 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $addToGroupID);
1877 // reset the group contact cache for this group
1878 CRM_Contact_BAO_GroupContactCache
::remove();
1881 CRM_Utils_Hook
::post('edit', 'Profile', $contactID, $params);
1884 CRM_Utils_Hook
::post('create', 'Profile', $contactID, $params);
1890 * @param array $params
1892 * @param int $contactID
1893 * @param int $ufGroupId
1894 * @param null $ctype
1895 * @param bool $skipCustom
1899 static function formatProfileContactParams(
1908 $data = $contactDetails = array();
1910 // get the contact details (hier)
1912 list($details, $options) = self
::getHierContactDetails($contactID, $fields);
1914 $contactDetails = $details[$contactID];
1915 $data['contact_type'] = CRM_Utils_Array
::value('contact_type', $contactDetails);
1916 $data['contact_sub_type'] = CRM_Utils_Array
::value('contact_sub_type', $contactDetails);
1919 //we should get contact type only if contact
1921 $data['contact_type'] = CRM_Core_BAO_UFField
::getProfileType($ufGroupId);
1923 //special case to handle profile with only contact fields
1924 if ($data['contact_type'] == 'Contact') {
1925 $data['contact_type'] = 'Individual';
1927 elseif (CRM_Contact_BAO_ContactType
::isaSubType($data['contact_type'])) {
1928 $data['contact_type'] = CRM_Contact_BAO_ContactType
::getBasicType($data['contact_type']);
1932 $data['contact_type'] = $ctype;
1935 $data['contact_type'] = 'Individual';
1939 //fix contact sub type CRM-5125
1940 if (array_key_exists('contact_sub_type', $params) &&
1941 !empty($params['contact_sub_type'])
1943 $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
;
1945 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
1946 !empty($params['contact_sub_type_hidden'])
1948 // if profile was used, and had any subtype, we obtain it from there
1949 $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
;
1952 if ($ctype == 'Organization') {
1953 $data['organization_name'] = CRM_Utils_Array
::value('organization_name', $contactDetails);
1955 elseif ($ctype == 'Household') {
1956 $data['household_name'] = CRM_Utils_Array
::value('household_name', $contactDetails);
1959 $locationType = array();
1964 $data['contact_id'] = $contactID;
1965 $primaryLocationType = self
::getPrimaryLocationType($contactID);
1968 $defaultLocation = CRM_Core_BAO_LocationType
::getDefault();
1969 $defaultLocationId = $defaultLocation->id
;
1972 // get the billing location type
1973 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
1974 $billingLocationTypeId = array_search('Billing', $locationTypes);
1976 $blocks = array('email', 'phone', 'im', 'openid');
1978 $multiplFields = array('url');
1979 // prevent overwritten of formatted array, reset all block from
1980 // params if it is not in valid format (since import pass valid format)
1981 foreach ($blocks as $blk) {
1982 if (array_key_exists($blk, $params) &&
1983 !is_array($params[$blk])
1985 unset($params[$blk]);
1989 $primaryPhoneLoc = NULL;
1990 $session = CRM_Core_Session
::singleton();
1991 foreach ($params as $key => $value) {
1992 $fieldName = $locTypeId = $typeId = NULL;
1993 list($fieldName, $locTypeId, $typeId) = CRM_Utils_System
::explode('-', $key, 3);
1995 //store original location type id
1996 $actualLocTypeId = $locTypeId;
1998 if ($locTypeId == 'Primary') {
2000 if(in_array( $fieldName, $blocks)){
2001 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, $fieldName);
2004 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, 'address');
2006 $primaryLocationType = $locTypeId;
2009 $locTypeId = $defaultLocationId;
2013 if (is_numeric($locTypeId) &&
2014 !in_array($fieldName, $multiplFields) &&
2015 substr($fieldName, 0, 7) != 'custom_'
2017 $index = $locTypeId;
2019 if (is_numeric($typeId)) {
2020 $index .= '-' . $typeId;
2022 if (!in_array($index, $locationType)) {
2023 $locationType[$count] = $index;
2027 $loc = CRM_Utils_Array
::key($index, $locationType);
2029 $blockName = in_array( $fieldName, $blocks) ?
$fieldName : 'address';
2031 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
2033 //set is_billing true, for location type "Billing"
2034 if ($locTypeId == $billingLocationTypeId) {
2035 $data[$blockName][$loc]['is_billing'] = 1;
2039 //get the primary location type
2040 if ($locTypeId == $primaryLocationType) {
2041 $data[$blockName][$loc]['is_primary'] = 1;
2044 elseif ($locTypeId == $defaultLocationId) {
2045 $data[$blockName][$loc]['is_primary'] = 1;
2048 if ( in_array($fieldName, array('phone'))) {
2050 $data['phone'][$loc]['phone_type_id'] = $typeId;
2053 $data['phone'][$loc]['phone_type_id'] = '';
2055 $data['phone'][$loc]['phone'] = $value;
2057 //special case to handle primary phone with different phone types
2058 // in this case we make first phone type as primary
2059 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
2060 $primaryPhoneLoc = $loc;
2063 if ($loc != $primaryPhoneLoc) {
2064 unset($data['phone'][$loc]['is_primary']);
2067 elseif ($fieldName == 'phone_ext') {
2068 $data['phone'][$loc]['phone_ext'] = $value;
2070 elseif ($fieldName == 'email') {
2071 $data['email'][$loc]['email'] = $value;
2073 elseif ($fieldName == 'im') {
2074 if (isset($params[$key . '-provider_id'])) {
2075 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
2077 if (strpos($key, '-provider_id') !== FALSE) {
2078 $data['im'][$loc]['provider_id'] = $params[$key];
2081 $data['im'][$loc]['name'] = $value;
2084 elseif ($fieldName == 'openid') {
2085 $data['openid'][$loc]['openid'] = $value;
2088 if ($fieldName === 'state_province') {
2090 if (is_numeric($value) && ((int ) $value) >= 1000) {
2091 $data['address'][$loc]['state_province_id'] = $value;
2093 elseif (empty($value)) {
2094 $data['address'][$loc]['state_province_id'] = '';
2097 $data['address'][$loc]['state_province'] = $value;
2100 elseif ($fieldName === 'country') {
2102 if (is_numeric($value) && ((int ) $value) >= 1000
2104 $data['address'][$loc]['country_id'] = $value;
2106 elseif (empty($value)) {
2107 $data['address'][$loc]['country_id'] = '';
2110 $data['address'][$loc]['country'] = $value;
2113 elseif ($fieldName === 'county') {
2114 $data['address'][$loc]['county_id'] = $value;
2116 elseif ($fieldName == 'address_name') {
2117 $data['address'][$loc]['name'] = $value;
2119 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2120 $data['address'][$loc][substr($fieldName, 8)] = $value;
2123 $data['address'][$loc][$fieldName] = $value;
2128 if (substr($key, 0, 4) === 'url-') {
2129 $websiteField = explode('-', $key);
2130 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
2131 $data['website'][$websiteField[1]]['url'] = $value;
2133 elseif (in_array($key, self
::$_greetingTypes, TRUE)) {
2134 //save email/postal greeting and addressee values if any, CRM-4575
2135 $data[$key . '_id'] = $value;
2137 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($key))) {
2138 // for autocomplete transfer hidden value instead of label
2139 if ($params[$key] && isset($params[$key . '_id'])) {
2140 $value = $params[$key . '_id'];
2143 // we need to append time with date
2144 if ($params[$key] && isset($params[$key . '_time'])) {
2145 $value .= ' ' . $params[$key . '_time'];
2148 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
2149 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 &&
2150 ($value == '' ||
!isset($value))) {
2155 if (!empty($params['customRecordValues'])) {
2156 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2157 foreach ($params['customRecordValues'] as $recId => $customFields) {
2158 if (is_array($customFields) && !empty($customFields)) {
2159 foreach ($customFields as $customFieldName) {
2160 if ($customFieldName == $key) {
2170 $type = $data['contact_type'];
2171 if (!empty($data['contact_sub_type'])) {
2172 $type = $data['contact_sub_type'];
2173 $type = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($type, CRM_Core_DAO
::VALUE_SEPARATOR
));
2174 // generally a contact even if, has multiple subtypes the parent-type is going to be one only
2175 // and since formatCustomField() would be interested in parent type, lets consider only one subtype
2176 // as the results going to be same.
2180 CRM_Core_BAO_CustomField
::formatCustomField($customFieldId,
2188 elseif ($key == 'edit') {
2192 if ($key == 'location') {
2193 foreach ($value as $locationTypeId => $field) {
2194 foreach ($field as $block => $val) {
2195 if ($block == 'address' && array_key_exists('address_name', $val)) {
2196 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2201 if($key == 'phone' && isset($params['phone_ext'])){
2202 $data[$key] = $value;
2203 foreach($value as $cnt => $phoneBlock){
2204 if($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']){
2205 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array
::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2209 else if (in_array($key,
2218 ($value == '' ||
!isset($value)) &&
2219 ($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0) {
2220 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
2221 // to avoid update with empty values
2225 $data[$key] = $value;
2231 if (!isset($data['contact_type'])) {
2232 $data['contact_type'] = 'Individual';
2235 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2236 $privacy = CRM_Core_SelectValues
::privacy();
2237 foreach ($privacy as $key => $value) {
2238 if (array_key_exists($key, $fields)) {
2239 // do not reset values for existing contacts, if fields are added to a profile
2240 if (array_key_exists($key, $params)) {
2241 $data[$key] = $params[$key];
2242 if (empty($params[$key])) {
2246 elseif (!$contactID) {
2252 return array($data, $contactDetails);
2256 * Find the get contact details
2257 * does not respect ACLs for now, which might need to be rectified at some
2258 * stage based on how its used
2260 * @param string $mail primary email address of the contact
2261 * @param string $ctype contact type
2263 * @return object $dao contact details
2266 static function &matchContactOnEmail($mail, $ctype = NULL) {
2267 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2268 $mail = $strtolower(trim($mail));
2270 SELECT civicrm_contact.id as contact_id,
2271 civicrm_contact.hash as hash,
2272 civicrm_contact.contact_type as contact_type,
2273 civicrm_contact.contact_sub_type as contact_sub_type
2274 FROM civicrm_contact
2275 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2278 if (CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
2279 'uniq_email_per_site'
2281 // try to find a match within a site (multisite).
2282 $groups = CRM_Core_BAO_Domain
::getChildGroupIds();
2283 if (!empty($groups)) {
2285 INNER JOIN civicrm_group_contact gc ON
2286 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2291 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2292 $p = array(1 => array($mail, 'String'));
2295 $query .= " AND civicrm_contact.contact_type = %3";
2296 $p[3] = array($ctype, 'String');
2299 $query .= " ORDER BY civicrm_email.is_primary DESC";
2301 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2303 if ($dao->fetch()) {
2306 return CRM_Core_DAO
::$_nullObject;
2310 * Find the contact details associated with an OpenID
2312 * @param string $openId openId of the contact
2313 * @param string $ctype contact type
2315 * @return object $dao contact details
2318 static function &matchContactOnOpenId($openId, $ctype = NULL) {
2319 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2320 $openId = $strtolower(trim($openId));
2322 SELECT civicrm_contact.id as contact_id,
2323 civicrm_contact.hash as hash,
2324 civicrm_contact.contact_type as contact_type,
2325 civicrm_contact.contact_sub_type as contact_sub_type
2326 FROM civicrm_contact
2327 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2328 WHERE civicrm_openid.openid = %1";
2329 $p = array(1 => array($openId, 'String'));
2332 $query .= " AND civicrm_contact.contact_type = %3";
2333 $p[3] = array($ctype, 'String');
2336 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2338 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2340 if ($dao->fetch()) {
2343 return CRM_Core_DAO
::$_nullObject;
2347 * Funtion to get primary email of the contact
2349 * @param int $contactID contact id
2351 * @return string $dao->email email address if present else null
2355 public static function getPrimaryEmail($contactID) {
2356 // fetch the primary email
2358 SELECT civicrm_email.email as email
2359 FROM civicrm_contact
2360 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2361 WHERE civicrm_email.is_primary = 1
2362 AND civicrm_contact.id = %1";
2363 $p = array(1 => array($contactID, 'Integer'));
2364 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2367 if ($dao->fetch()) {
2368 $email = $dao->email
;
2375 * Funtion to get primary OpenID of the contact
2377 * @param int $contactID contact id
2379 * @return string $dao->openid OpenID if present else null
2383 public static function getPrimaryOpenId($contactID) {
2384 // fetch the primary OpenID
2386 SELECT civicrm_openid.openid as openid
2387 FROM civicrm_contact
2388 LEFT JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2389 WHERE civicrm_contact.id = %1
2390 AND civicrm_openid.is_primary = 1";
2391 $p = array(1 => array($contactID, 'Integer'));
2392 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2395 if ($dao->fetch()) {
2396 $openId = $dao->openid
;
2403 * Given the list of params in the params array, fetch the object
2404 * and store the values in the values array
2406 * @param array $params input parameters to find object
2407 * @param array $values output values of the object
2409 * @return CRM_Contact_BAO_Contact|null the found object or null
2413 public static function getValues(&$params, &$values) {
2414 $contact = new CRM_Contact_BAO_Contact();
2416 $contact->copyValues($params);
2418 if ($contact->find(TRUE)) {
2420 CRM_Core_DAO
::storeValues($contact, $values);
2423 foreach (self
::$_commPrefs as $name) {
2424 if (isset($contact->$name)) {
2425 $privacy[$name] = $contact->$name;
2429 if (!empty($privacy)) {
2430 $values['privacy'] = $privacy;
2433 // communication Prefferance
2434 $preffComm = $comm = array();
2435 $comm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2436 $contact->preferred_communication_method
2438 foreach ($comm as $value) {
2439 $preffComm[$value] = 1;
2441 $temp = array('preferred_communication_method' => $contact->preferred_communication_method
);
2444 'preferred_communication_method' => array('newName' => 'preferred_communication_method_display',
2445 'groupName' => 'preferred_communication_method',
2448 CRM_Core_OptionGroup
::lookupValues($temp, $names, FALSE);
2450 $values['preferred_communication_method'] = $preffComm;
2451 $values['preferred_communication_method_display'] = CRM_Utils_Array
::value('preferred_communication_method_display', $temp);
2453 $preferredMailingFormat = CRM_Core_SelectValues
::pmf();
2454 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format
];
2456 // get preferred languages
2457 if (!empty($contact->preferred_language
)) {
2458 $values['preferred_language'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language
);
2461 // Calculating Year difference
2462 if ($contact->birth_date
) {
2463 $birthDate = CRM_Utils_Date
::customFormat($contact->birth_date
, '%Y%m%d');
2464 if ($birthDate < date('Ymd')) {
2465 $age = CRM_Utils_Date
::calculateAge($birthDate);
2466 $values['age']['y'] = CRM_Utils_Array
::value('years', $age);
2467 $values['age']['m'] = CRM_Utils_Array
::value('months', $age);
2470 list($values['birth_date']) = CRM_Utils_Date
::setDateDefaults($contact->birth_date
, 'birth');
2471 $values['birth_date_display'] = $contact->birth_date
;
2474 if ($contact->deceased_date
) {
2475 list($values['deceased_date']) = CRM_Utils_Date
::setDateDefaults($contact->deceased_date
, 'birth');
2476 $values['deceased_date_display'] = $contact->deceased_date
;
2479 $contact->contact_id
= $contact->id
;
2487 * Given the component name and returns
2488 * the count of participation of contact
2490 * @param string $component input component name
2491 * @param integer $contactId input contact id
2492 * @param string $tableName optional tableName if component is custom group
2494 * @return total number of count of occurence in database
2498 static function getCountComponent($component, $contactId, $tableName = NULL) {
2500 switch ($component) {
2502 return CRM_Core_BAO_EntityTag
::getContactTags($contactId, TRUE);
2505 return CRM_Contact_BAO_Relationship
::getRelationship($contactId,
2506 CRM_Contact_BAO_Relationship
::CURRENT
,
2511 return CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, "Added", NULL, TRUE);
2514 if (CRM_Core_BAO_Log
::useLoggingReport()) {
2517 return CRM_Core_BAO_Log
::getContactLogCount($contactId);
2520 return CRM_Core_BAO_Note
::getContactNoteCount($contactId);
2522 case 'contribution':
2523 return CRM_Contribute_BAO_Contribution
::contributionCount($contactId);
2526 return CRM_Member_BAO_Membership
::getContactMembershipCount($contactId, TRUE);
2529 return CRM_Event_BAO_Participant
::getContactParticipantCount($contactId);
2532 return CRM_Pledge_BAO_Pledge
::getContactPledgeCount($contactId);
2535 return CRM_Case_BAO_Case
::caseCount($contactId);
2538 return CRM_Grant_BAO_Grant
::getContactGrantCount($contactId);
2542 'contact_id' => $contactId,
2545 'context' => 'activity',
2547 return CRM_Activity_BAO_Activity
::getActivitiesCount($input);
2550 $params = array('contact_id' => $contactId);
2551 return CRM_Mailing_BAO_Mailing
::getContactMailingsCount($params);
2554 $custom = explode('_', $component);
2555 if ($custom['0'] = 'custom') {
2557 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2559 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2560 return CRM_Core_DAO
::singleValueQuery($queryString);
2566 * Process greetings and cache
2568 * @param object $contact contact object after save
2569 * @param boolean $useDefaults use default greeting values
2575 static function processGreetings(&$contact, $useDefaults = FALSE) {
2577 //retrieve default greetings
2578 $defaultGreetings = CRM_Core_PseudoConstant
::greetingDefaults();
2579 $contactDefaults = $defaultGreetings[$contact->contact_type
];
2582 // note that contact object not always has required greeting related
2583 // fields that are required to calculate greeting and
2584 // also other fields used in tokens etc,
2585 // hence we need to retrieve it again.
2586 if ( $contact->_query
!== FALSE ) {
2587 $contact->find(TRUE);
2590 // store object values to an array
2591 $contactDetails = array();
2592 CRM_Core_DAO
::storeValues($contact, $contactDetails);
2593 $contactDetails = array(array($contact->id
=> $contactDetails));
2595 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2596 $updateQueryString = array();
2598 //cache email and postal greeting to greeting display
2599 if ($contact->email_greeting_custom
!= 'null' && $contact->email_greeting_custom
) {
2600 $emailGreetingString = $contact->email_greeting_custom
;
2602 elseif ($contact->email_greeting_id
!= 'null' && $contact->email_greeting_id
) {
2603 // the filter value for Individual contact type is set to 1
2605 'contact_type' => $contact->contact_type
,
2606 'greeting_type' => 'email_greeting',
2609 $emailGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2610 $emailGreetingString = $emailGreeting[$contact->email_greeting_id
];
2611 $updateQueryString[] = " email_greeting_custom = NULL ";
2615 reset($contactDefaults['email_greeting']);
2616 $emailGreetingID = key($contactDefaults['email_greeting']);
2617 $emailGreetingString = $contactDefaults['email_greeting'][$emailGreetingID];
2618 $updateQueryString[] = " email_greeting_id = $emailGreetingID ";
2619 $updateQueryString[] = " email_greeting_custom = NULL ";
2621 elseif ($contact->email_greeting_custom
) {
2622 $updateQueryString[] = " email_greeting_display = NULL ";
2626 if ($emailGreetingString) {
2627 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($emailGreetingString,
2630 'CRM_Contact_BAO_Contact'
2632 $emailGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($emailGreetingString));
2633 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2637 if ($contact->postal_greeting_custom
!= 'null' && $contact->postal_greeting_custom
) {
2638 $postalGreetingString = $contact->postal_greeting_custom
;
2640 elseif ($contact->postal_greeting_id
!= 'null' && $contact->postal_greeting_id
) {
2642 'contact_type' => $contact->contact_type
,
2643 'greeting_type' => 'postal_greeting',
2645 $postalGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2646 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id
];
2647 $updateQueryString[] = " postal_greeting_custom = NULL ";
2651 reset($contactDefaults['postal_greeting']);
2652 $postalGreetingID = key($contactDefaults['postal_greeting']);
2653 $postalGreetingString = $contactDefaults['postal_greeting'][$postalGreetingID];
2654 $updateQueryString[] = " postal_greeting_id = $postalGreetingID ";
2655 $updateQueryString[] = " postal_greeting_custom = NULL ";
2657 elseif ($contact->postal_greeting_custom
) {
2658 $updateQueryString[] = " postal_greeting_display = NULL ";
2662 if ($postalGreetingString) {
2663 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($postalGreetingString,
2666 'CRM_Contact_BAO_Contact'
2668 $postalGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($postalGreetingString));
2669 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2673 if ($contact->addressee_custom
!= 'null' && $contact->addressee_custom
) {
2674 $addresseeString = $contact->addressee_custom
;
2676 elseif ($contact->addressee_id
!= 'null' && $contact->addressee_id
) {
2678 'contact_type' => $contact->contact_type
,
2679 'greeting_type' => 'addressee',
2682 $addressee = CRM_Core_PseudoConstant
::greeting($filter);
2683 $addresseeString = $addressee[$contact->addressee_id
];
2684 $updateQueryString[] = " addressee_custom = NULL ";
2688 reset($contactDefaults['addressee']);
2689 $addresseeID = key($contactDefaults['addressee']);
2690 $addresseeString = $contactDefaults['addressee'][$addresseeID];
2691 $updateQueryString[] = " addressee_id = $addresseeID ";
2692 $updateQueryString[] = " addressee_custom = NULL ";
2694 elseif ($contact->addressee_custom
) {
2695 $updateQueryString[] = " addressee_display = NULL ";
2699 if ($addresseeString) {
2700 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($addresseeString,
2703 'CRM_Contact_BAO_Contact'
2705 $addresseeString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($addresseeString));
2706 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2709 if (!empty($updateQueryString)) {
2710 $updateQueryString = implode(',', $updateQueryString);
2711 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2712 CRM_Core_DAO
::executeQuery($queryString);
2717 * Retrieve loc block ids w/ given condition.
2719 * @param int $contactId contact id.
2720 * @param array $criteria key => value pair which should be
2721 * fulfill by return record ids.
2722 * @param string $condOperator operator use for grouping multiple conditions.
2724 * @return array $locBlockIds loc block ids which fulfill condition.
2727 static function getLocBlockIds($contactId, $criteria = array(), $condOperator = 'AND') {
2728 $locBlockIds = array();
2730 return $locBlockIds;
2733 foreach (array('Email', 'OpenID', 'Phone', 'Address', 'IM') as $block) {
2734 $name = strtolower($block);
2735 $className = "CRM_Core_DAO_$block";
2736 $blockDAO = new $className();
2738 // build the condition.
2739 if (is_array($criteria)) {
2740 $fields = $blockDAO->fields();
2741 $conditions = array();
2742 foreach ($criteria as $field => $value) {
2743 if (array_key_exists($field, $fields)) {
2744 $cond = "( $field = $value )";
2745 // value might be zero or null.
2746 if (!$value ||
strtolower($value) == 'null') {
2747 $cond = "( $field = 0 OR $field IS NULL )";
2749 $conditions[] = $cond;
2752 if (!empty($conditions)) {
2753 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2757 $blockDAO->contact_id
= $contactId;
2759 while ($blockDAO->fetch()) {
2760 $locBlockIds[$name][] = $blockDAO->id
;
2765 return $locBlockIds;
2769 * Build context menu items.
2771 * @param int $contactId
2773 * @return array of context menu for logged in user.
2776 static function contextMenu($contactId = NULL) {
2779 'title' => ts('View Contact'),
2781 'ref' => 'view-contact',
2782 'class' => 'no-popup',
2784 'permissions' => array('view all contacts'),
2787 'title' => ts('Edit Contact'),
2789 'ref' => 'edit-contact',
2790 'class' => 'no-popup',
2792 'permissions' => array('edit all contacts'),
2795 'title' => ts('Delete Contact'),
2797 'ref' => 'delete-contact',
2799 'permissions' => array('access deleted contacts', 'delete contacts'),
2801 'contribution' => array(
2802 'title' => ts('Add Contribution'),
2804 'ref' => 'new-contribution',
2805 'key' => 'contribution',
2806 'tab' => 'contribute',
2807 'component' => 'CiviContribute',
2808 'href' => CRM_Utils_System
::url('civicrm/contact/view/contribution',
2809 'reset=1&action=add&context=contribution'
2811 'permissions' => array(
2812 'access CiviContribute',
2813 'edit contributions',
2816 'participant' => array(
2817 'title' => ts('Register for Event'),
2819 'ref' => 'new-participant',
2820 'key' => 'participant',
2821 'tab' => 'participant',
2822 'component' => 'CiviEvent',
2823 'href' => CRM_Utils_System
::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
2824 'permissions' => array(
2826 'edit event participants',
2829 'activity' => array(
2830 'title' => ts('Record Activity'),
2832 'ref' => 'new-activity',
2833 'key' => 'activity',
2834 'permissions' => array('edit all contacts'),
2837 'title' => ts('Add Pledge'),
2839 'ref' => 'new-pledge',
2842 'href' => CRM_Utils_System
::url('civicrm/contact/view/pledge',
2843 'reset=1&action=add&context=pledge'
2845 'component' => 'CiviPledge',
2846 'permissions' => array(
2847 'access CiviPledge',
2851 'membership' => array(
2852 'title' => ts('Add Membership'),
2854 'ref' => 'new-membership',
2855 'key' => 'membership',
2857 'component' => 'CiviMember',
2858 'href' => CRM_Utils_System
::url('civicrm/contact/view/membership',
2859 'reset=1&action=add&context=membership'
2861 'permissions' => array(
2862 'access CiviMember',
2867 'title' => ts('Add Case'),
2869 'ref' => 'new-case',
2872 'component' => 'CiviCase',
2873 'href' => CRM_Utils_System
::url('civicrm/case/add', 'reset=1&action=add&context=case'),
2874 'permissions' => array('add cases'),
2877 'title' => ts('Add Grant'),
2879 'ref' => 'new-grant',
2882 'component' => 'CiviGrant',
2883 'href' => CRM_Utils_System
::url('civicrm/contact/view/grant',
2884 'reset=1&action=add&context=grant'
2886 'permissions' => array('edit grants'),
2889 'title' => ts('Add Relationship'),
2891 'ref' => 'new-relationship',
2894 'href' => CRM_Utils_System
::url('civicrm/contact/view/rel',
2895 'reset=1&action=add'
2897 'permissions' => array('edit all contacts'),
2900 'title' => ts('Add Note'),
2902 'ref' => 'new-note',
2905 'class' => 'medium-popup',
2906 'href' => CRM_Utils_System
::url('civicrm/contact/view/note',
2907 'reset=1&action=add'
2909 'permissions' => array('edit all contacts'),
2912 'title' => ts('Send an Email'),
2914 'ref' => 'new-email',
2916 'permissions' => array('view all contacts'),
2919 'title' => ts('Add to Group'),
2921 'ref' => 'group-add-contact',
2924 'permissions' => array('edit groups'),
2927 'title' => ts('Tag Contact'),
2929 'ref' => 'tag-contact',
2932 'permissions' => array('edit all contacts'),
2936 CRM_Utils_Hook
::summaryActions($menu, $contactId);
2937 //1. check for component is active.
2938 //2. check for user permissions.
2939 //3. check for acls.
2940 //3. edit and view contact are directly accessible to user.
2942 $aclPermissionedTasks = array(
2943 'view-contact', 'edit-contact', 'new-activity',
2944 'new-email', 'group-add-contact', 'tag-contact', 'delete-contact',
2946 $corePermission = CRM_Core_Permission
::getPermission();
2948 $config = CRM_Core_Config
::singleton();
2950 $contextMenu = array();
2951 foreach ($menu as $key => $values) {
2952 $componentName = CRM_Utils_Array
::value('component', $values);
2954 // if component action - make sure component is enable.
2955 if ($componentName && !in_array($componentName, $config->enableComponents
)) {
2959 // make sure user has all required permissions.
2960 $hasAllPermissions = FALSE;
2962 $permissions = CRM_Utils_Array
::value('permissions', $values);
2963 if (!is_array($permissions) ||
empty($permissions)) {
2964 $hasAllPermissions = TRUE;
2967 // iterate for required permissions in given permissions array.
2968 if (!$hasAllPermissions) {
2969 $hasPermissions = 0;
2970 foreach ($permissions as $permission) {
2971 if (CRM_Core_Permission
::check($permission)) {
2976 if (count($permissions) == $hasPermissions) {
2977 $hasAllPermissions = TRUE;
2980 // if still user does not have required permissions, check acl.
2981 if (!$hasAllPermissions && $values['ref'] != 'delete-contact') {
2982 if (in_array($values['ref'], $aclPermissionedTasks) &&
2983 $corePermission == CRM_Core_Permission
::EDIT
2985 $hasAllPermissions = TRUE;
2987 elseif (in_array($values['ref'], array(
2989 // grant permissions for these tasks.
2990 $hasAllPermissions = TRUE;
2995 // user does not have necessary permissions.
2996 if (!$hasAllPermissions) {
3000 // build directly accessible action menu.
3001 if (in_array($values['ref'], array(
3002 'view-contact', 'edit-contact'))) {
3003 $contextMenu['primaryActions'][$key] = array(
3004 'title' => $values['title'],
3005 'ref' => $values['ref'],
3006 'class' => CRM_Utils_Array
::value('class', $values),
3007 'key' => $values['key'],
3012 // finally get menu item for -more- action widget.
3013 $contextMenu['moreActions'][$values['weight']] = array(
3014 'title' => $values['title'],
3015 'ref' => $values['ref'],
3016 'href' => CRM_Utils_Array
::value('href', $values),
3017 'tab' => CRM_Utils_Array
::value('tab', $values),
3018 'class' => CRM_Utils_Array
::value('class', $values),
3019 'key' => $values['key'],
3023 ksort($contextMenu['moreActions']);
3025 return $contextMenu;
3029 * Retrieve display name of contact that address is shared
3030 * based on $masterAddressId or $contactId .
3032 * @param int $masterAddressId master id.
3033 * @param int $contactId contact id.
3035 * @return display name |null the found display name or null.
3039 static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3040 $masterDisplayName = NULL;
3042 if (!$masterAddressId && !$contactId) {
3043 return $masterDisplayName;
3046 if ($masterAddressId) {
3048 SELECT display_name from civicrm_contact
3049 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3050 WHERE civicrm_address.id = " . $masterAddressId;
3052 elseif ($contactId) {
3054 SELECT display_name from civicrm_contact cc, civicrm_address add1
3055 LEFT JOIN civicrm_address add2 ON ( add1.master_id = add2.id )
3056 WHERE cc.id = add2.contact_id AND add1.contact_id = " . $contactId;
3059 $masterDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
3060 return $masterDisplayName;
3064 * Get the creation/modification times for a contact
3066 * @param int $contactId
3068 * @return array('created_date' => $, 'modified_date' => $)
3070 static function getTimestamps($contactId) {
3071 $timestamps = CRM_Core_DAO
::executeQuery(
3072 'SELECT created_date, modified_date
3073 FROM civicrm_contact
3076 1 => array($contactId, 'Integer'),
3079 if ($timestamps->fetch()) {
3081 'created_date' => $timestamps->created_date
,
3082 'modified_date' => $timestamps->modified_date
,
3091 * Generate triggers to update the timestamp on the corresponding civicrm_contact row,
3092 * on insert/update/delete to a table that extends civicrm_contact.
3093 * Don't regenerate triggers for all such tables if only asked for one table.
3095 * @param array $info
3096 * Reference to the array where generated trigger information is being stored
3097 * @param string|null $reqTableName
3098 * Name of the table for which triggers are being generated, or NULL if all tables
3099 * @param array $relatedTableNames
3100 * Array of all core or all custom table names extending civicrm_contact
3101 * @param string $contactRefColumn
3102 * 'contact_id' if processing core tables, 'entity_id' if processing custom tables
3105 * @link https://issues.civicrm.org/jira/browse/CRM-15602
3110 static function generateTimestampTriggers(&$info, $reqTableName, $relatedTableNames, $contactRefColumn) {
3112 $contactRefColumn = CRM_Core_DAO
::escapeString($contactRefColumn);
3113 // If specific related table requested, just process that one
3114 if (in_array($reqTableName, $relatedTableNames)) {
3115 $relatedTableNames = array($reqTableName);
3118 // If no specific table requested (include all related tables),
3119 // or a specific related table requested (as matched above)
3120 if (empty($reqTableName) ||
in_array($reqTableName, $relatedTableNames)) {
3122 'table' => $relatedTableNames,
3124 'event' => array('INSERT', 'UPDATE'),
3125 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = NEW.$contactRefColumn;\n",
3128 'table' => $relatedTableNames,
3130 'event' => array('DELETE'),
3131 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = OLD.$contactRefColumn;\n",
3137 * Get a list of triggers for the contact table
3139 * @see hook_civicrm_triggerInfo
3140 * @see CRM_Core_DAO::triggerRebuild
3141 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3143 static function triggerInfo(&$info, $tableName = NULL) {
3144 //during upgrade, first check for valid version and then create triggers
3145 //i.e the columns created_date and modified_date are introduced in 4.3.alpha1 so dont create triggers for older version
3146 if (CRM_Core_Config
::isUpgradeMode()) {
3147 $currentVer = CRM_Core_BAO_Domain
::version(TRUE);
3148 //if current version is less than 4.3.alpha1 dont create below triggers
3149 if (version_compare($currentVer, '4.3.alpha1') < 0) {
3154 // Update timestamp for civicrm_contact itself
3155 if ($tableName == NULL ||
$tableName == self
::getTableName()) {
3157 'table' => array(self
::getTableName()),
3159 'event' => array('INSERT'),
3160 'sql' => "\nSET NEW.created_date = CURRENT_TIMESTAMP;\n",
3164 // Update timestamp when modifying closely related core tables
3165 $relatedTables = array(
3172 self
::generateTimestampTriggers($info, $tableName, $relatedTables, 'contact_id');
3174 // Update timestamp when modifying related custom-data tables
3175 $customGroupTables = array();
3176 $customGroupDAO = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity('Contact');
3177 $customGroupDAO->is_multiple
= 0;
3178 $customGroupDAO->find();
3179 while ($customGroupDAO->fetch()) {
3180 $customGroupTables[] = $customGroupDAO->table_name
;
3182 if (!empty($customGroupTables)) {
3183 self
::generateTimestampTriggers($info, $tableName, $customGroupTables, 'entity_id');
3186 // Update phone table to populate phone_numeric field
3187 if (!$tableName ||
$tableName == 'civicrm_phone') {
3188 // Define stored sql function needed for phones
3189 CRM_Core_DAO
::executeQuery(self
::DROP_STRIP_FUNCTION_43
);
3190 CRM_Core_DAO
::executeQuery(self
::CREATE_STRIP_FUNCTION_43
);
3192 'table' => array('civicrm_phone'),
3194 'event' => array('INSERT', 'UPDATE'),
3195 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3201 * Check if contact is being used in civicrm_domain
3202 * based on $contactId
3204 * @param int $contactId contact id.
3206 * @return bool true if present else false.
3210 static function checkDomainContact($contactId) {
3213 $domainId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3223 * Get options for a given contact field.
3224 * @see CRM_Core_DAO::buildOptions
3226 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3227 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3229 * @param String $fieldName
3230 * @param String $context : @see CRM_Core_DAO::buildOptionsContext
3231 * @param Array $props : whatever is known about this dao object
3233 * @return Array|bool
3235 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3237 // Special logic for fields whose options depend on context or properties
3238 switch ($fieldName) {
3239 case 'contact_sub_type':
3240 if (!empty($props['contact_type'])) {
3241 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3245 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
3249 * Delete a contact-related object that has an 'is_primary' field
3250 * Ensures that is_primary gets assigned to another object if available
3251 * Also calls pre/post hooks
3253 * @var $type : object type
3254 * @var $id : object id
3257 public static function deleteObjectWithPrimary($type, $id) {
3258 if (!$id ||
!is_numeric($id)) {
3261 $daoName = "CRM_Core_DAO_$type";
3262 $obj = new $daoName();
3265 if ($obj->fetch()) {
3266 CRM_Utils_Hook
::pre('delete', $type, $id, CRM_Core_DAO
::$_nullArray);
3267 $contactId = $obj->contact_id
;
3273 // is_primary is only relavent if this field belongs to a contact
3275 $dao = new $daoName();
3276 $dao->contact_id
= $contactId;
3277 $dao->is_primary
= 1;
3278 // Pick another record to be primary (if one isn't already)
3279 if (!$dao->find(TRUE)) {
3280 $dao->is_primary
= 0;
3282 if ($dao->fetch()) {
3283 $dao->is_primary
= 1;
3289 CRM_Utils_Hook
::post('delete', $type, $id, $obj);