3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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;
91 function __construct() {
92 parent
::__construct();
96 * takes an associative array and creates a contact object
98 * the function extract all the params it needs to initialize the create a
99 * contact object. the params array could contain additional unused name/value
102 * @param array $params (reference ) an assoc array of name/value pairs
104 * @return object CRM_Contact_BAO_Contact object
108 static function add(&$params) {
109 $contact = new CRM_Contact_DAO_Contact();
111 if (empty($params)) {
115 //fix for validate contact sub type CRM-5143
116 if ( isset( $params['contact_sub_type'] ) ) {
117 if ( empty($params['contact_sub_type']) ) {
118 $params['contact_sub_type'] = 'null';
121 if (!CRM_Contact_BAO_ContactType
::isExtendsContactType($params['contact_sub_type'],
122 $params['contact_type'], TRUE
124 // we'll need to fix tests to handle this
126 CRM_Core_Error
::fatal(ts('The Contact Sub Type does not match the Contact type for this record'));
128 if (is_array($params['contact_sub_type'])) {
129 $params['contact_sub_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $params['contact_sub_type']) . CRM_Core_DAO
::VALUE_SEPARATOR
;
132 $params['contact_sub_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. trim($params['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
139 $params['contact_sub_type'] = 'null';
142 //fixed contact source
143 if (isset($params['contact_source'])) {
144 $params['source'] = $params['contact_source'];
147 //fix for preferred communication method
148 $prefComm = CRM_Utils_Array
::value('preferred_communication_method', $params);
149 if ($prefComm && is_array($prefComm)) {
150 unset($params['preferred_communication_method']);
153 foreach ($prefComm as $k => $v) {
159 $prefComm = $newPref;
160 if (is_array($prefComm) && !empty($prefComm)) {
161 $prefComm = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, array_keys($prefComm)) . CRM_Core_DAO
::VALUE_SEPARATOR
;
162 $contact->preferred_communication_method
= $prefComm;
165 $contact->preferred_communication_method
= '';
169 $allNull = $contact->copyValues($params);
171 $contact->id
= CRM_Utils_Array
::value('contact_id', $params);
173 if ($contact->contact_type
== 'Individual') {
176 //format individual fields
177 CRM_Contact_BAO_Individual
::format($params, $contact);
179 elseif ($contact->contact_type
== 'Household') {
180 if (isset($params['household_name'])) {
182 $contact->display_name
= $contact->sort_name
= CRM_Utils_Array
::value('household_name', $params, '');
185 elseif ($contact->contact_type
== 'Organization') {
186 if (isset($params['organization_name'])) {
188 $contact->display_name
= $contact->sort_name
= CRM_Utils_Array
::value('organization_name', $params, '');
193 $privacy = CRM_Utils_Array
::value('privacy', $params);
195 is_array($privacy) &&
199 foreach (self
::$_commPrefs as $name) {
200 $contact->$name = CRM_Utils_Array
::value($name, $privacy, FALSE);
204 // since hash was required, make sure we have a 0 value for it, CRM-1063
205 // fixed in 1.5 by making hash optional
206 // only do this in create mode, not update
207 if ((!array_key_exists('hash', $contact) ||
!$contact->hash
) && !$contact->id
) {
209 $contact->hash
= md5(uniqid(rand(), TRUE));
212 // Even if we don't need $employerId, it's important to call getFieldValue() before
213 // the contact is saved because we want the existing value to be cached.
214 // createCurrentEmployerRelationship() needs the old value not the updated one. CRM-10788
215 $employerId = empty($contact->id
) ?
NULL : CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contact->id
, 'employer_id');
220 CRM_Core_BAO_Log
::register($contact->id
,
226 if ($contact->contact_type
== 'Individual' && (isset($params['current_employer']) ||
isset($params['employer_id']))) {
227 $newEmployer = !empty($params['employer_id']) ?
$params['employer_id'] : CRM_Utils_Array
::value('current_employer', $params);
228 // create current employer
230 CRM_Contact_BAO_Contact_Utils
::createCurrentEmployerRelationship($contact->id
, $newEmployer, $employerId);
233 //unset if employer id exits
235 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($contact->id
, $employerId);
240 //update cached employee name
241 if ($contact->contact_type
== 'Organization') {
242 CRM_Contact_BAO_Contact_Utils
::updateCurrentEmployer($contact->id
);
249 * Function to create contact
250 * takes an associative array and creates a contact object and all the associated
251 * derived objects (i.e. individual, location, email, phone etc)
253 * This function is invoked from within the web form layer and also from the api layer
255 * @param array $params (reference ) an assoc array of name/value pairs
256 * @param boolean $fixAddress if we need to fix address
257 * @param boolean $invokeHooks if we need to invoke hooks
259 * @return object CRM_Contact_BAO_Contact object
263 static function &create(&$params, $fixAddress = TRUE, $invokeHooks = TRUE, $skipDelete = FALSE) {
265 if (empty($params['contact_type']) && empty($params['contact_id'])) {
271 if (!empty($params['contact_id'])) {
272 CRM_Utils_Hook
::pre('edit', $params['contact_type'], $params['contact_id'], $params);
275 CRM_Utils_Hook
::pre('create', $params['contact_type'], NULL, $params);
280 $config = CRM_Core_Config
::singleton();
282 // CRM-6942: set preferred language to the current language if it’s unset (and we’re creating a contact)
283 if (empty($params['contact_id']) && empty($params['preferred_language'])) {
284 $params['preferred_language'] = $config->lcMessages
;
287 // CRM-9739: set greeting & addressee if unset and we’re creating a contact
288 if (empty($params['contact_id'])) {
289 foreach (self
::$_greetingTypes as $greeting) {
290 if (empty($params[$greeting . '_id'])) {
291 if ($defaultGreetingTypeId =
292 CRM_Contact_BAO_Contact_Utils
::defaultGreeting($params['contact_type'], $greeting)
294 $params[$greeting . '_id'] = $defaultGreetingTypeId;
300 $transaction = new CRM_Core_Transaction();
302 $contact = self
::add($params);
304 // not dying here is stupid, since we get into wierd situation and into a bug that
305 // is impossible to figure out for the user or for us
307 CRM_Core_Error
::fatal();
310 $params['contact_id'] = $contact->id
;
312 if (CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
315 // Enabling multisite causes the contact to be added to the domain group
316 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
317 if(!empty($domainGroupID)){
318 if (!empty($params['group']) && is_array($params['group'])) {
319 $params['group'][$domainGroupID] = 1;
322 $params['group'] = array($domainGroupID => 1);
327 if (array_key_exists('group', $params)) {
328 $contactIds = array($params['contact_id']);
329 foreach ($params['group'] as $groupId => $flag) {
331 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
333 elseif ($flag == -1) {
334 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $groupId);
339 //add location Block data
340 $blocks = CRM_Core_BAO_Location
::create($params, $fixAddress);
341 foreach ($blocks as $name => $value) {
342 $contact->$name = $value;
346 CRM_Core_BAO_Website
::create($params['website'], $contact->id
, $skipDelete);
348 //get userID from session
349 $session = CRM_Core_Session
::singleton();
350 $userID = $session->get('userID');
352 if (!empty($params['note'])) {
353 if (is_array($params['note'])) {
354 foreach ($params['note'] as $note) {
355 $contactId = $contact->id
;
356 if (isset($note['contact_id'])) {
357 $contactId = $note['contact_id'];
359 //if logged in user, overwrite contactId
361 $contactId = $userID;
365 'entity_id' => $contact->id
,
366 'entity_table' => 'civicrm_contact',
367 'note' => $note['note'],
368 'subject' => CRM_Utils_Array
::value('subject', $note),
369 'contact_id' => $contactId,
371 CRM_Core_BAO_Note
::add($noteParams, CRM_Core_DAO
::$_nullArray);
375 $contactId = $contact->id
;
376 if (isset($note['contact_id'])) {
377 $contactId = $note['contact_id'];
379 //if logged in user, overwrite contactId
381 $contactId = $userID;
385 'entity_id' => $contact->id
,
386 'entity_table' => 'civicrm_contact',
387 'note' => $params['note'],
388 'subject' => CRM_Utils_Array
::value('subject', $params),
389 'contact_id' => $contactId,
391 CRM_Core_BAO_Note
::add($noteParams, CRM_Core_DAO
::$_nullArray);
396 // update the UF user_unique_id if that has changed
397 CRM_Core_BAO_UFMatch
::updateUFName($contact->id
);
399 if (!empty($params['custom']) &&
400 is_array($params['custom'])
402 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contact', $contact->id
);
405 // make a civicrm_subscription_history entry only on contact create (CRM-777)
406 if (empty($params['contact_id'])) {
407 $subscriptionParams = array(
408 'contact_id' => $contact->id
,
412 CRM_Contact_BAO_SubscriptionHistory
::create($subscriptionParams);
415 $transaction->commit();
417 // CRM-6367: fetch the right label for contact type’s display
418 $contact->contact_type_display
= CRM_Core_DAO
::getFieldValue(
419 'CRM_Contact_DAO_ContactType',
420 $contact->contact_type
,
425 if (!$config->doNotResetCache
) {
426 // Note: doNotResetCache flag is currently set by import contact process and merging,
427 // since resetting and
428 // rebuilding cache could be expensive (for many contacts). We might come out with better
429 // approach in future.
430 CRM_Contact_BAO_Contact_Utils
::clearContactCaches($contact->id
);
435 CRM_Utils_Hook
::post('edit', $params['contact_type'], $contact->id
, $contact);
438 CRM_Utils_Hook
::post('create', $params['contact_type'], $contact->id
, $contact);
442 // process greetings CRM-4575, cache greetings
443 self
::processGreetings($contact);
449 * Get the display name and image of a contact
451 * @param int $id the contactId
453 * @return array the displayName and contactImage for this contact
457 static function getDisplayAndImage($id, $type = FALSE) {
459 SELECT civicrm_contact.display_name as display_name,
460 civicrm_contact.contact_type as contact_type,
461 civicrm_contact.contact_sub_type as contact_sub_type,
462 civicrm_email.email as email
464 LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
465 AND civicrm_email.is_primary = 1
466 WHERE civicrm_contact.id = " . CRM_Utils_Type
::escape($id, 'Integer');
467 $dao = new CRM_Core_DAO();
470 $image = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
471 $dao->contact_sub_type
: $dao->contact_type
, FALSE, $id
473 $imageUrl = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
474 $dao->contact_sub_type
: $dao->contact_type
, TRUE, $id
477 // use email if display_name is empty
478 if (empty($dao->display_name
)) {
479 $dao->display_name
= $dao->email
;
481 return $type ?
array(
482 $dao->display_name
, $image,
483 $dao->contact_type
, $dao->contact_sub_type
, $imageUrl,
484 ) : array($dao->display_name
, $image, $imageUrl);
491 * Get the values for pseudoconstants for name->value and reverse.
493 * @param array $defaults (reference) the default values, some of which need to be resolved.
494 * @param boolean $reverse true if we want to resolve the values in the reverse direction (value -> name)
500 static function resolveDefaults(&$defaults, $reverse = FALSE) {
501 // hack for birth_date
502 if (!empty($defaults['birth_date'])) {
503 if (is_array($defaults['birth_date'])) {
504 $defaults['birth_date'] = CRM_Utils_Date
::format($defaults['birth_date'], '-');
508 CRM_Utils_Array
::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id'), $reverse);
509 CRM_Utils_Array
::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'suffix_id'), $reverse);
510 CRM_Utils_Array
::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'), $reverse);
511 CRM_Utils_Array
::lookupValue($defaults, 'communication_style', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'communication_style_id'), $reverse);
513 //lookup value of email/postal greeting, addressee, CRM-4575
514 foreach (self
::$_greetingTypes as $greeting) {
515 $filterCondition = array('contact_type' => CRM_Utils_Array
::value('contact_type', $defaults),
516 'greeting_type' => $greeting,
518 CRM_Utils_Array
::lookupValue($defaults, $greeting,
519 CRM_Core_PseudoConstant
::greeting($filterCondition), $reverse
523 $blocks = array('address', 'im', 'phone');
524 foreach ($blocks as $name) {
525 if (!array_key_exists($name, $defaults) ||
!is_array($defaults[$name])) {
528 foreach ($defaults[$name] as $count => & $values) {
530 //get location type id.
531 CRM_Utils_Array
::lookupValue($values, 'location_type', CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id'), $reverse);
533 if ($name == 'address') {
534 // FIXME: lookupValue doesn't work for vcard_name
535 if (!empty($values['location_type_id'])) {
536 $vcardNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array('labelColumn' => 'vcard_name'));
537 $values['vcard_name'] = $vcardNames[$values['location_type_id']];
540 if (!CRM_Utils_Array
::lookupValue($values,
542 CRM_Core_PseudoConstant
::country(),
547 CRM_Utils_Array
::lookupValue($values,
549 CRM_Core_PseudoConstant
::countryIsoCode(),
555 // if we find a country id above, we need to restrict it to that country
556 // rather than the list of all countries
558 if (!empty($values['country_id'])) {
559 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($values['country_id']);
562 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvince();
564 if (!CRM_Utils_Array
::lookupValue($values,
572 if (!empty($values['country_id'])) {
573 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($values['country_id'], 'abbreviation');
576 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviation();
578 CRM_Utils_Array
::lookupValue($values,
585 if (!empty($values['state_province_id'])) {
586 $countyList = CRM_Core_PseudoConstant
::countyForState($values['state_province_id']);
589 $countyList = CRM_Core_PseudoConstant
::county();
591 CRM_Utils_Array
::lookupValue($values,
599 CRM_Utils_Array
::lookupValue($values,
601 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id'),
606 if ($name == 'phone') {
607 CRM_Utils_Array
::lookupValue($values,
609 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id'),
614 //kill the reference.
621 * Takes a bunch of params that are needed to match certain criteria and
622 * retrieves the relevant objects. Typically the valid params are only
623 * contact_id. We'll tweak this function to be more full featured over a period
624 * of time. This is the inverse function of create. It also stores all the retrieved
625 * values in the default array
627 * @param array $params (reference ) an assoc array of name/value pairs
628 * @param array $defaults (reference ) an assoc array to hold the name / value pairs
629 * in a hierarchical manner
630 * @param boolean $microformat for location in microformat
632 * @return object CRM_Contact_BAO_Contact object
636 static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
637 if (array_key_exists('contact_id', $params)) {
638 $params['id'] = $params['contact_id'];
640 elseif (array_key_exists('id', $params)) {
641 $params['contact_id'] = $params['id'];
644 $contact = self
::getValues($params, $defaults);
646 unset($params['id']);
648 //get the block information for this contact
649 $entityBlock = array('contact_id' => $params['contact_id']);
650 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock, $microformat);
651 $defaults = array_merge($defaults, $blocks);
652 foreach ($blocks as $block => $value) $contact->$block = $value;
654 if (!isset($params['noNotes'])) {
655 $contact->notes
= CRM_Core_BAO_Note
::getValues($params, $defaults);
658 if (!isset($params['noRelationships'])) {
659 $contact->relationship
= CRM_Contact_BAO_Relationship
::getValues($params, $defaults);
662 if (!isset($params['noGroups'])) {
663 $contact->groupContact
= CRM_Contact_BAO_GroupContact
::getValues($params, $defaults);
666 if (!isset($params['noWebsite'])) {
667 $contact->website
= CRM_Core_BAO_Website
::getValues($params, $defaults);
674 * function to get the display name of a contact
676 * @param int $id id of the contact
678 * @return null|string display name of the contact if found
682 static function displayName($id) {
685 $displayName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
692 * Delete a contact and all its associated records
694 * @param int $id id of the contact to delete
695 * @param bool $restore whether to actually restore, not delete
696 * @param bool $skipUndelete whether to force contact delete or not
698 * @return boolean true if contact deleted, false otherwise
702 static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE) {
708 // make sure we have edit permission for this contact
710 if (($skipUndelete && !CRM_Core_Permission
::check('delete contacts')) ||
711 ($restore && !CRM_Core_Permission
::check('access deleted contacts'))
717 // Restrict contact to be delete if contact has financial trxns
719 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent(array($id), $error)) {
723 // make sure this contact_id does not have any membership types
724 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
727 'member_of_contact_id'
729 if ($membershipTypeID) {
733 $contact = new CRM_Contact_DAO_Contact();
735 if (!$contact->find(TRUE)) {
739 $contactType = $contact->contact_type
;
740 $action = ($restore) ?
'restore' : 'delete';
742 CRM_Utils_Hook
::pre($action, $contactType, $id, CRM_Core_DAO
::$_nullArray);
745 self
::contactTrashRestore($contact, TRUE);
746 CRM_Utils_Hook
::post($action, $contactType, $contact->id
, $contact);
751 // currently we only clear employer cache.
752 // we are not deleting inherited membership if any.
753 if ($contact->contact_type
== 'Organization') {
754 CRM_Contact_BAO_Contact_Utils
::clearAllEmployee($id);
757 // start a new transaction
758 $transaction = new CRM_Core_Transaction();
760 if ($skipUndelete or !CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'contact_undelete', NULL)) {
762 //delete billing address if exists.
763 CRM_Contribute_BAO_Contribution
::deleteAddress(NULL, $id);
765 // delete the log entries since we dont have triggers enabled as yet
766 $logDAO = new CRM_Core_DAO_Log();
767 $logDAO->entity_table
= 'civicrm_contact';
768 $logDAO->entity_id
= $id;
771 // delete contact participants CRM-12155
772 CRM_Event_BAO_Participant
::deleteContactParticipant($id);
774 // delete contact contributions CRM-12155
775 CRM_Contribute_BAO_Contribution
::deleteContactContribution($id);
777 // do activity cleanup, CRM-5604
778 CRM_Activity_BAO_Activity
::cleanupActivity($id);
780 // delete all notes related to contact
781 CRM_Core_BAO_Note
::cleanContactNotes($id);
783 // delete cases related to contact
784 $contactCases = CRM_Case_BAO_Case
::retrieveCaseIdsByContactId($id);
785 if (!empty($contactCases)) {
786 foreach ($contactCases as $caseId) {
787 //check if case is associate with other contact or not.
788 $caseContactId = CRM_Case_BAO_Case
::getCaseClients($caseId);
789 if (count($caseContactId) <= 1) {
790 CRM_Case_BAO_Case
::deleteCase($caseId);
798 self
::contactTrashRestore($contact);
801 //delete the contact id from recently view
802 CRM_Utils_Recent
::delContact($id);
804 // reset the group contact cache for this group
805 CRM_Contact_BAO_GroupContactCache
::remove();
807 // delete any dupe cache entry
808 CRM_Core_BAO_PrevNextCache
::deleteItem($id);
810 $transaction->commit();
812 CRM_Utils_Hook
::post('delete', $contactType, $contact->id
, $contact);
814 // also reset the DB_DO global array so we can reuse the memory
815 // http://issues.civicrm.org/jira/browse/CRM-4387
816 CRM_Core_DAO
::freeResult();
822 * function to delete the image of a contact
824 * @param int $id id of the contact
826 * @return boolean true if contact image is deleted
828 public static function deleteContactImage($id) {
833 UPDATE civicrm_contact
836 CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
841 * function to return relative path
842 * @todo make this a method of $config->userSystem (i.e. UF classes) rather than a static function
844 * @param String $absPath absolute path
846 * @return String $relativePath Relative url of uploaded image
848 public static function getRelativePath($absolutePath) {
849 $relativePath = NULL;
850 $config = CRM_Core_Config
::singleton();
851 if ($config->userFramework
== 'Joomla') {
852 $userFrameworkBaseURL = trim(str_replace('/administrator/', '', $config->userFrameworkBaseURL
));
853 $customFileUploadDirectory = strstr(str_replace('\\', '/', $absolutePath), '/media');
854 $relativePath = $userFrameworkBaseURL . $customFileUploadDirectory;
856 elseif ($config->userSystem
->is_drupal
== '1') {
857 //ideally we would do a bigger re-factoring & move the getRelativePath onto the UF class
858 $rootPath = $config->userSystem
->cmsRootPath();
859 $baseUrl = $config->userFrameworkBaseURL
;
861 //format url for language negotiation, CRM-7135
862 $baseUrl = CRM_Utils_System
::languageNegotiationURL($baseUrl, FALSE, TRUE);
864 $relativePath = str_replace("{$rootPath}/",
866 str_replace('\\', '/', $absolutePath)
868 } else if ( $config->userFramework
== 'WordPress' ) {
869 $userFrameworkBaseURL = trim( str_replace( '/wp-admin/', '', $config->userFrameworkBaseURL
) );
870 $customFileUploadDirectory = strstr( str_replace('\\', '/', $absolutePath), '/wp-content/' );
871 $relativePath = $userFrameworkBaseURL . $customFileUploadDirectory;
874 return $relativePath;
878 * function to return proportional height and width of the image
880 * @param Integer $imageWidth width of image
882 * @param Integer $imageHeight height of image
884 * @return Array thumb dimension of image
886 public static function getThumbSize($imageWidth, $imageHeight) {
888 if ($imageWidth && $imageHeight) {
889 $imageRatio = $imageWidth / $imageHeight;
894 if ($imageRatio > 1) {
895 $imageThumbWidth = $thumbWidth;
896 $imageThumbHeight = round($thumbWidth / $imageRatio);
899 $imageThumbHeight = $thumbWidth;
900 $imageThumbWidth = round($thumbWidth * $imageRatio);
903 return array($imageThumbWidth, $imageThumbHeight);
907 * function to validate type of contact image
909 * @param Array $param array of contact/profile field to be edited/added
911 * @param String $imageIndex index of image field
913 * @param String $statusMsg status message to be set after operation
915 * @opType String $opType type of operation like fatal, bounce etc
917 * @return boolean true if valid image extension
919 public static function processImageParams(&$params,
920 $imageIndex = 'image_URL',
934 if (in_array($params[$imageIndex]['type'], $mimeType)) {
935 $params[$imageIndex] = CRM_Contact_BAO_Contact
::getRelativePath($params[$imageIndex]['name']);
939 unset($params[$imageIndex]);
941 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
943 if ($opType == 'status') {
944 CRM_Core_Session
::setStatus($statusMsg, 'Sorry', 'error');
946 // FIXME: additional support for fatal, bounce etc could be added.
952 * function to extract contact id from url for deleting contact image
954 public static function processImage() {
956 $action = CRM_Utils_Request
::retrieve('action', 'String');
957 $cid = CRM_Utils_Request
::retrieve('cid', 'Positive');
958 // retrieve contact id in case of Profile context
959 $id = CRM_Utils_Request
::retrieve('id', 'Positive');
960 $cid = $cid ?
$cid : $id;
961 if ($action & CRM_Core_Action
::DELETE
) {
962 if (CRM_Utils_Request
::retrieve('confirmed', 'Boolean')) {
963 CRM_Contact_BAO_Contact
::deleteContactImage($cid);
964 CRM_Core_Session
::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
965 $session = CRM_Core_Session
::singleton();
966 $toUrl = $session->popUserContext();
967 CRM_Utils_System
::redirect($toUrl);
973 * Function to set is_delete true or restore deleted contact
975 * @param int $contact Contact DAO object
976 * @param boolean $restore true to set the is_delete = 1 else false to restore deleted contact,
982 static function contactTrashRestore($contact, $restore = FALSE) {
983 $op = ($restore ?
'restore' : 'trash');
985 CRM_Utils_Hook
::pre($op, $contact->contact_type
, $contact->id
, CRM_Core_DAO
::$_nullArray);
987 $params = array(1 => array($contact->id
, 'Integer'));
988 $isDelete = ' is_deleted = 1 ';
990 $isDelete = ' is_deleted = 0 ';
993 $query = "DELETE FROM civicrm_uf_match WHERE contact_id = %1";
994 CRM_Core_DAO
::executeQuery($query, $params);
997 $query = "UPDATE civicrm_contact SET {$isDelete} WHERE id = %1";
998 CRM_Core_DAO
::executeQuery($query, $params);
1000 CRM_Utils_Hook
::post($op, $contact->contact_type
, $contact->id
, $contact);
1004 * Get contact type for a contact.
1006 * @param int $id - id of the contact whose contact type is needed
1008 * @return string contact_type if $id found else null ""
1015 public static function getContactType($id) {
1016 return CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1020 * Get contact sub type for a contact.
1022 * @param int $id - id of the contact whose contact sub type is needed
1024 * @return string contact_sub_type if $id found else null ""
1031 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1032 $subtype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1034 return $implodeDelimiter ?
NULL : array();
1037 $subtype = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($subtype, CRM_Core_DAO
::VALUE_SEPARATOR
));
1039 if ($implodeDelimiter) {
1040 $subtype = implode($implodeDelimiter, $subtype);
1046 * Get pair of contact-type and sub-type for a contact.
1048 * @param int $id - id of the contact whose contact sub/contact type is needed
1057 public static function getContactTypes($id) {
1058 $params = array('id' => $id);
1060 $contact = CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact',
1063 array('contact_type', 'contact_sub_type')
1067 $contactTypes = array();
1068 if ($contact->contact_sub_type
)
1069 $contactTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($contact->contact_sub_type
, CRM_Core_DAO
::VALUE_SEPARATOR
));
1070 array_unshift($contactTypes, $contact->contact_type
);
1072 return $contactTypes;
1075 CRM_Core_Error
::fatal();
1080 * combine all the importable fields from the lower levels object
1082 * The ordering is important, since currently we do not have a weight
1083 * scheme. Adding weight is super important
1085 * @param int $contactType contact Type
1086 * @param boolean $status status is used to manipulate first title
1087 * @param boolean $showAll if true returns all fields (includes disabled fields)
1088 * @param boolean $isProfile if its profile mode
1089 * @param boolean $checkPermission if false, do not include permissioning clause (for custom data)
1091 * @return array array of importable Fields
1095 static function importableFields($contactType = 'Individual',
1099 $checkPermission = TRUE,
1100 $withMultiCustomFields = FALSE
1102 if (empty($contactType)) {
1103 $contactType = 'All';
1106 $cacheKeyString = "importableFields $contactType";
1107 $cacheKeyString .= $status ?
'_1' : '_0';
1108 $cacheKeyString .= $showAll ?
'_1' : '_0';
1109 $cacheKeyString .= $isProfile ?
'_1' : '_0';
1110 $cacheKeyString .= $checkPermission ?
'_1' : '_0';
1112 $fields = CRM_Utils_Array
::value($cacheKeyString, self
::$_importableFields);
1115 // check if we can retrieve from database cache
1116 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1120 $fields = CRM_Contact_DAO_Contact
::import();
1122 // get the fields thar are meant for contact types
1123 if (in_array($contactType, array(
1124 'Individual', 'Household', 'Organization', 'All'))) {
1125 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1128 $locationFields = array_merge(CRM_Core_DAO_Address
::import(),
1129 CRM_Core_DAO_Phone
::import(),
1130 CRM_Core_DAO_Email
::import(),
1131 CRM_Core_DAO_IM
::import(TRUE),
1132 CRM_Core_DAO_OpenID
::import()
1135 $locationFields = array_merge($locationFields,
1136 CRM_Core_BAO_CustomField
::getFieldsForImport('Address',
1144 foreach ($locationFields as $key => $field) {
1145 $locationFields[$key]['hasLocationType'] = TRUE;
1148 $fields = array_merge($fields, $locationFields);
1150 $fields = array_merge($fields, CRM_Contact_DAO_Contact
::import());
1151 $fields = array_merge($fields, CRM_Core_DAO_Note
::import());
1154 $fields = array_merge($fields, CRM_Core_DAO_Website
::import());
1156 if ($contactType != 'All') {
1157 $fields = array_merge($fields,
1158 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType,
1163 $withMultiCustomFields
1166 //unset the fields, which are not related to their
1168 $commonValues = array(
1169 'Individual' => array(
1175 'Household' => array(
1185 'organization_name',
1193 'Organization' => array(
1208 foreach ($commonValues[$contactType] as $value) {
1209 unset($fields[$value]);
1214 'Individual', 'Household', 'Organization') as $type) {
1215 $fields = array_merge($fields,
1216 CRM_Core_BAO_CustomField
::getFieldsForImport($type,
1221 $withMultiCustomFields
1228 $fields = array_merge($fields, array(
1230 'title' => ts('Group(s)'),
1234 'title' => ts('Tag(s)'),
1238 'title' => ts('Note(s)'),
1244 //Sorting fields in alphabetical order(CRM-1507)
1245 $fields = CRM_Utils_Array
::crmArraySortByField($fields, 'title');
1247 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1250 self
::$_importableFields[$cacheKeyString] = $fields;
1254 $fields = array_merge(array('do_not_import' => array('title' => ts('- do not import -'))),
1255 self
::$_importableFields[$cacheKeyString]
1259 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1260 self
::$_importableFields[$cacheKeyString]
1268 * combine all the exportable fields from the lower levels object
1270 * currentlty we are using importable fields as exportable fields
1272 * @param int|string $contactType contact Type
1273 * @param boolean $status true while exporting primary contacts
1274 * @param boolean $export true when used during export
1275 * @param boolean $search true when used during search, might conflict with export param?
1277 * @param bool $withMultiRecord
1279 * @return array array of exportable Fields
1283 static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE) {
1284 if (empty($contactType)) {
1285 $contactType = 'All';
1288 $cacheKeyString = "exportableFields $contactType";
1289 $cacheKeyString .= $export ?
'_1' : '_0';
1290 $cacheKeyString .= $status ?
'_1' : '_0';
1291 $cacheKeyString .= $search ?
'_1' : '_0';
1293 if (!self
::$_exportableFields ||
!CRM_Utils_Array
::value($cacheKeyString, self
::$_exportableFields)) {
1294 if (!self
::$_exportableFields) {
1295 self
::$_exportableFields = array();
1298 // check if we can retrieve from database cache
1299 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1302 $fields = CRM_Contact_DAO_Contact
::export();
1304 // the fields are meant for contact types
1308 array('Individual', 'Household', 'Organization', 'All')
1311 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1313 // add current employer for individuals
1314 $fields = array_merge($fields, array(
1315 'current_employer' =>
1317 'name' => 'organization_name',
1318 'title' => ts('Current Employer'),
1322 $locationType = array(
1323 'location_type' => array(
1324 'name' => 'location_type',
1325 'where' => 'civicrm_location_type.name',
1326 'title' => ts('Location Type'),
1329 $IMProvider = array(
1330 'im_provider' => array(
1331 'name' => 'im_provider',
1332 'where' => 'civicrm_im.provider_id',
1333 'title' => ts('IM Provider'),
1336 $locationFields = array_merge($locationType,
1337 CRM_Core_DAO_Address
::export(),
1338 CRM_Core_DAO_Phone
::export(),
1339 CRM_Core_DAO_Email
::export(),
1341 CRM_Core_DAO_IM
::export(TRUE),
1342 CRM_Core_DAO_OpenID
::export()
1345 $locationFields = array_merge($locationFields,
1346 CRM_Core_BAO_CustomField
::getFieldsForImport('Address')
1349 foreach ($locationFields as $key => $field) {
1350 $locationFields[$key]['hasLocationType'] = TRUE;
1353 $fields = array_merge($fields, $locationFields);
1356 $fields = array_merge($fields,
1357 CRM_Core_DAO_Worldregion
::export()
1361 $fields = array_merge($fields,
1362 CRM_Contact_DAO_Contact
::export()
1366 $fields = array_merge($fields, CRM_Core_DAO_Website
::export());
1368 if ($contactType != 'All') {
1369 $fields = array_merge($fields,
1370 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType, $status, TRUE, $search, TRUE, $withMultiRecord)
1375 'Individual', 'Household', 'Organization') as $type) {
1376 $fields = array_merge($fields,
1377 CRM_Core_BAO_CustomField
::getFieldsForImport($type, FALSE, FALSE, $search, TRUE, $withMultiRecord)
1384 $fields = array_merge($fields, array(
1386 'title' => ts('Group(s)'),
1390 'title' => ts('Tag(s)'),
1394 'title' => ts('Note(s)'),
1400 $fields = array_merge($fields, array(
1402 'title' => ts('Group(s)'),
1406 'title' => ts('Tag(s)'),
1410 'title' => ts('Note(s)'),
1416 //Sorting fields in alphabetical order(CRM-1507)
1417 foreach ($fields as $k => $v) {
1418 $sortArray[$k] = CRM_Utils_Array
::value('title', $v);
1421 $fields = array_merge($sortArray, $fields);
1422 //unset the field which are not related to their contact type.
1423 if ($contactType != 'All') {
1424 $commonValues = array(
1425 'Individual' => array(
1429 'organization_name',
1430 'email_greeting_custom',
1431 'postal_greeting_custom',
1434 'Household' => array(
1444 'organization_name',
1452 'email_greeting_custom',
1453 'postal_greeting_custom',
1458 'Organization' => array(
1469 'email_greeting_custom',
1470 'postal_greeting_custom',
1480 foreach ($commonValues[$contactType] as $value) {
1481 unset($fields[$value]);
1485 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1487 self
::$_exportableFields[$cacheKeyString] = $fields;
1491 $fields = self
::$_exportableFields[$cacheKeyString];
1494 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1495 self
::$_exportableFields[$cacheKeyString]
1503 * Function to get the all contact details(Hierarchical)
1505 * @param int $contactId contact id
1506 * @param array $fields fields array
1508 * @return $values array contains the contact details
1512 static function getHierContactDetails($contactId, &$fields) {
1513 $params = array(array('contact_id', '=', $contactId, 0, 0));
1516 $returnProperties = self
::makeHierReturnProperties($fields, $contactId);
1518 // we dont know the contents of return properties, but we need the lower level ids of the contact
1519 // so add a few fields
1520 $returnProperties['first_name'] =
1521 $returnProperties['organization_name'] =
1522 $returnProperties['household_name'] =
1523 $returnProperties['contact_type'] =
1524 $returnProperties['contact_sub_type'] = 1;
1525 return list($query, $options) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, $options);
1529 * given a set of flat profile style field names, create a hierarchy
1530 * for query to use and crete the right sql
1533 * @param int $contactId contact id
1535 * @internal param array $properties a flat return properties name value array
1536 * @return array a hierarchical property tree if appropriate
1540 static function &makeHierReturnProperties($fields, $contactId = NULL) {
1541 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1543 $returnProperties = array();
1545 $multipleFields = array('website' => 'url');
1546 foreach ($fields as $name => $dontCare) {
1547 if (strpos($name, '-') !== FALSE) {
1548 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $name, 3);
1550 if (!in_array($fieldName, $multipleFields)) {
1551 if ($id == 'Primary') {
1552 $locationTypeName = 1;
1555 $locationTypeName = CRM_Utils_Array
::value($id, $locationTypes);
1556 if (!$locationTypeName) {
1561 if (empty($returnProperties['location'])) {
1562 $returnProperties['location'] = array();
1564 if (empty($returnProperties['location'][$locationTypeName])) {
1565 $returnProperties['location'][$locationTypeName] = array();
1566 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1568 if (in_array($fieldName, array(
1569 'phone', 'im', 'email', 'openid', 'phone_ext'))) {
1571 $returnProperties['location'][$locationTypeName][$fieldName . '-' . $type] = 1;
1574 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1577 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1578 $returnProperties['location'][$locationTypeName][substr($fieldName, 8)] = 1;
1581 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1585 $returnProperties['website'][$id][$fieldName] = 1;
1589 $returnProperties[$name] = 1;
1593 return $returnProperties;
1597 * Function to return the primary location type of a contact
1599 * $params int $contactId contact_id
1600 * $params boolean $isPrimaryExist if true, return primary contact location type otherwise null
1601 * $params boolean $skipDefaultPriamry if true, return primary contact location type otherwise null
1604 * @param bool $skipDefaultPriamry
1605 * @param null $block
1607 * @return int $locationType location_type_id
1611 static function getPrimaryLocationType($contactId, $skipDefaultPriamry = FALSE, $block = NULL) {
1613 $entityBlock = array('contact_id' => $contactId);
1614 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock);
1615 foreach($blocks[$block] as $key => $value){
1616 if (!empty($value['is_primary'])){
1617 $locationType = CRM_Utils_Array
::value('location_type_id',$value);
1624 IF ( civicrm_email.location_type_id IS NULL,
1625 IF ( civicrm_address.location_type_id IS NULL,
1626 IF ( civicrm_phone.location_type_id IS NULL,
1627 IF ( civicrm_im.location_type_id IS NULL,
1628 IF ( civicrm_openid.location_type_id IS NULL, null, civicrm_openid.location_type_id)
1629 ,civicrm_im.location_type_id)
1630 ,civicrm_phone.location_type_id)
1631 ,civicrm_address.location_type_id)
1632 ,civicrm_email.location_type_id) as locationType
1633 FROM civicrm_contact
1634 LEFT JOIN civicrm_email ON ( civicrm_email.is_primary = 1 AND civicrm_email.contact_id = civicrm_contact.id )
1635 LEFT JOIN civicrm_address ON ( civicrm_address.is_primary = 1 AND civicrm_address.contact_id = civicrm_contact.id)
1636 LEFT JOIN civicrm_phone ON ( civicrm_phone.is_primary = 1 AND civicrm_phone.contact_id = civicrm_contact.id)
1637 LEFT JOIN civicrm_im ON ( civicrm_im.is_primary = 1 AND civicrm_im.contact_id = civicrm_contact.id)
1638 LEFT JOIN civicrm_openid ON ( civicrm_openid.is_primary = 1 AND civicrm_openid.contact_id = civicrm_contact.id)
1639 WHERE civicrm_contact.id = %1 ";
1641 $params = array(1 => array($contactId, 'Integer'));
1643 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1645 $locationType = NULL;
1646 if ($dao->fetch()) {
1647 $locationType = $dao->locationType
;
1650 if (isset($locationType)) {
1651 return $locationType;
1653 elseif ($skipDefaultPriamry) {
1654 // if there is no primary contact location then return null
1658 // if there is no primart contact location, then return default
1659 // location type of the system
1660 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
1661 return $defaultLocationType->id
;
1666 * function to get the display name, primary email and location type of a contact
1668 * @param int $id id of the contact
1670 * @return array of display_name, email if found, do_not_email or (null,null,null)
1674 static function getContactDetails($id) {
1675 // check if the contact type
1676 $contactType = self
::getContactType($id);
1678 $nameFields = ($contactType == 'Individual') ?
"civicrm_contact.first_name, civicrm_contact.last_name, civicrm_contact.display_name" : "civicrm_contact.display_name";
1681 SELECT $nameFields, civicrm_email.email, civicrm_contact.do_not_email, civicrm_email.on_hold, civicrm_contact.is_deceased
1682 FROM civicrm_contact LEFT JOIN civicrm_email ON (civicrm_contact.id = civicrm_email.contact_id)
1683 WHERE civicrm_contact.id = %1
1684 ORDER BY civicrm_email.is_primary DESC";
1685 $params = array(1 => array($id, 'Integer'));
1686 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
1688 if ($dao->fetch()) {
1689 if ($contactType == 'Individual') {
1690 if ($dao->first_name ||
$dao->last_name
) {
1691 $name = "{$dao->first_name} {$dao->last_name}";
1694 $name = $dao->display_name
;
1698 $name = $dao->display_name
;
1700 $email = $dao->email
;
1701 $doNotEmail = $dao->do_not_email ?
TRUE : FALSE;
1702 $onHold = $dao->on_hold ?
TRUE : FALSE;
1703 $isDeceased = $dao->is_deceased ?
TRUE : FALSE;
1704 return array($name, $email, $doNotEmail, $onHold, $isDeceased);
1706 return array(NULL, NULL, NULL, NULL, NULL);
1710 * function to add/edit/register contacts through profile.
1712 * @params array $params Array of profile fields to be edited/added.
1713 * @params int $contactID contact_id of the contact to be edited/added.
1714 * @params array $fields array of fields from UFGroup
1715 * @params int $addToGroupID specifies the default group to which contact is added.
1716 * @params int $ufGroupId uf group id (profile id)
1717 * @param string $ctype contact type
1718 * @param boolean $visibility basically lets us know where this request is coming from
1719 * if via a profile from web, we restrict what groups are changed
1721 * @return int contact id created/edited
1725 static function createProfileContact(
1729 $addToGroupID = NULL,
1734 // add ufGroupID to params array ( CRM-2012 )
1736 $params['uf_group_id'] = $ufGroupId;
1741 CRM_Utils_Hook
::pre('edit', 'Profile', $contactID, $params);
1745 CRM_Utils_Hook
::pre('create', 'Profile', NULL, $params);
1748 list($data, $contactDetails) = self
::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
1750 // manage is_opt_out
1751 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
1752 $wasOptOut = CRM_Utils_Array
::value('is_opt_out', $contactDetails, FALSE);
1753 $isOptOut = CRM_Utils_Array
::value('is_opt_out', $params, FALSE);
1754 $data['is_opt_out'] = $isOptOut;
1755 // on change, create new civicrm_subscription_history entry
1756 if (($wasOptOut != $isOptOut) && !empty($contactDetails['contact_id'])) {
1758 'contact_id' => $contactDetails['contact_id'],
1759 'status' => $isOptOut ?
'Removed' : 'Added',
1762 CRM_Contact_BAO_SubscriptionHistory
::create($shParams);
1766 $contact = self
::create($data);
1768 // contact is null if the profile does not have any contact fields
1770 $contactID = $contact->id
;
1773 if (empty($contactID)) {
1774 CRM_Core_Error
::fatal('Cannot proceed without a valid contact id');
1777 // Process group and tag
1778 if (!empty($fields['group'])) {
1780 // this for sure means we are coming in via profile since i added it to fix
1781 // removing contacts from user groups -- lobo
1785 CRM_Contact_BAO_GroupContact
::create($params['group'], $contactID, $visibility, $method);
1788 if (!empty($fields['tag'])) {
1789 CRM_Core_BAO_EntityTag
::create($params['tag'], 'civicrm_contact', $contactID);
1792 //to add profile in default group
1793 if (is_array($addToGroupID)) {
1794 $contactIds = array($contactID);
1795 foreach ($addToGroupID as $groupId) {
1796 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
1799 elseif ($addToGroupID) {
1800 $contactIds = array($contactID);
1801 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $addToGroupID);
1804 // reset the group contact cache for this group
1805 CRM_Contact_BAO_GroupContactCache
::remove();
1808 CRM_Utils_Hook
::post('edit', 'Profile', $contactID, $params);
1811 CRM_Utils_Hook
::post('create', 'Profile', $contactID, $params);
1816 static function formatProfileContactParams(
1825 $data = $contactDetails = array();
1827 // get the contact details (hier)
1829 list($details, $options) = self
::getHierContactDetails($contactID, $fields);
1831 $contactDetails = $details[$contactID];
1832 $data['contact_type'] = CRM_Utils_Array
::value('contact_type', $contactDetails);
1833 $data['contact_sub_type'] = CRM_Utils_Array
::value('contact_sub_type', $contactDetails);
1836 //we should get contact type only if contact
1838 $data['contact_type'] = CRM_Core_BAO_UFField
::getProfileType($ufGroupId);
1840 //special case to handle profile with only contact fields
1841 if ($data['contact_type'] == 'Contact') {
1842 $data['contact_type'] = 'Individual';
1844 elseif (CRM_Contact_BAO_ContactType
::isaSubType($data['contact_type'])) {
1845 $data['contact_type'] = CRM_Contact_BAO_ContactType
::getBasicType($data['contact_type']);
1849 $data['contact_type'] = $ctype;
1852 $data['contact_type'] = 'Individual';
1856 //fix contact sub type CRM-5125
1857 if (array_key_exists('contact_sub_type', $params) &&
1858 !empty($params['contact_sub_type'])
1860 $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
;
1862 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
1863 !empty($params['contact_sub_type_hidden'])
1865 // if profile was used, and had any subtype, we obtain it from there
1866 $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
;
1869 if ($ctype == 'Organization') {
1870 $data['organization_name'] = CRM_Utils_Array
::value('organization_name', $contactDetails);
1872 elseif ($ctype == 'Household') {
1873 $data['household_name'] = CRM_Utils_Array
::value('household_name', $contactDetails);
1876 $locationType = array();
1881 $data['contact_id'] = $contactID;
1882 $primaryLocationType = self
::getPrimaryLocationType($contactID);
1885 $defaultLocation = CRM_Core_BAO_LocationType
::getDefault();
1886 $defaultLocationId = $defaultLocation->id
;
1889 // get the billing location type
1890 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
1891 $billingLocationTypeId = array_search('Billing', $locationTypes);
1893 $blocks = array('email', 'phone', 'im', 'openid');
1895 $multiplFields = array('url');
1896 // prevent overwritten of formatted array, reset all block from
1897 // params if it is not in valid format (since import pass valid format)
1898 foreach ($blocks as $blk) {
1899 if (array_key_exists($blk, $params) &&
1900 !is_array($params[$blk])
1902 unset($params[$blk]);
1906 $primaryPhoneLoc = NULL;
1907 $session = CRM_Core_Session
::singleton();
1908 foreach ($params as $key => $value) {
1909 $fieldName = $locTypeId = $typeId = NULL;
1910 list($fieldName, $locTypeId, $typeId) = CRM_Utils_System
::explode('-', $key, 3);
1912 //store original location type id
1913 $actualLocTypeId = $locTypeId;
1915 if ($locTypeId == 'Primary') {
1917 if(in_array( $fieldName, $blocks)){
1918 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, $fieldName);
1921 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, 'address');
1923 $primaryLocationType = $locTypeId;
1926 $locTypeId = $defaultLocationId;
1930 if (is_numeric($locTypeId) &&
1931 !in_array($fieldName, $multiplFields) &&
1932 substr($fieldName, 0, 7) != 'custom_'
1934 $index = $locTypeId;
1936 if (is_numeric($typeId)) {
1937 $index .= '-' . $typeId;
1939 if (!in_array($index, $locationType)) {
1940 $locationType[$count] = $index;
1944 $loc = CRM_Utils_Array
::key($index, $locationType);
1946 $blockName = in_array( $fieldName, $blocks) ?
$fieldName : 'address';
1948 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
1950 //set is_billing true, for location type "Billing"
1951 if ($locTypeId == $billingLocationTypeId) {
1952 $data[$blockName][$loc]['is_billing'] = 1;
1956 //get the primary location type
1957 if ($locTypeId == $primaryLocationType) {
1958 $data[$blockName][$loc]['is_primary'] = 1;
1961 elseif ($locTypeId == $defaultLocationId) {
1962 $data[$blockName][$loc]['is_primary'] = 1;
1965 if ( in_array($fieldName, array('phone'))) {
1967 $data['phone'][$loc]['phone_type_id'] = $typeId;
1970 $data['phone'][$loc]['phone_type_id'] = '';
1972 $data['phone'][$loc]['phone'] = $value;
1974 //special case to handle primary phone with different phone types
1975 // in this case we make first phone type as primary
1976 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
1977 $primaryPhoneLoc = $loc;
1980 if ($loc != $primaryPhoneLoc) {
1981 unset($data['phone'][$loc]['is_primary']);
1984 elseif ($fieldName == 'phone_ext') {
1985 $data['phone'][$loc]['phone_ext'] = $value;
1987 elseif ($fieldName == 'email') {
1988 $data['email'][$loc]['email'] = $value;
1990 elseif ($fieldName == 'im') {
1991 if (isset($params[$key . '-provider_id'])) {
1992 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
1994 if (strpos($key, '-provider_id') !== FALSE) {
1995 $data['im'][$loc]['provider_id'] = $params[$key];
1998 $data['im'][$loc]['name'] = $value;
2001 elseif ($fieldName == 'openid') {
2002 $data['openid'][$loc]['openid'] = $value;
2005 if ($fieldName === 'state_province') {
2007 if (is_numeric($value) && ((int ) $value) >= 1000) {
2008 $data['address'][$loc]['state_province_id'] = $value;
2010 elseif (empty($value)) {
2011 $data['address'][$loc]['state_province_id'] = '';
2014 $data['address'][$loc]['state_province'] = $value;
2017 elseif ($fieldName === 'country') {
2019 if (is_numeric($value) && ((int ) $value) >= 1000
2021 $data['address'][$loc]['country_id'] = $value;
2023 elseif (empty($value)) {
2024 $data['address'][$loc]['country_id'] = '';
2027 $data['address'][$loc]['country'] = $value;
2030 elseif ($fieldName === 'county') {
2031 $data['address'][$loc]['county_id'] = $value;
2033 elseif ($fieldName == 'address_name') {
2034 $data['address'][$loc]['name'] = $value;
2036 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2037 $data['address'][$loc][substr($fieldName, 8)] = $value;
2040 $data['address'][$loc][$fieldName] = $value;
2045 if (substr($key, 0, 4) === 'url-') {
2046 $websiteField = explode('-', $key);
2047 if (isset($websiteField[2])) {
2048 $data['website'][$websiteField[1]]['website_type_id'] = $value;
2051 $data['website'][$websiteField[1]]['url'] = $value;
2054 elseif (in_array($key, self
::$_greetingTypes, TRUE)) {
2055 //save email/postal greeting and addressee values if any, CRM-4575
2056 $data[$key . '_id'] = $value;
2058 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($key))) {
2059 // for autocomplete transfer hidden value instead of label
2060 if ($params[$key] && isset($params[$key . '_id'])) {
2061 $value = $params[$key . '_id'];
2064 // we need to append time with date
2065 if ($params[$key] && isset($params[$key . '_time'])) {
2066 $value .= ' ' . $params[$key . '_time'];
2069 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
2070 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 &&
2071 ($value == '' ||
!isset($value))) {
2076 if (!empty($params['customRecordValues'])) {
2077 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2078 foreach ($params['customRecordValues'] as $recId => $customFields) {
2079 if (is_array($customFields) && !empty($customFields)) {
2080 foreach ($customFields as $customFieldName) {
2081 if ($customFieldName == $key) {
2091 $type = $data['contact_type'];
2092 if (!empty($data['contact_sub_type'])) {
2093 $type = $data['contact_sub_type'];
2094 $type = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($type, CRM_Core_DAO
::VALUE_SEPARATOR
));
2095 // generally a contact even if, has multiple subtypes the parent-type is going to be one only
2096 // and since formatCustomField() would be interested in parent type, lets consider only one subtype
2097 // as the results going to be same.
2101 CRM_Core_BAO_CustomField
::formatCustomField($customFieldId,
2109 elseif ($key == 'edit') {
2113 if ($key == 'location') {
2114 foreach ($value as $locationTypeId => $field) {
2115 foreach ($field as $block => $val) {
2116 if ($block == 'address' && array_key_exists('address_name', $val)) {
2117 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2122 if($key == 'phone' && isset($params['phone_ext'])){
2123 $data[$key] = $value;
2124 foreach($value as $cnt => $phoneBlock){
2125 if($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']){
2126 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array
::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2130 else if (in_array($key,
2139 ($value == '' ||
!isset($value)) &&
2140 ($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0) {
2141 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
2142 // to avoid update with empty values
2146 $data[$key] = $value;
2152 if (!isset($data['contact_type'])) {
2153 $data['contact_type'] = 'Individual';
2156 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2157 $privacy = CRM_Core_SelectValues
::privacy();
2158 foreach ($privacy as $key => $value) {
2159 if (array_key_exists($key, $fields)) {
2160 // do not reset values for existing contacts, if fields are added to a profile
2161 if (array_key_exists($key, $params)) {
2162 $data[$key] = $params[$key];
2163 if (empty($params[$key])) {
2167 elseif (!$contactID) {
2173 return array($data, $contactDetails);
2177 * Function to find the get contact details
2178 * does not respect ACLs for now, which might need to be rectified at some
2179 * stage based on how its used
2181 * @param string $mail primary email address of the contact
2182 * @param string $ctype contact type
2184 * @return object $dao contact details
2187 static function &matchContactOnEmail($mail, $ctype = NULL) {
2188 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2189 $mail = $strtolower(trim($mail));
2191 SELECT civicrm_contact.id as contact_id,
2192 civicrm_contact.hash as hash,
2193 civicrm_contact.contact_type as contact_type,
2194 civicrm_contact.contact_sub_type as contact_sub_type
2195 FROM civicrm_contact
2196 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2199 if (CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
2200 'uniq_email_per_site'
2202 // try to find a match within a site (multisite).
2203 $groups = CRM_Core_BAO_Domain
::getChildGroupIds();
2204 if (!empty($groups)) {
2206 INNER JOIN civicrm_group_contact gc ON
2207 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2212 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2213 $p = array(1 => array($mail, 'String'));
2216 $query .= " AND civicrm_contact.contact_type = %3";
2217 $p[3] = array($ctype, 'String');
2220 $query .= " ORDER BY civicrm_email.is_primary DESC";
2222 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2224 if ($dao->fetch()) {
2227 return CRM_Core_DAO
::$_nullObject;
2231 * Function to find the contact details associated with an OpenID
2233 * @param string $openId openId of the contact
2234 * @param string $ctype contact type
2236 * @return object $dao contact details
2239 static function &matchContactOnOpenId($openId, $ctype = NULL) {
2240 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2241 $openId = $strtolower(trim($openId));
2243 SELECT civicrm_contact.id as contact_id,
2244 civicrm_contact.hash as hash,
2245 civicrm_contact.contact_type as contact_type,
2246 civicrm_contact.contact_sub_type as contact_sub_type
2247 FROM civicrm_contact
2248 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2249 WHERE civicrm_openid.openid = %1";
2250 $p = array(1 => array($openId, 'String'));
2253 $query .= " AND civicrm_contact.contact_type = %3";
2254 $p[3] = array($ctype, 'String');
2257 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2259 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2261 if ($dao->fetch()) {
2264 return CRM_Core_DAO
::$_nullObject;
2268 * Funtion to get primary email of the contact
2270 * @param int $contactID contact id
2272 * @return string $dao->email email address if present else null
2276 public static function getPrimaryEmail($contactID) {
2277 // fetch the primary email
2279 SELECT civicrm_email.email as email
2280 FROM civicrm_contact
2281 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2282 WHERE civicrm_email.is_primary = 1
2283 AND civicrm_contact.id = %1";
2284 $p = array(1 => array($contactID, 'Integer'));
2285 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2288 if ($dao->fetch()) {
2289 $email = $dao->email
;
2296 * Funtion to get primary OpenID of the contact
2298 * @param int $contactID contact id
2300 * @return string $dao->openid OpenID if present else null
2304 public static function getPrimaryOpenId($contactID) {
2305 // fetch the primary OpenID
2307 SELECT civicrm_openid.openid as openid
2308 FROM civicrm_contact
2309 LEFT JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2310 WHERE civicrm_contact.id = %1
2311 AND civicrm_openid.is_primary = 1";
2312 $p = array(1 => array($contactID, 'Integer'));
2313 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2316 if ($dao->fetch()) {
2317 $openId = $dao->openid
;
2324 * Given the list of params in the params array, fetch the object
2325 * and store the values in the values array
2327 * @param array $params input parameters to find object
2328 * @param array $values output values of the object
2330 * @return CRM_Contact_BAO_Contact|null the found object or null
2334 public static function getValues(&$params, &$values) {
2335 $contact = new CRM_Contact_BAO_Contact();
2337 $contact->copyValues($params);
2339 if ($contact->find(TRUE)) {
2341 CRM_Core_DAO
::storeValues($contact, $values);
2344 foreach (self
::$_commPrefs as $name) {
2345 if (isset($contact->$name)) {
2346 $privacy[$name] = $contact->$name;
2350 if (!empty($privacy)) {
2351 $values['privacy'] = $privacy;
2354 // communication Prefferance
2355 $preffComm = $comm = array();
2356 $comm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2357 $contact->preferred_communication_method
2359 foreach ($comm as $value) {
2360 $preffComm[$value] = 1;
2362 $temp = array('preferred_communication_method' => $contact->preferred_communication_method
);
2365 'preferred_communication_method' => array('newName' => 'preferred_communication_method_display',
2366 'groupName' => 'preferred_communication_method',
2369 CRM_Core_OptionGroup
::lookupValues($temp, $names, FALSE);
2371 $values['preferred_communication_method'] = $preffComm;
2372 $values['preferred_communication_method_display'] = CRM_Utils_Array
::value('preferred_communication_method_display', $temp);
2374 $preferredMailingFormat = CRM_Core_SelectValues
::pmf();
2375 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format
];
2377 // get preferred languages
2378 if (!empty($contact->preferred_language
)) {
2379 $values['preferred_language'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language
);
2382 // Calculating Year difference
2383 if ($contact->birth_date
) {
2384 $birthDate = CRM_Utils_Date
::customFormat($contact->birth_date
, '%Y%m%d');
2385 if ($birthDate < date('Ymd')) {
2386 $age = CRM_Utils_Date
::calculateAge($birthDate);
2387 $values['age']['y'] = CRM_Utils_Array
::value('years', $age);
2388 $values['age']['m'] = CRM_Utils_Array
::value('months', $age);
2391 list($values['birth_date']) = CRM_Utils_Date
::setDateDefaults($contact->birth_date
, 'birth');
2392 $values['birth_date_display'] = $contact->birth_date
;
2395 if ($contact->deceased_date
) {
2396 list($values['deceased_date']) = CRM_Utils_Date
::setDateDefaults($contact->deceased_date
, 'birth');
2397 $values['deceased_date_display'] = $contact->deceased_date
;
2400 $contact->contact_id
= $contact->id
;
2408 * Given the component name and returns
2409 * the count of participation of contact
2411 * @param string $component input component name
2412 * @param integer $contactId input contact id
2413 * @param string $tableName optional tableName if component is custom group
2415 * @return total number of count of occurence in database
2419 static function getCountComponent($component, $contactId, $tableName = NULL) {
2421 switch ($component) {
2423 return CRM_Core_BAO_EntityTag
::getContactTags($contactId, TRUE);
2426 return CRM_Contact_BAO_Relationship
::getRelationship($contactId,
2427 CRM_Contact_BAO_Relationship
::CURRENT
,
2432 return CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, "Added", NULL, TRUE);
2435 if (CRM_Core_BAO_Log
::useLoggingReport()) {
2438 return CRM_Core_BAO_Log
::getContactLogCount($contactId);
2441 return CRM_Core_BAO_Note
::getContactNoteCount($contactId);
2443 case 'contribution':
2444 return CRM_Contribute_BAO_Contribution
::contributionCount($contactId);
2447 return CRM_Member_BAO_Membership
::getContactMembershipCount($contactId, TRUE);
2450 return CRM_Event_BAO_Participant
::getContactParticipantCount($contactId);
2453 return CRM_Pledge_BAO_Pledge
::getContactPledgeCount($contactId);
2456 return CRM_Case_BAO_Case
::caseCount($contactId);
2459 return CRM_Grant_BAO_Grant
::getContactGrantCount($contactId);
2463 'contact_id' => $contactId,
2466 'context' => 'activity',
2468 return CRM_Activity_BAO_Activity
::getActivitiesCount($input);
2471 $params = array('contact_id' => $contactId);
2472 return CRM_Mailing_BAO_Mailing
::getContactMailingsCount($params);
2475 $custom = explode('_', $component);
2476 if ($custom['0'] = 'custom') {
2478 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2480 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2481 return CRM_Core_DAO
::singleValueQuery($queryString);
2487 * Function to process greetings and cache
2489 * @param object $contact contact object after save
2490 * @param boolean $useDefaults use default greeting values
2496 static function processGreetings(&$contact, $useDefaults = FALSE) {
2498 //retrieve default greetings
2499 $defaultGreetings = CRM_Core_PseudoConstant
::greetingDefaults();
2500 $contactDefaults = $defaultGreetings[$contact->contact_type
];
2503 // note that contact object not always has required greeting related
2504 // fields that are required to calculate greeting and
2505 // also other fields used in tokens etc,
2506 // hence we need to retrieve it again.
2507 if ( $contact->_query
!== FALSE ) {
2508 $contact->find(TRUE);
2511 // store object values to an array
2512 $contactDetails = array();
2513 CRM_Core_DAO
::storeValues($contact, $contactDetails);
2514 $contactDetails = array(array($contact->id
=> $contactDetails));
2516 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2517 $updateQueryString = array();
2519 //cache email and postal greeting to greeting display
2520 if ($contact->email_greeting_custom
!= 'null' && $contact->email_greeting_custom
) {
2521 $emailGreetingString = $contact->email_greeting_custom
;
2523 elseif ($contact->email_greeting_id
!= 'null' && $contact->email_greeting_id
) {
2524 // the filter value for Individual contact type is set to 1
2526 'contact_type' => $contact->contact_type
,
2527 'greeting_type' => 'email_greeting',
2530 $emailGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2531 $emailGreetingString = $emailGreeting[$contact->email_greeting_id
];
2532 $updateQueryString[] = " email_greeting_custom = NULL ";
2536 reset($contactDefaults['email_greeting']);
2537 $emailGreetingID = key($contactDefaults['email_greeting']);
2538 $emailGreetingString = $contactDefaults['email_greeting'][$emailGreetingID];
2539 $updateQueryString[] = " email_greeting_id = $emailGreetingID ";
2540 $updateQueryString[] = " email_greeting_custom = NULL ";
2542 elseif ($contact->email_greeting_custom
) {
2543 $updateQueryString[] = " email_greeting_display = NULL ";
2547 if ($emailGreetingString) {
2548 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($emailGreetingString,
2551 'CRM_Contact_BAO_Contact'
2553 $emailGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($emailGreetingString));
2554 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2558 if ($contact->postal_greeting_custom
!= 'null' && $contact->postal_greeting_custom
) {
2559 $postalGreetingString = $contact->postal_greeting_custom
;
2561 elseif ($contact->postal_greeting_id
!= 'null' && $contact->postal_greeting_id
) {
2563 'contact_type' => $contact->contact_type
,
2564 'greeting_type' => 'postal_greeting',
2566 $postalGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2567 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id
];
2568 $updateQueryString[] = " postal_greeting_custom = NULL ";
2572 reset($contactDefaults['postal_greeting']);
2573 $postalGreetingID = key($contactDefaults['postal_greeting']);
2574 $postalGreetingString = $contactDefaults['postal_greeting'][$postalGreetingID];
2575 $updateQueryString[] = " postal_greeting_id = $postalGreetingID ";
2576 $updateQueryString[] = " postal_greeting_custom = NULL ";
2578 elseif ($contact->postal_greeting_custom
) {
2579 $updateQueryString[] = " postal_greeting_display = NULL ";
2583 if ($postalGreetingString) {
2584 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($postalGreetingString,
2587 'CRM_Contact_BAO_Contact'
2589 $postalGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($postalGreetingString));
2590 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2594 if ($contact->addressee_custom
!= 'null' && $contact->addressee_custom
) {
2595 $addresseeString = $contact->addressee_custom
;
2597 elseif ($contact->addressee_id
!= 'null' && $contact->addressee_id
) {
2599 'contact_type' => $contact->contact_type
,
2600 'greeting_type' => 'addressee',
2603 $addressee = CRM_Core_PseudoConstant
::greeting($filter);
2604 $addresseeString = $addressee[$contact->addressee_id
];
2605 $updateQueryString[] = " addressee_custom = NULL ";
2609 reset($contactDefaults['addressee']);
2610 $addresseeID = key($contactDefaults['addressee']);
2611 $addresseeString = $contactDefaults['addressee'][$addresseeID];
2612 $updateQueryString[] = " addressee_id = $addresseeID ";
2613 $updateQueryString[] = " addressee_custom = NULL ";
2615 elseif ($contact->addressee_custom
) {
2616 $updateQueryString[] = " addressee_display = NULL ";
2620 if ($addresseeString) {
2621 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($addresseeString,
2624 'CRM_Contact_BAO_Contact'
2626 $addresseeString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($addresseeString));
2627 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2630 if (!empty($updateQueryString)) {
2631 $updateQueryString = implode(',', $updateQueryString);
2632 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2633 CRM_Core_DAO
::executeQuery($queryString);
2638 * Function to retrieve loc block ids w/ given condition.
2640 * @param int $contactId contact id.
2641 * @param array $criteria key => value pair which should be
2642 * fulfill by return record ids.
2643 * @param string $condOperator operator use for grouping multiple conditions.
2645 * @return array $locBlockIds loc block ids which fulfill condition.
2648 static function getLocBlockIds($contactId, $criteria = array(), $condOperator = 'AND') {
2649 $locBlockIds = array();
2651 return $locBlockIds;
2654 foreach (array('Email', 'OpenID', 'Phone', 'Address', 'IM') as $block) {
2655 $name = strtolower($block);
2656 $className = "CRM_Core_DAO_$block";
2657 $blockDAO = new $className();
2659 // build the condition.
2660 if (is_array($criteria)) {
2661 $fields = $blockDAO->fields();
2662 $conditions = array();
2663 foreach ($criteria as $field => $value) {
2664 if (array_key_exists($field, $fields)) {
2665 $cond = "( $field = $value )";
2666 // value might be zero or null.
2667 if (!$value ||
strtolower($value) == 'null') {
2668 $cond = "( $field = 0 OR $field IS NULL )";
2670 $conditions[] = $cond;
2673 if (!empty($conditions)) {
2674 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2678 $blockDAO->contact_id
= $contactId;
2680 while ($blockDAO->fetch()) {
2681 $locBlockIds[$name][] = $blockDAO->id
;
2686 return $locBlockIds;
2690 * Function to build context menu items.
2692 * @return array of context menu for logged in user.
2695 static function contextMenu($contactId = NULL) {
2698 'title' => ts('View Contact'),
2700 'ref' => 'view-contact',
2701 'class' => 'no-popup',
2703 'permissions' => array('view all contacts'),
2706 'title' => ts('Edit Contact'),
2708 'ref' => 'edit-contact',
2709 'class' => 'no-popup',
2711 'permissions' => array('edit all contacts'),
2714 'title' => ts('Delete Contact'),
2716 'ref' => 'delete-contact',
2718 'permissions' => array('access deleted contacts', 'delete contacts'),
2720 'contribution' => array(
2721 'title' => ts('Add Contribution'),
2723 'ref' => 'new-contribution',
2724 'key' => 'contribution',
2725 'tab' => 'contribute',
2726 'component' => 'CiviContribute',
2727 'href' => CRM_Utils_System
::url('civicrm/contact/view/contribution',
2728 'reset=1&action=add&context=contribution'
2730 'permissions' => array(
2731 'access CiviContribute',
2732 'edit contributions',
2735 'participant' => array(
2736 'title' => ts('Register for Event'),
2738 'ref' => 'new-participant',
2739 'key' => 'participant',
2740 'tab' => 'participant',
2741 'component' => 'CiviEvent',
2742 'href' => CRM_Utils_System
::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
2743 'permissions' => array(
2745 'edit event participants',
2748 'activity' => array(
2749 'title' => ts('Record Activity'),
2751 'ref' => 'new-activity',
2752 'key' => 'activity',
2753 'permissions' => array('edit all contacts'),
2756 'title' => ts('Add Pledge'),
2758 'ref' => 'new-pledge',
2761 'href' => CRM_Utils_System
::url('civicrm/contact/view/pledge',
2762 'reset=1&action=add&context=pledge'
2764 'component' => 'CiviPledge',
2765 'permissions' => array(
2766 'access CiviPledge',
2770 'membership' => array(
2771 'title' => ts('Add Membership'),
2773 'ref' => 'new-membership',
2774 'key' => 'membership',
2776 'component' => 'CiviMember',
2777 'href' => CRM_Utils_System
::url('civicrm/contact/view/membership',
2778 'reset=1&action=add&context=membership'
2780 'permissions' => array(
2781 'access CiviMember',
2786 'title' => ts('Add Case'),
2788 'ref' => 'new-case',
2791 'component' => 'CiviCase',
2792 'href' => CRM_Utils_System
::url('civicrm/case/add', 'reset=1&action=add&context=case'),
2793 'permissions' => array('add cases'),
2796 'title' => ts('Add Grant'),
2798 'ref' => 'new-grant',
2801 'component' => 'CiviGrant',
2802 'href' => CRM_Utils_System
::url('civicrm/contact/view/grant',
2803 'reset=1&action=add&context=grant'
2805 'permissions' => array('edit grants'),
2808 'title' => ts('Add Relationship'),
2810 'ref' => 'new-relationship',
2813 'href' => CRM_Utils_System
::url('civicrm/contact/view/rel',
2814 'reset=1&action=add'
2816 'permissions' => array('edit all contacts'),
2819 'title' => ts('Add Note'),
2821 'ref' => 'new-note',
2824 'href' => CRM_Utils_System
::url('civicrm/contact/view/note',
2825 'reset=1&action=add'
2827 'permissions' => array('edit all contacts'),
2830 'title' => ts('Send an Email'),
2832 'ref' => 'new-email',
2834 'permissions' => array('view all contacts'),
2837 'title' => ts('Add to Group'),
2839 'ref' => 'group-add-contact',
2842 'permissions' => array('edit groups'),
2845 'title' => ts('Tag Contact'),
2847 'ref' => 'tag-contact',
2850 'permissions' => array('edit all contacts'),
2854 CRM_Utils_Hook
::summaryActions($menu, $contactId);
2855 //1. check for component is active.
2856 //2. check for user permissions.
2857 //3. check for acls.
2858 //3. edit and view contact are directly accessible to user.
2860 $aclPermissionedTasks = array(
2861 'view-contact', 'edit-contact', 'new-activity',
2862 'new-email', 'group-add-contact', 'tag-contact', 'delete-contact',
2864 $corePermission = CRM_Core_Permission
::getPermission();
2866 $config = CRM_Core_Config
::singleton();
2868 $contextMenu = array();
2869 foreach ($menu as $key => $values) {
2870 $componentName = CRM_Utils_Array
::value('component', $values);
2872 // if component action - make sure component is enable.
2873 if ($componentName && !in_array($componentName, $config->enableComponents
)) {
2877 // make sure user has all required permissions.
2878 $hasAllPermissions = FALSE;
2880 $permissions = CRM_Utils_Array
::value('permissions', $values);
2881 if (!is_array($permissions) ||
empty($permissions)) {
2882 $hasAllPermissions = TRUE;
2885 // iterate for required permissions in given permissions array.
2886 if (!$hasAllPermissions) {
2887 $hasPermissions = 0;
2888 foreach ($permissions as $permission) {
2889 if (CRM_Core_Permission
::check($permission)) {
2894 if (count($permissions) == $hasPermissions) {
2895 $hasAllPermissions = TRUE;
2898 // if still user does not have required permissions, check acl.
2899 if (!$hasAllPermissions && $values['ref'] != 'delete-contact') {
2900 if (in_array($values['ref'], $aclPermissionedTasks) &&
2901 $corePermission == CRM_Core_Permission
::EDIT
2903 $hasAllPermissions = TRUE;
2905 elseif (in_array($values['ref'], array(
2907 // grant permissions for these tasks.
2908 $hasAllPermissions = TRUE;
2913 // user does not have necessary permissions.
2914 if (!$hasAllPermissions) {
2918 // build directly accessible action menu.
2919 if (in_array($values['ref'], array(
2920 'view-contact', 'edit-contact'))) {
2921 $contextMenu['primaryActions'][$key] = array(
2922 'title' => $values['title'],
2923 'ref' => $values['ref'],
2924 'class' => CRM_Utils_Array
::value('class', $values),
2925 'key' => $values['key'],
2930 // finally get menu item for -more- action widget.
2931 $contextMenu['moreActions'][$values['weight']] = array(
2932 'title' => $values['title'],
2933 'ref' => $values['ref'],
2934 'href' => CRM_Utils_Array
::value('href', $values),
2935 'tab' => CRM_Utils_Array
::value('tab', $values),
2936 'class' => CRM_Utils_Array
::value('class', $values),
2937 'key' => $values['key'],
2941 ksort($contextMenu['moreActions']);
2943 return $contextMenu;
2947 * Function to retrieve display name of contact that address is shared
2948 * based on $masterAddressId or $contactId .
2950 * @param int $masterAddressId master id.
2951 * @param int $contactId contact id.
2953 * @return display name |null the found display name or null.
2957 static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
2958 $masterDisplayName = NULL;
2960 if (!$masterAddressId && !$contactId) {
2961 return $masterDisplayName;
2964 if ($masterAddressId) {
2966 SELECT display_name from civicrm_contact
2967 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
2968 WHERE civicrm_address.id = " . $masterAddressId;
2970 elseif ($contactId) {
2972 SELECT display_name from civicrm_contact cc, civicrm_address add1
2973 LEFT JOIN civicrm_address add2 ON ( add1.master_id = add2.id )
2974 WHERE cc.id = add2.contact_id AND add1.contact_id = " . $contactId;
2977 $masterDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
2978 return $masterDisplayName;
2982 * Get the creation/modification times for a contact
2984 * @return array('created_date' => $, 'modified_date' => $)
2986 static function getTimestamps($contactId) {
2987 $timestamps = CRM_Core_DAO
::executeQuery(
2988 'SELECT created_date, modified_date
2989 FROM civicrm_contact
2992 1 => array($contactId, 'Integer'),
2995 if ($timestamps->fetch()) {
2997 'created_date' => $timestamps->created_date
,
2998 'modified_date' => $timestamps->modified_date
,
3007 * Get a list of triggers for the contact table
3009 * @see hook_civicrm_triggerInfo
3010 * @see CRM_Core_DAO::triggerRebuild
3011 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3013 static function triggerInfo(&$info, $tableName = NULL) {
3014 //during upgrade, first check for valid version and then create triggers
3015 //i.e the columns created_date and modified_date are introduced in 4.3.alpha1 so dont create triggers for older version
3016 if (CRM_Core_Config
::isUpgradeMode()) {
3017 $currentVer = CRM_Core_BAO_Domain
::version(TRUE);
3018 //if current version is less than 4.3.alpha1 dont create below triggers
3019 if (version_compare($currentVer, '4.3.alpha1') < 0) {
3024 if ($tableName == NULL ||
$tableName == self
::getTableName()) {
3026 'table' => array(self
::getTableName()),
3028 'event' => array('INSERT'),
3029 'sql' => "\nSET NEW.created_date = CURRENT_TIMESTAMP;\n",
3033 // Update timestamp when modifying closely related core tables
3034 $relatedTables = array(
3042 'table' => $relatedTables,
3044 'event' => array('INSERT', 'UPDATE'),
3045 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = NEW.contact_id;\n",
3048 'table' => $relatedTables,
3050 'event' => array('DELETE'),
3051 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = OLD.contact_id;\n",
3054 // Update timestamp when modifying related custom-data tables
3055 $customGroupTables = array();
3056 $customGroupDAO = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity('Contact');
3057 $customGroupDAO->is_multiple
= 0;
3058 $customGroupDAO->find();
3059 while ($customGroupDAO->fetch()) {
3060 $customGroupTables[] = $customGroupDAO->table_name
;
3062 if (!empty($customGroupTables)) {
3064 'table' => $customGroupTables,
3066 'event' => array('INSERT', 'UPDATE'),
3067 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = NEW.entity_id;\n",
3070 'table' => $customGroupTables,
3072 'event' => array('DELETE'),
3073 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = OLD.entity_id;\n",
3077 // Update phone table to populate phone_numeric field
3078 if (!$tableName ||
$tableName == 'civicrm_phone') {
3079 // Define stored sql function needed for phones
3080 CRM_Core_DAO
::executeQuery(self
::DROP_STRIP_FUNCTION_43
);
3081 CRM_Core_DAO
::executeQuery(self
::CREATE_STRIP_FUNCTION_43
);
3083 'table' => array('civicrm_phone'),
3085 'event' => array('INSERT', 'UPDATE'),
3086 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3092 * Function to check if contact is being used in civicrm_domain
3093 * based on $contactId
3095 * @param int $contactId contact id.
3097 * @return true if present else false.
3101 static function checkDomainContact($contactId) {
3104 $domainId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3114 * Get options for a given contact field.
3115 * @see CRM_Core_DAO::buildOptions
3117 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3118 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3120 * @param String $fieldName
3121 * @param String $context: @see CRM_Core_DAO::buildOptionsContext
3122 * @param Array $props: whatever is known about this dao object
3124 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3126 // Special logic for fields whose options depend on context or properties
3127 switch ($fieldName) {
3128 case 'contact_sub_type':
3129 if (!empty($props['contact_type'])) {
3130 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3134 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
3138 * Delete a contact-related object that has an 'is_primary' field
3139 * Ensures that is_primary gets assigned to another object if available
3140 * Also calls pre/post hooks
3142 * @var $type: object type
3143 * @var $id: object id
3145 public static function deleteObjectWithPrimary($type, $id) {
3146 if (!$id ||
!is_numeric($id)) {
3149 $daoName = "CRM_Core_DAO_$type";
3150 $obj = new $daoName();
3153 if ($obj->fetch()) {
3154 CRM_Utils_Hook
::pre('delete', $type, $id, CRM_Core_DAO
::$_nullArray);
3155 $contactId = $obj->contact_id
;
3161 // is_primary is only relavent if this field belongs to a contact
3163 $dao = new $daoName();
3164 $dao->contact_id
= $contactId;
3165 $dao->is_primary
= 1;
3166 // Pick another record to be primary (if one isn't already)
3167 if (!$dao->find(TRUE)) {
3168 $dao->is_primary
= 0;
3170 if ($dao->fetch()) {
3171 $dao->is_primary
= 1;
3177 CRM_Utils_Hook
::post('delete', $type, $id, $obj);