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 // reset the group contact cache for this group
864 CRM_Contact_BAO_GroupContactCache
::remove();
866 // delete any dupe cache entry
867 CRM_Core_BAO_PrevNextCache
::deleteItem($id);
869 $transaction->commit();
871 CRM_Utils_Hook
::post('delete', $contactType, $contact->id
, $contact);
873 // also reset the DB_DO global array so we can reuse the memory
874 // http://issues.civicrm.org/jira/browse/CRM-4387
875 CRM_Core_DAO
::freeResult();
881 * delete the image of a contact
883 * @param int $id id of the contact
885 * @return boolean true if contact image is deleted
887 public static function deleteContactImage($id) {
892 UPDATE civicrm_contact
895 CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
900 * Return relative path
901 * @todo make this a method of $config->userSystem (i.e. UF classes) rather than a static function
903 * @param string $absolutePath absolute path
905 * @return String $relativePath Relative url of uploaded image
907 public static function getRelativePath($absolutePath) {
908 $relativePath = NULL;
909 $config = CRM_Core_Config
::singleton();
910 if ($config->userFramework
== 'Joomla') {
911 $userFrameworkBaseURL = trim(str_replace('/administrator/', '', $config->userFrameworkBaseURL
));
912 $customFileUploadDirectory = strstr(str_replace('\\', '/', $absolutePath), '/media');
913 $relativePath = $userFrameworkBaseURL . $customFileUploadDirectory;
915 elseif ($config->userSystem
->is_drupal
== '1') {
916 //ideally we would do a bigger re-factoring & move the getRelativePath onto the UF class
917 $rootPath = $config->userSystem
->cmsRootPath();
918 $baseUrl = $config->userFrameworkBaseURL
;
920 //format url for language negotiation, CRM-7135
921 $baseUrl = CRM_Utils_System
::languageNegotiationURL($baseUrl, FALSE, TRUE);
923 $relativePath = str_replace("{$rootPath}/",
925 str_replace('\\', '/', $absolutePath)
927 } else if ( $config->userFramework
== 'WordPress' ) {
928 $userFrameworkBaseURL = trim( str_replace( '/wp-admin/', '', $config->userFrameworkBaseURL
) );
929 $customFileUploadDirectory = strstr( str_replace('\\', '/', $absolutePath), '/wp-content/' );
930 $relativePath = $userFrameworkBaseURL . $customFileUploadDirectory;
933 return $relativePath;
937 * function to return proportional height and width of the image
939 * @param Integer $imageWidth width of image
941 * @param Integer $imageHeight height of image
943 * @return Array thumb dimension of image
945 public static function getThumbSize($imageWidth, $imageHeight) {
947 if ($imageWidth && $imageHeight) {
948 $imageRatio = $imageWidth / $imageHeight;
953 if ($imageRatio > 1) {
954 $imageThumbWidth = $thumbWidth;
955 $imageThumbHeight = round($thumbWidth / $imageRatio);
958 $imageThumbHeight = $thumbWidth;
959 $imageThumbWidth = round($thumbWidth * $imageRatio);
962 return array($imageThumbWidth, $imageThumbHeight);
966 * Validate type of contact image
968 * @param array $params
969 * @param String $imageIndex index of image field
970 * @param String $statusMsg status message to be set after operation
971 * @param string $opType type of operation like fatal, bounce etc
973 * @return boolean true if valid image extension
975 public static function processImageParams(&$params,
976 $imageIndex = 'image_URL',
990 if (in_array($params[$imageIndex]['type'], $mimeType)) {
991 $photo = basename($params[$imageIndex]['name']);
992 $params[$imageIndex] = CRM_Utils_System
::url('civicrm/contact/imagefile', 'photo='.$photo, TRUE, NULL, TRUE, TRUE);
996 unset($params[$imageIndex]);
998 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
1000 if ($opType == 'status') {
1001 CRM_Core_Session
::setStatus($statusMsg, 'Sorry', 'error');
1003 // FIXME: additional support for fatal, bounce etc could be added.
1009 * function to extract contact id from url for deleting contact image
1011 public static function processImage() {
1013 $action = CRM_Utils_Request
::retrieve('action', 'String');
1014 $cid = CRM_Utils_Request
::retrieve('cid', 'Positive');
1015 // retrieve contact id in case of Profile context
1016 $id = CRM_Utils_Request
::retrieve('id', 'Positive');
1017 $cid = $cid ?
$cid : $id;
1018 if ($action & CRM_Core_Action
::DELETE
) {
1019 if (CRM_Utils_Request
::retrieve('confirmed', 'Boolean')) {
1020 CRM_Contact_BAO_Contact
::deleteContactImage($cid);
1021 CRM_Core_Session
::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
1022 $session = CRM_Core_Session
::singleton();
1023 $toUrl = $session->popUserContext();
1024 CRM_Utils_System
::redirect($toUrl);
1030 * Function to set is_delete true or restore deleted contact
1032 * @param int $contact Contact DAO object
1033 * @param boolean $restore true to set the is_delete = 1 else false to restore deleted contact,
1034 * i.e. is_delete = 0
1039 static function contactTrashRestore($contact, $restore = FALSE) {
1040 $op = ($restore ?
'restore' : 'trash');
1042 CRM_Utils_Hook
::pre($op, $contact->contact_type
, $contact->id
, CRM_Core_DAO
::$_nullArray);
1044 $params = array(1 => array($contact->id
, 'Integer'));
1045 $isDelete = ' is_deleted = 1 ';
1047 $isDelete = ' is_deleted = 0 ';
1050 $query = "DELETE FROM civicrm_uf_match WHERE contact_id = %1";
1051 CRM_Core_DAO
::executeQuery($query, $params);
1054 $query = "UPDATE civicrm_contact SET {$isDelete} WHERE id = %1";
1055 CRM_Core_DAO
::executeQuery($query, $params);
1057 CRM_Utils_Hook
::post($op, $contact->contact_type
, $contact->id
, $contact);
1061 * Get contact type for a contact.
1063 * @param int $id - id of the contact whose contact type is needed
1065 * @return string contact_type if $id found else null ""
1072 public static function getContactType($id) {
1073 return CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1077 * Get contact sub type for a contact.
1079 * @param int $id - id of the contact whose contact sub type is needed
1081 * @param null $implodeDelimiter
1083 * @return string contact_sub_type if $id found else null ""
1089 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1090 $subtype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1092 return $implodeDelimiter ?
NULL : array();
1095 $subtype = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($subtype, CRM_Core_DAO
::VALUE_SEPARATOR
));
1097 if ($implodeDelimiter) {
1098 $subtype = implode($implodeDelimiter, $subtype);
1104 * Get pair of contact-type and sub-type for a contact.
1106 * @param int $id - id of the contact whose contact sub/contact type is needed
1115 public static function getContactTypes($id) {
1116 $params = array('id' => $id);
1118 $contact = CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact',
1121 array('contact_type', 'contact_sub_type')
1125 $contactTypes = array();
1126 if ($contact->contact_sub_type
)
1127 $contactTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($contact->contact_sub_type
, CRM_Core_DAO
::VALUE_SEPARATOR
));
1128 array_unshift($contactTypes, $contact->contact_type
);
1130 return $contactTypes;
1133 CRM_Core_Error
::fatal();
1138 * combine all the importable fields from the lower levels object
1140 * The ordering is important, since currently we do not have a weight
1141 * scheme. Adding weight is super important
1143 * @param int|string $contactType contact Type
1144 * @param boolean $status status is used to manipulate first title
1145 * @param boolean $showAll if true returns all fields (includes disabled fields)
1146 * @param boolean $isProfile if its profile mode
1147 * @param boolean $checkPermission if false, do not include permissioning clause (for custom data)
1149 * @param bool $withMultiCustomFields
1151 * @return array array of importable Fields
1155 static function importableFields($contactType = 'Individual',
1159 $checkPermission = TRUE,
1160 $withMultiCustomFields = FALSE
1162 if (empty($contactType)) {
1163 $contactType = 'All';
1166 $cacheKeyString = "importableFields $contactType";
1167 $cacheKeyString .= $status ?
'_1' : '_0';
1168 $cacheKeyString .= $showAll ?
'_1' : '_0';
1169 $cacheKeyString .= $isProfile ?
'_1' : '_0';
1170 $cacheKeyString .= $checkPermission ?
'_1' : '_0';
1172 $fields = CRM_Utils_Array
::value($cacheKeyString, self
::$_importableFields);
1175 // check if we can retrieve from database cache
1176 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1180 $fields = CRM_Contact_DAO_Contact
::import();
1182 // get the fields thar are meant for contact types
1183 if (in_array($contactType, array(
1184 'Individual', 'Household', 'Organization', 'All'))) {
1185 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1188 $locationFields = array_merge(CRM_Core_DAO_Address
::import(),
1189 CRM_Core_DAO_Phone
::import(),
1190 CRM_Core_DAO_Email
::import(),
1191 CRM_Core_DAO_IM
::import(TRUE),
1192 CRM_Core_DAO_OpenID
::import()
1195 $locationFields = array_merge($locationFields,
1196 CRM_Core_BAO_CustomField
::getFieldsForImport('Address',
1204 foreach ($locationFields as $key => $field) {
1205 $locationFields[$key]['hasLocationType'] = TRUE;
1208 $fields = array_merge($fields, $locationFields);
1210 $fields = array_merge($fields, CRM_Contact_DAO_Contact
::import());
1211 $fields = array_merge($fields, CRM_Core_DAO_Note
::import());
1214 $fields = array_merge($fields, CRM_Core_DAO_Website
::import());
1215 $fields['url']['hasWebsiteType'] = TRUE;
1217 if ($contactType != 'All') {
1218 $fields = array_merge($fields,
1219 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType,
1224 $withMultiCustomFields
1227 //unset the fields, which are not related to their
1229 $commonValues = array(
1230 'Individual' => array(
1236 'Household' => array(
1246 'organization_name',
1254 'Organization' => array(
1269 foreach ($commonValues[$contactType] as $value) {
1270 unset($fields[$value]);
1275 'Individual', 'Household', 'Organization') as $type) {
1276 $fields = array_merge($fields,
1277 CRM_Core_BAO_CustomField
::getFieldsForImport($type,
1282 $withMultiCustomFields
1289 $fields = array_merge($fields, array(
1291 'title' => ts('Group(s)'),
1295 'title' => ts('Tag(s)'),
1299 'title' => ts('Note(s)'),
1302 'communication_style_id' => array(
1303 'title' => ts('Communication Style'),
1304 'name' => 'communication_style_id',
1309 //Sorting fields in alphabetical order(CRM-1507)
1310 $fields = CRM_Utils_Array
::crmArraySortByField($fields, 'title');
1312 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1315 self
::$_importableFields[$cacheKeyString] = $fields;
1319 $fields = array_merge(array('do_not_import' => array('title' => ts('- do not import -'))),
1320 self
::$_importableFields[$cacheKeyString]
1324 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1325 self
::$_importableFields[$cacheKeyString]
1333 * combine all the exportable fields from the lower levels object
1335 * currentlty we are using importable fields as exportable fields
1337 * @param int|string $contactType contact Type
1338 * @param boolean $status true while exporting primary contacts
1339 * @param boolean $export true when used during export
1340 * @param boolean $search true when used during search, might conflict with export param?
1342 * @param bool $withMultiRecord
1344 * @return array array of exportable Fields
1348 static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE) {
1349 if (empty($contactType)) {
1350 $contactType = 'All';
1353 $cacheKeyString = "exportableFields $contactType";
1354 $cacheKeyString .= $export ?
'_1' : '_0';
1355 $cacheKeyString .= $status ?
'_1' : '_0';
1356 $cacheKeyString .= $search ?
'_1' : '_0';
1357 //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
1358 //calculates custom fields takes into account the logged in user & caches that for all users
1359 //as an interim fix we will cache the fields by contact
1360 $cacheKeyString .= '_' . CRM_Core_Session
::getLoggedInContactID();
1362 if (!self
::$_exportableFields ||
!CRM_Utils_Array
::value($cacheKeyString, self
::$_exportableFields)) {
1363 if (!self
::$_exportableFields) {
1364 self
::$_exportableFields = array();
1367 // check if we can retrieve from database cache
1368 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1371 $fields = CRM_Contact_DAO_Contact
::export();
1373 // the fields are meant for contact types
1377 array('Individual', 'Household', 'Organization', 'All')
1380 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1382 // add current employer for individuals
1383 $fields = array_merge($fields, array(
1384 'current_employer' =>
1386 'name' => 'organization_name',
1387 'title' => ts('Current Employer'),
1391 $locationType = array(
1392 'location_type' => array(
1393 'name' => 'location_type',
1394 'where' => 'civicrm_location_type.name',
1395 'title' => ts('Location Type'),
1398 $IMProvider = array(
1399 'im_provider' => array(
1400 'name' => 'im_provider',
1401 'where' => 'civicrm_im.provider_id',
1402 'title' => ts('IM Provider'),
1405 $locationFields = array_merge($locationType,
1406 CRM_Core_DAO_Address
::export(),
1407 CRM_Core_DAO_Phone
::export(),
1408 CRM_Core_DAO_Email
::export(),
1410 CRM_Core_DAO_IM
::export(TRUE),
1411 CRM_Core_DAO_OpenID
::export()
1414 $locationFields = array_merge($locationFields,
1415 CRM_Core_BAO_CustomField
::getFieldsForImport('Address')
1418 foreach ($locationFields as $key => $field) {
1419 $locationFields[$key]['hasLocationType'] = TRUE;
1422 $fields = array_merge($fields, $locationFields);
1425 $fields = array_merge($fields,
1426 CRM_Core_DAO_Worldregion
::export()
1430 $fields = array_merge($fields,
1431 CRM_Contact_DAO_Contact
::export()
1435 $fields = array_merge($fields, CRM_Core_DAO_Website
::export());
1437 if ($contactType != 'All') {
1438 $fields = array_merge($fields,
1439 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType, $status, FALSE, $search, TRUE, $withMultiRecord)
1444 'Individual', 'Household', 'Organization') as $type) {
1445 $fields = array_merge($fields,
1446 CRM_Core_BAO_CustomField
::getFieldsForImport($type, FALSE, FALSE, $search, TRUE, $withMultiRecord)
1453 $fields = array_merge($fields, array(
1455 'title' => ts('Group(s)'),
1459 'title' => ts('Tag(s)'),
1463 'title' => ts('Note(s)'),
1469 $fields = array_merge($fields, array(
1471 'title' => ts('Group(s)'),
1475 'title' => ts('Tag(s)'),
1479 'title' => ts('Note(s)'),
1485 //Sorting fields in alphabetical order(CRM-1507)
1486 foreach ($fields as $k => $v) {
1487 $sortArray[$k] = CRM_Utils_Array
::value('title', $v);
1490 $fields = array_merge($sortArray, $fields);
1491 //unset the field which are not related to their contact type.
1492 if ($contactType != 'All') {
1493 $commonValues = array(
1494 'Individual' => array(
1498 'organization_name',
1499 'email_greeting_custom',
1500 'postal_greeting_custom',
1503 'Household' => array(
1513 'organization_name',
1521 'email_greeting_custom',
1522 'postal_greeting_custom',
1527 'Organization' => array(
1538 'email_greeting_custom',
1539 'postal_greeting_custom',
1549 foreach ($commonValues[$contactType] as $value) {
1550 unset($fields[$value]);
1554 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1556 self
::$_exportableFields[$cacheKeyString] = $fields;
1560 $fields = self
::$_exportableFields[$cacheKeyString];
1563 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1564 self
::$_exportableFields[$cacheKeyString]
1572 * Function to get the all contact details(Hierarchical)
1574 * @param int $contactId contact id
1575 * @param array $fields fields array
1577 * @return $values array contains the contact details
1581 static function getHierContactDetails($contactId, &$fields) {
1582 $params = array(array('contact_id', '=', $contactId, 0, 0));
1585 $returnProperties = self
::makeHierReturnProperties($fields, $contactId);
1587 // we dont know the contents of return properties, but we need the lower level ids of the contact
1588 // so add a few fields
1589 $returnProperties['first_name'] =
1590 $returnProperties['organization_name'] =
1591 $returnProperties['household_name'] =
1592 $returnProperties['contact_type'] =
1593 $returnProperties['contact_sub_type'] = 1;
1594 return list($query, $options) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, $options);
1598 * given a set of flat profile style field names, create a hierarchy
1599 * for query to use and crete the right sql
1602 * @param int $contactId contact id
1604 * @return array a hierarchical property tree if appropriate
1608 static function &makeHierReturnProperties($fields, $contactId = NULL) {
1609 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1611 $returnProperties = array();
1613 $multipleFields = array('website' => 'url');
1614 foreach ($fields as $name => $dontCare) {
1615 if (strpos($name, '-') !== FALSE) {
1616 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $name, 3);
1618 if (!in_array($fieldName, $multipleFields)) {
1619 if ($id == 'Primary') {
1620 $locationTypeName = 1;
1623 $locationTypeName = CRM_Utils_Array
::value($id, $locationTypes);
1624 if (!$locationTypeName) {
1629 if (empty($returnProperties['location'])) {
1630 $returnProperties['location'] = array();
1632 if (empty($returnProperties['location'][$locationTypeName])) {
1633 $returnProperties['location'][$locationTypeName] = array();
1634 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1636 if (in_array($fieldName, array(
1637 'phone', 'im', 'email', 'openid', 'phone_ext'))) {
1639 $returnProperties['location'][$locationTypeName][$fieldName . '-' . $type] = 1;
1642 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1645 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1646 $returnProperties['location'][$locationTypeName][substr($fieldName, 8)] = 1;
1649 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1653 $returnProperties['website'][$id][$fieldName] = 1;
1657 $returnProperties[$name] = 1;
1661 return $returnProperties;
1665 * Function to return the primary location type of a contact
1667 * $params int $contactId contact_id
1668 * $params boolean $isPrimaryExist if true, return primary contact location type otherwise null
1669 * $params boolean $skipDefaultPriamry if true, return primary contact location type otherwise null
1672 * @param bool $skipDefaultPriamry
1673 * @param null $block
1675 * @return int $locationType location_type_id
1679 static function getPrimaryLocationType($contactId, $skipDefaultPriamry = FALSE, $block = NULL) {
1681 $entityBlock = array('contact_id' => $contactId);
1682 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock);
1683 foreach($blocks[$block] as $key => $value){
1684 if (!empty($value['is_primary'])){
1685 $locationType = CRM_Utils_Array
::value('location_type_id',$value);
1692 IF ( civicrm_email.location_type_id IS NULL,
1693 IF ( civicrm_address.location_type_id IS NULL,
1694 IF ( civicrm_phone.location_type_id IS NULL,
1695 IF ( civicrm_im.location_type_id IS NULL,
1696 IF ( civicrm_openid.location_type_id IS NULL, null, civicrm_openid.location_type_id)
1697 ,civicrm_im.location_type_id)
1698 ,civicrm_phone.location_type_id)
1699 ,civicrm_address.location_type_id)
1700 ,civicrm_email.location_type_id) as locationType
1701 FROM civicrm_contact
1702 LEFT JOIN civicrm_email ON ( civicrm_email.is_primary = 1 AND civicrm_email.contact_id = civicrm_contact.id )
1703 LEFT JOIN civicrm_address ON ( civicrm_address.is_primary = 1 AND civicrm_address.contact_id = civicrm_contact.id)
1704 LEFT JOIN civicrm_phone ON ( civicrm_phone.is_primary = 1 AND civicrm_phone.contact_id = civicrm_contact.id)
1705 LEFT JOIN civicrm_im ON ( civicrm_im.is_primary = 1 AND civicrm_im.contact_id = civicrm_contact.id)
1706 LEFT JOIN civicrm_openid ON ( civicrm_openid.is_primary = 1 AND civicrm_openid.contact_id = civicrm_contact.id)
1707 WHERE civicrm_contact.id = %1 ";
1709 $params = array(1 => array($contactId, 'Integer'));
1711 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1713 $locationType = NULL;
1714 if ($dao->fetch()) {
1715 $locationType = $dao->locationType
;
1718 if (isset($locationType)) {
1719 return $locationType;
1721 elseif ($skipDefaultPriamry) {
1722 // if there is no primary contact location then return null
1726 // if there is no primart contact location, then return default
1727 // location type of the system
1728 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
1729 return $defaultLocationType->id
;
1734 * function to get the display name, primary email and location type of a contact
1736 * @param int $id id of the contact
1738 * @return array of display_name, email if found, do_not_email or (null,null,null)
1742 static function getContactDetails($id) {
1743 // check if the contact type
1744 $contactType = self
::getContactType($id);
1746 $nameFields = ($contactType == 'Individual') ?
"civicrm_contact.first_name, civicrm_contact.last_name, civicrm_contact.display_name" : "civicrm_contact.display_name";
1749 SELECT $nameFields, civicrm_email.email, civicrm_contact.do_not_email, civicrm_email.on_hold, civicrm_contact.is_deceased
1750 FROM civicrm_contact LEFT JOIN civicrm_email ON (civicrm_contact.id = civicrm_email.contact_id)
1751 WHERE civicrm_contact.id = %1
1752 ORDER BY civicrm_email.is_primary DESC";
1753 $params = array(1 => array($id, 'Integer'));
1754 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
1756 if ($dao->fetch()) {
1757 if ($contactType == 'Individual') {
1758 if ($dao->first_name ||
$dao->last_name
) {
1759 $name = "{$dao->first_name} {$dao->last_name}";
1762 $name = $dao->display_name
;
1766 $name = $dao->display_name
;
1768 $email = $dao->email
;
1769 $doNotEmail = $dao->do_not_email ?
TRUE : FALSE;
1770 $onHold = $dao->on_hold ?
TRUE : FALSE;
1771 $isDeceased = $dao->is_deceased ?
TRUE : FALSE;
1772 return array($name, $email, $doNotEmail, $onHold, $isDeceased);
1774 return array(NULL, NULL, NULL, NULL, NULL);
1778 * function to add/edit/register contacts through profile.
1780 * @param array $params Array of profile fields to be edited/added.
1781 * @param array $fields Array of fields from UFGroup
1782 * @param int $contactID id of the contact to be edited/added.
1783 * @param int $addToGroupID specifies the default group to which contact is added.
1784 * @param int $ufGroupId uf group id (profile id)
1786 * @param boolean $visibility basically lets us know where this request is coming from
1787 * if via a profile from web, we restrict what groups are changed
1789 * @return int contact id created/edited
1793 static function createProfileContact(
1797 $addToGroupID = NULL,
1802 // add ufGroupID to params array ( CRM-2012 )
1804 $params['uf_group_id'] = $ufGroupId;
1809 CRM_Utils_Hook
::pre('edit', 'Profile', $contactID, $params);
1813 CRM_Utils_Hook
::pre('create', 'Profile', NULL, $params);
1816 list($data, $contactDetails) = self
::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
1818 // manage is_opt_out
1819 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
1820 $wasOptOut = CRM_Utils_Array
::value('is_opt_out', $contactDetails, FALSE);
1821 $isOptOut = CRM_Utils_Array
::value('is_opt_out', $params, FALSE);
1822 $data['is_opt_out'] = $isOptOut;
1823 // on change, create new civicrm_subscription_history entry
1824 if (($wasOptOut != $isOptOut) && !empty($contactDetails['contact_id'])) {
1826 'contact_id' => $contactDetails['contact_id'],
1827 'status' => $isOptOut ?
'Removed' : 'Added',
1830 CRM_Contact_BAO_SubscriptionHistory
::create($shParams);
1834 $contact = self
::create($data);
1836 // contact is null if the profile does not have any contact fields
1838 $contactID = $contact->id
;
1841 if (empty($contactID)) {
1842 CRM_Core_Error
::fatal('Cannot proceed without a valid contact id');
1845 // Process group and tag
1846 if (!empty($fields['group'])) {
1848 // this for sure means we are coming in via profile since i added it to fix
1849 // removing contacts from user groups -- lobo
1853 CRM_Contact_BAO_GroupContact
::create($params['group'], $contactID, $visibility, $method);
1856 if (!empty($fields['tag'])) {
1857 CRM_Core_BAO_EntityTag
::create($params['tag'], 'civicrm_contact', $contactID);
1860 //to add profile in default group
1861 if (is_array($addToGroupID)) {
1862 $contactIds = array($contactID);
1863 foreach ($addToGroupID as $groupId) {
1864 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
1867 elseif ($addToGroupID) {
1868 $contactIds = array($contactID);
1869 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $addToGroupID);
1872 // reset the group contact cache for this group
1873 CRM_Contact_BAO_GroupContactCache
::remove();
1876 CRM_Utils_Hook
::post('edit', 'Profile', $contactID, $params);
1879 CRM_Utils_Hook
::post('create', 'Profile', $contactID, $params);
1885 * @param array $params
1887 * @param null $contactID
1888 * @param null $ufGroupId
1889 * @param null $ctype
1890 * @param bool $skipCustom
1894 static function formatProfileContactParams(
1903 $data = $contactDetails = array();
1905 // get the contact details (hier)
1907 list($details, $options) = self
::getHierContactDetails($contactID, $fields);
1909 $contactDetails = $details[$contactID];
1910 $data['contact_type'] = CRM_Utils_Array
::value('contact_type', $contactDetails);
1911 $data['contact_sub_type'] = CRM_Utils_Array
::value('contact_sub_type', $contactDetails);
1914 //we should get contact type only if contact
1916 $data['contact_type'] = CRM_Core_BAO_UFField
::getProfileType($ufGroupId);
1918 //special case to handle profile with only contact fields
1919 if ($data['contact_type'] == 'Contact') {
1920 $data['contact_type'] = 'Individual';
1922 elseif (CRM_Contact_BAO_ContactType
::isaSubType($data['contact_type'])) {
1923 $data['contact_type'] = CRM_Contact_BAO_ContactType
::getBasicType($data['contact_type']);
1927 $data['contact_type'] = $ctype;
1930 $data['contact_type'] = 'Individual';
1934 //fix contact sub type CRM-5125
1935 if (array_key_exists('contact_sub_type', $params) &&
1936 !empty($params['contact_sub_type'])
1938 $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
;
1940 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
1941 !empty($params['contact_sub_type_hidden'])
1943 // if profile was used, and had any subtype, we obtain it from there
1944 $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
;
1947 if ($ctype == 'Organization') {
1948 $data['organization_name'] = CRM_Utils_Array
::value('organization_name', $contactDetails);
1950 elseif ($ctype == 'Household') {
1951 $data['household_name'] = CRM_Utils_Array
::value('household_name', $contactDetails);
1954 $locationType = array();
1959 $data['contact_id'] = $contactID;
1960 $primaryLocationType = self
::getPrimaryLocationType($contactID);
1963 $defaultLocation = CRM_Core_BAO_LocationType
::getDefault();
1964 $defaultLocationId = $defaultLocation->id
;
1967 // get the billing location type
1968 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
1969 $billingLocationTypeId = array_search('Billing', $locationTypes);
1971 $blocks = array('email', 'phone', 'im', 'openid');
1973 $multiplFields = array('url');
1974 // prevent overwritten of formatted array, reset all block from
1975 // params if it is not in valid format (since import pass valid format)
1976 foreach ($blocks as $blk) {
1977 if (array_key_exists($blk, $params) &&
1978 !is_array($params[$blk])
1980 unset($params[$blk]);
1984 $primaryPhoneLoc = NULL;
1985 $session = CRM_Core_Session
::singleton();
1986 foreach ($params as $key => $value) {
1987 $fieldName = $locTypeId = $typeId = NULL;
1988 list($fieldName, $locTypeId, $typeId) = CRM_Utils_System
::explode('-', $key, 3);
1990 //store original location type id
1991 $actualLocTypeId = $locTypeId;
1993 if ($locTypeId == 'Primary') {
1995 if(in_array( $fieldName, $blocks)){
1996 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, $fieldName);
1999 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, 'address');
2001 $primaryLocationType = $locTypeId;
2004 $locTypeId = $defaultLocationId;
2008 if (is_numeric($locTypeId) &&
2009 !in_array($fieldName, $multiplFields) &&
2010 substr($fieldName, 0, 7) != 'custom_'
2012 $index = $locTypeId;
2014 if (is_numeric($typeId)) {
2015 $index .= '-' . $typeId;
2017 if (!in_array($index, $locationType)) {
2018 $locationType[$count] = $index;
2022 $loc = CRM_Utils_Array
::key($index, $locationType);
2024 $blockName = in_array( $fieldName, $blocks) ?
$fieldName : 'address';
2026 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
2028 //set is_billing true, for location type "Billing"
2029 if ($locTypeId == $billingLocationTypeId) {
2030 $data[$blockName][$loc]['is_billing'] = 1;
2034 //get the primary location type
2035 if ($locTypeId == $primaryLocationType) {
2036 $data[$blockName][$loc]['is_primary'] = 1;
2039 elseif ($locTypeId == $defaultLocationId) {
2040 $data[$blockName][$loc]['is_primary'] = 1;
2043 if ( in_array($fieldName, array('phone'))) {
2045 $data['phone'][$loc]['phone_type_id'] = $typeId;
2048 $data['phone'][$loc]['phone_type_id'] = '';
2050 $data['phone'][$loc]['phone'] = $value;
2052 //special case to handle primary phone with different phone types
2053 // in this case we make first phone type as primary
2054 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
2055 $primaryPhoneLoc = $loc;
2058 if ($loc != $primaryPhoneLoc) {
2059 unset($data['phone'][$loc]['is_primary']);
2062 elseif ($fieldName == 'phone_ext') {
2063 $data['phone'][$loc]['phone_ext'] = $value;
2065 elseif ($fieldName == 'email') {
2066 $data['email'][$loc]['email'] = $value;
2068 elseif ($fieldName == 'im') {
2069 if (isset($params[$key . '-provider_id'])) {
2070 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
2072 if (strpos($key, '-provider_id') !== FALSE) {
2073 $data['im'][$loc]['provider_id'] = $params[$key];
2076 $data['im'][$loc]['name'] = $value;
2079 elseif ($fieldName == 'openid') {
2080 $data['openid'][$loc]['openid'] = $value;
2083 if ($fieldName === 'state_province') {
2085 if (is_numeric($value) && ((int ) $value) >= 1000) {
2086 $data['address'][$loc]['state_province_id'] = $value;
2088 elseif (empty($value)) {
2089 $data['address'][$loc]['state_province_id'] = '';
2092 $data['address'][$loc]['state_province'] = $value;
2095 elseif ($fieldName === 'country') {
2097 if (is_numeric($value) && ((int ) $value) >= 1000
2099 $data['address'][$loc]['country_id'] = $value;
2101 elseif (empty($value)) {
2102 $data['address'][$loc]['country_id'] = '';
2105 $data['address'][$loc]['country'] = $value;
2108 elseif ($fieldName === 'county') {
2109 $data['address'][$loc]['county_id'] = $value;
2111 elseif ($fieldName == 'address_name') {
2112 $data['address'][$loc]['name'] = $value;
2114 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2115 $data['address'][$loc][substr($fieldName, 8)] = $value;
2118 $data['address'][$loc][$fieldName] = $value;
2123 if (substr($key, 0, 4) === 'url-') {
2124 $websiteField = explode('-', $key);
2125 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
2126 $data['website'][$websiteField[1]]['url'] = $value;
2128 elseif (in_array($key, self
::$_greetingTypes, TRUE)) {
2129 //save email/postal greeting and addressee values if any, CRM-4575
2130 $data[$key . '_id'] = $value;
2132 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($key))) {
2133 // for autocomplete transfer hidden value instead of label
2134 if ($params[$key] && isset($params[$key . '_id'])) {
2135 $value = $params[$key . '_id'];
2138 // we need to append time with date
2139 if ($params[$key] && isset($params[$key . '_time'])) {
2140 $value .= ' ' . $params[$key . '_time'];
2143 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
2144 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 &&
2145 ($value == '' ||
!isset($value))) {
2150 if (!empty($params['customRecordValues'])) {
2151 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2152 foreach ($params['customRecordValues'] as $recId => $customFields) {
2153 if (is_array($customFields) && !empty($customFields)) {
2154 foreach ($customFields as $customFieldName) {
2155 if ($customFieldName == $key) {
2165 $type = $data['contact_type'];
2166 if (!empty($data['contact_sub_type'])) {
2167 $type = $data['contact_sub_type'];
2168 $type = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($type, CRM_Core_DAO
::VALUE_SEPARATOR
));
2169 // generally a contact even if, has multiple subtypes the parent-type is going to be one only
2170 // and since formatCustomField() would be interested in parent type, lets consider only one subtype
2171 // as the results going to be same.
2175 CRM_Core_BAO_CustomField
::formatCustomField($customFieldId,
2183 elseif ($key == 'edit') {
2187 if ($key == 'location') {
2188 foreach ($value as $locationTypeId => $field) {
2189 foreach ($field as $block => $val) {
2190 if ($block == 'address' && array_key_exists('address_name', $val)) {
2191 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2196 if($key == 'phone' && isset($params['phone_ext'])){
2197 $data[$key] = $value;
2198 foreach($value as $cnt => $phoneBlock){
2199 if($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']){
2200 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array
::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2204 else if (in_array($key,
2213 ($value == '' ||
!isset($value)) &&
2214 ($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0) {
2215 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
2216 // to avoid update with empty values
2220 $data[$key] = $value;
2226 if (!isset($data['contact_type'])) {
2227 $data['contact_type'] = 'Individual';
2230 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2231 $privacy = CRM_Core_SelectValues
::privacy();
2232 foreach ($privacy as $key => $value) {
2233 if (array_key_exists($key, $fields)) {
2234 // do not reset values for existing contacts, if fields are added to a profile
2235 if (array_key_exists($key, $params)) {
2236 $data[$key] = $params[$key];
2237 if (empty($params[$key])) {
2241 elseif (!$contactID) {
2247 return array($data, $contactDetails);
2251 * Function to find the get contact details
2252 * does not respect ACLs for now, which might need to be rectified at some
2253 * stage based on how its used
2255 * @param string $mail primary email address of the contact
2256 * @param string $ctype contact type
2258 * @return object $dao contact details
2261 static function &matchContactOnEmail($mail, $ctype = NULL) {
2262 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2263 $mail = $strtolower(trim($mail));
2265 SELECT civicrm_contact.id as contact_id,
2266 civicrm_contact.hash as hash,
2267 civicrm_contact.contact_type as contact_type,
2268 civicrm_contact.contact_sub_type as contact_sub_type
2269 FROM civicrm_contact
2270 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2273 if (CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
2274 'uniq_email_per_site'
2276 // try to find a match within a site (multisite).
2277 $groups = CRM_Core_BAO_Domain
::getChildGroupIds();
2278 if (!empty($groups)) {
2280 INNER JOIN civicrm_group_contact gc ON
2281 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2286 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2287 $p = array(1 => array($mail, 'String'));
2290 $query .= " AND civicrm_contact.contact_type = %3";
2291 $p[3] = array($ctype, 'String');
2294 $query .= " ORDER BY civicrm_email.is_primary DESC";
2296 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2298 if ($dao->fetch()) {
2301 return CRM_Core_DAO
::$_nullObject;
2305 * Function to find the contact details associated with an OpenID
2307 * @param string $openId openId of the contact
2308 * @param string $ctype contact type
2310 * @return object $dao contact details
2313 static function &matchContactOnOpenId($openId, $ctype = NULL) {
2314 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2315 $openId = $strtolower(trim($openId));
2317 SELECT civicrm_contact.id as contact_id,
2318 civicrm_contact.hash as hash,
2319 civicrm_contact.contact_type as contact_type,
2320 civicrm_contact.contact_sub_type as contact_sub_type
2321 FROM civicrm_contact
2322 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2323 WHERE civicrm_openid.openid = %1";
2324 $p = array(1 => array($openId, 'String'));
2327 $query .= " AND civicrm_contact.contact_type = %3";
2328 $p[3] = array($ctype, 'String');
2331 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2333 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2335 if ($dao->fetch()) {
2338 return CRM_Core_DAO
::$_nullObject;
2342 * Funtion to get primary email of the contact
2344 * @param int $contactID contact id
2346 * @return string $dao->email email address if present else null
2350 public static function getPrimaryEmail($contactID) {
2351 // fetch the primary email
2353 SELECT civicrm_email.email as email
2354 FROM civicrm_contact
2355 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2356 WHERE civicrm_email.is_primary = 1
2357 AND civicrm_contact.id = %1";
2358 $p = array(1 => array($contactID, 'Integer'));
2359 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2362 if ($dao->fetch()) {
2363 $email = $dao->email
;
2370 * Funtion to get primary OpenID of the contact
2372 * @param int $contactID contact id
2374 * @return string $dao->openid OpenID if present else null
2378 public static function getPrimaryOpenId($contactID) {
2379 // fetch the primary OpenID
2381 SELECT civicrm_openid.openid as openid
2382 FROM civicrm_contact
2383 LEFT JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2384 WHERE civicrm_contact.id = %1
2385 AND civicrm_openid.is_primary = 1";
2386 $p = array(1 => array($contactID, 'Integer'));
2387 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2390 if ($dao->fetch()) {
2391 $openId = $dao->openid
;
2398 * Given the list of params in the params array, fetch the object
2399 * and store the values in the values array
2401 * @param array $params input parameters to find object
2402 * @param array $values output values of the object
2404 * @return CRM_Contact_BAO_Contact|null the found object or null
2408 public static function getValues(&$params, &$values) {
2409 $contact = new CRM_Contact_BAO_Contact();
2411 $contact->copyValues($params);
2413 if ($contact->find(TRUE)) {
2415 CRM_Core_DAO
::storeValues($contact, $values);
2418 foreach (self
::$_commPrefs as $name) {
2419 if (isset($contact->$name)) {
2420 $privacy[$name] = $contact->$name;
2424 if (!empty($privacy)) {
2425 $values['privacy'] = $privacy;
2428 // communication Prefferance
2429 $preffComm = $comm = array();
2430 $comm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2431 $contact->preferred_communication_method
2433 foreach ($comm as $value) {
2434 $preffComm[$value] = 1;
2436 $temp = array('preferred_communication_method' => $contact->preferred_communication_method
);
2439 'preferred_communication_method' => array('newName' => 'preferred_communication_method_display',
2440 'groupName' => 'preferred_communication_method',
2443 CRM_Core_OptionGroup
::lookupValues($temp, $names, FALSE);
2445 $values['preferred_communication_method'] = $preffComm;
2446 $values['preferred_communication_method_display'] = CRM_Utils_Array
::value('preferred_communication_method_display', $temp);
2448 $preferredMailingFormat = CRM_Core_SelectValues
::pmf();
2449 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format
];
2451 // get preferred languages
2452 if (!empty($contact->preferred_language
)) {
2453 $values['preferred_language'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language
);
2456 // Calculating Year difference
2457 if ($contact->birth_date
) {
2458 $birthDate = CRM_Utils_Date
::customFormat($contact->birth_date
, '%Y%m%d');
2459 if ($birthDate < date('Ymd')) {
2460 $age = CRM_Utils_Date
::calculateAge($birthDate);
2461 $values['age']['y'] = CRM_Utils_Array
::value('years', $age);
2462 $values['age']['m'] = CRM_Utils_Array
::value('months', $age);
2465 list($values['birth_date']) = CRM_Utils_Date
::setDateDefaults($contact->birth_date
, 'birth');
2466 $values['birth_date_display'] = $contact->birth_date
;
2469 if ($contact->deceased_date
) {
2470 list($values['deceased_date']) = CRM_Utils_Date
::setDateDefaults($contact->deceased_date
, 'birth');
2471 $values['deceased_date_display'] = $contact->deceased_date
;
2474 $contact->contact_id
= $contact->id
;
2482 * Given the component name and returns
2483 * the count of participation of contact
2485 * @param string $component input component name
2486 * @param integer $contactId input contact id
2487 * @param string $tableName optional tableName if component is custom group
2489 * @return total number of count of occurence in database
2493 static function getCountComponent($component, $contactId, $tableName = NULL) {
2495 switch ($component) {
2497 return CRM_Core_BAO_EntityTag
::getContactTags($contactId, TRUE);
2500 return CRM_Contact_BAO_Relationship
::getRelationship($contactId,
2501 CRM_Contact_BAO_Relationship
::CURRENT
,
2506 return CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, "Added", NULL, TRUE);
2509 if (CRM_Core_BAO_Log
::useLoggingReport()) {
2512 return CRM_Core_BAO_Log
::getContactLogCount($contactId);
2515 return CRM_Core_BAO_Note
::getContactNoteCount($contactId);
2517 case 'contribution':
2518 return CRM_Contribute_BAO_Contribution
::contributionCount($contactId);
2521 return CRM_Member_BAO_Membership
::getContactMembershipCount($contactId, TRUE);
2524 return CRM_Event_BAO_Participant
::getContactParticipantCount($contactId);
2527 return CRM_Pledge_BAO_Pledge
::getContactPledgeCount($contactId);
2530 return CRM_Case_BAO_Case
::caseCount($contactId);
2533 return CRM_Grant_BAO_Grant
::getContactGrantCount($contactId);
2537 'contact_id' => $contactId,
2540 'context' => 'activity',
2542 return CRM_Activity_BAO_Activity
::getActivitiesCount($input);
2545 $params = array('contact_id' => $contactId);
2546 return CRM_Mailing_BAO_Mailing
::getContactMailingsCount($params);
2549 $custom = explode('_', $component);
2550 if ($custom['0'] = 'custom') {
2552 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2554 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2555 return CRM_Core_DAO
::singleValueQuery($queryString);
2561 * Function to process greetings and cache
2563 * @param object $contact contact object after save
2564 * @param boolean $useDefaults use default greeting values
2570 static function processGreetings(&$contact, $useDefaults = FALSE) {
2572 //retrieve default greetings
2573 $defaultGreetings = CRM_Core_PseudoConstant
::greetingDefaults();
2574 $contactDefaults = $defaultGreetings[$contact->contact_type
];
2577 // note that contact object not always has required greeting related
2578 // fields that are required to calculate greeting and
2579 // also other fields used in tokens etc,
2580 // hence we need to retrieve it again.
2581 if ( $contact->_query
!== FALSE ) {
2582 $contact->find(TRUE);
2585 // store object values to an array
2586 $contactDetails = array();
2587 CRM_Core_DAO
::storeValues($contact, $contactDetails);
2588 $contactDetails = array(array($contact->id
=> $contactDetails));
2590 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2591 $updateQueryString = array();
2593 //cache email and postal greeting to greeting display
2594 if ($contact->email_greeting_custom
!= 'null' && $contact->email_greeting_custom
) {
2595 $emailGreetingString = $contact->email_greeting_custom
;
2597 elseif ($contact->email_greeting_id
!= 'null' && $contact->email_greeting_id
) {
2598 // the filter value for Individual contact type is set to 1
2600 'contact_type' => $contact->contact_type
,
2601 'greeting_type' => 'email_greeting',
2604 $emailGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2605 $emailGreetingString = $emailGreeting[$contact->email_greeting_id
];
2606 $updateQueryString[] = " email_greeting_custom = NULL ";
2610 reset($contactDefaults['email_greeting']);
2611 $emailGreetingID = key($contactDefaults['email_greeting']);
2612 $emailGreetingString = $contactDefaults['email_greeting'][$emailGreetingID];
2613 $updateQueryString[] = " email_greeting_id = $emailGreetingID ";
2614 $updateQueryString[] = " email_greeting_custom = NULL ";
2616 elseif ($contact->email_greeting_custom
) {
2617 $updateQueryString[] = " email_greeting_display = NULL ";
2621 if ($emailGreetingString) {
2622 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($emailGreetingString,
2625 'CRM_Contact_BAO_Contact'
2627 $emailGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($emailGreetingString));
2628 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2632 if ($contact->postal_greeting_custom
!= 'null' && $contact->postal_greeting_custom
) {
2633 $postalGreetingString = $contact->postal_greeting_custom
;
2635 elseif ($contact->postal_greeting_id
!= 'null' && $contact->postal_greeting_id
) {
2637 'contact_type' => $contact->contact_type
,
2638 'greeting_type' => 'postal_greeting',
2640 $postalGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2641 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id
];
2642 $updateQueryString[] = " postal_greeting_custom = NULL ";
2646 reset($contactDefaults['postal_greeting']);
2647 $postalGreetingID = key($contactDefaults['postal_greeting']);
2648 $postalGreetingString = $contactDefaults['postal_greeting'][$postalGreetingID];
2649 $updateQueryString[] = " postal_greeting_id = $postalGreetingID ";
2650 $updateQueryString[] = " postal_greeting_custom = NULL ";
2652 elseif ($contact->postal_greeting_custom
) {
2653 $updateQueryString[] = " postal_greeting_display = NULL ";
2657 if ($postalGreetingString) {
2658 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($postalGreetingString,
2661 'CRM_Contact_BAO_Contact'
2663 $postalGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($postalGreetingString));
2664 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2668 if ($contact->addressee_custom
!= 'null' && $contact->addressee_custom
) {
2669 $addresseeString = $contact->addressee_custom
;
2671 elseif ($contact->addressee_id
!= 'null' && $contact->addressee_id
) {
2673 'contact_type' => $contact->contact_type
,
2674 'greeting_type' => 'addressee',
2677 $addressee = CRM_Core_PseudoConstant
::greeting($filter);
2678 $addresseeString = $addressee[$contact->addressee_id
];
2679 $updateQueryString[] = " addressee_custom = NULL ";
2683 reset($contactDefaults['addressee']);
2684 $addresseeID = key($contactDefaults['addressee']);
2685 $addresseeString = $contactDefaults['addressee'][$addresseeID];
2686 $updateQueryString[] = " addressee_id = $addresseeID ";
2687 $updateQueryString[] = " addressee_custom = NULL ";
2689 elseif ($contact->addressee_custom
) {
2690 $updateQueryString[] = " addressee_display = NULL ";
2694 if ($addresseeString) {
2695 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($addresseeString,
2698 'CRM_Contact_BAO_Contact'
2700 $addresseeString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($addresseeString));
2701 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2704 if (!empty($updateQueryString)) {
2705 $updateQueryString = implode(',', $updateQueryString);
2706 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2707 CRM_Core_DAO
::executeQuery($queryString);
2712 * Function to retrieve loc block ids w/ given condition.
2714 * @param int $contactId contact id.
2715 * @param array $criteria key => value pair which should be
2716 * fulfill by return record ids.
2717 * @param string $condOperator operator use for grouping multiple conditions.
2719 * @return array $locBlockIds loc block ids which fulfill condition.
2722 static function getLocBlockIds($contactId, $criteria = array(), $condOperator = 'AND') {
2723 $locBlockIds = array();
2725 return $locBlockIds;
2728 foreach (array('Email', 'OpenID', 'Phone', 'Address', 'IM') as $block) {
2729 $name = strtolower($block);
2730 $className = "CRM_Core_DAO_$block";
2731 $blockDAO = new $className();
2733 // build the condition.
2734 if (is_array($criteria)) {
2735 $fields = $blockDAO->fields();
2736 $conditions = array();
2737 foreach ($criteria as $field => $value) {
2738 if (array_key_exists($field, $fields)) {
2739 $cond = "( $field = $value )";
2740 // value might be zero or null.
2741 if (!$value ||
strtolower($value) == 'null') {
2742 $cond = "( $field = 0 OR $field IS NULL )";
2744 $conditions[] = $cond;
2747 if (!empty($conditions)) {
2748 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2752 $blockDAO->contact_id
= $contactId;
2754 while ($blockDAO->fetch()) {
2755 $locBlockIds[$name][] = $blockDAO->id
;
2760 return $locBlockIds;
2764 * Function to build context menu items.
2766 * @param null $contactId
2768 * @return array of context menu for logged in user.
2771 static function contextMenu($contactId = NULL) {
2774 'title' => ts('View Contact'),
2776 'ref' => 'view-contact',
2777 'class' => 'no-popup',
2779 'permissions' => array('view all contacts'),
2782 'title' => ts('Edit Contact'),
2784 'ref' => 'edit-contact',
2785 'class' => 'no-popup',
2787 'permissions' => array('edit all contacts'),
2790 'title' => ts('Delete Contact'),
2792 'ref' => 'delete-contact',
2794 'permissions' => array('access deleted contacts', 'delete contacts'),
2796 'contribution' => array(
2797 'title' => ts('Add Contribution'),
2799 'ref' => 'new-contribution',
2800 'key' => 'contribution',
2801 'tab' => 'contribute',
2802 'component' => 'CiviContribute',
2803 'href' => CRM_Utils_System
::url('civicrm/contact/view/contribution',
2804 'reset=1&action=add&context=contribution'
2806 'permissions' => array(
2807 'access CiviContribute',
2808 'edit contributions',
2811 'participant' => array(
2812 'title' => ts('Register for Event'),
2814 'ref' => 'new-participant',
2815 'key' => 'participant',
2816 'tab' => 'participant',
2817 'component' => 'CiviEvent',
2818 'href' => CRM_Utils_System
::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
2819 'permissions' => array(
2821 'edit event participants',
2824 'activity' => array(
2825 'title' => ts('Record Activity'),
2827 'ref' => 'new-activity',
2828 'key' => 'activity',
2829 'permissions' => array('edit all contacts'),
2832 'title' => ts('Add Pledge'),
2834 'ref' => 'new-pledge',
2837 'href' => CRM_Utils_System
::url('civicrm/contact/view/pledge',
2838 'reset=1&action=add&context=pledge'
2840 'component' => 'CiviPledge',
2841 'permissions' => array(
2842 'access CiviPledge',
2846 'membership' => array(
2847 'title' => ts('Add Membership'),
2849 'ref' => 'new-membership',
2850 'key' => 'membership',
2852 'component' => 'CiviMember',
2853 'href' => CRM_Utils_System
::url('civicrm/contact/view/membership',
2854 'reset=1&action=add&context=membership'
2856 'permissions' => array(
2857 'access CiviMember',
2862 'title' => ts('Add Case'),
2864 'ref' => 'new-case',
2867 'component' => 'CiviCase',
2868 'href' => CRM_Utils_System
::url('civicrm/case/add', 'reset=1&action=add&context=case'),
2869 'permissions' => array('add cases'),
2872 'title' => ts('Add Grant'),
2874 'ref' => 'new-grant',
2877 'component' => 'CiviGrant',
2878 'href' => CRM_Utils_System
::url('civicrm/contact/view/grant',
2879 'reset=1&action=add&context=grant'
2881 'permissions' => array('edit grants'),
2884 'title' => ts('Add Relationship'),
2886 'ref' => 'new-relationship',
2889 'href' => CRM_Utils_System
::url('civicrm/contact/view/rel',
2890 'reset=1&action=add'
2892 'permissions' => array('edit all contacts'),
2895 'title' => ts('Add Note'),
2897 'ref' => 'new-note',
2900 'class' => 'medium-popup',
2901 'href' => CRM_Utils_System
::url('civicrm/contact/view/note',
2902 'reset=1&action=add'
2904 'permissions' => array('edit all contacts'),
2907 'title' => ts('Send an Email'),
2909 'ref' => 'new-email',
2911 'permissions' => array('view all contacts'),
2914 'title' => ts('Add to Group'),
2916 'ref' => 'group-add-contact',
2919 'permissions' => array('edit groups'),
2922 'title' => ts('Tag Contact'),
2924 'ref' => 'tag-contact',
2927 'permissions' => array('edit all contacts'),
2931 CRM_Utils_Hook
::summaryActions($menu, $contactId);
2932 //1. check for component is active.
2933 //2. check for user permissions.
2934 //3. check for acls.
2935 //3. edit and view contact are directly accessible to user.
2937 $aclPermissionedTasks = array(
2938 'view-contact', 'edit-contact', 'new-activity',
2939 'new-email', 'group-add-contact', 'tag-contact', 'delete-contact',
2941 $corePermission = CRM_Core_Permission
::getPermission();
2943 $config = CRM_Core_Config
::singleton();
2945 $contextMenu = array();
2946 foreach ($menu as $key => $values) {
2947 $componentName = CRM_Utils_Array
::value('component', $values);
2949 // if component action - make sure component is enable.
2950 if ($componentName && !in_array($componentName, $config->enableComponents
)) {
2954 // make sure user has all required permissions.
2955 $hasAllPermissions = FALSE;
2957 $permissions = CRM_Utils_Array
::value('permissions', $values);
2958 if (!is_array($permissions) ||
empty($permissions)) {
2959 $hasAllPermissions = TRUE;
2962 // iterate for required permissions in given permissions array.
2963 if (!$hasAllPermissions) {
2964 $hasPermissions = 0;
2965 foreach ($permissions as $permission) {
2966 if (CRM_Core_Permission
::check($permission)) {
2971 if (count($permissions) == $hasPermissions) {
2972 $hasAllPermissions = TRUE;
2975 // if still user does not have required permissions, check acl.
2976 if (!$hasAllPermissions && $values['ref'] != 'delete-contact') {
2977 if (in_array($values['ref'], $aclPermissionedTasks) &&
2978 $corePermission == CRM_Core_Permission
::EDIT
2980 $hasAllPermissions = TRUE;
2982 elseif (in_array($values['ref'], array(
2984 // grant permissions for these tasks.
2985 $hasAllPermissions = TRUE;
2990 // user does not have necessary permissions.
2991 if (!$hasAllPermissions) {
2995 // build directly accessible action menu.
2996 if (in_array($values['ref'], array(
2997 'view-contact', 'edit-contact'))) {
2998 $contextMenu['primaryActions'][$key] = array(
2999 'title' => $values['title'],
3000 'ref' => $values['ref'],
3001 'class' => CRM_Utils_Array
::value('class', $values),
3002 'key' => $values['key'],
3007 // finally get menu item for -more- action widget.
3008 $contextMenu['moreActions'][$values['weight']] = array(
3009 'title' => $values['title'],
3010 'ref' => $values['ref'],
3011 'href' => CRM_Utils_Array
::value('href', $values),
3012 'tab' => CRM_Utils_Array
::value('tab', $values),
3013 'class' => CRM_Utils_Array
::value('class', $values),
3014 'key' => $values['key'],
3018 ksort($contextMenu['moreActions']);
3020 return $contextMenu;
3024 * Function to retrieve display name of contact that address is shared
3025 * based on $masterAddressId or $contactId .
3027 * @param int $masterAddressId master id.
3028 * @param int $contactId contact id.
3030 * @return display name |null the found display name or null.
3034 static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3035 $masterDisplayName = NULL;
3037 if (!$masterAddressId && !$contactId) {
3038 return $masterDisplayName;
3041 if ($masterAddressId) {
3043 SELECT display_name from civicrm_contact
3044 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3045 WHERE civicrm_address.id = " . $masterAddressId;
3047 elseif ($contactId) {
3049 SELECT display_name from civicrm_contact cc, civicrm_address add1
3050 LEFT JOIN civicrm_address add2 ON ( add1.master_id = add2.id )
3051 WHERE cc.id = add2.contact_id AND add1.contact_id = " . $contactId;
3054 $masterDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
3055 return $masterDisplayName;
3059 * Get the creation/modification times for a contact
3063 * @return array('created_date' => $, 'modified_date' => $)
3065 static function getTimestamps($contactId) {
3066 $timestamps = CRM_Core_DAO
::executeQuery(
3067 'SELECT created_date, modified_date
3068 FROM civicrm_contact
3071 1 => array($contactId, 'Integer'),
3074 if ($timestamps->fetch()) {
3076 'created_date' => $timestamps->created_date
,
3077 'modified_date' => $timestamps->modified_date
,
3086 * Generate triggers to update the timestamp on the corresponding civicrm_contact row,
3087 * on insert/update/delete to a table that extends civicrm_contact.
3088 * Don't regenerate triggers for all such tables if only asked for one table.
3090 * @param array $info
3091 * Reference to the array where generated trigger information is being stored
3092 * @param string|null $reqTableName
3093 * Name of the table for which triggers are being generated, or NULL if all tables
3094 * @param array $relatedTableNames
3095 * Array of all core or all custom table names extending civicrm_contact
3096 * @param string $contactRefColumn
3097 * 'contact_id' if processing core tables, 'entity_id' if processing custom tables
3100 * @link https://issues.civicrm.org/jira/browse/CRM-15602
3105 static function generateTimestampTriggers(&$info, $reqTableName, $relatedTableNames, $contactRefColumn) {
3107 $contactRefColumn = CRM_Core_DAO
::escapeString($contactRefColumn);
3108 // If specific related table requested, just process that one
3109 if (in_array($reqTableName, $relatedTableNames)) {
3110 $relatedTableNames = array($reqTableName);
3113 // If no specific table requested (include all related tables),
3114 // or a specific related table requested (as matched above)
3115 if (empty($reqTableName) ||
in_array($reqTableName, $relatedTableNames)) {
3117 'table' => $relatedTableNames,
3119 'event' => array('INSERT', 'UPDATE'),
3120 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = NEW.$contactRefColumn;\n",
3123 'table' => $relatedTableNames,
3125 'event' => array('DELETE'),
3126 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = OLD.$contactRefColumn;\n",
3132 * Get a list of triggers for the contact table
3134 * @see hook_civicrm_triggerInfo
3135 * @see CRM_Core_DAO::triggerRebuild
3136 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3138 static function triggerInfo(&$info, $tableName = NULL) {
3139 //during upgrade, first check for valid version and then create triggers
3140 //i.e the columns created_date and modified_date are introduced in 4.3.alpha1 so dont create triggers for older version
3141 if (CRM_Core_Config
::isUpgradeMode()) {
3142 $currentVer = CRM_Core_BAO_Domain
::version(TRUE);
3143 //if current version is less than 4.3.alpha1 dont create below triggers
3144 if (version_compare($currentVer, '4.3.alpha1') < 0) {
3149 // Update timestamp for civicrm_contact itself
3150 if ($tableName == NULL ||
$tableName == self
::getTableName()) {
3152 'table' => array(self
::getTableName()),
3154 'event' => array('INSERT'),
3155 'sql' => "\nSET NEW.created_date = CURRENT_TIMESTAMP;\n",
3159 // Update timestamp when modifying closely related core tables
3160 $relatedTables = array(
3167 self
::generateTimestampTriggers($info, $tableName, $relatedTables, 'contact_id');
3169 // Update timestamp when modifying related custom-data tables
3170 $customGroupTables = array();
3171 $customGroupDAO = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity('Contact');
3172 $customGroupDAO->is_multiple
= 0;
3173 $customGroupDAO->find();
3174 while ($customGroupDAO->fetch()) {
3175 $customGroupTables[] = $customGroupDAO->table_name
;
3177 if (!empty($customGroupTables)) {
3178 self
::generateTimestampTriggers($info, $tableName, $customGroupTables, 'entity_id');
3181 // Update phone table to populate phone_numeric field
3182 if (!$tableName ||
$tableName == 'civicrm_phone') {
3183 // Define stored sql function needed for phones
3184 CRM_Core_DAO
::executeQuery(self
::DROP_STRIP_FUNCTION_43
);
3185 CRM_Core_DAO
::executeQuery(self
::CREATE_STRIP_FUNCTION_43
);
3187 'table' => array('civicrm_phone'),
3189 'event' => array('INSERT', 'UPDATE'),
3190 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3196 * Function to check if contact is being used in civicrm_domain
3197 * based on $contactId
3199 * @param int $contactId contact id.
3201 * @return bool true if present else false.
3205 static function checkDomainContact($contactId) {
3208 $domainId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3218 * Get options for a given contact field.
3219 * @see CRM_Core_DAO::buildOptions
3221 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3222 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3224 * @param String $fieldName
3225 * @param String $context : @see CRM_Core_DAO::buildOptionsContext
3226 * @param Array $props : whatever is known about this dao object
3228 * @return Array|bool
3230 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3232 // Special logic for fields whose options depend on context or properties
3233 switch ($fieldName) {
3234 case 'contact_sub_type':
3235 if (!empty($props['contact_type'])) {
3236 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3240 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
3244 * Delete a contact-related object that has an 'is_primary' field
3245 * Ensures that is_primary gets assigned to another object if available
3246 * Also calls pre/post hooks
3248 * @var $type : object type
3249 * @var $id : object id
3252 public static function deleteObjectWithPrimary($type, $id) {
3253 if (!$id ||
!is_numeric($id)) {
3256 $daoName = "CRM_Core_DAO_$type";
3257 $obj = new $daoName();
3260 if ($obj->fetch()) {
3261 CRM_Utils_Hook
::pre('delete', $type, $id, CRM_Core_DAO
::$_nullArray);
3262 $contactId = $obj->contact_id
;
3268 // is_primary is only relavent if this field belongs to a contact
3270 $dao = new $daoName();
3271 $dao->contact_id
= $contactId;
3272 $dao->is_primary
= 1;
3273 // Pick another record to be primary (if one isn't already)
3274 if (!$dao->find(TRUE)) {
3275 $dao->is_primary
= 0;
3277 if ($dao->fetch()) {
3278 $dao->is_primary
= 1;
3284 CRM_Utils_Hook
::post('delete', $type, $id, $obj);