3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
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' &&
227 (isset($params['current_employer']) ||
228 isset($params['employer_id'])
231 // create current employer
232 if (isset($params['employer_id'])) {
233 CRM_Contact_BAO_Contact_Utils
::createCurrentEmployerRelationship($contact->id
,
234 $params['employer_id']
237 elseif ($params['current_employer']) {
238 CRM_Contact_BAO_Contact_Utils
::createCurrentEmployerRelationship($contact->id
,
239 $params['current_employer']
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 * @return object CRM_Contact_BAO_Contact object
273 static function &create(&$params, $fixAddress = TRUE, $invokeHooks = TRUE, $skipDelete = FALSE) {
275 if (!CRM_Utils_Array
::value('contact_type', $params) &&
276 !CRM_Utils_Array
::value('contact_id', $params)
283 if (!empty($params['contact_id'])) {
284 CRM_Utils_Hook
::pre('edit', $params['contact_type'], $params['contact_id'], $params);
287 CRM_Utils_Hook
::pre('create', $params['contact_type'], NULL, $params);
292 $config = CRM_Core_Config
::singleton();
294 // CRM-6942: set preferred language to the current language if it’s unset (and we’re creating a contact)
295 if (empty($params['contact_id']) && empty($params['preferred_language'])) {
296 $params['preferred_language'] = $config->lcMessages
;
299 // CRM-9739: set greeting & addressee if unset and we’re creating a contact
300 if (empty($params['contact_id'])) {
301 foreach (self
::$_greetingTypes as $greeting) {
302 if (empty($params[$greeting . '_id'])) {
303 if ($defaultGreetingTypeId =
304 CRM_Contact_BAO_Contact_Utils
::defaultGreeting($params['contact_type'], $greeting)
306 $params[$greeting . '_id'] = $defaultGreetingTypeId;
312 $transaction = new CRM_Core_Transaction();
314 $contact = self
::add($params);
316 // not dying here is stupid, since we get into wierd situation and into a bug that
317 // is impossible to figure out for the user or for us
319 CRM_Core_Error
::fatal();
322 $params['contact_id'] = $contact->id
;
324 if (CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
327 // Enabling multisite causes the contact to be added to the domain group
328 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
329 if(!empty($domainGroupID)){
330 if (CRM_Utils_Array
::value('group', $params) && is_array($params['group'])) {
331 $params['group'][$domainGroupID] = 1;
334 $params['group'] = array($domainGroupID => 1);
339 if (array_key_exists('group', $params)) {
340 $contactIds = array($params['contact_id']);
341 foreach ($params['group'] as $groupId => $flag) {
343 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
345 elseif ($flag == -1) {
346 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $groupId);
351 //add location Block data
352 $blocks = CRM_Core_BAO_Location
::create($params, $fixAddress);
353 foreach ($blocks as $name => $value) {
354 $contact->$name = $value;
358 CRM_Core_BAO_Website
::create($params['website'], $contact->id
, $skipDelete);
360 //get userID from session
361 $session = CRM_Core_Session
::singleton();
362 $userID = $session->get('userID');
364 if (CRM_Utils_Array
::value('note', $params)) {
365 if (is_array($params['note'])) {
366 foreach ($params['note'] as $note) {
367 $contactId = $contact->id
;
368 if (isset($note['contact_id'])) {
369 $contactId = $note['contact_id'];
371 //if logged in user, overwrite contactId
373 $contactId = $userID;
377 'entity_id' => $contact->id
,
378 'entity_table' => 'civicrm_contact',
379 'note' => $note['note'],
380 'subject' => CRM_Utils_Array
::value('subject', $note),
381 'contact_id' => $contactId,
383 CRM_Core_BAO_Note
::add($noteParams, CRM_Core_DAO
::$_nullArray);
387 $contactId = $contact->id
;
388 if (isset($note['contact_id'])) {
389 $contactId = $note['contact_id'];
391 //if logged in user, overwrite contactId
393 $contactId = $userID;
397 'entity_id' => $contact->id
,
398 'entity_table' => 'civicrm_contact',
399 'note' => $params['note'],
400 'subject' => CRM_Utils_Array
::value('subject', $params),
401 'contact_id' => $contactId,
403 CRM_Core_BAO_Note
::add($noteParams, CRM_Core_DAO
::$_nullArray);
408 // update the UF user_unique_id if that has changed
409 CRM_Core_BAO_UFMatch
::updateUFName($contact->id
);
411 if (CRM_Utils_Array
::value('custom', $params) &&
412 is_array($params['custom'])
414 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contact', $contact->id
);
417 // make a civicrm_subscription_history entry only on contact create (CRM-777)
418 if (!CRM_Utils_Array
::value('contact_id', $params)) {
419 $subscriptionParams = array(
420 'contact_id' => $contact->id
,
424 CRM_Contact_BAO_SubscriptionHistory
::create($subscriptionParams);
427 $transaction->commit();
429 // CRM-6367: fetch the right label for contact type’s display
430 $contact->contact_type_display
= CRM_Core_DAO
::getFieldValue(
431 'CRM_Contact_DAO_ContactType',
432 $contact->contact_type
,
437 if (!$config->doNotResetCache
) {
438 // Note: doNotResetCache flag is currently set by import contact process and merging,
439 // since resetting and
440 // rebuilding cache could be expensive (for many contacts). We might come out with better
441 // approach in future.
442 CRM_Contact_BAO_Contact_Utils
::clearContactCaches($contact->id
);
447 CRM_Utils_Hook
::post('edit', $params['contact_type'], $contact->id
, $contact);
450 CRM_Utils_Hook
::post('create', $params['contact_type'], $contact->id
, $contact);
454 // process greetings CRM-4575, cache greetings
455 self
::processGreetings($contact);
461 * Get the display name and image of a contact
463 * @param int $id the contactId
465 * @return array the displayName and contactImage for this contact
469 static function getDisplayAndImage($id, $type = FALSE) {
471 SELECT civicrm_contact.display_name as display_name,
472 civicrm_contact.contact_type as contact_type,
473 civicrm_contact.contact_sub_type as contact_sub_type,
474 civicrm_email.email as email
476 LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
477 AND civicrm_email.is_primary = 1
478 WHERE civicrm_contact.id = " . CRM_Utils_Type
::escape($id, 'Integer');
479 $dao = new CRM_Core_DAO();
482 $image = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
483 $dao->contact_sub_type
: $dao->contact_type
, FALSE, $id
485 $imageUrl = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
486 $dao->contact_sub_type
: $dao->contact_type
, TRUE, $id
489 // use email if display_name is empty
490 if (empty($dao->display_name
)) {
491 $dao->display_name
= $dao->email
;
493 return $type ?
array(
494 $dao->display_name
, $image,
495 $dao->contact_type
, $dao->contact_sub_type
, $imageUrl,
496 ) : array($dao->display_name
, $image, $imageUrl);
503 * Get the values for pseudoconstants for name->value and reverse.
505 * @param array $defaults (reference) the default values, some of which need to be resolved.
506 * @param boolean $reverse true if we want to resolve the values in the reverse direction (value -> name)
512 static function resolveDefaults(&$defaults, $reverse = FALSE) {
513 // hack for birth_date
514 if (CRM_Utils_Array
::value('birth_date', $defaults)) {
515 if (is_array($defaults['birth_date'])) {
516 $defaults['birth_date'] = CRM_Utils_Date
::format($defaults['birth_date'], '-');
520 CRM_Utils_Array
::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant
::individualPrefix(), $reverse);
521 CRM_Utils_Array
::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant
::individualSuffix(), $reverse);
522 CRM_Utils_Array
::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant
::gender(), $reverse);
524 //lookup value of email/postal greeting, addressee, CRM-4575
525 foreach (self
::$_greetingTypes as $greeting) {
526 $filterCondition = array('contact_type' => CRM_Utils_Array
::value('contact_type', $defaults),
527 'greeting_type' => $greeting,
529 CRM_Utils_Array
::lookupValue($defaults, $greeting,
530 CRM_Core_PseudoConstant
::greeting($filterCondition), $reverse
534 $blocks = array('address', 'im', 'phone');
535 foreach ($blocks as $name) {
536 if (!array_key_exists($name, $defaults) ||
!is_array($defaults[$name])) {
539 foreach ($defaults[$name] as $count => & $values) {
541 //get location type id.
542 CRM_Utils_Array
::lookupValue($values, 'location_type', CRM_Core_PseudoConstant
::locationType(), $reverse);
544 if ($name == 'address') {
545 // FIXME: lookupValue doesn't work for vcard_name
546 if (CRM_Utils_Array
::value('location_type_id', $values)) {
547 $vcardNames = CRM_Core_PseudoConstant
::locationVcardName();
548 $values['vcard_name'] = $vcardNames[$values['location_type_id']];
551 if (!CRM_Utils_Array
::lookupValue($values,
553 CRM_Core_PseudoConstant
::country(),
558 CRM_Utils_Array
::lookupValue($values,
560 CRM_Core_PseudoConstant
::countryIsoCode(),
566 // if we find a country id above, we need to restrict it to that country
567 // rather than the list of all countries
569 if (!empty($values['country_id'])) {
570 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($values['country_id']);
573 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvince();
575 if (!CRM_Utils_Array
::lookupValue($values,
583 if (!empty($values['country_id'])) {
584 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($values['country_id'], 'abbreviation');
587 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviation();
589 CRM_Utils_Array
::lookupValue($values,
596 if (!empty($values['state_province_id'])) {
597 $countyList = CRM_Core_PseudoConstant
::countyForState($values['state_province_id']);
600 $countyList = CRM_Core_PseudoConstant
::county();
602 CRM_Utils_Array
::lookupValue($values,
610 CRM_Utils_Array
::lookupValue($values,
612 CRM_Core_PseudoConstant
::IMProvider(),
617 if ($name == 'phone') {
618 CRM_Utils_Array
::lookupValue($values,
620 CRM_Core_PseudoConstant
::phoneType(),
625 //kill the reference.
632 * Takes a bunch of params that are needed to match certain criteria and
633 * retrieves the relevant objects. Typically the valid params are only
634 * contact_id. We'll tweak this function to be more full featured over a period
635 * of time. This is the inverse function of create. It also stores all the retrieved
636 * values in the default array
638 * @param array $params (reference ) an assoc array of name/value pairs
639 * @param array $defaults (reference ) an assoc array to hold the name / value pairs
640 * in a hierarchical manner
641 * @param boolean $microformat for location in microformat
643 * @return object CRM_Contact_BAO_Contact object
647 static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
648 if (array_key_exists('contact_id', $params)) {
649 $params['id'] = $params['contact_id'];
651 elseif (array_key_exists('id', $params)) {
652 $params['contact_id'] = $params['id'];
655 $contact = self
::getValues($params, $defaults);
657 unset($params['id']);
659 //get the block information for this contact
660 $entityBlock = array('contact_id' => $params['contact_id']);
661 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock, $microformat);
662 $defaults = array_merge($defaults, $blocks);
663 foreach ($blocks as $block => $value) $contact->$block = $value;
665 if (!isset($params['noNotes'])) {
666 $contact->notes
= CRM_Core_BAO_Note
::getValues($params, $defaults);
669 if (!isset($params['noRelationships'])) {
670 $contact->relationship
= CRM_Contact_BAO_Relationship
::getValues($params, $defaults);
673 if (!isset($params['noGroups'])) {
674 $contact->groupContact
= CRM_Contact_BAO_GroupContact
::getValues($params, $defaults);
677 if (!isset($params['noWebsite'])) {
678 $contact->website
= CRM_Core_BAO_Website
::getValues($params, $defaults);
685 * function to get the display name of a contact
687 * @param int $id id of the contact
689 * @return null|string display name of the contact if found
693 static function displayName($id) {
696 $displayName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
703 * Delete a contact and all its associated records
705 * @param int $id id of the contact to delete
706 * @param bool $restore whether to actually restore, not delete
707 * @param bool $skipUndelete whether to force contact delete or not
709 * @return boolean true if contact deleted, false otherwise
713 static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE) {
719 // make sure we have edit permission for this contact
721 if (($skipUndelete && !CRM_Core_Permission
::check('delete contacts')) ||
722 ($restore && !CRM_Core_Permission
::check('access deleted contacts'))
728 // Restrict contact to be delete if contact has financial trxns
730 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent(array($id), $error)) {
734 // make sure this contact_id does not have any membership types
735 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
738 'member_of_contact_id'
740 if ($membershipTypeID) {
744 $contact = new CRM_Contact_DAO_Contact();
746 if (!$contact->find(TRUE)) {
750 $contactType = $contact->contact_type
;
751 $action = ($restore) ?
'restore' : 'delete';
753 CRM_Utils_Hook
::pre($action, $contactType, $id, CRM_Core_DAO
::$_nullArray);
756 self
::contactTrashRestore($contact, TRUE);
757 CRM_Utils_Hook
::post($action, $contactType, $contact->id
, $contact);
762 // currently we only clear employer cache.
763 // we are not deleting inherited membership if any.
764 if ($contact->contact_type
== 'Organization') {
765 CRM_Contact_BAO_Contact_Utils
::clearAllEmployee($id);
768 // start a new transaction
769 $transaction = new CRM_Core_Transaction();
771 if ($skipUndelete or !CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'contact_undelete', NULL)) {
773 //delete billing address if exists.
774 CRM_Contribute_BAO_Contribution
::deleteAddress(NULL, $id);
776 // delete the log entries since we dont have triggers enabled as yet
777 $logDAO = new CRM_Core_DAO_Log();
778 $logDAO->entity_table
= 'civicrm_contact';
779 $logDAO->entity_id
= $id;
782 // delete contact participants CRM-12155
783 CRM_Event_BAO_Participant
::deleteContactParticipant($id);
785 // delete contact contributions CRM-12155
786 CRM_Contribute_BAO_Contribution
::deleteContactContribution($id);
788 // do activity cleanup, CRM-5604
789 CRM_Activity_BAO_Activity
::cleanupActivity($id);
791 // delete all notes related to contact
792 CRM_Core_BAO_Note
::cleanContactNotes($id);
794 // delete cases related to contact
795 $contactCases = CRM_Case_BAO_Case
::retrieveCaseIdsByContactId($id);
796 if (!empty($contactCases)) {
797 foreach ($contactCases as $caseId) {
798 //check if case is associate with other contact or not.
799 $caseContactId = CRM_Case_BAO_Case
::getCaseClients($caseId);
800 if (count($caseContactId) <= 1) {
801 CRM_Case_BAO_Case
::deleteCase($caseId);
809 self
::contactTrashRestore($contact);
812 //delete the contact id from recently view
813 CRM_Utils_Recent
::delContact($id);
815 // reset the group contact cache for this group
816 CRM_Contact_BAO_GroupContactCache
::remove();
818 // delete any dupe cache entry
819 CRM_Core_BAO_PrevNextCache
::deleteItem($id);
821 $transaction->commit();
823 CRM_Utils_Hook
::post('delete', $contactType, $contact->id
, $contact);
825 // also reset the DB_DO global array so we can reuse the memory
826 // http://issues.civicrm.org/jira/browse/CRM-4387
827 CRM_Core_DAO
::freeResult();
833 * function to delete the image of a contact
835 * @param int $id id of the contact
837 * @return boolean true if contact image is deleted
839 public static function deleteContactImage($id) {
844 UPDATE civicrm_contact
847 CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
852 * function to return relative path
853 * @todo make this a method of $config->userSystem (i.e. UF classes) rather than a static function
855 * @param String $absPath absolute path
857 * @return String $relativePath Relative url of uploaded image
859 public static function getRelativePath($absolutePath) {
860 $relativePath = NULL;
861 $config = CRM_Core_Config
::singleton();
862 if ($config->userFramework
== 'Joomla') {
863 $userFrameworkBaseURL = trim(str_replace('/administrator/', '', $config->userFrameworkBaseURL
));
864 $customFileUploadDirectory = strstr(str_replace('\\', '/', $absolutePath), '/media');
865 $relativePath = $userFrameworkBaseURL . $customFileUploadDirectory;
867 elseif ($config->userSystem
->is_drupal
== '1') {
868 //ideally we would do a bigger re-factoring & move the getRelativePath onto the UF class
869 $rootPath = $config->userSystem
->cmsRootPath();
870 $baseUrl = $config->userFrameworkBaseURL
;
872 //format url for language negotiation, CRM-7135
873 $baseUrl = CRM_Utils_System
::languageNegotiationURL($baseUrl, FALSE, TRUE);
875 $relativePath = str_replace("{$rootPath}/",
877 str_replace('\\', '/', $absolutePath)
879 } else if ( $config->userFramework
== 'WordPress' ) {
880 $userFrameworkBaseURL = trim( str_replace( '/wp-admin/', '', $config->userFrameworkBaseURL
) );
881 $customFileUploadDirectory = strstr( str_replace('\\', '/', $absolutePath), '/wp-content/' );
882 $relativePath = $userFrameworkBaseURL . $customFileUploadDirectory;
885 return $relativePath;
889 * function to return proportional height and width of the image
891 * @param Integer $imageWidth width of image
893 * @param Integer $imageHeight height of image
895 * @return Array thumb dimension of image
897 public static function getThumbSize($imageWidth, $imageHeight) {
899 if ($imageWidth && $imageHeight) {
900 $imageRatio = $imageWidth / $imageHeight;
905 if ($imageRatio > 1) {
906 $imageThumbWidth = $thumbWidth;
907 $imageThumbHeight = round($thumbWidth / $imageRatio);
910 $imageThumbHeight = $thumbWidth;
911 $imageThumbWidth = round($thumbWidth * $imageRatio);
914 return array($imageThumbWidth, $imageThumbHeight);
918 * function to validate type of contact image
920 * @param Array $param array of contact/profile field to be edited/added
922 * @param String $imageIndex index of image field
924 * @param String $statusMsg status message to be set after operation
926 * @opType String $opType type of operation like fatal, bounce etc
928 * @return boolean true if valid image extension
930 public static function processImageParams(&$params,
931 $imageIndex = 'image_URL',
945 if (in_array($params[$imageIndex]['type'], $mimeType)) {
946 $params[$imageIndex] = CRM_Contact_BAO_Contact
::getRelativePath($params[$imageIndex]['name']);
950 unset($params[$imageIndex]);
952 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
954 if ($opType == 'status') {
955 CRM_Core_Session
::setStatus($statusMsg, 'Sorry', 'error');
957 // FIXME: additional support for fatal, bounce etc could be added.
963 * function to extract contact id from url for deleting contact image
965 public static function processImage() {
967 $action = CRM_Utils_Request
::retrieve('action', 'String', $this);
968 $cid = CRM_Utils_Request
::retrieve('cid', 'Positive', $this);
969 // retrieve contact id in case of Profile context
970 $id = CRM_Utils_Request
::retrieve('id', 'Positive', $this);
971 $cid = $cid ?
$cid : $id;
972 if ($action & CRM_Core_Action
::DELETE
) {
973 if (CRM_Utils_Request
::retrieve('confirmed', 'Boolean', $this)) {
974 CRM_Contact_BAO_Contact
::deleteContactImage($cid);
975 CRM_Core_Session
::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
976 $session = CRM_Core_Session
::singleton();
977 $toUrl = $session->popUserContext();
978 CRM_Utils_System
::redirect($toUrl);
984 * Function to set is_delete true or restore deleted contact
986 * @param int $contact Contact DAO object
987 * @param boolean $restore true to set the is_delete = 1 else false to restore deleted contact,
993 static function contactTrashRestore($contact, $restore = FALSE) {
994 $op = ($restore ?
'restore' : 'trash');
996 CRM_Utils_Hook
::pre($op, $contact->contact_type
, $contact->id
, CRM_Core_DAO
::$_nullArray);
998 $params = array(1 => array($contact->id
, 'Integer'));
999 $isDelete = ' is_deleted = 1 ';
1001 $isDelete = ' is_deleted = 0 ';
1004 $query = "DELETE FROM civicrm_uf_match WHERE contact_id = %1";
1005 CRM_Core_DAO
::executeQuery($query, $params);
1008 $query = "UPDATE civicrm_contact SET {$isDelete} WHERE id = %1";
1009 CRM_Core_DAO
::executeQuery($query, $params);
1011 CRM_Utils_Hook
::post($op, $contact->contact_type
, $contact->id
, $contact);
1015 * Get contact type for a contact.
1017 * @param int $id - id of the contact whose contact type is needed
1019 * @return string contact_type if $id found else null ""
1026 public static function getContactType($id) {
1027 return CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1031 * Get contact sub type for a contact.
1033 * @param int $id - id of the contact whose contact sub type is needed
1035 * @return string contact_sub_type if $id found else null ""
1042 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1043 $subtype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1045 return $implodeDelimiter ?
NULL : array();
1048 $subtype = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($subtype, CRM_Core_DAO
::VALUE_SEPARATOR
));
1050 if ($implodeDelimiter) {
1051 $subtype = implode($implodeDelimiter, $subtype);
1057 * Get pair of contact-type and sub-type for a contact.
1059 * @param int $id - id of the contact whose contact sub/contact type is needed
1068 public static function getContactTypes($id) {
1069 $params = array('id' => $id);
1071 $contact = CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact',
1074 array('contact_type', 'contact_sub_type')
1078 $contactTypes = array();
1079 if ($contact->contact_sub_type
)
1080 $contactTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($contact->contact_sub_type
, CRM_Core_DAO
::VALUE_SEPARATOR
));
1081 array_unshift($contactTypes, $contact->contact_type
);
1083 return $contactTypes;
1086 CRM_Core_Error
::fatal();
1091 * combine all the importable fields from the lower levels object
1093 * The ordering is important, since currently we do not have a weight
1094 * scheme. Adding weight is super important and should be done in the
1095 * next week or so, before this can be called complete.
1097 * @param int $contactType contact Type
1098 * @param boolean $status status is used to manipulate first title
1099 * @param boolean $showAll if true returns all fields (includes disabled fields)
1100 * @param boolean $isProfile if its profile mode
1101 * @param boolean $checkPermission if false, do not include permissioning clause (for custom data)
1103 * @return array array of importable Fields
1107 static function importableFields($contactType = 'Individual',
1111 $checkPermission = TRUE,
1112 $withMultiCustomFields = FALSE
1114 if (empty($contactType)) {
1115 $contactType = 'All';
1118 $cacheKeyString = "importableFields $contactType";
1119 $cacheKeyString .= $status ?
'_1' : '_0';
1120 $cacheKeyString .= $showAll ?
'_1' : '_0';
1121 $cacheKeyString .= $isProfile ?
'_1' : '_0';
1122 $cacheKeyString .= $checkPermission ?
'_1' : '_0';
1124 $fields = CRM_Utils_Array
::value($cacheKeyString, self
::$_importableFields);
1127 // check if we can retrieve from database cache
1128 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1132 $fields = CRM_Contact_DAO_Contact
::import();
1134 // get the fields thar are meant for contact types
1135 if (in_array($contactType, array(
1136 'Individual', 'Household', 'Organization', 'All'))) {
1137 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1140 $locationFields = array_merge(CRM_Core_DAO_Address
::import(),
1141 CRM_Core_DAO_Phone
::import(),
1142 CRM_Core_DAO_Email
::import(),
1143 CRM_Core_DAO_IM
::import(TRUE),
1144 CRM_Core_DAO_OpenID
::import()
1147 $locationFields = array_merge($locationFields,
1148 CRM_Core_BAO_CustomField
::getFieldsForImport('Address',
1156 foreach ($locationFields as $key => $field) {
1157 $locationFields[$key]['hasLocationType'] = TRUE;
1160 $fields = array_merge($fields, $locationFields);
1162 $fields = array_merge($fields,
1163 CRM_Contact_DAO_Contact
::import()
1165 $fields = array_merge($fields,
1166 CRM_Core_DAO_Note
::import()
1170 $fields = array_merge($fields, CRM_Core_DAO_Website
::import());
1172 if ($contactType != 'All') {
1173 $fields = array_merge($fields,
1174 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType,
1179 $withMultiCustomFields
1182 //unset the fields, which are not related to their
1184 $commonValues = array(
1185 'Individual' => array('household_name', 'legal_name', 'sic_code', 'organization_name'),
1186 'Household' => array(
1187 'first_name', 'middle_name', 'last_name', 'job_title',
1188 'gender_id', 'birth_date', 'organization_name', 'legal_name',
1189 'legal_identifier', 'sic_code', 'home_URL', 'is_deceased',
1192 'Organization' => array(
1193 'first_name', 'middle_name', 'last_name', 'job_title',
1194 'gender_id', 'birth_date', 'household_name', 'is_deceased', 'deceased_date',
1197 foreach ($commonValues[$contactType] as $value) {
1198 unset($fields[$value]);
1203 'Individual', 'Household', 'Organization') as $type) {
1204 $fields = array_merge($fields,
1205 CRM_Core_BAO_CustomField
::getFieldsForImport($type,
1210 $withMultiCustomFields
1217 $fields = array_merge($fields, array('group' => array('title' => ts('Group(s)'),
1220 'tag' => array('title' => ts('Tag(s)'),
1223 'note' => array('title' => ts('Note(s)'),
1229 //Sorting fields in alphabetical order(CRM-1507)
1230 $fields = CRM_Utils_Array
::crmArraySortByField($fields, 'title');
1232 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1235 self
::$_importableFields[$cacheKeyString] = $fields;
1239 $fields = array_merge(array('do_not_import' => array('title' => ts('- do not import -'))),
1240 self
::$_importableFields[$cacheKeyString]
1244 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1245 self
::$_importableFields[$cacheKeyString]
1253 * combine all the exportable fields from the lower levels object
1255 * currentlty we are using importable fields as exportable fields
1257 * @param int $contactType contact Type
1258 * @param boolean $status true while exporting primary contacts
1259 * @param boolean $export true when used during export
1260 * @param boolean $search true when used during search, might conflict with export param?
1262 * @return array array of exportable Fields
1266 static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE) {
1267 if (empty($contactType)) {
1268 $contactType = 'All';
1271 $cacheKeyString = "exportableFields $contactType";
1272 $cacheKeyString .= $export ?
'_1' : '_0';
1273 $cacheKeyString .= $status ?
'_1' : '_0';
1274 $cacheKeyString .= $search ?
'_1' : '_0';
1276 if (!self
::$_exportableFields ||
!CRM_Utils_Array
::value($cacheKeyString, self
::$_exportableFields)) {
1277 if (!self
::$_exportableFields) {
1278 self
::$_exportableFields = array();
1281 // check if we can retrieve from database cache
1282 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1286 $fields = CRM_Contact_DAO_Contact
::export();
1288 // the fields are meant for contact types
1289 if (in_array($contactType, array(
1290 'Individual', 'Household', 'Organization', 'All'))) {
1291 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1293 // add current employer for individuals
1294 $fields = array_merge($fields, array(
1295 'current_employer' =>
1297 'name' => 'organization_name',
1298 'title' => ts('Current Employer'),
1302 $locationType = array(
1303 'location_type' => array('name' => 'location_type',
1304 'where' => 'civicrm_location_type.name',
1305 'title' => ts('Location Type'),
1308 $IMProvider = array(
1309 'im_provider' => array('name' => 'im_provider',
1310 'where' => 'civicrm_im.provider_id',
1311 'title' => ts('IM Provider'),
1314 $locationFields = array_merge($locationType,
1315 CRM_Core_DAO_Address
::export(),
1316 CRM_Core_DAO_Phone
::export(),
1317 CRM_Core_DAO_Email
::export(),
1319 CRM_Core_DAO_IM
::export(TRUE),
1320 CRM_Core_DAO_OpenID
::export()
1323 $locationFields = array_merge($locationFields,
1324 CRM_Core_BAO_CustomField
::getFieldsForImport('Address')
1327 foreach ($locationFields as $key => $field) {
1328 $locationFields[$key]['hasLocationType'] = TRUE;
1331 $fields = array_merge($fields, $locationFields);
1334 $fields = array_merge($fields,
1335 CRM_Core_DAO_Worldregion
::export()
1339 $fields = array_merge($fields,
1340 CRM_Contact_DAO_Contact
::export()
1344 $fields = array_merge($fields, CRM_Core_DAO_Website
::export());
1346 if ($contactType != 'All') {
1347 $fields = array_merge($fields,
1348 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType, $status, TRUE, $search, TRUE, $withMultiRecord)
1353 'Individual', 'Household', 'Organization') as $type) {
1354 $fields = array_merge($fields,
1355 CRM_Core_BAO_CustomField
::getFieldsForImport($type, FALSE, FALSE, $search, TRUE, $withMultiRecord)
1362 $fields = array_merge($fields, array('groups' => array('title' => ts('Group(s)'),
1365 'tags' => array('title' => ts('Tag(s)'),
1368 'notes' => array('title' => ts('Note(s)'),
1374 $fields = array_merge($fields, array('group' => array('title' => ts('Group(s)'),
1377 'tag' => array('title' => ts('Tag(s)'),
1380 'note' => array('title' => ts('Note(s)'),
1386 //Sorting fields in alphabetical order(CRM-1507)
1387 foreach ($fields as $k => $v) {
1388 $sortArray[$k] = CRM_Utils_Array
::value('title', $v);
1391 $fields = array_merge($sortArray, $fields);
1392 //unset the field which are not related to their contact type.
1393 if ($contactType != 'All') {
1394 $commonValues = array(
1395 'Individual' => array('household_name', 'legal_name', 'sic_code', 'organization_name',
1396 'email_greeting_custom', 'postal_greeting_custom',
1399 'Household' => array(
1400 'first_name', 'middle_name', 'last_name', 'job_title',
1401 'gender_id', 'birth_date', 'organization_name', 'legal_name',
1402 'legal_identifier', 'sic_code', 'home_URL', 'is_deceased',
1403 'deceased_date', 'current_employer', 'email_greeting_custom',
1404 'postal_greeting_custom', 'addressee_custom',
1405 'individual_prefix', 'individual_suffix', 'gender',
1407 'Organization' => array(
1408 'first_name', 'middle_name', 'last_name', 'job_title',
1409 'gender_id', 'birth_date', 'household_name',
1410 'email_greeting_custom',
1411 'postal_greeting_custom', 'individual_prefix',
1412 'individual_suffix', 'gender', 'addressee_custom',
1413 'is_deceased', 'deceased_date', 'current_employer',
1416 foreach ($commonValues[$contactType] as $value) {
1417 unset($fields[$value]);
1421 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1423 self
::$_exportableFields[$cacheKeyString] = $fields;
1427 $fields = self
::$_exportableFields[$cacheKeyString];
1430 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1431 self
::$_exportableFields[$cacheKeyString]
1439 * Function to get the all contact details(Hierarchical)
1441 * @param int $contactId contact id
1442 * @param array $fields fields array
1444 * @return $values array contains the contact details
1448 static function getHierContactDetails($contactId, &$fields) {
1449 $params = array(array('contact_id', '=', $contactId, 0, 0));
1452 $returnProperties = self
::makeHierReturnProperties($fields, $contactId);
1454 // we dont know the contents of return properties, but we need the lower level ids of the contact
1455 // so add a few fields
1456 $returnProperties['first_name'] =
1457 $returnProperties['organization_name'] =
1458 $returnProperties['household_name'] =
1459 $returnProperties['contact_type'] =
1460 $returnProperties['contact_sub_type'] = 1;
1461 return list($query, $options) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, $options);
1465 * given a set of flat profile style field names, create a hierarchy
1466 * for query to use and crete the right sql
1468 * @param array $properties a flat return properties name value array
1469 * @param int $contactId contact id
1471 * @return array a hierarchical property tree if appropriate
1475 static function &makeHierReturnProperties($fields, $contactId = NULL) {
1476 $locationTypes = CRM_Core_PseudoConstant
::locationType();
1478 $returnProperties = array();
1480 $multipleFields = array('website' => 'url');
1481 foreach ($fields as $name => $dontCare) {
1482 if (strpos($name, '-') !== FALSE) {
1483 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $name, 3);
1485 if (!in_array($fieldName, $multipleFields)) {
1486 if ($id == 'Primary') {
1487 $locationTypeName = 1;
1490 $locationTypeName = CRM_Utils_Array
::value($id, $locationTypes);
1491 if (!$locationTypeName) {
1496 if (!CRM_Utils_Array
::value('location', $returnProperties)) {
1497 $returnProperties['location'] = array();
1499 if (!CRM_Utils_Array
::value($locationTypeName, $returnProperties['location'])) {
1500 $returnProperties['location'][$locationTypeName] = array();
1501 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1503 if (in_array($fieldName, array(
1504 'phone', 'im', 'email', 'openid', 'phone_ext'))) {
1506 $returnProperties['location'][$locationTypeName][$fieldName . '-' . $type] = 1;
1509 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1512 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1513 $returnProperties['location'][$locationTypeName][substr($fieldName, 8)] = 1;
1516 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1520 $returnProperties['website'][$id][$fieldName] = 1;
1524 $returnProperties[$name] = 1;
1528 return $returnProperties;
1532 * Function to return the primary location type of a contact
1534 * $params int $contactId contact_id
1535 * $params boolean $isPrimaryExist if true, return primary contact location type otherwise null
1536 * $params boolean $skipDefaultPriamry if true, return primary contact location type otherwise null
1538 * @return int $locationType location_type_id
1542 static function getPrimaryLocationType($contactId, $skipDefaultPriamry = FALSE, $block = NULL) {
1544 $entityBlock = array('contact_id' => $contactId);
1545 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock);
1546 foreach($blocks[$block] as $key => $value){
1547 if (CRM_Utils_Array
::value('is_primary', $value)){
1548 $locationType = CRM_Utils_Array
::value('location_type_id',$value);
1555 IF ( civicrm_email.location_type_id IS NULL,
1556 IF ( civicrm_address.location_type_id IS NULL,
1557 IF ( civicrm_phone.location_type_id IS NULL,
1558 IF ( civicrm_im.location_type_id IS NULL,
1559 IF ( civicrm_openid.location_type_id IS NULL, null, civicrm_openid.location_type_id)
1560 ,civicrm_im.location_type_id)
1561 ,civicrm_phone.location_type_id)
1562 ,civicrm_address.location_type_id)
1563 ,civicrm_email.location_type_id) as locationType
1564 FROM civicrm_contact
1565 LEFT JOIN civicrm_email ON ( civicrm_email.is_primary = 1 AND civicrm_email.contact_id = civicrm_contact.id )
1566 LEFT JOIN civicrm_address ON ( civicrm_address.is_primary = 1 AND civicrm_address.contact_id = civicrm_contact.id)
1567 LEFT JOIN civicrm_phone ON ( civicrm_phone.is_primary = 1 AND civicrm_phone.contact_id = civicrm_contact.id)
1568 LEFT JOIN civicrm_im ON ( civicrm_im.is_primary = 1 AND civicrm_im.contact_id = civicrm_contact.id)
1569 LEFT JOIN civicrm_openid ON ( civicrm_openid.is_primary = 1 AND civicrm_openid.contact_id = civicrm_contact.id)
1570 WHERE civicrm_contact.id = %1 ";
1572 $params = array(1 => array($contactId, 'Integer'));
1574 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1576 $locationType = NULL;
1577 if ($dao->fetch()) {
1578 $locationType = $dao->locationType
;
1581 if (isset($locationType)) {
1582 return $locationType;
1584 elseif ($skipDefaultPriamry) {
1585 // if there is no primary contact location then return null
1589 // if there is no primart contact location, then return default
1590 // location type of the system
1591 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
1592 return $defaultLocationType->id
;
1597 * function to get the display name, primary email and location type of a contact
1599 * @param int $id id of the contact
1601 * @return array of display_name, email if found, do_not_email or (null,null,null)
1605 static function getContactDetails($id) {
1606 // check if the contact type
1607 $contactType = self
::getContactType($id);
1609 $nameFields = ($contactType == 'Individual') ?
"civicrm_contact.first_name, civicrm_contact.last_name, civicrm_contact.display_name" : "civicrm_contact.display_name";
1612 SELECT $nameFields, civicrm_email.email, civicrm_contact.do_not_email, civicrm_email.on_hold, civicrm_contact.is_deceased
1613 FROM civicrm_contact LEFT JOIN civicrm_email ON (civicrm_contact.id = civicrm_email.contact_id)
1614 WHERE civicrm_contact.id = %1
1615 ORDER BY civicrm_email.is_primary DESC";
1616 $params = array(1 => array($id, 'Integer'));
1617 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
1619 if ($dao->fetch()) {
1620 if ($contactType == 'Individual') {
1621 if ($dao->first_name ||
$dao->last_name
) {
1622 $name = "{$dao->first_name} {$dao->last_name}";
1625 $name = $dao->display_name
;
1629 $name = $dao->display_name
;
1631 $email = $dao->email
;
1632 $doNotEmail = $dao->do_not_email ?
TRUE : FALSE;
1633 $onHold = $dao->on_hold ?
TRUE : FALSE;
1634 $isDeceased = $dao->is_deceased ?
TRUE : FALSE;
1635 return array($name, $email, $doNotEmail, $onHold, $isDeceased);
1637 return array(NULL, NULL, NULL, NULL, NULL);
1641 * function to add/edit/register contacts through profile.
1643 * @params array $params Array of profile fields to be edited/added.
1644 * @params int $contactID contact_id of the contact to be edited/added.
1645 * @params array $fields array of fields from UFGroup
1646 * @params int $addToGroupID specifies the default group to which contact is added.
1647 * @params int $ufGroupId uf group id (profile id)
1648 * @param string $ctype contact type
1649 * @param boolean $visibility basically lets us know where this request is coming from
1650 * if via a profile from web, we restrict what groups are changed
1652 * @return int contact id created/edited
1656 static function createProfileContact(
1660 $addToGroupID = NULL,
1665 // add ufGroupID to params array ( CRM-2012 )
1667 $params['uf_group_id'] = $ufGroupId;
1672 CRM_Utils_Hook
::pre('edit', 'Profile', $contactID, $params);
1676 CRM_Utils_Hook
::pre('create', 'Profile', NULL, $params);
1679 list($data, $contactDetails) = self
::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
1681 // manage is_opt_out
1682 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
1683 $wasOptOut = CRM_Utils_Array
::value('is_opt_out', $contactDetails, FALSE);
1684 $isOptOut = CRM_Utils_Array
::value('is_opt_out', $params, FALSE);
1685 $data['is_opt_out'] = $isOptOut;
1686 // on change, create new civicrm_subscription_history entry
1687 if (($wasOptOut != $isOptOut) &&
1688 CRM_Utils_Array
::value('contact_id', $contactDetails)
1691 'contact_id' => $contactDetails['contact_id'],
1692 'status' => $isOptOut ?
'Removed' : 'Added',
1695 CRM_Contact_BAO_SubscriptionHistory
::create($shParams);
1699 $contact = self
::create($data);
1701 // contact is null if the profile does not have any contact fields
1703 $contactID = $contact->id
;
1706 if (empty($contactID)) {
1707 CRM_Core_Error
::fatal('Cannot proceed without a valid contact id');
1710 // Process group and tag
1711 if (CRM_Utils_Array
::value('group', $fields)) {
1713 // this for sure means we are coming in via profile since i added it to fix
1714 // removing contacts from user groups -- lobo
1718 CRM_Contact_BAO_GroupContact
::create($params['group'], $contactID, $visibility, $method);
1721 if (CRM_Utils_Array
::value('tag', $fields)) {
1722 CRM_Core_BAO_EntityTag
::create($params['tag'], 'civicrm_contact', $contactID);
1725 //to add profile in default group
1726 if (is_array($addToGroupID)) {
1727 $contactIds = array($contactID);
1728 foreach ($addToGroupID as $groupId) {
1729 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
1732 elseif ($addToGroupID) {
1733 $contactIds = array($contactID);
1734 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $addToGroupID);
1737 // reset the group contact cache for this group
1738 CRM_Contact_BAO_GroupContactCache
::remove();
1741 CRM_Utils_Hook
::post('edit', 'Profile', $contactID, $params);
1744 CRM_Utils_Hook
::post('create', 'Profile', $contactID, $params);
1749 static function formatProfileContactParams(
1758 $data = $contactDetails = array();
1760 // get the contact details (hier)
1762 list($details, $options) = self
::getHierContactDetails($contactID, $fields);
1764 $contactDetails = $details[$contactID];
1765 $data['contact_type'] = CRM_Utils_Array
::value('contact_type', $contactDetails);
1766 $data['contact_sub_type'] = CRM_Utils_Array
::value('contact_sub_type', $contactDetails);
1769 //we should get contact type only if contact
1771 $data['contact_type'] = CRM_Core_BAO_UFField
::getProfileType($ufGroupId);
1773 //special case to handle profile with only contact fields
1774 if ($data['contact_type'] == 'Contact') {
1775 $data['contact_type'] = 'Individual';
1777 elseif (CRM_Contact_BAO_ContactType
::isaSubType($data['contact_type'])) {
1778 $data['contact_type'] = CRM_Contact_BAO_ContactType
::getBasicType($data['contact_type']);
1782 $data['contact_type'] = $ctype;
1785 $data['contact_type'] = 'Individual';
1789 //fix contact sub type CRM-5125
1790 if (array_key_exists('contact_sub_type', $params) &&
1791 !empty($params['contact_sub_type'])
1793 $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
;
1795 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
1796 !empty($params['contact_sub_type_hidden'])
1798 // if profile was used, and had any subtype, we obtain it from there
1799 $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
;
1802 if ($ctype == 'Organization') {
1803 $data['organization_name'] = CRM_Utils_Array
::value('organization_name', $contactDetails);
1805 elseif ($ctype == 'Household') {
1806 $data['household_name'] = CRM_Utils_Array
::value('household_name', $contactDetails);
1809 $locationType = array();
1814 $data['contact_id'] = $contactID;
1815 $primaryLocationType = self
::getPrimaryLocationType($contactID);
1818 $defaultLocation = CRM_Core_BAO_LocationType
::getDefault();
1819 $defaultLocationId = $defaultLocation->id
;
1822 // get the billing location type
1823 $locationTypes = CRM_Core_PseudoConstant
::locationType();
1824 $billingLocationTypeId = array_search('Billing', $locationTypes);
1826 $blocks = array('email', 'phone', 'im', 'openid');
1828 $multiplFields = array('url');
1829 // prevent overwritten of formatted array, reset all block from
1830 // params if it is not in valid format (since import pass valid format)
1831 foreach ($blocks as $blk) {
1832 if (array_key_exists($blk, $params) &&
1833 !is_array($params[$blk])
1835 unset($params[$blk]);
1839 $primaryPhoneLoc = NULL;
1840 foreach ($params as $key => $value) {
1841 $fieldName = $locTypeId = $typeId = NULL;
1842 list($fieldName, $locTypeId, $typeId) = CRM_Utils_System
::explode('-', $key, 3);
1844 //store original location type id
1845 $actualLocTypeId = $locTypeId;
1847 if ($locTypeId == 'Primary') {
1849 if(in_array( $fieldName, $blocks)){
1850 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, $fieldName);
1853 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, 'address');
1855 $primaryLocationType = $locTypeId;
1858 $locTypeId = $defaultLocationId;
1862 if (is_numeric($locTypeId) &&
1863 !in_array($fieldName, $multiplFields) &&
1864 substr($fieldName, 0, 7) != 'custom_'
1866 $index = $locTypeId;
1868 if (is_numeric($typeId)) {
1869 $index .= '-' . $typeId;
1871 if (!in_array($index, $locationType)) {
1872 $locationType[$count] = $index;
1876 $loc = CRM_Utils_Array
::key($index, $locationType);
1878 $blockName = in_array( $fieldName, $blocks) ?
$fieldName : 'address';
1880 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
1882 //set is_billing true, for location type "Billing"
1883 if ($locTypeId == $billingLocationTypeId) {
1884 $data[$blockName][$loc]['is_billing'] = 1;
1888 //get the primary location type
1889 if ($locTypeId == $primaryLocationType) {
1890 $data[$blockName][$loc]['is_primary'] = 1;
1893 elseif ($locTypeId == $defaultLocationId) {
1894 $data[$blockName][$loc]['is_primary'] = 1;
1897 if ( in_array($fieldName, array('phone'))) {
1899 $data['phone'][$loc]['phone_type_id'] = $typeId;
1902 $data['phone'][$loc]['phone_type_id'] = '';
1904 $data['phone'][$loc]['phone'] = $value;
1906 //special case to handle primary phone with different phone types
1907 // in this case we make first phone type as primary
1908 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
1909 $primaryPhoneLoc = $loc;
1912 if ($loc != $primaryPhoneLoc) {
1913 unset($data['phone'][$loc]['is_primary']);
1916 elseif ($fieldName == 'phone_ext') {
1917 $data['phone'][$loc]['phone_ext'] = $value;
1919 elseif ($fieldName == 'email') {
1920 $data['email'][$loc]['email'] = $value;
1922 elseif ($fieldName == 'im') {
1923 if (isset($params[$key . '-provider_id'])) {
1924 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
1926 if (strpos($key, '-provider_id') !== FALSE) {
1927 $data['im'][$loc]['provider_id'] = $params[$key];
1930 $data['im'][$loc]['name'] = $value;
1933 elseif ($fieldName == 'openid') {
1934 $data['openid'][$loc]['openid'] = $value;
1937 if ($fieldName === 'state_province') {
1939 if (is_numeric($value) && ((int ) $value) >= 1000) {
1940 $data['address'][$loc]['state_province_id'] = $value;
1942 elseif (empty($value)) {
1943 $data['address'][$loc]['state_province_id'] = '';
1946 $data['address'][$loc]['state_province'] = $value;
1949 elseif ($fieldName === 'country') {
1951 if (is_numeric($value) && ((int ) $value) >= 1000
1953 $data['address'][$loc]['country_id'] = $value;
1955 elseif (empty($value)) {
1956 $data['address'][$loc]['country_id'] = '';
1959 $data['address'][$loc]['country'] = $value;
1962 elseif ($fieldName === 'county') {
1963 $data['address'][$loc]['county_id'] = $value;
1965 elseif ($fieldName == 'address_name') {
1966 $data['address'][$loc]['name'] = $value;
1968 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1969 $data['address'][$loc][substr($fieldName, 8)] = $value;
1972 $data['address'][$loc][$fieldName] = $value;
1977 if (substr($key, 0, 4) === 'url-') {
1978 $websiteField = explode('-', $key);
1979 if (isset($websiteField[2])) {
1980 $data['website'][$websiteField[1]]['website_type_id'] = $value;
1983 $data['website'][$websiteField[1]]['url'] = $value;
1986 elseif ($key === 'individual_suffix') {
1987 $data['suffix_id'] = $value;
1989 elseif ($key === 'individual_prefix') {
1990 $data['prefix_id'] = $value;
1992 elseif ($key === 'gender') {
1993 $data['gender_id'] = $value;
1995 //save email/postal greeting and addressee values if any, CRM-4575
1996 elseif (in_array($key, self
::$_greetingTypes, TRUE)) {
1997 $data[$key . '_id'] = $value;
1999 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($key))) {
2000 // for autocomplete transfer hidden value instead of label
2001 if ($params[$key] && isset($params[$key . '_id'])) {
2002 $value = $params[$key . '_id'];
2005 // we need to append time with date
2006 if ($params[$key] && isset($params[$key . '_time'])) {
2007 $value .= ' ' . $params[$key . '_time'];
2011 if (CRM_Utils_Array
::value('customRecordValues', $params)) {
2012 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2013 foreach ($params['customRecordValues'] as $recId => $customFields) {
2014 if (is_array($customFields) && !empty($customFields)) {
2015 foreach ($customFields as $customFieldName) {
2016 if ($customFieldName == $key) {
2026 $type = $data['contact_type'];
2027 if ( CRM_Utils_Array
::value('contact_sub_type', $data) ) {
2028 $type = $data['contact_sub_type'];
2029 $type = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($type, CRM_Core_DAO
::VALUE_SEPARATOR
));
2030 // generally a contact even if, has multiple subtypes the parent-type is going to be one only
2031 // and since formatCustomField() would be interested in parent type, lets consider only one subtype
2032 // as the results going to be same.
2036 CRM_Core_BAO_CustomField
::formatCustomField($customFieldId,
2044 elseif ($key == 'edit') {
2048 if ($key == 'location') {
2049 foreach ($value as $locationTypeId => $field) {
2050 foreach ($field as $block => $val) {
2051 if ($block == 'address' && array_key_exists('address_name', $val)) {
2052 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2057 if($key == 'phone' && isset($params['phone_ext'])){
2058 $data[$key] = $value;
2059 foreach($value as $cnt => $phoneBlock){
2060 if($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']){
2061 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array
::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2066 $data[$key] = $value;
2072 if (!isset($data['contact_type'])) {
2073 $data['contact_type'] = 'Individual';
2076 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2077 $privacy = CRM_Core_SelectValues
::privacy();
2078 foreach ($privacy as $key => $value) {
2079 if (array_key_exists($key, $fields)) {
2080 if (array_key_exists($key, $params)) {
2081 $data[$key] = $params[$key];
2082 // dont reset it for existing contacts
2084 elseif (!$contactID) {
2090 return array($data, $contactDetails);
2094 * Function to find the get contact details
2095 * does not respect ACLs for now, which might need to be rectified at some
2096 * stage based on how its used
2098 * @param string $mail primary email address of the contact
2099 * @param string $ctype contact type
2101 * @return object $dao contact details
2104 static function &matchContactOnEmail($mail, $ctype = NULL) {
2105 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2106 $mail = $strtolower(trim($mail));
2108 SELECT civicrm_contact.id as contact_id,
2109 civicrm_contact.hash as hash,
2110 civicrm_contact.contact_type as contact_type,
2111 civicrm_contact.contact_sub_type as contact_sub_type
2112 FROM civicrm_contact
2113 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2116 if (CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
2117 'uniq_email_per_site'
2119 // try to find a match within a site (multisite).
2120 $groups = CRM_Core_BAO_Domain
::getChildGroupIds();
2121 if (!empty($groups)) {
2123 INNER JOIN civicrm_group_contact gc ON
2124 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2129 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2130 $p = array(1 => array($mail, 'String'));
2133 $query .= " AND civicrm_contact.contact_type = %3";
2134 $p[3] = array($ctype, 'String');
2137 $query .= " ORDER BY civicrm_email.is_primary DESC";
2139 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2141 if ($dao->fetch()) {
2144 return CRM_Core_DAO
::$_nullObject;
2148 * Function to find the contact details associated with an OpenID
2150 * @param string $openId openId of the contact
2151 * @param string $ctype contact type
2153 * @return object $dao contact details
2156 static function &matchContactOnOpenId($openId, $ctype = NULL) {
2157 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2158 $openId = $strtolower(trim($openId));
2160 SELECT civicrm_contact.id as contact_id,
2161 civicrm_contact.hash as hash,
2162 civicrm_contact.contact_type as contact_type,
2163 civicrm_contact.contact_sub_type as contact_sub_type
2164 FROM civicrm_contact
2165 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2166 WHERE civicrm_openid.openid = %1";
2167 $p = array(1 => array($openId, 'String'));
2170 $query .= " AND civicrm_contact.contact_type = %3";
2171 $p[3] = array($ctype, 'String');
2174 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2176 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2178 if ($dao->fetch()) {
2181 return CRM_Core_DAO
::$_nullObject;
2185 * Funtion to get primary email of the contact
2187 * @param int $contactID contact id
2189 * @return string $dao->email email address if present else null
2193 public static function getPrimaryEmail($contactID) {
2194 // fetch the primary email
2196 SELECT civicrm_email.email as email
2197 FROM civicrm_contact
2198 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2199 WHERE civicrm_email.is_primary = 1
2200 AND civicrm_contact.id = %1";
2201 $p = array(1 => array($contactID, 'Integer'));
2202 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2205 if ($dao->fetch()) {
2206 $email = $dao->email
;
2213 * Funtion to get primary OpenID of the contact
2215 * @param int $contactID contact id
2217 * @return string $dao->openid OpenID if present else null
2221 public static function getPrimaryOpenId($contactID) {
2222 // fetch the primary OpenID
2224 SELECT civicrm_openid.openid as openid
2225 FROM civicrm_contact
2226 LEFT JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2227 WHERE civicrm_contact.id = %1
2228 AND civicrm_openid.is_primary = 1";
2229 $p = array(1 => array($contactID, 'Integer'));
2230 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2233 if ($dao->fetch()) {
2234 $openId = $dao->openid
;
2241 * Given the list of params in the params array, fetch the object
2242 * and store the values in the values array
2244 * @param array $params input parameters to find object
2245 * @param array $values output values of the object
2247 * @return CRM_Contact_BAO_Contact|null the found object or null
2251 public static function getValues(&$params, &$values) {
2252 $contact = new CRM_Contact_BAO_Contact();
2254 $contact->copyValues($params);
2256 if ($contact->find(TRUE)) {
2258 CRM_Core_DAO
::storeValues($contact, $values);
2261 foreach (self
::$_commPrefs as $name) {
2262 if (isset($contact->$name)) {
2263 $privacy[$name] = $contact->$name;
2267 if (!empty($privacy)) {
2268 $values['privacy'] = $privacy;
2271 // communication Prefferance
2272 $preffComm = $comm = array();
2273 $comm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2274 $contact->preferred_communication_method
2276 foreach ($comm as $value) {
2277 $preffComm[$value] = 1;
2279 $temp = array('preferred_communication_method' => $contact->preferred_communication_method
);
2282 'preferred_communication_method' => array('newName' => 'preferred_communication_method_display',
2283 'groupName' => 'preferred_communication_method',
2286 CRM_Core_OptionGroup
::lookupValues($temp, $names, FALSE);
2288 $values['preferred_communication_method'] = $preffComm;
2289 $values['preferred_communication_method_display'] = CRM_Utils_Array
::value('preferred_communication_method_display', $temp);
2291 CRM_Contact_DAO_Contact
::addDisplayEnums($values);
2293 // get preferred languages
2294 if (!empty($contact->preferred_language
)) {
2295 $languages = CRM_Core_PseudoConstant
::languages();
2296 $values['preferred_language'] = CRM_Utils_Array
::value($contact->preferred_language
, $languages);
2299 // Calculating Year difference
2300 if ($contact->birth_date
) {
2301 $birthDate = CRM_Utils_Date
::customFormat($contact->birth_date
, '%Y%m%d');
2302 if ($birthDate < date('Ymd')) {
2303 $age = CRM_Utils_Date
::calculateAge($birthDate);
2304 $values['age']['y'] = CRM_Utils_Array
::value('years', $age);
2305 $values['age']['m'] = CRM_Utils_Array
::value('months', $age);
2308 list($values['birth_date']) = CRM_Utils_Date
::setDateDefaults($contact->birth_date
, 'birth');
2309 $values['birth_date_display'] = $contact->birth_date
;
2312 if ($contact->deceased_date
) {
2313 list($values['deceased_date']) = CRM_Utils_Date
::setDateDefaults($contact->deceased_date
, 'birth');
2314 $values['deceased_date_display'] = $contact->deceased_date
;
2317 $contact->contact_id
= $contact->id
;
2325 * Given the component name and returns
2326 * the count of participation of contact
2328 * @param string $component input component name
2329 * @param integer $contactId input contact id
2330 * @param string $tableName optional tableName if component is custom group
2332 * @return total number of count of occurence in database
2336 static function getCountComponent($component, $contactId, $tableName = NULL) {
2338 switch ($component) {
2340 return CRM_Core_BAO_EntityTag
::getContactTags($contactId, TRUE);
2343 return CRM_Contact_BAO_Relationship
::getRelationship($contactId,
2344 CRM_Contact_BAO_Relationship
::CURRENT
,
2349 return CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, "Added", NULL, TRUE);
2352 if (CRM_Core_BAO_Log
::useLoggingReport()) {
2355 return CRM_Core_BAO_Log
::getContactLogCount($contactId);
2358 return CRM_Core_BAO_Note
::getContactNoteCount($contactId);
2360 case 'contribution':
2361 return CRM_Contribute_BAO_Contribution
::contributionCount($contactId);
2364 return CRM_Member_BAO_Membership
::getContactMembershipCount($contactId, TRUE);
2367 return CRM_Event_BAO_Participant
::getContactParticipantCount($contactId);
2370 return CRM_Pledge_BAO_Pledge
::getContactPledgeCount($contactId);
2373 return CRM_Case_BAO_Case
::caseCount($contactId);
2376 return CRM_Grant_BAO_Grant
::getContactGrantCount($contactId);
2380 'contact_id' => $contactId,
2383 'context' => 'activity',
2385 return CRM_Activity_BAO_Activity
::getActivitiesCount($input);
2388 $custom = explode('_', $component);
2389 if ($custom['0'] = 'custom') {
2391 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2393 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2394 return CRM_Core_DAO
::singleValueQuery($queryString);
2400 * Function to process greetings and cache
2402 * @param object $contact contact object after save
2403 * @param boolean $useDefaults use default greeting values
2409 static function processGreetings(&$contact, $useDefaults = FALSE) {
2411 //retrieve default greetings
2412 $defaultGreetings = CRM_Core_PseudoConstant
::greetingDefaults();
2413 $contactDefaults = $defaultGreetings[$contact->contact_type
];
2416 // note that contact object not always has required greeting related
2417 // fields that are required to calculate greeting and
2418 // also other fields used in tokens etc,
2419 // hence we need to retrieve it again.
2420 $contact->find(TRUE);
2422 // store object values to an array
2423 $contactDetails = array();
2424 CRM_Core_DAO
::storeValues($contact, $contactDetails);
2425 $contactDetails = array(array($contact->id
=> $contactDetails));
2427 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2428 $updateQueryString = array();
2430 //cache email and postal greeting to greeting display
2431 if ($contact->email_greeting_custom
!= 'null' && $contact->email_greeting_custom
) {
2432 $emailGreetingString = $contact->email_greeting_custom
;
2434 elseif ($contact->email_greeting_id
!= 'null' && $contact->email_greeting_id
) {
2435 // the filter value for Individual contact type is set to 1
2437 'contact_type' => $contact->contact_type
,
2438 'greeting_type' => 'email_greeting',
2441 $emailGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2442 $emailGreetingString = $emailGreeting[$contact->email_greeting_id
];
2443 $updateQueryString[] = " email_greeting_custom = NULL ";
2447 reset($contactDefaults['email_greeting']);
2448 $emailGreetingID = key($contactDefaults['email_greeting']);
2449 $emailGreetingString = $contactDefaults['email_greeting'][$emailGreetingID];
2450 $updateQueryString[] = " email_greeting_id = $emailGreetingID ";
2451 $updateQueryString[] = " email_greeting_custom = NULL ";
2453 elseif ($contact->email_greeting_custom
) {
2454 $updateQueryString[] = " email_greeting_display = NULL ";
2458 if ($emailGreetingString) {
2459 CRM_Utils_Token
::replaceGreetingTokens($emailGreetingString,
2462 'CRM_Contact_BAO_Contact'
2464 $emailGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($emailGreetingString));
2465 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2469 if ($contact->postal_greeting_custom
!= 'null' && $contact->postal_greeting_custom
) {
2470 $postalGreetingString = $contact->postal_greeting_custom
;
2472 elseif ($contact->postal_greeting_id
!= 'null' && $contact->postal_greeting_id
) {
2474 'contact_type' => $contact->contact_type
,
2475 'greeting_type' => 'postal_greeting',
2477 $postalGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2478 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id
];
2479 $updateQueryString[] = " postal_greeting_custom = NULL ";
2483 reset($contactDefaults['postal_greeting']);
2484 $postalGreetingID = key($contactDefaults['postal_greeting']);
2485 $postalGreetingString = $contactDefaults['postal_greeting'][$postalGreetingID];
2486 $updateQueryString[] = " postal_greeting_id = $postalGreetingID ";
2487 $updateQueryString[] = " postal_greeting_custom = NULL ";
2489 elseif ($contact->postal_greeting_custom
) {
2490 $updateQueryString[] = " postal_greeting_display = NULL ";
2494 if ($postalGreetingString) {
2495 CRM_Utils_Token
::replaceGreetingTokens($postalGreetingString,
2498 'CRM_Contact_BAO_Contact'
2500 $postalGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($postalGreetingString));
2501 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2505 if ($contact->addressee_custom
!= 'null' && $contact->addressee_custom
) {
2506 $addresseeString = $contact->addressee_custom
;
2508 elseif ($contact->addressee_id
!= 'null' && $contact->addressee_id
) {
2510 'contact_type' => $contact->contact_type
,
2511 'greeting_type' => 'addressee',
2514 $addressee = CRM_Core_PseudoConstant
::greeting($filter);
2515 $addresseeString = $addressee[$contact->addressee_id
];
2516 $updateQueryString[] = " addressee_custom = NULL ";
2520 reset($contactDefaults['addressee']);
2521 $addresseeID = key($contactDefaults['addressee']);
2522 $addresseeString = $contactDefaults['addressee'][$addresseeID];
2523 $updateQueryString[] = " addressee_id = $addresseeID ";
2524 $updateQueryString[] = " addressee_custom = NULL ";
2526 elseif ($contact->addressee_custom
) {
2527 $updateQueryString[] = " addressee_display = NULL ";
2531 if ($addresseeString) {
2532 CRM_Utils_Token
::replaceGreetingTokens($addresseeString,
2535 'CRM_Contact_BAO_Contact'
2537 $addresseeString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($addresseeString));
2538 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2541 if (!empty($updateQueryString)) {
2542 $updateQueryString = implode(',', $updateQueryString);
2543 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2544 CRM_Core_DAO
::executeQuery($queryString);
2549 * Function to retrieve loc block ids w/ given condition.
2551 * @param int $contactId contact id.
2552 * @param array $criteria key => value pair which should be
2553 * fulfill by return record ids.
2554 * @param string $condOperator operator use for grouping multiple conditions.
2556 * @return array $locBlockIds loc block ids which fulfill condition.
2559 static function getLocBlockIds($contactId, $criteria = array(
2560 ), $condOperator = 'AND') {
2561 $locBlockIds = array();
2563 return $locBlockIds;
2567 'Email', 'OpenID', 'Phone', 'Address', 'IM') as $block) {
2568 $name = strtolower($block);
2569 eval("\$blockDAO = new CRM_Core_DAO_$block();");
2571 // build the condition.
2572 if (is_array($criteria)) {
2573 eval('$object = new CRM_Core_DAO_' . $block . '( );');
2574 $fields = $object->fields();
2575 $conditions = array();
2576 foreach ($criteria as $field => $value) {
2577 if (array_key_exists($field, $fields)) {
2578 $cond = "( $field = $value )";
2579 // value might be zero or null.
2580 if (!$value ||
strtolower($value) == 'null') {
2581 $cond = "( $field = 0 OR $field IS NULL )";
2583 $conditions[] = $cond;
2586 if (!empty($conditions)) {
2587 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2591 $blockDAO->contact_id
= $contactId;
2593 while ($blockDAO->fetch()) {
2594 $locBlockIds[$name][] = $blockDAO->id
;
2599 return $locBlockIds;
2603 * Function to build context menu items.
2605 * @return array of context menu for logged in user.
2608 static function contextMenu($contactId = NULL) {
2610 'view' => array('title' => ts('View Contact'),
2612 'ref' => 'view-contact',
2614 'permissions' => array('view all contacts'),
2616 'add' => array('title' => ts('Edit Contact'),
2618 'ref' => 'edit-contact',
2620 'permissions' => array('edit all contacts'),
2622 'delete' => array('title' => ts('Delete Contact'),
2624 'ref' => 'delete-contact',
2626 'permissions' => array('access deleted contacts', 'delete contacts'),
2628 'contribution' => array('title' => ts('Add Contribution'),
2630 'ref' => 'new-contribution',
2631 'key' => 'contribution',
2632 'component' => 'CiviContribute',
2633 'href' => CRM_Utils_System
::url('civicrm/contact/view/contribution',
2634 'reset=1&action=add&context=contribution'
2636 'permissions' => array(
2637 'access CiviContribute',
2638 'edit contributions',
2641 'participant' => array('title' => ts('Register for Event'),
2643 'ref' => 'new-participant',
2644 'key' => 'participant',
2645 'component' => 'CiviEvent',
2646 'href' => CRM_Utils_System
::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
2647 'permissions' => array(
2649 'edit event participants',
2652 'activity' => array('title' => ts('Record Activity'),
2654 'ref' => 'new-activity',
2655 'key' => 'activity',
2656 'permissions' => array('edit all contacts'),
2658 'pledge' => array('title' => ts('Add Pledge'),
2660 'ref' => 'new-pledge',
2662 'href' => CRM_Utils_System
::url('civicrm/contact/view/pledge',
2663 'reset=1&action=add&context=pledge'
2665 'component' => 'CiviPledge',
2666 'permissions' => array(
2667 'access CiviPledge',
2671 'membership' => array('title' => ts('Add Membership'),
2673 'ref' => 'new-membership',
2674 'key' => 'membership',
2675 'component' => 'CiviMember',
2676 'href' => CRM_Utils_System
::url('civicrm/contact/view/membership',
2677 'reset=1&action=add&context=membership'
2679 'permissions' => array(
2680 'access CiviMember',
2684 'case' => array('title' => ts('Add Case'),
2686 'ref' => 'new-case',
2688 'component' => 'CiviCase',
2689 'href' => CRM_Utils_System
::url('civicrm/case/add', 'reset=1&action=add&context=case'),
2690 'permissions' => array('add cases'),
2692 'grant' => array('title' => ts('Add Grant'),
2694 'ref' => 'new-grant',
2696 'component' => 'CiviGrant',
2697 'href' => CRM_Utils_System
::url('civicrm/contact/view/grant',
2698 'reset=1&action=add&context=grant'
2700 'permissions' => array('edit grants'),
2702 'rel' => array('title' => ts('Add Relationship'),
2704 'ref' => 'new-relationship',
2706 'href' => CRM_Utils_System
::url('civicrm/contact/view/rel',
2707 'reset=1&action=add'
2709 'permissions' => array('edit all contacts'),
2711 'note' => array('title' => ts('Add Note'),
2713 'ref' => 'new-note',
2715 'href' => CRM_Utils_System
::url('civicrm/contact/view/note',
2716 'reset=1&action=add'
2718 'permissions' => array('edit all contacts'),
2720 'email' => array('title' => ts('Send an Email'),
2722 'ref' => 'new-email',
2724 'permissions' => array('view all contacts'),
2726 'group' => array('title' => ts('Add to Group'),
2728 'ref' => 'group-add-contact',
2730 'permissions' => array('edit groups'),
2732 'tag' => array('title' => ts('Tag'),
2734 'ref' => 'tag-contact',
2736 'permissions' => array('edit all contacts'),
2740 CRM_Utils_Hook
::summaryActions($menu, $contactId);
2741 //1. check for component is active.
2742 //2. check for user permissions.
2743 //3. check for acls.
2744 //3. edit and view contact are directly accessible to user.
2746 $aclPermissionedTasks = array(
2747 'view-contact', 'edit-contact', 'new-activity',
2748 'new-email', 'group-add-contact', 'tag-contact', 'delete-contact',
2750 $corePermission = CRM_Core_Permission
::getPermission();
2752 $config = CRM_Core_Config
::singleton();
2754 $contextMenu = array();
2755 foreach ($menu as $key => $values) {
2756 $componentName = CRM_Utils_Array
::value('component', $values);
2758 // if component action - make sure component is enable.
2759 if ($componentName && !in_array($componentName, $config->enableComponents
)) {
2763 // make sure user has all required permissions.
2764 $hasAllPermissions = FALSE;
2766 $permissions = CRM_Utils_Array
::value('permissions', $values);
2767 if (!is_array($permissions) ||
empty($permissions)) {
2768 $hasAllPermissions = TRUE;
2771 // iterate for required permissions in given permissions array.
2772 if (!$hasAllPermissions) {
2773 $hasPermissions = 0;
2774 foreach ($permissions as $permission) {
2775 if (CRM_Core_Permission
::check($permission)) {
2780 if (count($permissions) == $hasPermissions) {
2781 $hasAllPermissions = TRUE;
2784 // if still user does not have required permissions, check acl.
2785 if (!$hasAllPermissions && $values['ref'] != 'delete-contact') {
2786 if (in_array($values['ref'], $aclPermissionedTasks) &&
2787 $corePermission == CRM_Core_Permission
::EDIT
2789 $hasAllPermissions = TRUE;
2791 elseif (in_array($values['ref'], array(
2793 // grant permissions for these tasks.
2794 $hasAllPermissions = TRUE;
2799 // user does not have necessary permissions.
2800 if (!$hasAllPermissions) {
2804 // build directly accessible action menu.
2805 if (in_array($values['ref'], array(
2806 'view-contact', 'edit-contact'))) {
2807 $contextMenu['primaryActions'][$key] = array(
2808 'title' => $values['title'],
2809 'ref' => $values['ref'],
2810 'key' => $values['key'],
2815 // finally get menu item for -more- action widget.
2816 $contextMenu['moreActions'][$values['weight']] = array(
2817 'title' => $values['title'],
2818 'ref' => $values['ref'],
2819 'href' => CRM_Utils_Array
::value('href', $values),
2820 'key' => $values['key'],
2824 ksort($contextMenu['moreActions']);
2826 return $contextMenu;
2830 * Function to retrieve display name of contact that address is shared
2831 * based on $masterAddressId or $contactId .
2833 * @param int $masterAddressId master id.
2834 * @param int $contactId contact id.
2836 * @return display name |null the found display name or null.
2840 static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
2841 $masterDisplayName = NULL;
2843 if (!$masterAddressId && !$contactId) {
2844 return $masterDisplayName;
2847 if ($masterAddressId) {
2849 SELECT display_name from civicrm_contact
2850 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
2851 WHERE civicrm_address.id = " . $masterAddressId;
2853 elseif ($contactId) {
2855 SELECT display_name from civicrm_contact cc, civicrm_address add1
2856 LEFT JOIN civicrm_address add2 ON ( add1.master_id = add2.id )
2857 WHERE cc.id = add2.contact_id AND add1.contact_id = " . $contactId;
2860 $masterDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
2861 return $masterDisplayName;
2865 * Get the creation/modification times for a contact
2867 * @return array('created_date' => $, 'modified_date' => $)
2869 static function getTimestamps($contactId) {
2870 $timestamps = CRM_Core_DAO
::executeQuery(
2871 'SELECT created_date, modified_date
2872 FROM civicrm_contact
2875 1 => array($contactId, 'Integer'),
2878 if ($timestamps->fetch()) {
2880 'created_date' => $timestamps->created_date
,
2881 'modified_date' => $timestamps->modified_date
,
2890 * Get a list of triggers for the contact table
2892 * @see hook_civicrm_triggerInfo
2893 * @see CRM_Core_DAO::triggerRebuild
2894 * @see http://issues.civicrm.org/jira/browse/CRM-10554
2896 static function triggerInfo(&$info, $tableName = NULL) {
2897 //during upgrade, first check for valid version and then create triggers
2898 //i.e the columns created_date and modified_date are introduced in 4.3.alpha1 so dont create triggers for older version
2899 if (CRM_Core_Config
::isUpgradeMode()) {
2900 $currentVer = CRM_Core_BAO_Domain
::version(TRUE);
2901 //if current version is less than 4.3.alpha1 dont create below triggers
2902 if (version_compare($currentVer, '4.3.alpha1') < 0) {
2907 if ($tableName == NULL ||
$tableName == self
::getTableName()) {
2909 'table' => array(self
::getTableName()),
2911 'event' => array('INSERT'),
2912 'sql' => "\nSET NEW.created_date = CURRENT_TIMESTAMP;\n",
2916 // Update timestamp when modifying closely related core tables
2917 $relatedTables = array(
2925 'table' => $relatedTables,
2927 'event' => array('INSERT', 'UPDATE'),
2928 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = NEW.contact_id;\n",
2931 'table' => $relatedTables,
2933 'event' => array('DELETE'),
2934 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = OLD.contact_id;\n",
2937 // Update timestamp when modifying related custom-data tables
2938 $customGroupTables = array();
2939 $customGroupDAO = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity('Contact');
2940 $customGroupDAO->is_multiple
= 0;
2941 $customGroupDAO->find();
2942 while ($customGroupDAO->fetch()) {
2943 $customGroupTables[] = $customGroupDAO->table_name
;
2945 if (!empty($customGroupTables)) {
2947 'table' => $customGroupTables,
2949 'event' => array('INSERT', 'UPDATE'),
2950 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = NEW.entity_id;\n",
2953 'table' => $customGroupTables,
2955 'event' => array('DELETE'),
2956 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = OLD.entity_id;\n",
2960 // Update phone table to populate phone_numeric field
2961 if (!$tableName ||
$tableName == 'civicrm_phone') {
2962 // Define stored sql function needed for phones
2963 CRM_Core_DAO
::executeQuery(self
::DROP_STRIP_FUNCTION_43
);
2964 CRM_Core_DAO
::executeQuery(self
::CREATE_STRIP_FUNCTION_43
);
2966 'table' => array('civicrm_phone'),
2968 'event' => array('INSERT', 'UPDATE'),
2969 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
2975 * Function to check if contact is being used in civicrm_domain
2976 * based on $contactId
2978 * @param int $contactId contact id.
2980 * @return true if present else false.
2984 static function checkDomainContact($contactId) {
2987 $domainId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
2998 * Delete a contact-related object that has an 'is_primary' field
2999 * Ensures that is_primary gets assigned to another object if available
3000 * Also calls pre/post hooks
3002 * @var $type: object type
3003 * @var $id: object id
3005 public static function deleteObjectWithPrimary($type, $id) {
3006 if (!$id ||
!is_numeric($id)) {
3009 $daoName = "CRM_Core_DAO_$type";
3010 $obj = new $daoName();
3013 if ($obj->fetch()) {
3014 CRM_Utils_Hook
::pre('delete', $type, $id, CRM_Core_DAO
::$_nullArray);
3015 $contactId = $obj->contact_id
;
3021 // is_primary is only relavent if this field belongs to a contact
3023 $dao = new $daoName();
3024 $dao->contact_id
= $contactId;
3025 $dao->is_primary
= 1;
3026 // Pick another record to be primary (if one isn't already)
3027 if (!$dao->find(TRUE)) {
3028 $dao->is_primary
= 0;
3030 if ($dao->fetch()) {
3031 $dao->is_primary
= 1;
3037 CRM_Utils_Hook
::post('delete', $type, $id, $obj);