3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
35 class CRM_Contact_BAO_Contact
extends CRM_Contact_DAO_Contact
{
38 * SQL function used to format the phone_numeric field via trigger.
39 * @see self::triggerInfo()
41 * Note that this is also used by the 4.3 upgrade script.
42 * @see CRM_Upgrade_Incremental_php_FourThree
44 const DROP_STRIP_FUNCTION_43
= "DROP FUNCTION IF EXISTS civicrm_strip_non_numeric";
45 const CREATE_STRIP_FUNCTION_43
= "
46 CREATE FUNCTION civicrm_strip_non_numeric(input VARCHAR(255) CHARACTER SET utf8)
47 RETURNS VARCHAR(255) CHARACTER SET utf8
51 DECLARE output VARCHAR(255) CHARACTER SET utf8 DEFAULT '';
52 DECLARE iterator INT DEFAULT 1;
53 WHILE iterator < (LENGTH(input) + 1) DO
54 IF SUBSTRING(input, iterator, 1) IN ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') THEN
55 SET output = CONCAT(output, SUBSTRING(input, iterator, 1));
57 SET iterator = iterator + 1;
63 * the types of communication preferences
67 static $_commPrefs = array('do_not_phone', 'do_not_email', 'do_not_mail', 'do_not_sms', 'do_not_trade');
74 static $_greetingTypes = array('addressee', 'email_greeting', 'postal_greeting');
77 * static field for all the contact information that we can potentially import
82 static $_importableFields = array();
85 * static field for all the contact information that we can potentially export
90 static $_exportableFields = NULL;
96 * @return \CRM_Contact_DAO_Contact
101 function __construct() {
102 parent
::__construct();
106 * takes an associative array and creates a contact object
108 * the function extract all the params it needs to initialize the create a
109 * contact object. the params array could contain additional unused name/value
112 * @param array $params (reference ) an assoc array of name/value pairs
114 * @return object CRM_Contact_BAO_Contact object
118 static function add(&$params) {
119 $contact = new CRM_Contact_DAO_Contact();
121 if (empty($params)) {
125 //fix for validate contact sub type CRM-5143
126 if ( isset( $params['contact_sub_type'] ) ) {
127 if ( empty($params['contact_sub_type']) ) {
128 $params['contact_sub_type'] = 'null';
131 if (!CRM_Contact_BAO_ContactType
::isExtendsContactType($params['contact_sub_type'],
132 $params['contact_type'], TRUE
134 // we'll need to fix tests to handle this
136 CRM_Core_Error
::fatal(ts('The Contact Sub Type does not match the Contact type for this record'));
138 if (is_array($params['contact_sub_type'])) {
139 $params['contact_sub_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $params['contact_sub_type']) . CRM_Core_DAO
::VALUE_SEPARATOR
;
142 $params['contact_sub_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. trim($params['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
149 $params['contact_sub_type'] = 'null';
152 //fixed contact source
153 if (isset($params['contact_source'])) {
154 $params['source'] = $params['contact_source'];
157 //fix for preferred communication method
158 $prefComm = CRM_Utils_Array
::value('preferred_communication_method', $params);
159 if ($prefComm && is_array($prefComm)) {
160 unset($params['preferred_communication_method']);
163 foreach ($prefComm as $k => $v) {
169 $prefComm = $newPref;
170 if (is_array($prefComm) && !empty($prefComm)) {
171 $prefComm = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, array_keys($prefComm)) . CRM_Core_DAO
::VALUE_SEPARATOR
;
172 $contact->preferred_communication_method
= $prefComm;
175 $contact->preferred_communication_method
= '';
179 $allNull = $contact->copyValues($params);
181 $contact->id
= CRM_Utils_Array
::value('contact_id', $params);
183 if ($contact->contact_type
== 'Individual') {
186 //format individual fields
187 CRM_Contact_BAO_Individual
::format($params, $contact);
189 elseif ($contact->contact_type
== 'Household') {
190 if (isset($params['household_name'])) {
192 $contact->display_name
= $contact->sort_name
= CRM_Utils_Array
::value('household_name', $params, '');
195 elseif ($contact->contact_type
== 'Organization') {
196 if (isset($params['organization_name'])) {
198 $contact->display_name
= $contact->sort_name
= CRM_Utils_Array
::value('organization_name', $params, '');
203 $privacy = CRM_Utils_Array
::value('privacy', $params);
205 is_array($privacy) &&
209 foreach (self
::$_commPrefs as $name) {
210 $contact->$name = CRM_Utils_Array
::value($name, $privacy, FALSE);
214 // since hash was required, make sure we have a 0 value for it, CRM-1063
215 // fixed in 1.5 by making hash optional
216 // only do this in create mode, not update
217 if ((!array_key_exists('hash', $contact) ||
!$contact->hash
) && !$contact->id
) {
219 $contact->hash
= md5(uniqid(rand(), TRUE));
222 // Even if we don't need $employerId, it's important to call getFieldValue() before
223 // the contact is saved because we want the existing value to be cached.
224 // createCurrentEmployerRelationship() needs the old value not the updated one. CRM-10788
225 $employerId = empty($contact->id
) ?
NULL : CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contact->id
, 'employer_id');
230 CRM_Core_BAO_Log
::register($contact->id
,
236 if ($contact->contact_type
== 'Individual' && (isset($params['current_employer']) ||
isset($params['employer_id']))) {
237 $newEmployer = !empty($params['employer_id']) ?
$params['employer_id'] : CRM_Utils_Array
::value('current_employer', $params);
238 // create current employer
240 CRM_Contact_BAO_Contact_Utils
::createCurrentEmployerRelationship($contact->id
, $newEmployer, $employerId);
243 //unset if employer id exits
245 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($contact->id
, $employerId);
250 //update cached employee name
251 if ($contact->contact_type
== 'Organization') {
252 CRM_Contact_BAO_Contact_Utils
::updateCurrentEmployer($contact->id
);
259 * Function to create contact
260 * takes an associative array and creates a contact object and all the associated
261 * derived objects (i.e. individual, location, email, phone etc)
263 * This function is invoked from within the web form layer and also from the api layer
265 * @param array $params (reference ) an assoc array of name/value pairs
266 * @param boolean $fixAddress if we need to fix address
267 * @param boolean $invokeHooks if we need to invoke hooks
269 * @param bool $skipDelete
272 * @return object CRM_Contact_BAO_Contact object
276 static function &create(&$params, $fixAddress = TRUE, $invokeHooks = TRUE, $skipDelete = FALSE) {
278 if (empty($params['contact_type']) && empty($params['contact_id'])) {
284 if (!empty($params['contact_id'])) {
285 CRM_Utils_Hook
::pre('edit', $params['contact_type'], $params['contact_id'], $params);
288 CRM_Utils_Hook
::pre('create', $params['contact_type'], NULL, $params);
293 $config = CRM_Core_Config
::singleton();
295 // CRM-6942: set preferred language to the current language if it’s unset (and we’re creating a contact)
296 if (empty($params['contact_id']) && empty($params['preferred_language'])) {
297 $params['preferred_language'] = $config->lcMessages
;
300 // CRM-9739: set greeting & addressee if unset and we’re creating a contact
301 if (empty($params['contact_id'])) {
302 foreach (self
::$_greetingTypes as $greeting) {
303 if (empty($params[$greeting . '_id'])) {
304 if ($defaultGreetingTypeId =
305 CRM_Contact_BAO_Contact_Utils
::defaultGreeting($params['contact_type'], $greeting)
307 $params[$greeting . '_id'] = $defaultGreetingTypeId;
313 $transaction = new CRM_Core_Transaction();
315 $contact = self
::add($params);
317 // not dying here is stupid, since we get into wierd situation and into a bug that
318 // is impossible to figure out for the user or for us
320 CRM_Core_Error
::fatal();
323 $params['contact_id'] = $contact->id
;
325 if (CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
328 // Enabling multisite causes the contact to be added to the domain group
329 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
330 if(!empty($domainGroupID)){
331 if (!empty($params['group']) && is_array($params['group'])) {
332 $params['group'][$domainGroupID] = 1;
335 $params['group'] = array($domainGroupID => 1);
340 if (array_key_exists('group', $params)) {
341 $contactIds = array($params['contact_id']);
342 foreach ($params['group'] as $groupId => $flag) {
344 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
346 elseif ($flag == -1) {
347 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $groupId);
352 //add location Block data
353 $blocks = CRM_Core_BAO_Location
::create($params, $fixAddress);
354 foreach ($blocks as $name => $value) {
355 $contact->$name = $value;
359 CRM_Core_BAO_Website
::create($params['website'], $contact->id
, $skipDelete);
361 //get userID from session
362 $session = CRM_Core_Session
::singleton();
363 $userID = $session->get('userID');
365 if (!empty($params['note'])) {
366 if (is_array($params['note'])) {
367 foreach ($params['note'] as $note) {
368 $contactId = $contact->id
;
369 if (isset($note['contact_id'])) {
370 $contactId = $note['contact_id'];
372 //if logged in user, overwrite contactId
374 $contactId = $userID;
378 'entity_id' => $contact->id
,
379 'entity_table' => 'civicrm_contact',
380 'note' => $note['note'],
381 'subject' => CRM_Utils_Array
::value('subject', $note),
382 'contact_id' => $contactId,
384 CRM_Core_BAO_Note
::add($noteParams, CRM_Core_DAO
::$_nullArray);
388 $contactId = $contact->id
;
389 if (isset($note['contact_id'])) {
390 $contactId = $note['contact_id'];
392 //if logged in user, overwrite contactId
394 $contactId = $userID;
398 'entity_id' => $contact->id
,
399 'entity_table' => 'civicrm_contact',
400 'note' => $params['note'],
401 'subject' => CRM_Utils_Array
::value('subject', $params),
402 'contact_id' => $contactId,
404 CRM_Core_BAO_Note
::add($noteParams, CRM_Core_DAO
::$_nullArray);
409 // update the UF user_unique_id if that has changed
410 CRM_Core_BAO_UFMatch
::updateUFName($contact->id
);
412 if (!empty($params['custom']) &&
413 is_array($params['custom'])
415 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contact', $contact->id
);
418 // make a civicrm_subscription_history entry only on contact create (CRM-777)
419 if (empty($params['contact_id'])) {
420 $subscriptionParams = array(
421 'contact_id' => $contact->id
,
425 CRM_Contact_BAO_SubscriptionHistory
::create($subscriptionParams);
428 $transaction->commit();
430 // CRM-6367: fetch the right label for contact type’s display
431 $contact->contact_type_display
= CRM_Core_DAO
::getFieldValue(
432 'CRM_Contact_DAO_ContactType',
433 $contact->contact_type
,
438 if (!$config->doNotResetCache
) {
439 // Note: doNotResetCache flag is currently set by import contact process and merging,
440 // since resetting and
441 // rebuilding cache could be expensive (for many contacts). We might come out with better
442 // approach in future.
443 CRM_Contact_BAO_Contact_Utils
::clearContactCaches($contact->id
);
448 CRM_Utils_Hook
::post('edit', $params['contact_type'], $contact->id
, $contact);
451 CRM_Utils_Hook
::post('create', $params['contact_type'], $contact->id
, $contact);
455 // process greetings CRM-4575, cache greetings
456 self
::processGreetings($contact);
462 * Get the display name and image of a contact
464 * @param int $id the contactId
468 * @return array the displayName and contactImage for this contact
472 static function getDisplayAndImage($id, $type = FALSE) {
473 //CRM-14276 added the * on the civicrm_contact table so that we have all the contact info available
475 SELECT civicrm_contact.*,
476 civicrm_email.email as email
478 LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
479 AND civicrm_email.is_primary = 1
480 WHERE civicrm_contact.id = " . CRM_Utils_Type
::escape($id, 'Integer');
481 $dao = new CRM_Core_DAO();
484 $image = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
485 $dao->contact_sub_type
: $dao->contact_type
, FALSE, $id
487 $imageUrl = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
488 $dao->contact_sub_type
: $dao->contact_type
, TRUE, $id
491 // use email if display_name is empty
492 if (empty($dao->display_name
)) {
493 $displayName = $dao->email
;
496 $displayName = $dao->display_name
;
499 CRM_Utils_Hook
::alterDisplayName($displayName, $id, $dao);
501 return $type ?
array(
505 $dao->contact_sub_type
,
507 ) : array($displayName, $image, $imageUrl);
513 * @param array $crudLinkSpec with keys:
514 * - action: int, CRM_Core_Action::UPDATE or CRM_Core_Action::VIEW [default: VIEW]
515 * - entity_table: string, eg "civicrm_contact"
517 * @return array|NULL NULL if unavailable, or an array. array has keys:
521 * @see CRM_Utils_System::createDefaultCrudLink
523 public function createDefaultCrudLink($crudLinkSpec) {
524 switch ($crudLinkSpec['action']) {
525 case CRM_Core_Action
::VIEW
:
527 'title' => $this->display_name
,
528 'path' => 'civicrm/contact/view',
534 case CRM_Core_Action
::UPDATE
:
536 'title' => $this->display_name
,
537 'path' => 'civicrm/contact/add',
540 'action' => 'update',
550 * Get the values for pseudoconstants for name->value and reverse.
552 * @param array $defaults (reference) the default values, some of which need to be resolved.
553 * @param boolean $reverse true if we want to resolve the values in the reverse direction (value -> name)
559 static function resolveDefaults(&$defaults, $reverse = FALSE) {
560 // hack for birth_date
561 if (!empty($defaults['birth_date'])) {
562 if (is_array($defaults['birth_date'])) {
563 $defaults['birth_date'] = CRM_Utils_Date
::format($defaults['birth_date'], '-');
567 CRM_Utils_Array
::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id'), $reverse);
568 CRM_Utils_Array
::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'suffix_id'), $reverse);
569 CRM_Utils_Array
::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'), $reverse);
570 CRM_Utils_Array
::lookupValue($defaults, 'communication_style', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'communication_style_id'), $reverse);
572 //lookup value of email/postal greeting, addressee, CRM-4575
573 foreach (self
::$_greetingTypes as $greeting) {
574 $filterCondition = array('contact_type' => CRM_Utils_Array
::value('contact_type', $defaults),
575 'greeting_type' => $greeting,
577 CRM_Utils_Array
::lookupValue($defaults, $greeting,
578 CRM_Core_PseudoConstant
::greeting($filterCondition), $reverse
582 $blocks = array('address', 'im', 'phone');
583 foreach ($blocks as $name) {
584 if (!array_key_exists($name, $defaults) ||
!is_array($defaults[$name])) {
587 foreach ($defaults[$name] as $count => & $values) {
589 //get location type id.
590 CRM_Utils_Array
::lookupValue($values, 'location_type', CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id'), $reverse);
592 if ($name == 'address') {
593 // FIXME: lookupValue doesn't work for vcard_name
594 if (!empty($values['location_type_id'])) {
595 $vcardNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array('labelColumn' => 'vcard_name'));
596 $values['vcard_name'] = $vcardNames[$values['location_type_id']];
599 if (!CRM_Utils_Array
::lookupValue($values,
601 CRM_Core_PseudoConstant
::country(),
606 CRM_Utils_Array
::lookupValue($values,
608 CRM_Core_PseudoConstant
::countryIsoCode(),
614 // if we find a country id above, we need to restrict it to that country
615 // rather than the list of all countries
617 if (!empty($values['country_id'])) {
618 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($values['country_id']);
621 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvince();
623 if (!CRM_Utils_Array
::lookupValue($values,
631 if (!empty($values['country_id'])) {
632 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($values['country_id'], 'abbreviation');
635 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviation();
637 CRM_Utils_Array
::lookupValue($values,
644 if (!empty($values['state_province_id'])) {
645 $countyList = CRM_Core_PseudoConstant
::countyForState($values['state_province_id']);
648 $countyList = CRM_Core_PseudoConstant
::county();
650 CRM_Utils_Array
::lookupValue($values,
658 CRM_Utils_Array
::lookupValue($values,
660 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id'),
665 if ($name == 'phone') {
666 CRM_Utils_Array
::lookupValue($values,
668 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id'),
673 //kill the reference.
680 * Takes a bunch of params that are needed to match certain criteria and
681 * retrieves the relevant objects. Typically the valid params are only
682 * contact_id. We'll tweak this function to be more full featured over a period
683 * of time. This is the inverse function of create. It also stores all the retrieved
684 * values in the default array
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 object 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 * function to 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 * function to 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 * function to return relative path
901 * @todo make this a method of $config->userSystem (i.e. UF classes) rather than a static function
903 * @param $absolutePath
905 * @internal param String $absPath absolute path
907 * @return String $relativePath Relative url of uploaded image
909 public static function getRelativePath($absolutePath) {
910 $relativePath = NULL;
911 $config = CRM_Core_Config
::singleton();
912 if ($config->userFramework
== 'Joomla') {
913 $userFrameworkBaseURL = trim(str_replace('/administrator/', '', $config->userFrameworkBaseURL
));
914 $customFileUploadDirectory = strstr(str_replace('\\', '/', $absolutePath), '/media');
915 $relativePath = $userFrameworkBaseURL . $customFileUploadDirectory;
917 elseif ($config->userSystem
->is_drupal
== '1') {
918 //ideally we would do a bigger re-factoring & move the getRelativePath onto the UF class
919 $rootPath = $config->userSystem
->cmsRootPath();
920 $baseUrl = $config->userFrameworkBaseURL
;
922 //format url for language negotiation, CRM-7135
923 $baseUrl = CRM_Utils_System
::languageNegotiationURL($baseUrl, FALSE, TRUE);
925 $relativePath = str_replace("{$rootPath}/",
927 str_replace('\\', '/', $absolutePath)
929 } else if ( $config->userFramework
== 'WordPress' ) {
930 $userFrameworkBaseURL = trim( str_replace( '/wp-admin/', '', $config->userFrameworkBaseURL
) );
931 $customFileUploadDirectory = strstr( str_replace('\\', '/', $absolutePath), '/wp-content/' );
932 $relativePath = $userFrameworkBaseURL . $customFileUploadDirectory;
935 return $relativePath;
939 * function to return proportional height and width of the image
941 * @param Integer $imageWidth width of image
943 * @param Integer $imageHeight height of image
945 * @return Array thumb dimension of image
947 public static function getThumbSize($imageWidth, $imageHeight) {
949 if ($imageWidth && $imageHeight) {
950 $imageRatio = $imageWidth / $imageHeight;
955 if ($imageRatio > 1) {
956 $imageThumbWidth = $thumbWidth;
957 $imageThumbHeight = round($thumbWidth / $imageRatio);
960 $imageThumbHeight = $thumbWidth;
961 $imageThumbWidth = round($thumbWidth * $imageRatio);
964 return array($imageThumbWidth, $imageThumbHeight);
968 * function to validate type of contact image
971 * @param String $imageIndex index of image field
973 * @param String $statusMsg status message to be set after operation
975 * @param string $opType
977 * @internal param Array $param array of contact/profile field to be edited/added
979 * @opType String $opType type of operation like fatal, bounce etc
981 * @return boolean true if valid image extension
983 public static function processImageParams(&$params,
984 $imageIndex = 'image_URL',
998 if (in_array($params[$imageIndex]['type'], $mimeType)) {
999 $photo = basename($params[$imageIndex]['name']);
1000 $params[$imageIndex] = CRM_Utils_System
::url('civicrm/contact/imagefile', 'photo='.$photo, TRUE);
1004 unset($params[$imageIndex]);
1006 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
1008 if ($opType == 'status') {
1009 CRM_Core_Session
::setStatus($statusMsg, 'Sorry', 'error');
1011 // FIXME: additional support for fatal, bounce etc could be added.
1017 * function to extract contact id from url for deleting contact image
1019 public static function processImage() {
1021 $action = CRM_Utils_Request
::retrieve('action', 'String');
1022 $cid = CRM_Utils_Request
::retrieve('cid', 'Positive');
1023 // retrieve contact id in case of Profile context
1024 $id = CRM_Utils_Request
::retrieve('id', 'Positive');
1025 $cid = $cid ?
$cid : $id;
1026 if ($action & CRM_Core_Action
::DELETE
) {
1027 if (CRM_Utils_Request
::retrieve('confirmed', 'Boolean')) {
1028 CRM_Contact_BAO_Contact
::deleteContactImage($cid);
1029 CRM_Core_Session
::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
1030 $session = CRM_Core_Session
::singleton();
1031 $toUrl = $session->popUserContext();
1032 CRM_Utils_System
::redirect($toUrl);
1038 * Function to set is_delete true or restore deleted contact
1040 * @param int $contact Contact DAO object
1041 * @param boolean $restore true to set the is_delete = 1 else false to restore deleted contact,
1042 * i.e. is_delete = 0
1047 static function contactTrashRestore($contact, $restore = FALSE) {
1048 $op = ($restore ?
'restore' : 'trash');
1050 CRM_Utils_Hook
::pre($op, $contact->contact_type
, $contact->id
, CRM_Core_DAO
::$_nullArray);
1052 $params = array(1 => array($contact->id
, 'Integer'));
1053 $isDelete = ' is_deleted = 1 ';
1055 $isDelete = ' is_deleted = 0 ';
1058 $query = "DELETE FROM civicrm_uf_match WHERE contact_id = %1";
1059 CRM_Core_DAO
::executeQuery($query, $params);
1062 $query = "UPDATE civicrm_contact SET {$isDelete} WHERE id = %1";
1063 CRM_Core_DAO
::executeQuery($query, $params);
1065 CRM_Utils_Hook
::post($op, $contact->contact_type
, $contact->id
, $contact);
1069 * Get contact type for a contact.
1071 * @param int $id - id of the contact whose contact type is needed
1073 * @return string contact_type if $id found else null ""
1080 public static function getContactType($id) {
1081 return CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1085 * Get contact sub type for a contact.
1087 * @param int $id - id of the contact whose contact sub type is needed
1089 * @param null $implodeDelimiter
1091 * @return string contact_sub_type if $id found else null ""
1097 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1098 $subtype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1100 return $implodeDelimiter ?
NULL : array();
1103 $subtype = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($subtype, CRM_Core_DAO
::VALUE_SEPARATOR
));
1105 if ($implodeDelimiter) {
1106 $subtype = implode($implodeDelimiter, $subtype);
1112 * Get pair of contact-type and sub-type for a contact.
1114 * @param int $id - id of the contact whose contact sub/contact type is needed
1123 public static function getContactTypes($id) {
1124 $params = array('id' => $id);
1126 $contact = CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact',
1129 array('contact_type', 'contact_sub_type')
1133 $contactTypes = array();
1134 if ($contact->contact_sub_type
)
1135 $contactTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($contact->contact_sub_type
, CRM_Core_DAO
::VALUE_SEPARATOR
));
1136 array_unshift($contactTypes, $contact->contact_type
);
1138 return $contactTypes;
1141 CRM_Core_Error
::fatal();
1146 * combine all the importable fields from the lower levels object
1148 * The ordering is important, since currently we do not have a weight
1149 * scheme. Adding weight is super important
1151 * @param int|string $contactType contact Type
1152 * @param boolean $status status is used to manipulate first title
1153 * @param boolean $showAll if true returns all fields (includes disabled fields)
1154 * @param boolean $isProfile if its profile mode
1155 * @param boolean $checkPermission if false, do not include permissioning clause (for custom data)
1157 * @param bool $withMultiCustomFields
1159 * @return array array of importable Fields
1163 static function importableFields($contactType = 'Individual',
1167 $checkPermission = TRUE,
1168 $withMultiCustomFields = FALSE
1170 if (empty($contactType)) {
1171 $contactType = 'All';
1174 $cacheKeyString = "importableFields $contactType";
1175 $cacheKeyString .= $status ?
'_1' : '_0';
1176 $cacheKeyString .= $showAll ?
'_1' : '_0';
1177 $cacheKeyString .= $isProfile ?
'_1' : '_0';
1178 $cacheKeyString .= $checkPermission ?
'_1' : '_0';
1180 $fields = CRM_Utils_Array
::value($cacheKeyString, self
::$_importableFields);
1183 // check if we can retrieve from database cache
1184 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1188 $fields = CRM_Contact_DAO_Contact
::import();
1190 // get the fields thar are meant for contact types
1191 if (in_array($contactType, array(
1192 'Individual', 'Household', 'Organization', 'All'))) {
1193 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1196 $locationFields = array_merge(CRM_Core_DAO_Address
::import(),
1197 CRM_Core_DAO_Phone
::import(),
1198 CRM_Core_DAO_Email
::import(),
1199 CRM_Core_DAO_IM
::import(TRUE),
1200 CRM_Core_DAO_OpenID
::import()
1203 $locationFields = array_merge($locationFields,
1204 CRM_Core_BAO_CustomField
::getFieldsForImport('Address',
1212 foreach ($locationFields as $key => $field) {
1213 $locationFields[$key]['hasLocationType'] = TRUE;
1216 $fields = array_merge($fields, $locationFields);
1218 $fields = array_merge($fields, CRM_Contact_DAO_Contact
::import());
1219 $fields = array_merge($fields, CRM_Core_DAO_Note
::import());
1222 $fields = array_merge($fields, CRM_Core_DAO_Website
::import());
1223 $fields['url']['hasWebsiteType'] = TRUE;
1225 if ($contactType != 'All') {
1226 $fields = array_merge($fields,
1227 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType,
1232 $withMultiCustomFields
1235 //unset the fields, which are not related to their
1237 $commonValues = array(
1238 'Individual' => array(
1244 'Household' => array(
1254 'organization_name',
1262 'Organization' => array(
1277 foreach ($commonValues[$contactType] as $value) {
1278 unset($fields[$value]);
1283 'Individual', 'Household', 'Organization') as $type) {
1284 $fields = array_merge($fields,
1285 CRM_Core_BAO_CustomField
::getFieldsForImport($type,
1290 $withMultiCustomFields
1297 $fields = array_merge($fields, array(
1299 'title' => ts('Group(s)'),
1303 'title' => ts('Tag(s)'),
1307 'title' => ts('Note(s)'),
1313 //Sorting fields in alphabetical order(CRM-1507)
1314 $fields = CRM_Utils_Array
::crmArraySortByField($fields, 'title');
1316 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1319 self
::$_importableFields[$cacheKeyString] = $fields;
1323 $fields = array_merge(array('do_not_import' => array('title' => ts('- do not import -'))),
1324 self
::$_importableFields[$cacheKeyString]
1328 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1329 self
::$_importableFields[$cacheKeyString]
1337 * combine all the exportable fields from the lower levels object
1339 * currentlty we are using importable fields as exportable fields
1341 * @param int|string $contactType contact Type
1342 * @param boolean $status true while exporting primary contacts
1343 * @param boolean $export true when used during export
1344 * @param boolean $search true when used during search, might conflict with export param?
1346 * @param bool $withMultiRecord
1348 * @return array array of exportable Fields
1352 static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE) {
1353 if (empty($contactType)) {
1354 $contactType = 'All';
1357 $cacheKeyString = "exportableFields $contactType";
1358 $cacheKeyString .= $export ?
'_1' : '_0';
1359 $cacheKeyString .= $status ?
'_1' : '_0';
1360 $cacheKeyString .= $search ?
'_1' : '_0';
1361 //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
1362 //calculates custom fields takes into account the logged in user & caches that for all users
1363 //as an interim fix we will cache the fields by contact
1364 $cacheKeyString .= '_' . CRM_Core_Session
::getLoggedInContactID();
1366 if (!self
::$_exportableFields ||
!CRM_Utils_Array
::value($cacheKeyString, self
::$_exportableFields)) {
1367 if (!self
::$_exportableFields) {
1368 self
::$_exportableFields = array();
1371 // check if we can retrieve from database cache
1372 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1375 $fields = CRM_Contact_DAO_Contact
::export();
1377 // the fields are meant for contact types
1381 array('Individual', 'Household', 'Organization', 'All')
1384 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1386 // add current employer for individuals
1387 $fields = array_merge($fields, array(
1388 'current_employer' =>
1390 'name' => 'organization_name',
1391 'title' => ts('Current Employer'),
1395 $locationType = array(
1396 'location_type' => array(
1397 'name' => 'location_type',
1398 'where' => 'civicrm_location_type.name',
1399 'title' => ts('Location Type'),
1402 $IMProvider = array(
1403 'im_provider' => array(
1404 'name' => 'im_provider',
1405 'where' => 'civicrm_im.provider_id',
1406 'title' => ts('IM Provider'),
1409 $locationFields = array_merge($locationType,
1410 CRM_Core_DAO_Address
::export(),
1411 CRM_Core_DAO_Phone
::export(),
1412 CRM_Core_DAO_Email
::export(),
1414 CRM_Core_DAO_IM
::export(TRUE),
1415 CRM_Core_DAO_OpenID
::export()
1418 $locationFields = array_merge($locationFields,
1419 CRM_Core_BAO_CustomField
::getFieldsForImport('Address')
1422 foreach ($locationFields as $key => $field) {
1423 $locationFields[$key]['hasLocationType'] = TRUE;
1426 $fields = array_merge($fields, $locationFields);
1429 $fields = array_merge($fields,
1430 CRM_Core_DAO_Worldregion
::export()
1434 $fields = array_merge($fields,
1435 CRM_Contact_DAO_Contact
::export()
1439 $fields = array_merge($fields, CRM_Core_DAO_Website
::export());
1441 if ($contactType != 'All') {
1442 $fields = array_merge($fields,
1443 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType, $status, TRUE, $search, TRUE, $withMultiRecord)
1448 'Individual', 'Household', 'Organization') as $type) {
1449 $fields = array_merge($fields,
1450 CRM_Core_BAO_CustomField
::getFieldsForImport($type, FALSE, FALSE, $search, TRUE, $withMultiRecord)
1457 $fields = array_merge($fields, array(
1459 'title' => ts('Group(s)'),
1463 'title' => ts('Tag(s)'),
1467 'title' => ts('Note(s)'),
1473 $fields = array_merge($fields, array(
1475 'title' => ts('Group(s)'),
1479 'title' => ts('Tag(s)'),
1483 'title' => ts('Note(s)'),
1489 //Sorting fields in alphabetical order(CRM-1507)
1490 foreach ($fields as $k => $v) {
1491 $sortArray[$k] = CRM_Utils_Array
::value('title', $v);
1494 $fields = array_merge($sortArray, $fields);
1495 //unset the field which are not related to their contact type.
1496 if ($contactType != 'All') {
1497 $commonValues = array(
1498 'Individual' => array(
1502 'organization_name',
1503 'email_greeting_custom',
1504 'postal_greeting_custom',
1507 'Household' => array(
1517 'organization_name',
1525 'email_greeting_custom',
1526 'postal_greeting_custom',
1531 'Organization' => array(
1542 'email_greeting_custom',
1543 'postal_greeting_custom',
1553 foreach ($commonValues[$contactType] as $value) {
1554 unset($fields[$value]);
1558 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1560 self
::$_exportableFields[$cacheKeyString] = $fields;
1564 $fields = self
::$_exportableFields[$cacheKeyString];
1567 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1568 self
::$_exportableFields[$cacheKeyString]
1576 * Function to get the all contact details(Hierarchical)
1578 * @param int $contactId contact id
1579 * @param array $fields fields array
1581 * @return $values array contains the contact details
1585 static function getHierContactDetails($contactId, &$fields) {
1586 $params = array(array('contact_id', '=', $contactId, 0, 0));
1589 $returnProperties = self
::makeHierReturnProperties($fields, $contactId);
1591 // we dont know the contents of return properties, but we need the lower level ids of the contact
1592 // so add a few fields
1593 $returnProperties['first_name'] =
1594 $returnProperties['organization_name'] =
1595 $returnProperties['household_name'] =
1596 $returnProperties['contact_type'] =
1597 $returnProperties['contact_sub_type'] = 1;
1598 return list($query, $options) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, $options);
1602 * given a set of flat profile style field names, create a hierarchy
1603 * for query to use and crete the right sql
1606 * @param int $contactId contact id
1608 * @internal param array $properties a flat return properties name value array
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 * Function to 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
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 * function to 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 * function to add/edit/register contacts through profile.
1785 * @params array $params Array of profile fields to be edited/added.
1786 * @params int $contactID contact_id of the contact to be edited/added.
1787 * @params array $fields array of fields from UFGroup
1788 * @params int $addToGroupID specifies the default group to which contact is added.
1789 * @params int $ufGroupId uf group id (profile id)
1792 * @param null $contactID
1793 * @param null $addToGroupID
1794 * @param null $ufGroupId
1795 * @param string $ctype contact type
1796 * @param boolean $visibility basically lets us know where this request is coming from
1797 * if via a profile from web, we restrict what groups are changed
1799 * @return int contact id created/edited
1803 static function createProfileContact(
1807 $addToGroupID = NULL,
1812 // add ufGroupID to params array ( CRM-2012 )
1814 $params['uf_group_id'] = $ufGroupId;
1819 CRM_Utils_Hook
::pre('edit', 'Profile', $contactID, $params);
1823 CRM_Utils_Hook
::pre('create', 'Profile', NULL, $params);
1826 list($data, $contactDetails) = self
::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
1828 // manage is_opt_out
1829 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
1830 $wasOptOut = CRM_Utils_Array
::value('is_opt_out', $contactDetails, FALSE);
1831 $isOptOut = CRM_Utils_Array
::value('is_opt_out', $params, FALSE);
1832 $data['is_opt_out'] = $isOptOut;
1833 // on change, create new civicrm_subscription_history entry
1834 if (($wasOptOut != $isOptOut) && !empty($contactDetails['contact_id'])) {
1836 'contact_id' => $contactDetails['contact_id'],
1837 'status' => $isOptOut ?
'Removed' : 'Added',
1840 CRM_Contact_BAO_SubscriptionHistory
::create($shParams);
1844 $contact = self
::create($data);
1846 // contact is null if the profile does not have any contact fields
1848 $contactID = $contact->id
;
1851 if (empty($contactID)) {
1852 CRM_Core_Error
::fatal('Cannot proceed without a valid contact id');
1855 // Process group and tag
1856 if (!empty($fields['group'])) {
1858 // this for sure means we are coming in via profile since i added it to fix
1859 // removing contacts from user groups -- lobo
1863 CRM_Contact_BAO_GroupContact
::create($params['group'], $contactID, $visibility, $method);
1866 if (!empty($fields['tag'])) {
1867 CRM_Core_BAO_EntityTag
::create($params['tag'], 'civicrm_contact', $contactID);
1870 //to add profile in default group
1871 if (is_array($addToGroupID)) {
1872 $contactIds = array($contactID);
1873 foreach ($addToGroupID as $groupId) {
1874 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
1877 elseif ($addToGroupID) {
1878 $contactIds = array($contactID);
1879 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $addToGroupID);
1882 // reset the group contact cache for this group
1883 CRM_Contact_BAO_GroupContactCache
::remove();
1886 CRM_Utils_Hook
::post('edit', 'Profile', $contactID, $params);
1889 CRM_Utils_Hook
::post('create', 'Profile', $contactID, $params);
1897 * @param null $contactID
1898 * @param null $ufGroupId
1899 * @param null $ctype
1900 * @param bool $skipCustom
1904 static function formatProfileContactParams(
1913 $data = $contactDetails = array();
1915 // get the contact details (hier)
1917 list($details, $options) = self
::getHierContactDetails($contactID, $fields);
1919 $contactDetails = $details[$contactID];
1920 $data['contact_type'] = CRM_Utils_Array
::value('contact_type', $contactDetails);
1921 $data['contact_sub_type'] = CRM_Utils_Array
::value('contact_sub_type', $contactDetails);
1924 //we should get contact type only if contact
1926 $data['contact_type'] = CRM_Core_BAO_UFField
::getProfileType($ufGroupId);
1928 //special case to handle profile with only contact fields
1929 if ($data['contact_type'] == 'Contact') {
1930 $data['contact_type'] = 'Individual';
1932 elseif (CRM_Contact_BAO_ContactType
::isaSubType($data['contact_type'])) {
1933 $data['contact_type'] = CRM_Contact_BAO_ContactType
::getBasicType($data['contact_type']);
1937 $data['contact_type'] = $ctype;
1940 $data['contact_type'] = 'Individual';
1944 //fix contact sub type CRM-5125
1945 if (array_key_exists('contact_sub_type', $params) &&
1946 !empty($params['contact_sub_type'])
1948 $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
;
1950 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
1951 !empty($params['contact_sub_type_hidden'])
1953 // if profile was used, and had any subtype, we obtain it from there
1954 $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
;
1957 if ($ctype == 'Organization') {
1958 $data['organization_name'] = CRM_Utils_Array
::value('organization_name', $contactDetails);
1960 elseif ($ctype == 'Household') {
1961 $data['household_name'] = CRM_Utils_Array
::value('household_name', $contactDetails);
1964 $locationType = array();
1969 $data['contact_id'] = $contactID;
1970 $primaryLocationType = self
::getPrimaryLocationType($contactID);
1973 $defaultLocation = CRM_Core_BAO_LocationType
::getDefault();
1974 $defaultLocationId = $defaultLocation->id
;
1977 // get the billing location type
1978 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
1979 $billingLocationTypeId = array_search('Billing', $locationTypes);
1981 $blocks = array('email', 'phone', 'im', 'openid');
1983 $multiplFields = array('url');
1984 // prevent overwritten of formatted array, reset all block from
1985 // params if it is not in valid format (since import pass valid format)
1986 foreach ($blocks as $blk) {
1987 if (array_key_exists($blk, $params) &&
1988 !is_array($params[$blk])
1990 unset($params[$blk]);
1994 $primaryPhoneLoc = NULL;
1995 $session = CRM_Core_Session
::singleton();
1996 foreach ($params as $key => $value) {
1997 $fieldName = $locTypeId = $typeId = NULL;
1998 list($fieldName, $locTypeId, $typeId) = CRM_Utils_System
::explode('-', $key, 3);
2000 //store original location type id
2001 $actualLocTypeId = $locTypeId;
2003 if ($locTypeId == 'Primary') {
2005 if(in_array( $fieldName, $blocks)){
2006 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, $fieldName);
2009 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, 'address');
2011 $primaryLocationType = $locTypeId;
2014 $locTypeId = $defaultLocationId;
2018 if (is_numeric($locTypeId) &&
2019 !in_array($fieldName, $multiplFields) &&
2020 substr($fieldName, 0, 7) != 'custom_'
2022 $index = $locTypeId;
2024 if (is_numeric($typeId)) {
2025 $index .= '-' . $typeId;
2027 if (!in_array($index, $locationType)) {
2028 $locationType[$count] = $index;
2032 $loc = CRM_Utils_Array
::key($index, $locationType);
2034 $blockName = in_array( $fieldName, $blocks) ?
$fieldName : 'address';
2036 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
2038 //set is_billing true, for location type "Billing"
2039 if ($locTypeId == $billingLocationTypeId) {
2040 $data[$blockName][$loc]['is_billing'] = 1;
2044 //get the primary location type
2045 if ($locTypeId == $primaryLocationType) {
2046 $data[$blockName][$loc]['is_primary'] = 1;
2049 elseif ($locTypeId == $defaultLocationId) {
2050 $data[$blockName][$loc]['is_primary'] = 1;
2053 if ( in_array($fieldName, array('phone'))) {
2055 $data['phone'][$loc]['phone_type_id'] = $typeId;
2058 $data['phone'][$loc]['phone_type_id'] = '';
2060 $data['phone'][$loc]['phone'] = $value;
2062 //special case to handle primary phone with different phone types
2063 // in this case we make first phone type as primary
2064 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
2065 $primaryPhoneLoc = $loc;
2068 if ($loc != $primaryPhoneLoc) {
2069 unset($data['phone'][$loc]['is_primary']);
2072 elseif ($fieldName == 'phone_ext') {
2073 $data['phone'][$loc]['phone_ext'] = $value;
2075 elseif ($fieldName == 'email') {
2076 $data['email'][$loc]['email'] = $value;
2078 elseif ($fieldName == 'im') {
2079 if (isset($params[$key . '-provider_id'])) {
2080 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
2082 if (strpos($key, '-provider_id') !== FALSE) {
2083 $data['im'][$loc]['provider_id'] = $params[$key];
2086 $data['im'][$loc]['name'] = $value;
2089 elseif ($fieldName == 'openid') {
2090 $data['openid'][$loc]['openid'] = $value;
2093 if ($fieldName === 'state_province') {
2095 if (is_numeric($value) && ((int ) $value) >= 1000) {
2096 $data['address'][$loc]['state_province_id'] = $value;
2098 elseif (empty($value)) {
2099 $data['address'][$loc]['state_province_id'] = '';
2102 $data['address'][$loc]['state_province'] = $value;
2105 elseif ($fieldName === 'country') {
2107 if (is_numeric($value) && ((int ) $value) >= 1000
2109 $data['address'][$loc]['country_id'] = $value;
2111 elseif (empty($value)) {
2112 $data['address'][$loc]['country_id'] = '';
2115 $data['address'][$loc]['country'] = $value;
2118 elseif ($fieldName === 'county') {
2119 $data['address'][$loc]['county_id'] = $value;
2121 elseif ($fieldName == 'address_name') {
2122 $data['address'][$loc]['name'] = $value;
2124 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2125 $data['address'][$loc][substr($fieldName, 8)] = $value;
2128 $data['address'][$loc][$fieldName] = $value;
2133 if (substr($key, 0, 4) === 'url-') {
2134 $websiteField = explode('-', $key);
2135 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
2136 $data['website'][$websiteField[1]]['url'] = $value;
2138 elseif (in_array($key, self
::$_greetingTypes, TRUE)) {
2139 //save email/postal greeting and addressee values if any, CRM-4575
2140 $data[$key . '_id'] = $value;
2142 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($key))) {
2143 // for autocomplete transfer hidden value instead of label
2144 if ($params[$key] && isset($params[$key . '_id'])) {
2145 $value = $params[$key . '_id'];
2148 // we need to append time with date
2149 if ($params[$key] && isset($params[$key . '_time'])) {
2150 $value .= ' ' . $params[$key . '_time'];
2153 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
2154 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 &&
2155 ($value == '' ||
!isset($value))) {
2160 if (!empty($params['customRecordValues'])) {
2161 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2162 foreach ($params['customRecordValues'] as $recId => $customFields) {
2163 if (is_array($customFields) && !empty($customFields)) {
2164 foreach ($customFields as $customFieldName) {
2165 if ($customFieldName == $key) {
2175 $type = $data['contact_type'];
2176 if (!empty($data['contact_sub_type'])) {
2177 $type = $data['contact_sub_type'];
2178 $type = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($type, CRM_Core_DAO
::VALUE_SEPARATOR
));
2179 // generally a contact even if, has multiple subtypes the parent-type is going to be one only
2180 // and since formatCustomField() would be interested in parent type, lets consider only one subtype
2181 // as the results going to be same.
2185 CRM_Core_BAO_CustomField
::formatCustomField($customFieldId,
2193 elseif ($key == 'edit') {
2197 if ($key == 'location') {
2198 foreach ($value as $locationTypeId => $field) {
2199 foreach ($field as $block => $val) {
2200 if ($block == 'address' && array_key_exists('address_name', $val)) {
2201 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2206 if($key == 'phone' && isset($params['phone_ext'])){
2207 $data[$key] = $value;
2208 foreach($value as $cnt => $phoneBlock){
2209 if($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']){
2210 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array
::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2214 else if (in_array($key,
2223 ($value == '' ||
!isset($value)) &&
2224 ($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0) {
2225 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
2226 // to avoid update with empty values
2230 $data[$key] = $value;
2236 if (!isset($data['contact_type'])) {
2237 $data['contact_type'] = 'Individual';
2240 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2241 $privacy = CRM_Core_SelectValues
::privacy();
2242 foreach ($privacy as $key => $value) {
2243 if (array_key_exists($key, $fields)) {
2244 // do not reset values for existing contacts, if fields are added to a profile
2245 if (array_key_exists($key, $params)) {
2246 $data[$key] = $params[$key];
2247 if (empty($params[$key])) {
2251 elseif (!$contactID) {
2257 return array($data, $contactDetails);
2261 * Function to find the get contact details
2262 * does not respect ACLs for now, which might need to be rectified at some
2263 * stage based on how its used
2265 * @param string $mail primary email address of the contact
2266 * @param string $ctype contact type
2268 * @return object $dao contact details
2271 static function &matchContactOnEmail($mail, $ctype = NULL) {
2272 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2273 $mail = $strtolower(trim($mail));
2275 SELECT civicrm_contact.id as contact_id,
2276 civicrm_contact.hash as hash,
2277 civicrm_contact.contact_type as contact_type,
2278 civicrm_contact.contact_sub_type as contact_sub_type
2279 FROM civicrm_contact
2280 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2283 if (CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
2284 'uniq_email_per_site'
2286 // try to find a match within a site (multisite).
2287 $groups = CRM_Core_BAO_Domain
::getChildGroupIds();
2288 if (!empty($groups)) {
2290 INNER JOIN civicrm_group_contact gc ON
2291 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2296 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2297 $p = array(1 => array($mail, 'String'));
2300 $query .= " AND civicrm_contact.contact_type = %3";
2301 $p[3] = array($ctype, 'String');
2304 $query .= " ORDER BY civicrm_email.is_primary DESC";
2306 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2308 if ($dao->fetch()) {
2311 return CRM_Core_DAO
::$_nullObject;
2315 * Function to find the contact details associated with an OpenID
2317 * @param string $openId openId of the contact
2318 * @param string $ctype contact type
2320 * @return object $dao contact details
2323 static function &matchContactOnOpenId($openId, $ctype = NULL) {
2324 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2325 $openId = $strtolower(trim($openId));
2327 SELECT civicrm_contact.id as contact_id,
2328 civicrm_contact.hash as hash,
2329 civicrm_contact.contact_type as contact_type,
2330 civicrm_contact.contact_sub_type as contact_sub_type
2331 FROM civicrm_contact
2332 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2333 WHERE civicrm_openid.openid = %1";
2334 $p = array(1 => array($openId, 'String'));
2337 $query .= " AND civicrm_contact.contact_type = %3";
2338 $p[3] = array($ctype, 'String');
2341 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2343 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2345 if ($dao->fetch()) {
2348 return CRM_Core_DAO
::$_nullObject;
2352 * Funtion to get primary email of the contact
2354 * @param int $contactID contact id
2356 * @return string $dao->email email address if present else null
2360 public static function getPrimaryEmail($contactID) {
2361 // fetch the primary email
2363 SELECT civicrm_email.email as email
2364 FROM civicrm_contact
2365 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2366 WHERE civicrm_email.is_primary = 1
2367 AND civicrm_contact.id = %1";
2368 $p = array(1 => array($contactID, 'Integer'));
2369 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2372 if ($dao->fetch()) {
2373 $email = $dao->email
;
2380 * Funtion to get primary OpenID of the contact
2382 * @param int $contactID contact id
2384 * @return string $dao->openid OpenID if present else null
2388 public static function getPrimaryOpenId($contactID) {
2389 // fetch the primary OpenID
2391 SELECT civicrm_openid.openid as openid
2392 FROM civicrm_contact
2393 LEFT JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2394 WHERE civicrm_contact.id = %1
2395 AND civicrm_openid.is_primary = 1";
2396 $p = array(1 => array($contactID, 'Integer'));
2397 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2400 if ($dao->fetch()) {
2401 $openId = $dao->openid
;
2408 * Given the list of params in the params array, fetch the object
2409 * and store the values in the values array
2411 * @param array $params input parameters to find object
2412 * @param array $values output values of the object
2414 * @return CRM_Contact_BAO_Contact|null the found object or null
2418 public static function getValues(&$params, &$values) {
2419 $contact = new CRM_Contact_BAO_Contact();
2421 $contact->copyValues($params);
2423 if ($contact->find(TRUE)) {
2425 CRM_Core_DAO
::storeValues($contact, $values);
2428 foreach (self
::$_commPrefs as $name) {
2429 if (isset($contact->$name)) {
2430 $privacy[$name] = $contact->$name;
2434 if (!empty($privacy)) {
2435 $values['privacy'] = $privacy;
2438 // communication Prefferance
2439 $preffComm = $comm = array();
2440 $comm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2441 $contact->preferred_communication_method
2443 foreach ($comm as $value) {
2444 $preffComm[$value] = 1;
2446 $temp = array('preferred_communication_method' => $contact->preferred_communication_method
);
2449 'preferred_communication_method' => array('newName' => 'preferred_communication_method_display',
2450 'groupName' => 'preferred_communication_method',
2453 CRM_Core_OptionGroup
::lookupValues($temp, $names, FALSE);
2455 $values['preferred_communication_method'] = $preffComm;
2456 $values['preferred_communication_method_display'] = CRM_Utils_Array
::value('preferred_communication_method_display', $temp);
2458 $preferredMailingFormat = CRM_Core_SelectValues
::pmf();
2459 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format
];
2461 // get preferred languages
2462 if (!empty($contact->preferred_language
)) {
2463 $values['preferred_language'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language
);
2466 // Calculating Year difference
2467 if ($contact->birth_date
) {
2468 $birthDate = CRM_Utils_Date
::customFormat($contact->birth_date
, '%Y%m%d');
2469 if ($birthDate < date('Ymd')) {
2470 $age = CRM_Utils_Date
::calculateAge($birthDate);
2471 $values['age']['y'] = CRM_Utils_Array
::value('years', $age);
2472 $values['age']['m'] = CRM_Utils_Array
::value('months', $age);
2475 list($values['birth_date']) = CRM_Utils_Date
::setDateDefaults($contact->birth_date
, 'birth');
2476 $values['birth_date_display'] = $contact->birth_date
;
2479 if ($contact->deceased_date
) {
2480 list($values['deceased_date']) = CRM_Utils_Date
::setDateDefaults($contact->deceased_date
, 'birth');
2481 $values['deceased_date_display'] = $contact->deceased_date
;
2484 $contact->contact_id
= $contact->id
;
2492 * Given the component name and returns
2493 * the count of participation of contact
2495 * @param string $component input component name
2496 * @param integer $contactId input contact id
2497 * @param string $tableName optional tableName if component is custom group
2499 * @return total number of count of occurence in database
2503 static function getCountComponent($component, $contactId, $tableName = NULL) {
2505 switch ($component) {
2507 return CRM_Core_BAO_EntityTag
::getContactTags($contactId, TRUE);
2510 return CRM_Contact_BAO_Relationship
::getRelationship($contactId,
2511 CRM_Contact_BAO_Relationship
::CURRENT
,
2516 return CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, "Added", NULL, TRUE);
2519 if (CRM_Core_BAO_Log
::useLoggingReport()) {
2522 return CRM_Core_BAO_Log
::getContactLogCount($contactId);
2525 return CRM_Core_BAO_Note
::getContactNoteCount($contactId);
2527 case 'contribution':
2528 return CRM_Contribute_BAO_Contribution
::contributionCount($contactId);
2531 return CRM_Member_BAO_Membership
::getContactMembershipCount($contactId, TRUE);
2534 return CRM_Event_BAO_Participant
::getContactParticipantCount($contactId);
2537 return CRM_Pledge_BAO_Pledge
::getContactPledgeCount($contactId);
2540 return CRM_Case_BAO_Case
::caseCount($contactId);
2543 return CRM_Grant_BAO_Grant
::getContactGrantCount($contactId);
2547 'contact_id' => $contactId,
2550 'context' => 'activity',
2552 return CRM_Activity_BAO_Activity
::getActivitiesCount($input);
2555 $params = array('contact_id' => $contactId);
2556 return CRM_Mailing_BAO_Mailing
::getContactMailingsCount($params);
2559 $custom = explode('_', $component);
2560 if ($custom['0'] = 'custom') {
2562 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2564 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2565 return CRM_Core_DAO
::singleValueQuery($queryString);
2571 * Function to process greetings and cache
2573 * @param object $contact contact object after save
2574 * @param boolean $useDefaults use default greeting values
2580 static function processGreetings(&$contact, $useDefaults = FALSE) {
2582 //retrieve default greetings
2583 $defaultGreetings = CRM_Core_PseudoConstant
::greetingDefaults();
2584 $contactDefaults = $defaultGreetings[$contact->contact_type
];
2587 // note that contact object not always has required greeting related
2588 // fields that are required to calculate greeting and
2589 // also other fields used in tokens etc,
2590 // hence we need to retrieve it again.
2591 if ( $contact->_query
!== FALSE ) {
2592 $contact->find(TRUE);
2595 // store object values to an array
2596 $contactDetails = array();
2597 CRM_Core_DAO
::storeValues($contact, $contactDetails);
2598 $contactDetails = array(array($contact->id
=> $contactDetails));
2600 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2601 $updateQueryString = array();
2603 //cache email and postal greeting to greeting display
2604 if ($contact->email_greeting_custom
!= 'null' && $contact->email_greeting_custom
) {
2605 $emailGreetingString = $contact->email_greeting_custom
;
2607 elseif ($contact->email_greeting_id
!= 'null' && $contact->email_greeting_id
) {
2608 // the filter value for Individual contact type is set to 1
2610 'contact_type' => $contact->contact_type
,
2611 'greeting_type' => 'email_greeting',
2614 $emailGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2615 $emailGreetingString = $emailGreeting[$contact->email_greeting_id
];
2616 $updateQueryString[] = " email_greeting_custom = NULL ";
2620 reset($contactDefaults['email_greeting']);
2621 $emailGreetingID = key($contactDefaults['email_greeting']);
2622 $emailGreetingString = $contactDefaults['email_greeting'][$emailGreetingID];
2623 $updateQueryString[] = " email_greeting_id = $emailGreetingID ";
2624 $updateQueryString[] = " email_greeting_custom = NULL ";
2626 elseif ($contact->email_greeting_custom
) {
2627 $updateQueryString[] = " email_greeting_display = NULL ";
2631 if ($emailGreetingString) {
2632 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($emailGreetingString,
2635 'CRM_Contact_BAO_Contact'
2637 $emailGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($emailGreetingString));
2638 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2642 if ($contact->postal_greeting_custom
!= 'null' && $contact->postal_greeting_custom
) {
2643 $postalGreetingString = $contact->postal_greeting_custom
;
2645 elseif ($contact->postal_greeting_id
!= 'null' && $contact->postal_greeting_id
) {
2647 'contact_type' => $contact->contact_type
,
2648 'greeting_type' => 'postal_greeting',
2650 $postalGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2651 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id
];
2652 $updateQueryString[] = " postal_greeting_custom = NULL ";
2656 reset($contactDefaults['postal_greeting']);
2657 $postalGreetingID = key($contactDefaults['postal_greeting']);
2658 $postalGreetingString = $contactDefaults['postal_greeting'][$postalGreetingID];
2659 $updateQueryString[] = " postal_greeting_id = $postalGreetingID ";
2660 $updateQueryString[] = " postal_greeting_custom = NULL ";
2662 elseif ($contact->postal_greeting_custom
) {
2663 $updateQueryString[] = " postal_greeting_display = NULL ";
2667 if ($postalGreetingString) {
2668 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($postalGreetingString,
2671 'CRM_Contact_BAO_Contact'
2673 $postalGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($postalGreetingString));
2674 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2678 if ($contact->addressee_custom
!= 'null' && $contact->addressee_custom
) {
2679 $addresseeString = $contact->addressee_custom
;
2681 elseif ($contact->addressee_id
!= 'null' && $contact->addressee_id
) {
2683 'contact_type' => $contact->contact_type
,
2684 'greeting_type' => 'addressee',
2687 $addressee = CRM_Core_PseudoConstant
::greeting($filter);
2688 $addresseeString = $addressee[$contact->addressee_id
];
2689 $updateQueryString[] = " addressee_custom = NULL ";
2693 reset($contactDefaults['addressee']);
2694 $addresseeID = key($contactDefaults['addressee']);
2695 $addresseeString = $contactDefaults['addressee'][$addresseeID];
2696 $updateQueryString[] = " addressee_id = $addresseeID ";
2697 $updateQueryString[] = " addressee_custom = NULL ";
2699 elseif ($contact->addressee_custom
) {
2700 $updateQueryString[] = " addressee_display = NULL ";
2704 if ($addresseeString) {
2705 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($addresseeString,
2708 'CRM_Contact_BAO_Contact'
2710 $addresseeString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($addresseeString));
2711 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2714 if (!empty($updateQueryString)) {
2715 $updateQueryString = implode(',', $updateQueryString);
2716 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2717 CRM_Core_DAO
::executeQuery($queryString);
2722 * Function to retrieve loc block ids w/ given condition.
2724 * @param int $contactId contact id.
2725 * @param array $criteria key => value pair which should be
2726 * fulfill by return record ids.
2727 * @param string $condOperator operator use for grouping multiple conditions.
2729 * @return array $locBlockIds loc block ids which fulfill condition.
2732 static function getLocBlockIds($contactId, $criteria = array(), $condOperator = 'AND') {
2733 $locBlockIds = array();
2735 return $locBlockIds;
2738 foreach (array('Email', 'OpenID', 'Phone', 'Address', 'IM') as $block) {
2739 $name = strtolower($block);
2740 $className = "CRM_Core_DAO_$block";
2741 $blockDAO = new $className();
2743 // build the condition.
2744 if (is_array($criteria)) {
2745 $fields = $blockDAO->fields();
2746 $conditions = array();
2747 foreach ($criteria as $field => $value) {
2748 if (array_key_exists($field, $fields)) {
2749 $cond = "( $field = $value )";
2750 // value might be zero or null.
2751 if (!$value ||
strtolower($value) == 'null') {
2752 $cond = "( $field = 0 OR $field IS NULL )";
2754 $conditions[] = $cond;
2757 if (!empty($conditions)) {
2758 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2762 $blockDAO->contact_id
= $contactId;
2764 while ($blockDAO->fetch()) {
2765 $locBlockIds[$name][] = $blockDAO->id
;
2770 return $locBlockIds;
2774 * Function to build context menu items.
2776 * @param null $contactId
2778 * @return array of context menu for logged in user.
2781 static function contextMenu($contactId = NULL) {
2784 'title' => ts('View Contact'),
2786 'ref' => 'view-contact',
2787 'class' => 'no-popup',
2789 'permissions' => array('view all contacts'),
2792 'title' => ts('Edit Contact'),
2794 'ref' => 'edit-contact',
2795 'class' => 'no-popup',
2797 'permissions' => array('edit all contacts'),
2800 'title' => ts('Delete Contact'),
2802 'ref' => 'delete-contact',
2804 'permissions' => array('access deleted contacts', 'delete contacts'),
2806 'contribution' => array(
2807 'title' => ts('Add Contribution'),
2809 'ref' => 'new-contribution',
2810 'class' => 'huge-popup',
2811 'key' => 'contribution',
2812 'tab' => 'contribute',
2813 'component' => 'CiviContribute',
2814 'href' => CRM_Utils_System
::url('civicrm/contact/view/contribution',
2815 'reset=1&action=add&context=contribution'
2817 'permissions' => array(
2818 'access CiviContribute',
2819 'edit contributions',
2822 'participant' => array(
2823 'title' => ts('Register for Event'),
2825 'ref' => 'new-participant',
2826 'class' => 'huge-popup',
2827 'key' => 'participant',
2828 'tab' => 'participant',
2829 'component' => 'CiviEvent',
2830 'href' => CRM_Utils_System
::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
2831 'permissions' => array(
2833 'edit event participants',
2836 'activity' => array(
2837 'title' => ts('Record Activity'),
2839 'ref' => 'new-activity',
2840 'key' => 'activity',
2841 'permissions' => array('edit all contacts'),
2844 'title' => ts('Add Pledge'),
2846 'ref' => 'new-pledge',
2849 'href' => CRM_Utils_System
::url('civicrm/contact/view/pledge',
2850 'reset=1&action=add&context=pledge'
2852 'component' => 'CiviPledge',
2853 'permissions' => array(
2854 'access CiviPledge',
2858 'membership' => array(
2859 'title' => ts('Add Membership'),
2861 'ref' => 'new-membership',
2862 'class' => 'huge-popup',
2863 'key' => 'membership',
2865 'component' => 'CiviMember',
2866 'href' => CRM_Utils_System
::url('civicrm/contact/view/membership',
2867 'reset=1&action=add&context=membership'
2869 'permissions' => array(
2870 'access CiviMember',
2875 'title' => ts('Add Case'),
2877 'ref' => 'new-case',
2880 'component' => 'CiviCase',
2881 'href' => CRM_Utils_System
::url('civicrm/case/add', 'reset=1&action=add&context=case'),
2882 'permissions' => array('add cases'),
2885 'title' => ts('Add Grant'),
2887 'ref' => 'new-grant',
2890 'component' => 'CiviGrant',
2891 'href' => CRM_Utils_System
::url('civicrm/contact/view/grant',
2892 'reset=1&action=add&context=grant'
2894 'permissions' => array('edit grants'),
2897 'title' => ts('Add Relationship'),
2899 'ref' => 'new-relationship',
2902 'href' => CRM_Utils_System
::url('civicrm/contact/view/rel',
2903 'reset=1&action=add'
2905 'permissions' => array('edit all contacts'),
2908 'title' => ts('Add Note'),
2910 'ref' => 'new-note',
2913 'class' => 'medium-popup',
2914 'href' => CRM_Utils_System
::url('civicrm/contact/view/note',
2915 'reset=1&action=add'
2917 'permissions' => array('edit all contacts'),
2920 'title' => ts('Send an Email'),
2922 'ref' => 'new-email',
2924 'permissions' => array('view all contacts'),
2927 'title' => ts('Add to Group'),
2929 'ref' => 'group-add-contact',
2932 'permissions' => array('edit groups'),
2935 'title' => ts('Tag Contact'),
2937 'ref' => 'tag-contact',
2940 'permissions' => array('edit all contacts'),
2944 CRM_Utils_Hook
::summaryActions($menu, $contactId);
2945 //1. check for component is active.
2946 //2. check for user permissions.
2947 //3. check for acls.
2948 //3. edit and view contact are directly accessible to user.
2950 $aclPermissionedTasks = array(
2951 'view-contact', 'edit-contact', 'new-activity',
2952 'new-email', 'group-add-contact', 'tag-contact', 'delete-contact',
2954 $corePermission = CRM_Core_Permission
::getPermission();
2956 $config = CRM_Core_Config
::singleton();
2958 $contextMenu = array();
2959 foreach ($menu as $key => $values) {
2960 $componentName = CRM_Utils_Array
::value('component', $values);
2962 // if component action - make sure component is enable.
2963 if ($componentName && !in_array($componentName, $config->enableComponents
)) {
2967 // make sure user has all required permissions.
2968 $hasAllPermissions = FALSE;
2970 $permissions = CRM_Utils_Array
::value('permissions', $values);
2971 if (!is_array($permissions) ||
empty($permissions)) {
2972 $hasAllPermissions = TRUE;
2975 // iterate for required permissions in given permissions array.
2976 if (!$hasAllPermissions) {
2977 $hasPermissions = 0;
2978 foreach ($permissions as $permission) {
2979 if (CRM_Core_Permission
::check($permission)) {
2984 if (count($permissions) == $hasPermissions) {
2985 $hasAllPermissions = TRUE;
2988 // if still user does not have required permissions, check acl.
2989 if (!$hasAllPermissions && $values['ref'] != 'delete-contact') {
2990 if (in_array($values['ref'], $aclPermissionedTasks) &&
2991 $corePermission == CRM_Core_Permission
::EDIT
2993 $hasAllPermissions = TRUE;
2995 elseif (in_array($values['ref'], array(
2997 // grant permissions for these tasks.
2998 $hasAllPermissions = TRUE;
3003 // user does not have necessary permissions.
3004 if (!$hasAllPermissions) {
3008 // build directly accessible action menu.
3009 if (in_array($values['ref'], array(
3010 'view-contact', 'edit-contact'))) {
3011 $contextMenu['primaryActions'][$key] = array(
3012 'title' => $values['title'],
3013 'ref' => $values['ref'],
3014 'class' => CRM_Utils_Array
::value('class', $values),
3015 'key' => $values['key'],
3020 // finally get menu item for -more- action widget.
3021 $contextMenu['moreActions'][$values['weight']] = array(
3022 'title' => $values['title'],
3023 'ref' => $values['ref'],
3024 'href' => CRM_Utils_Array
::value('href', $values),
3025 'tab' => CRM_Utils_Array
::value('tab', $values),
3026 'class' => CRM_Utils_Array
::value('class', $values),
3027 'key' => $values['key'],
3031 ksort($contextMenu['moreActions']);
3033 return $contextMenu;
3037 * Function to retrieve display name of contact that address is shared
3038 * based on $masterAddressId or $contactId .
3040 * @param int $masterAddressId master id.
3041 * @param int $contactId contact id.
3043 * @return display name |null the found display name or null.
3047 static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3048 $masterDisplayName = NULL;
3050 if (!$masterAddressId && !$contactId) {
3051 return $masterDisplayName;
3054 if ($masterAddressId) {
3056 SELECT display_name from civicrm_contact
3057 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3058 WHERE civicrm_address.id = " . $masterAddressId;
3060 elseif ($contactId) {
3062 SELECT display_name from civicrm_contact cc, civicrm_address add1
3063 LEFT JOIN civicrm_address add2 ON ( add1.master_id = add2.id )
3064 WHERE cc.id = add2.contact_id AND add1.contact_id = " . $contactId;
3067 $masterDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
3068 return $masterDisplayName;
3072 * Get the creation/modification times for a contact
3076 * @return array('created_date' => $, 'modified_date' => $)
3078 static function getTimestamps($contactId) {
3079 $timestamps = CRM_Core_DAO
::executeQuery(
3080 'SELECT created_date, modified_date
3081 FROM civicrm_contact
3084 1 => array($contactId, 'Integer'),
3087 if ($timestamps->fetch()) {
3089 'created_date' => $timestamps->created_date
,
3090 'modified_date' => $timestamps->modified_date
,
3099 * Get a list of triggers for the contact table
3101 * @see hook_civicrm_triggerInfo
3102 * @see CRM_Core_DAO::triggerRebuild
3103 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3105 static function triggerInfo(&$info, $tableName = NULL) {
3106 //during upgrade, first check for valid version and then create triggers
3107 //i.e the columns created_date and modified_date are introduced in 4.3.alpha1 so dont create triggers for older version
3108 if (CRM_Core_Config
::isUpgradeMode()) {
3109 $currentVer = CRM_Core_BAO_Domain
::version(TRUE);
3110 //if current version is less than 4.3.alpha1 dont create below triggers
3111 if (version_compare($currentVer, '4.3.alpha1') < 0) {
3116 if ($tableName == NULL ||
$tableName == self
::getTableName()) {
3118 'table' => array(self
::getTableName()),
3120 'event' => array('INSERT'),
3121 'sql' => "\nSET NEW.created_date = CURRENT_TIMESTAMP;\n",
3125 // Update timestamp when modifying closely related core tables
3126 $relatedTables = array(
3134 'table' => $relatedTables,
3136 'event' => array('INSERT', 'UPDATE'),
3137 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = NEW.contact_id;\n",
3140 'table' => $relatedTables,
3142 'event' => array('DELETE'),
3143 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = OLD.contact_id;\n",
3146 // Update timestamp when modifying related custom-data tables
3147 $customGroupTables = array();
3148 $customGroupDAO = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity('Contact');
3149 $customGroupDAO->is_multiple
= 0;
3150 $customGroupDAO->find();
3151 while ($customGroupDAO->fetch()) {
3152 $customGroupTables[] = $customGroupDAO->table_name
;
3154 if (!empty($customGroupTables)) {
3156 'table' => $customGroupTables,
3158 'event' => array('INSERT', 'UPDATE'),
3159 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = NEW.entity_id;\n",
3162 'table' => $customGroupTables,
3164 'event' => array('DELETE'),
3165 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = OLD.entity_id;\n",
3169 // Update phone table to populate phone_numeric field
3170 if (!$tableName ||
$tableName == 'civicrm_phone') {
3171 // Define stored sql function needed for phones
3172 CRM_Core_DAO
::executeQuery(self
::DROP_STRIP_FUNCTION_43
);
3173 CRM_Core_DAO
::executeQuery(self
::CREATE_STRIP_FUNCTION_43
);
3175 'table' => array('civicrm_phone'),
3177 'event' => array('INSERT', 'UPDATE'),
3178 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3184 * Function to check if contact is being used in civicrm_domain
3185 * based on $contactId
3187 * @param int $contactId contact id.
3189 * @return true if present else false.
3193 static function checkDomainContact($contactId) {
3196 $domainId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3206 * Get options for a given contact field.
3207 * @see CRM_Core_DAO::buildOptions
3209 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3210 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3212 * @param String $fieldName
3213 * @param String $context : @see CRM_Core_DAO::buildOptionsContext
3214 * @param Array $props : whatever is known about this dao object
3216 * @return Array|bool
3218 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3220 // Special logic for fields whose options depend on context or properties
3221 switch ($fieldName) {
3222 case 'contact_sub_type':
3223 if (!empty($props['contact_type'])) {
3224 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3228 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
3232 * Delete a contact-related object that has an 'is_primary' field
3233 * Ensures that is_primary gets assigned to another object if available
3234 * Also calls pre/post hooks
3236 * @var $type : object type
3237 * @var $id : object id
3240 public static function deleteObjectWithPrimary($type, $id) {
3241 if (!$id ||
!is_numeric($id)) {
3244 $daoName = "CRM_Core_DAO_$type";
3245 $obj = new $daoName();
3248 if ($obj->fetch()) {
3249 CRM_Utils_Hook
::pre('delete', $type, $id, CRM_Core_DAO
::$_nullArray);
3250 $contactId = $obj->contact_id
;
3256 // is_primary is only relavent if this field belongs to a contact
3258 $dao = new $daoName();
3259 $dao->contact_id
= $contactId;
3260 $dao->is_primary
= 1;
3261 // Pick another record to be primary (if one isn't already)
3262 if (!$dao->find(TRUE)) {
3263 $dao->is_primary
= 0;
3265 if ($dao->fetch()) {
3266 $dao->is_primary
= 1;
3272 CRM_Utils_Hook
::post('delete', $type, $id, $obj);