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 // in order to make sure that every contact must be added to a group (CRM-4613) -
328 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
329 if (CRM_Utils_Array
::value('group', $params) && is_array($params['group'])) {
330 $grpFlp = array_flip($params['group']);
331 if (!array_key_exists(1, $grpFlp)) {
332 $params['group'][$domainGroupID] = 1;
336 $params['group'] = array($domainGroupID => 1);
340 if (array_key_exists('group', $params)) {
341 $contactIds = array($params['contact_id']);
342 foreach ($params['group'] as $groupId => $flag) {
344 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
346 elseif ($flag == -1) {
347 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $groupId);
352 //add location Block data
353 $blocks = CRM_Core_BAO_Location
::create($params, $fixAddress);
354 foreach ($blocks as $name => $value) {
355 $contact->$name = $value;
359 CRM_Core_BAO_Website
::create($params['website'], $contact->id
, $skipDelete);
361 //get userID from session
362 $session = CRM_Core_Session
::singleton();
363 $userID = $session->get('userID');
365 if (CRM_Utils_Array
::value('note', $params)) {
366 if (is_array($params['note'])) {
367 foreach ($params['note'] as $note) {
368 $contactId = $contact->id
;
369 if (isset($note['contact_id'])) {
370 $contactId = $note['contact_id'];
372 //if logged in user, overwrite contactId
374 $contactId = $userID;
378 'entity_id' => $contact->id
,
379 'entity_table' => 'civicrm_contact',
380 'note' => $note['note'],
381 'subject' => CRM_Utils_Array
::value('subject', $note),
382 'contact_id' => $contactId,
384 CRM_Core_BAO_Note
::add($noteParams, CRM_Core_DAO
::$_nullArray);
388 $contactId = $contact->id
;
389 if (isset($note['contact_id'])) {
390 $contactId = $note['contact_id'];
392 //if logged in user, overwrite contactId
394 $contactId = $userID;
398 'entity_id' => $contact->id
,
399 'entity_table' => 'civicrm_contact',
400 'note' => $params['note'],
401 'subject' => CRM_Utils_Array
::value('subject', $params),
402 'contact_id' => $contactId,
404 CRM_Core_BAO_Note
::add($noteParams, CRM_Core_DAO
::$_nullArray);
409 // update the UF user_unique_id if that has changed
410 CRM_Core_BAO_UFMatch
::updateUFName($contact->id
);
412 if (CRM_Utils_Array
::value('custom', $params) &&
413 is_array($params['custom'])
415 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contact', $contact->id
);
418 // make a civicrm_subscription_history entry only on contact create (CRM-777)
419 if (!CRM_Utils_Array
::value('contact_id', $params)) {
420 $subscriptionParams = array(
421 'contact_id' => $contact->id
,
425 CRM_Contact_BAO_SubscriptionHistory
::create($subscriptionParams);
428 $transaction->commit();
430 // CRM-6367: fetch the right label for contact type’s display
431 $contact->contact_type_display
= CRM_Core_DAO
::getFieldValue(
432 'CRM_Contact_DAO_ContactType',
433 $contact->contact_type
,
438 if (!$config->doNotResetCache
) {
439 // Note: doNotResetCache flag is currently set by import contact process and merging,
440 // since resetting and
441 // rebuilding cache could be expensive (for many contacts). We might come out with better
442 // approach in future.
443 CRM_Contact_BAO_Contact_Utils
::clearContactCaches($contact->id
);
448 CRM_Utils_Hook
::post('edit', $params['contact_type'], $contact->id
, $contact);
451 CRM_Utils_Hook
::post('create', $params['contact_type'], $contact->id
, $contact);
455 // process greetings CRM-4575, cache greetings
456 self
::processGreetings($contact);
462 * Get the display name and image of a contact
464 * @param int $id the contactId
466 * @return array the displayName and contactImage for this contact
470 static function getDisplayAndImage($id, $type = FALSE) {
472 SELECT civicrm_contact.display_name as display_name,
473 civicrm_contact.contact_type as contact_type,
474 civicrm_contact.contact_sub_type as contact_sub_type,
475 civicrm_email.email as email
477 LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
478 AND civicrm_email.is_primary = 1
479 WHERE civicrm_contact.id = " . CRM_Utils_Type
::escape($id, 'Integer');
480 $dao = new CRM_Core_DAO();
483 $image = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
484 $dao->contact_sub_type
: $dao->contact_type
, FALSE, $id
486 $imageUrl = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
487 $dao->contact_sub_type
: $dao->contact_type
, TRUE, $id
490 // use email if display_name is empty
491 if (empty($dao->display_name
)) {
492 $dao->display_name
= $dao->email
;
494 return $type ?
array(
495 $dao->display_name
, $image,
496 $dao->contact_type
, $dao->contact_sub_type
, $imageUrl,
497 ) : array($dao->display_name
, $image, $imageUrl);
504 * Get the values for pseudoconstants for name->value and reverse.
506 * @param array $defaults (reference) the default values, some of which need to be resolved.
507 * @param boolean $reverse true if we want to resolve the values in the reverse direction (value -> name)
513 static function resolveDefaults(&$defaults, $reverse = FALSE) {
514 // hack for birth_date
515 if (CRM_Utils_Array
::value('birth_date', $defaults)) {
516 if (is_array($defaults['birth_date'])) {
517 $defaults['birth_date'] = CRM_Utils_Date
::format($defaults['birth_date'], '-');
521 CRM_Utils_Array
::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant
::individualPrefix(), $reverse);
522 CRM_Utils_Array
::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant
::individualSuffix(), $reverse);
523 CRM_Utils_Array
::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant
::gender(), $reverse);
525 //lookup value of email/postal greeting, addressee, CRM-4575
526 foreach (self
::$_greetingTypes as $greeting) {
527 $filterCondition = array('contact_type' => CRM_Utils_Array
::value('contact_type', $defaults),
528 'greeting_type' => $greeting,
530 CRM_Utils_Array
::lookupValue($defaults, $greeting,
531 CRM_Core_PseudoConstant
::greeting($filterCondition), $reverse
535 $blocks = array('address', 'im', 'phone');
536 foreach ($blocks as $name) {
537 if (!array_key_exists($name, $defaults) ||
!is_array($defaults[$name])) {
540 foreach ($defaults[$name] as $count => & $values) {
542 //get location type id.
543 CRM_Utils_Array
::lookupValue($values, 'location_type', CRM_Core_PseudoConstant
::locationType(), $reverse);
545 if ($name == 'address') {
546 // FIXME: lookupValue doesn't work for vcard_name
547 if (CRM_Utils_Array
::value('location_type_id', $values)) {
548 $vcardNames = CRM_Core_PseudoConstant
::locationVcardName();
549 $values['vcard_name'] = $vcardNames[$values['location_type_id']];
552 if (!CRM_Utils_Array
::lookupValue($values,
554 CRM_Core_PseudoConstant
::country(),
559 CRM_Utils_Array
::lookupValue($values,
561 CRM_Core_PseudoConstant
::countryIsoCode(),
567 // if we find a country id above, we need to restrict it to that country
568 // rather than the list of all countries
570 if (!empty($values['country_id'])) {
571 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($values['country_id']);
574 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvince();
576 if (!CRM_Utils_Array
::lookupValue($values,
584 if (!empty($values['country_id'])) {
585 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($values['country_id'], 'abbreviation');
588 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviation();
590 CRM_Utils_Array
::lookupValue($values,
597 if (!empty($values['state_province_id'])) {
598 $countyList = CRM_Core_PseudoConstant
::countyForState($values['state_province_id']);
601 $countyList = CRM_Core_PseudoConstant
::county();
603 CRM_Utils_Array
::lookupValue($values,
611 CRM_Utils_Array
::lookupValue($values,
613 CRM_Core_PseudoConstant
::IMProvider(),
618 if ($name == 'phone') {
619 CRM_Utils_Array
::lookupValue($values,
621 CRM_Core_PseudoConstant
::phoneType(),
626 //kill the reference.
633 * Takes a bunch of params that are needed to match certain criteria and
634 * retrieves the relevant objects. Typically the valid params are only
635 * contact_id. We'll tweak this function to be more full featured over a period
636 * of time. This is the inverse function of create. It also stores all the retrieved
637 * values in the default array
639 * @param array $params (reference ) an assoc array of name/value pairs
640 * @param array $defaults (reference ) an assoc array to hold the name / value pairs
641 * in a hierarchical manner
642 * @param boolean $microformat for location in microformat
644 * @return object CRM_Contact_BAO_Contact object
648 static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
649 if (array_key_exists('contact_id', $params)) {
650 $params['id'] = $params['contact_id'];
652 elseif (array_key_exists('id', $params)) {
653 $params['contact_id'] = $params['id'];
656 $contact = self
::getValues($params, $defaults);
658 unset($params['id']);
660 //get the block information for this contact
661 $entityBlock = array('contact_id' => $params['contact_id']);
662 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock, $microformat);
663 $defaults = array_merge($defaults, $blocks);
664 foreach ($blocks as $block => $value) $contact->$block = $value;
666 if (!isset($params['noNotes'])) {
667 $contact->notes
= CRM_Core_BAO_Note
::getValues($params, $defaults);
670 if (!isset($params['noRelationships'])) {
671 $contact->relationship
= CRM_Contact_BAO_Relationship
::getValues($params, $defaults);
674 if (!isset($params['noGroups'])) {
675 $contact->groupContact
= CRM_Contact_BAO_GroupContact
::getValues($params, $defaults);
678 if (!isset($params['noWebsite'])) {
679 $contact->website
= CRM_Core_BAO_Website
::getValues($params, $defaults);
686 * function to get the display name of a contact
688 * @param int $id id of the contact
690 * @return null|string display name of the contact if found
694 static function displayName($id) {
697 $displayName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
704 * Delete a contact and all its associated records
706 * @param int $id id of the contact to delete
707 * @param bool $restore whether to actually restore, not delete
708 * @param bool $skipUndelete whether to force contact delete or not
710 * @return boolean true if contact deleted, false otherwise
714 static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE) {
720 // make sure we have edit permission for this contact
722 if (($skipUndelete && !CRM_Core_Permission
::check('delete contacts')) ||
723 ($restore && !CRM_Core_Permission
::check('access deleted contacts'))
728 // make sure this contact_id does not have any membership types
729 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
732 'member_of_contact_id'
734 if ($membershipTypeID) {
738 $contact = new CRM_Contact_DAO_Contact();
740 if (!$contact->find(TRUE)) {
744 $contactType = $contact->contact_type
;
745 $action = ($restore) ?
'restore' : 'delete';
747 CRM_Utils_Hook
::pre($action, $contactType, $id, CRM_Core_DAO
::$_nullArray);
750 self
::contactTrashRestore($contact, TRUE);
751 CRM_Utils_Hook
::post($action, $contactType, $contact->id
, $contact);
756 // currently we only clear employer cache.
757 // we are not deleting inherited membership if any.
758 if ($contact->contact_type
== 'Organization') {
759 CRM_Contact_BAO_Contact_Utils
::clearAllEmployee($id);
762 // start a new transaction
763 $transaction = new CRM_Core_Transaction();
765 if ($skipUndelete or !CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'contact_undelete', NULL)) {
767 //delete billing address if exists.
768 CRM_Contribute_BAO_Contribution
::deleteAddress(NULL, $id);
770 // delete the log entries since we dont have triggers enabled as yet
771 $logDAO = new CRM_Core_DAO_Log();
772 $logDAO->entity_table
= 'civicrm_contact';
773 $logDAO->entity_id
= $id;
776 // delete contact participants CRM-12155
777 CRM_Event_BAO_Participant
::deleteContactParticipant($id);
779 // delete contact contributions CRM-12155
780 CRM_Contribute_BAO_Contribution
::deleteContactContribution($id);
782 // do activity cleanup, CRM-5604
783 CRM_Activity_BAO_Activity
::cleanupActivity($id);
785 // delete all notes related to contact
786 CRM_Core_BAO_Note
::cleanContactNotes($id);
791 self
::contactTrashRestore($contact);
794 //delete the contact id from recently view
795 CRM_Utils_Recent
::delContact($id);
797 // reset the group contact cache for this group
798 CRM_Contact_BAO_GroupContactCache
::remove();
800 // delete any dupe cache entry
801 CRM_Core_BAO_PrevNextCache
::deleteItem($id);
803 $transaction->commit();
805 CRM_Utils_Hook
::post('delete', $contactType, $contact->id
, $contact);
807 // also reset the DB_DO global array so we can reuse the memory
808 // http://issues.civicrm.org/jira/browse/CRM-4387
809 CRM_Core_DAO
::freeResult();
815 * function to delete the image of a contact
817 * @param int $id id of the contact
819 * @return boolean true if contact image is deleted
821 public static function deleteContactImage($id) {
826 UPDATE civicrm_contact
829 CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
834 * function to return relative path
835 * @todo make this a method of $config->userSystem (i.e. UF classes) rather than a static function
837 * @param String $absPath absolute path
839 * @return String $relativePath Relative url of uploaded image
841 public static function getRelativePath($absolutePath) {
842 $relativePath = NULL;
843 $config = CRM_Core_Config
::singleton();
844 if ($config->userFramework
== 'Joomla') {
845 $userFrameworkBaseURL = trim(str_replace('/administrator/', '', $config->userFrameworkBaseURL
));
846 $customFileUploadDirectory = strstr(str_replace('\\', '/', $absolutePath), '/media');
847 $relativePath = $userFrameworkBaseURL . $customFileUploadDirectory;
849 elseif ($config->userSystem
->is_drupal
== '1') {
850 //ideally we would do a bigger re-factoring & move the getRelativePath onto the UF class
851 $rootPath = $config->userSystem
->cmsRootPath();
852 $baseUrl = $config->userFrameworkBaseURL
;
854 //format url for language negotiation, CRM-7135
855 $baseUrl = CRM_Utils_System
::languageNegotiationURL($baseUrl, FALSE, TRUE);
857 $relativePath = str_replace("{$rootPath}/",
859 str_replace('\\', '/', $absolutePath)
861 } else if ( $config->userFramework
== 'WordPress' ) {
862 $userFrameworkBaseURL = trim( str_replace( '/wp-admin/', '', $config->userFrameworkBaseURL
) );
863 $customFileUploadDirectory = strstr( str_replace('\\', '/', $absolutePath), '/wp-content/' );
864 $relativePath = $userFrameworkBaseURL . $customFileUploadDirectory;
867 return $relativePath;
871 * function to return proportional height and width of the image
873 * @param Integer $imageWidth width of image
875 * @param Integer $imageHeight height of image
877 * @return Array thumb dimension of image
879 public static function getThumbSize($imageWidth, $imageHeight) {
881 if ($imageWidth && $imageHeight) {
882 $imageRatio = $imageWidth / $imageHeight;
887 if ($imageRatio > 1) {
888 $imageThumbWidth = $thumbWidth;
889 $imageThumbHeight = round($thumbWidth / $imageRatio);
892 $imageThumbHeight = $thumbWidth;
893 $imageThumbWidth = round($thumbWidth * $imageRatio);
896 return array($imageThumbWidth, $imageThumbHeight);
900 * function to validate type of contact image
902 * @param Array $param array of contact/profile field to be edited/added
904 * @param String $imageIndex index of image field
906 * @param String $statusMsg status message to be set after operation
908 * @opType String $opType type of operation like fatal, bounce etc
910 * @return boolean true if valid image extension
912 public static function processImageParams(&$params,
913 $imageIndex = 'image_URL',
927 if (in_array($params[$imageIndex]['type'], $mimeType)) {
928 $params[$imageIndex] = CRM_Contact_BAO_Contact
::getRelativePath($params[$imageIndex]['name']);
932 unset($params[$imageIndex]);
934 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
936 if ($opType == 'status') {
937 CRM_Core_Session
::setStatus($statusMsg, 'Sorry', 'error');
939 // FIXME: additional support for fatal, bounce etc could be added.
945 * function to extract contact id from url for deleting contact image
947 public static function processImage() {
949 $action = CRM_Utils_Request
::retrieve('action', 'String', $this);
950 $cid = CRM_Utils_Request
::retrieve('cid', 'Positive', $this);
951 // retrieve contact id in case of Profile context
952 $id = CRM_Utils_Request
::retrieve('id', 'Positive', $this);
953 $cid = $cid ?
$cid : $id;
954 if ($action & CRM_Core_Action
::DELETE
) {
955 if (CRM_Utils_Request
::retrieve('confirmed', 'Boolean', $this)) {
956 CRM_Contact_BAO_Contact
::deleteContactImage($cid);
957 CRM_Core_Session
::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
958 $session = CRM_Core_Session
::singleton();
959 $toUrl = $session->popUserContext();
960 CRM_Utils_System
::redirect($toUrl);
966 * Function to set is_delete true or restore deleted contact
968 * @param int $contact Contact DAO object
969 * @param boolean $restore true to set the is_delete = 1 else false to restore deleted contact,
975 static function contactTrashRestore($contact, $restore = FALSE) {
976 $op = ($restore ?
'restore' : 'trash');
978 CRM_Utils_Hook
::pre($op, $contact->contact_type
, $contact->id
, CRM_Core_DAO
::$_nullArray);
980 $params = array(1 => array($contact->id
, 'Integer'));
981 $isDelete = ' is_deleted = 1 ';
983 $isDelete = ' is_deleted = 0 ';
986 $query = "DELETE FROM civicrm_uf_match WHERE contact_id = %1";
987 CRM_Core_DAO
::executeQuery($query, $params);
990 $query = "UPDATE civicrm_contact SET {$isDelete} WHERE id = %1";
991 CRM_Core_DAO
::executeQuery($query, $params);
993 CRM_Utils_Hook
::post($op, $contact->contact_type
, $contact->id
, $contact);
997 * Get contact type for a contact.
999 * @param int $id - id of the contact whose contact type is needed
1001 * @return string contact_type if $id found else null ""
1008 public static function getContactType($id) {
1009 return CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1013 * Get contact sub type for a contact.
1015 * @param int $id - id of the contact whose contact sub type is needed
1017 * @return string contact_sub_type if $id found else null ""
1024 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1025 $subtype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1027 return $implodeDelimiter ?
NULL : array();
1030 $subtype = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($subtype, CRM_Core_DAO
::VALUE_SEPARATOR
));
1032 if ($implodeDelimiter) {
1033 $subtype = implode($implodeDelimiter, $subtype);
1039 * Get pair of contact-type and sub-type for a contact.
1041 * @param int $id - id of the contact whose contact sub/contact type is needed
1050 public static function getContactTypes($id) {
1051 $params = array('id' => $id);
1053 $contact = CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact',
1056 array('contact_type', 'contact_sub_type')
1060 $contactTypes = array();
1061 if ($contact->contact_sub_type
)
1062 $contactTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($contact->contact_sub_type
, CRM_Core_DAO
::VALUE_SEPARATOR
));
1063 array_unshift($contactTypes, $contact->contact_type
);
1065 return $contactTypes;
1068 CRM_Core_Error
::fatal();
1073 * combine all the importable fields from the lower levels object
1075 * The ordering is important, since currently we do not have a weight
1076 * scheme. Adding weight is super important and should be done in the
1077 * next week or so, before this can be called complete.
1079 * @param int $contactType contact Type
1080 * @param boolean $status status is used to manipulate first title
1081 * @param boolean $showAll if true returns all fields (includes disabled fields)
1082 * @param boolean $isProfile if its profile mode
1083 * @param boolean $checkPermission if false, do not include permissioning clause (for custom data)
1085 * @return array array of importable Fields
1089 static function importableFields($contactType = 'Individual',
1093 $checkPermission = TRUE,
1094 $withMultiCustomFields = FALSE
1096 if (empty($contactType)) {
1097 $contactType = 'All';
1100 $cacheKeyString = "importableFields $contactType";
1101 $cacheKeyString .= $status ?
'_1' : '_0';
1102 $cacheKeyString .= $showAll ?
'_1' : '_0';
1103 $cacheKeyString .= $isProfile ?
'_1' : '_0';
1104 $cacheKeyString .= $checkPermission ?
'_1' : '_0';
1106 $fields = CRM_Utils_Array
::value($cacheKeyString, self
::$_importableFields);
1109 // check if we can retrieve from database cache
1110 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1114 $fields = CRM_Contact_DAO_Contact
::import();
1116 // get the fields thar are meant for contact types
1117 if (in_array($contactType, array(
1118 'Individual', 'Household', 'Organization', 'All'))) {
1119 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1122 $locationFields = array_merge(CRM_Core_DAO_Address
::import(),
1123 CRM_Core_DAO_Phone
::import(),
1124 CRM_Core_DAO_Email
::import(),
1125 CRM_Core_DAO_IM
::import(TRUE),
1126 CRM_Core_DAO_OpenID
::import()
1129 $locationFields = array_merge($locationFields,
1130 CRM_Core_BAO_CustomField
::getFieldsForImport('Address',
1138 foreach ($locationFields as $key => $field) {
1139 $locationFields[$key]['hasLocationType'] = TRUE;
1142 $fields = array_merge($fields, $locationFields);
1144 $fields = array_merge($fields,
1145 CRM_Contact_DAO_Contact
::import()
1147 $fields = array_merge($fields,
1148 CRM_Core_DAO_Note
::import()
1152 $fields = array_merge($fields, CRM_Core_DAO_Website
::import());
1154 if ($contactType != 'All') {
1155 $fields = array_merge($fields,
1156 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType,
1161 $withMultiCustomFields
1164 //unset the fields, which are not related to their
1166 $commonValues = array(
1167 'Individual' => array('household_name', 'legal_name', 'sic_code', 'organization_name'),
1168 'Household' => array(
1169 'first_name', 'middle_name', 'last_name', 'job_title',
1170 'gender_id', 'birth_date', 'organization_name', 'legal_name',
1171 'legal_identifier', 'sic_code', 'home_URL', 'is_deceased',
1174 'Organization' => array(
1175 'first_name', 'middle_name', 'last_name', 'job_title',
1176 'gender_id', 'birth_date', 'household_name', 'is_deceased', 'deceased_date',
1179 foreach ($commonValues[$contactType] as $value) {
1180 unset($fields[$value]);
1185 'Individual', 'Household', 'Organization') as $type) {
1186 $fields = array_merge($fields,
1187 CRM_Core_BAO_CustomField
::getFieldsForImport($type,
1192 $withMultiCustomFields
1199 $fields = array_merge($fields, array('group' => array('title' => ts('Group(s)'),
1202 'tag' => array('title' => ts('Tag(s)'),
1205 'note' => array('title' => ts('Note(s)'),
1211 //Sorting fields in alphabetical order(CRM-1507)
1212 $fields = CRM_Utils_Array
::crmArraySortByField($fields, 'title');
1214 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1217 self
::$_importableFields[$cacheKeyString] = $fields;
1221 $fields = array_merge(array('do_not_import' => array('title' => ts('- do not import -'))),
1222 self
::$_importableFields[$cacheKeyString]
1226 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1227 self
::$_importableFields[$cacheKeyString]
1235 * combine all the exportable fields from the lower levels object
1237 * currentlty we are using importable fields as exportable fields
1239 * @param int $contactType contact Type
1240 * @param boolean $status true while exporting primary contacts
1241 * @param boolean $export true when used during export
1242 * @param boolean $search true when used during search, might conflict with export param?
1244 * @return array array of exportable Fields
1248 static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE) {
1249 if (empty($contactType)) {
1250 $contactType = 'All';
1253 $cacheKeyString = "exportableFields $contactType";
1254 $cacheKeyString .= $export ?
'_1' : '_0';
1255 $cacheKeyString .= $status ?
'_1' : '_0';
1256 $cacheKeyString .= $search ?
'_1' : '_0';
1258 if (!self
::$_exportableFields ||
!CRM_Utils_Array
::value($cacheKeyString, self
::$_exportableFields)) {
1259 if (!self
::$_exportableFields) {
1260 self
::$_exportableFields = array();
1263 // check if we can retrieve from database cache
1264 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1268 $fields = CRM_Contact_DAO_Contact
::export();
1270 // the fields are meant for contact types
1271 if (in_array($contactType, array(
1272 'Individual', 'Household', 'Organization', 'All'))) {
1273 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1275 // add current employer for individuals
1276 $fields = array_merge($fields, array(
1277 'current_employer' =>
1279 'name' => 'organization_name',
1280 'title' => ts('Current Employer'),
1284 $locationType = array(
1285 'location_type' => array('name' => 'location_type',
1286 'where' => 'civicrm_location_type.name',
1287 'title' => ts('Location Type'),
1290 $IMProvider = array(
1291 'im_provider' => array('name' => 'im_provider',
1292 'where' => 'civicrm_im.provider_id',
1293 'title' => ts('IM Provider'),
1296 $locationFields = array_merge($locationType,
1297 CRM_Core_DAO_Address
::export(),
1298 CRM_Core_DAO_Phone
::export(),
1299 CRM_Core_DAO_Email
::export(),
1301 CRM_Core_DAO_IM
::export(TRUE),
1302 CRM_Core_DAO_OpenID
::export()
1305 $locationFields = array_merge($locationFields,
1306 CRM_Core_BAO_CustomField
::getFieldsForImport('Address')
1309 foreach ($locationFields as $key => $field) {
1310 $locationFields[$key]['hasLocationType'] = TRUE;
1313 $fields = array_merge($fields, $locationFields);
1316 $fields = array_merge($fields,
1317 CRM_Core_DAO_Worldregion
::export()
1321 $fields = array_merge($fields,
1322 CRM_Contact_DAO_Contact
::export()
1326 $fields = array_merge($fields, CRM_Core_DAO_Website
::export());
1328 if ($contactType != 'All') {
1329 $fields = array_merge($fields,
1330 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType, $status, TRUE, $search, TRUE, $withMultiRecord)
1335 'Individual', 'Household', 'Organization') as $type) {
1336 $fields = array_merge($fields,
1337 CRM_Core_BAO_CustomField
::getFieldsForImport($type, FALSE, FALSE, $search, TRUE, $withMultiRecord)
1344 $fields = array_merge($fields, array('groups' => array('title' => ts('Group(s)'),
1347 'tags' => array('title' => ts('Tag(s)'),
1350 'notes' => array('title' => ts('Note(s)'),
1356 $fields = array_merge($fields, array('group' => array('title' => ts('Group(s)'),
1359 'tag' => array('title' => ts('Tag(s)'),
1362 'note' => array('title' => ts('Note(s)'),
1368 //Sorting fields in alphabetical order(CRM-1507)
1369 foreach ($fields as $k => $v) {
1370 $sortArray[$k] = CRM_Utils_Array
::value('title', $v);
1373 $fields = array_merge($sortArray, $fields);
1374 //unset the field which are not related to their contact type.
1375 if ($contactType != 'All') {
1376 $commonValues = array(
1377 'Individual' => array('household_name', 'legal_name', 'sic_code', 'organization_name',
1378 'email_greeting_custom', 'postal_greeting_custom',
1381 'Household' => array(
1382 'first_name', 'middle_name', 'last_name', 'job_title',
1383 'gender_id', 'birth_date', 'organization_name', 'legal_name',
1384 'legal_identifier', 'sic_code', 'home_URL', 'is_deceased',
1385 'deceased_date', 'current_employer', 'email_greeting_custom',
1386 'postal_greeting_custom', 'addressee_custom',
1387 'individual_prefix', 'individual_suffix', 'gender',
1389 'Organization' => array(
1390 'first_name', 'middle_name', 'last_name', 'job_title',
1391 'gender_id', 'birth_date', 'household_name',
1392 'email_greeting_custom',
1393 'postal_greeting_custom', 'individual_prefix',
1394 'individual_suffix', 'gender', 'addressee_custom',
1395 'is_deceased', 'deceased_date', 'current_employer',
1398 foreach ($commonValues[$contactType] as $value) {
1399 unset($fields[$value]);
1403 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1405 self
::$_exportableFields[$cacheKeyString] = $fields;
1409 $fields = self
::$_exportableFields[$cacheKeyString];
1412 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1413 self
::$_exportableFields[$cacheKeyString]
1421 * Function to get the all contact details(Hierarchical)
1423 * @param int $contactId contact id
1424 * @param array $fields fields array
1426 * @return $values array contains the contact details
1430 static function getHierContactDetails($contactId, &$fields) {
1431 $params = array(array('contact_id', '=', $contactId, 0, 0));
1434 $returnProperties = self
::makeHierReturnProperties($fields, $contactId);
1436 // we dont know the contents of return properties, but we need the lower level ids of the contact
1437 // so add a few fields
1438 $returnProperties['first_name'] =
1439 $returnProperties['organization_name'] =
1440 $returnProperties['household_name'] =
1441 $returnProperties['contact_type'] =
1442 $returnProperties['contact_sub_type'] = 1;
1443 return list($query, $options) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, $options);
1447 * given a set of flat profile style field names, create a hierarchy
1448 * for query to use and crete the right sql
1450 * @param array $properties a flat return properties name value array
1451 * @param int $contactId contact id
1453 * @return array a hierarchical property tree if appropriate
1457 static function &makeHierReturnProperties($fields, $contactId = NULL) {
1458 $locationTypes = CRM_Core_PseudoConstant
::locationType();
1460 $returnProperties = array();
1462 $multipleFields = array('website' => 'url');
1463 foreach ($fields as $name => $dontCare) {
1464 if (strpos($name, '-') !== FALSE) {
1465 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $name, 3);
1467 if (!in_array($fieldName, $multipleFields)) {
1468 if ($id == 'Primary') {
1469 $locationTypeName = 1;
1472 $locationTypeName = CRM_Utils_Array
::value($id, $locationTypes);
1473 if (!$locationTypeName) {
1478 if (!CRM_Utils_Array
::value('location', $returnProperties)) {
1479 $returnProperties['location'] = array();
1481 if (!CRM_Utils_Array
::value($locationTypeName, $returnProperties['location'])) {
1482 $returnProperties['location'][$locationTypeName] = array();
1483 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1485 if (in_array($fieldName, array(
1486 'phone', 'im', 'email', 'openid', 'phone_ext'))) {
1488 $returnProperties['location'][$locationTypeName][$fieldName . '-' . $type] = 1;
1491 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1494 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1495 $returnProperties['location'][$locationTypeName][substr($fieldName, 8)] = 1;
1498 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1502 $returnProperties['website'][$id][$fieldName] = 1;
1506 $returnProperties[$name] = 1;
1510 return $returnProperties;
1514 * Function to return the primary location type of a contact
1516 * $params int $contactId contact_id
1517 * $params boolean $isPrimaryExist if true, return primary contact location type otherwise null
1518 * $params boolean $skipDefaultPriamry if true, return primary contact location type otherwise null
1520 * @return int $locationType location_type_id
1524 static function getPrimaryLocationType($contactId, $skipDefaultPriamry = FALSE, $block = NULL) {
1526 $entityBlock = array('contact_id' => $contactId);
1527 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock);
1528 foreach($blocks[$block] as $key => $value){
1529 if (CRM_Utils_Array
::value('is_primary', $value)){
1530 $locationType = CRM_Utils_Array
::value('location_type_id',$value);
1537 IF ( civicrm_email.location_type_id IS NULL,
1538 IF ( civicrm_address.location_type_id IS NULL,
1539 IF ( civicrm_phone.location_type_id IS NULL,
1540 IF ( civicrm_im.location_type_id IS NULL,
1541 IF ( civicrm_openid.location_type_id IS NULL, null, civicrm_openid.location_type_id)
1542 ,civicrm_im.location_type_id)
1543 ,civicrm_phone.location_type_id)
1544 ,civicrm_address.location_type_id)
1545 ,civicrm_email.location_type_id) as locationType
1546 FROM civicrm_contact
1547 LEFT JOIN civicrm_email ON ( civicrm_email.is_primary = 1 AND civicrm_email.contact_id = civicrm_contact.id )
1548 LEFT JOIN civicrm_address ON ( civicrm_address.is_primary = 1 AND civicrm_address.contact_id = civicrm_contact.id)
1549 LEFT JOIN civicrm_phone ON ( civicrm_phone.is_primary = 1 AND civicrm_phone.contact_id = civicrm_contact.id)
1550 LEFT JOIN civicrm_im ON ( civicrm_im.is_primary = 1 AND civicrm_im.contact_id = civicrm_contact.id)
1551 LEFT JOIN civicrm_openid ON ( civicrm_openid.is_primary = 1 AND civicrm_openid.contact_id = civicrm_contact.id)
1552 WHERE civicrm_contact.id = %1 ";
1554 $params = array(1 => array($contactId, 'Integer'));
1556 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1558 $locationType = NULL;
1559 if ($dao->fetch()) {
1560 $locationType = $dao->locationType
;
1563 if (isset($locationType)) {
1564 return $locationType;
1566 elseif ($skipDefaultPriamry) {
1567 // if there is no primary contact location then return null
1571 // if there is no primart contact location, then return default
1572 // location type of the system
1573 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
1574 return $defaultLocationType->id
;
1579 * function to get the display name, primary email and location type of a contact
1581 * @param int $id id of the contact
1583 * @return array of display_name, email if found, do_not_email or (null,null,null)
1587 static function getContactDetails($id) {
1588 // check if the contact type
1589 $contactType = self
::getContactType($id);
1591 $nameFields = ($contactType == 'Individual') ?
"civicrm_contact.first_name, civicrm_contact.last_name, civicrm_contact.display_name" : "civicrm_contact.display_name";
1594 SELECT $nameFields, civicrm_email.email, civicrm_contact.do_not_email, civicrm_email.on_hold, civicrm_contact.is_deceased
1595 FROM civicrm_contact LEFT JOIN civicrm_email ON (civicrm_contact.id = civicrm_email.contact_id)
1596 WHERE civicrm_contact.id = %1
1597 ORDER BY civicrm_email.is_primary DESC";
1598 $params = array(1 => array($id, 'Integer'));
1599 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
1601 if ($dao->fetch()) {
1602 if ($contactType == 'Individual') {
1603 if ($dao->first_name ||
$dao->last_name
) {
1604 $name = "{$dao->first_name} {$dao->last_name}";
1607 $name = $dao->display_name
;
1611 $name = $dao->display_name
;
1613 $email = $dao->email
;
1614 $doNotEmail = $dao->do_not_email ?
TRUE : FALSE;
1615 $onHold = $dao->on_hold ?
TRUE : FALSE;
1616 $isDeceased = $dao->is_deceased ?
TRUE : FALSE;
1617 return array($name, $email, $doNotEmail, $onHold, $isDeceased);
1619 return array(NULL, NULL, NULL, NULL, NULL);
1623 * function to add/edit/register contacts through profile.
1625 * @params array $params Array of profile fields to be edited/added.
1626 * @params int $contactID contact_id of the contact to be edited/added.
1627 * @params array $fields array of fields from UFGroup
1628 * @params int $addToGroupID specifies the default group to which contact is added.
1629 * @params int $ufGroupId uf group id (profile id)
1630 * @param string $ctype contact type
1631 * @param boolean $visibility basically lets us know where this request is coming from
1632 * if via a profile from web, we restrict what groups are changed
1634 * @return int contact id created/edited
1638 static function createProfileContact(
1642 $addToGroupID = NULL,
1647 // add ufGroupID to params array ( CRM-2012 )
1649 $params['uf_group_id'] = $ufGroupId;
1654 CRM_Utils_Hook
::pre('edit', 'Profile', $contactID, $params);
1658 CRM_Utils_Hook
::pre('create', 'Profile', NULL, $params);
1661 list($data, $contactDetails) = self
::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
1663 // manage is_opt_out
1664 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
1665 $wasOptOut = CRM_Utils_Array
::value('is_opt_out', $contactDetails, FALSE);
1666 $isOptOut = CRM_Utils_Array
::value('is_opt_out', $params, FALSE);
1667 $data['is_opt_out'] = $isOptOut;
1668 // on change, create new civicrm_subscription_history entry
1669 if (($wasOptOut != $isOptOut) &&
1670 CRM_Utils_Array
::value('contact_id', $contactDetails)
1673 'contact_id' => $contactDetails['contact_id'],
1674 'status' => $isOptOut ?
'Removed' : 'Added',
1677 CRM_Contact_BAO_SubscriptionHistory
::create($shParams);
1681 $contact = self
::create($data);
1683 // contact is null if the profile does not have any contact fields
1685 $contactID = $contact->id
;
1688 if (empty($contactID)) {
1689 CRM_Core_Error
::fatal('Cannot proceed without a valid contact id');
1692 // Process group and tag
1693 if (CRM_Utils_Array
::value('group', $fields)) {
1695 // this for sure means we are coming in via profile since i added it to fix
1696 // removing contacts from user groups -- lobo
1700 CRM_Contact_BAO_GroupContact
::create($params['group'], $contactID, $visibility, $method);
1703 if (CRM_Utils_Array
::value('tag', $fields)) {
1704 CRM_Core_BAO_EntityTag
::create($params['tag'], 'civicrm_contact', $contactID);
1707 //to add profile in default group
1708 if (is_array($addToGroupID)) {
1709 $contactIds = array($contactID);
1710 foreach ($addToGroupID as $groupId) {
1711 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
1714 elseif ($addToGroupID) {
1715 $contactIds = array($contactID);
1716 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $addToGroupID);
1719 // reset the group contact cache for this group
1720 CRM_Contact_BAO_GroupContactCache
::remove();
1723 CRM_Utils_Hook
::post('edit', 'Profile', $contactID, $params);
1726 CRM_Utils_Hook
::post('create', 'Profile', $contactID, $params);
1731 static function formatProfileContactParams(
1740 $data = $contactDetails = array();
1742 // get the contact details (hier)
1744 list($details, $options) = self
::getHierContactDetails($contactID, $fields);
1746 $contactDetails = $details[$contactID];
1747 $data['contact_type'] = CRM_Utils_Array
::value('contact_type', $contactDetails);
1748 $data['contact_sub_type'] = CRM_Utils_Array
::value('contact_sub_type', $contactDetails);
1751 //we should get contact type only if contact
1753 $data['contact_type'] = CRM_Core_BAO_UFField
::getProfileType($ufGroupId);
1755 //special case to handle profile with only contact fields
1756 if ($data['contact_type'] == 'Contact') {
1757 $data['contact_type'] = 'Individual';
1759 elseif (CRM_Contact_BAO_ContactType
::isaSubType($data['contact_type'])) {
1760 $data['contact_type'] = CRM_Contact_BAO_ContactType
::getBasicType($data['contact_type']);
1764 $data['contact_type'] = $ctype;
1767 $data['contact_type'] = 'Individual';
1771 //fix contact sub type CRM-5125
1772 if (array_key_exists('contact_sub_type', $params) &&
1773 !empty($params['contact_sub_type'])
1775 $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
;
1777 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
1778 !empty($params['contact_sub_type_hidden'])
1780 // if profile was used, and had any subtype, we obtain it from there
1781 $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
;
1784 if ($ctype == 'Organization') {
1785 $data['organization_name'] = CRM_Utils_Array
::value('organization_name', $contactDetails);
1787 elseif ($ctype == 'Household') {
1788 $data['household_name'] = CRM_Utils_Array
::value('household_name', $contactDetails);
1791 $locationType = array();
1796 $data['contact_id'] = $contactID;
1797 $primaryLocationType = self
::getPrimaryLocationType($contactID);
1800 $defaultLocation = CRM_Core_BAO_LocationType
::getDefault();
1801 $defaultLocationId = $defaultLocation->id
;
1804 // get the billing location type
1805 $locationTypes = CRM_Core_PseudoConstant
::locationType();
1806 $billingLocationTypeId = array_search('Billing', $locationTypes);
1808 $blocks = array('email', 'phone', 'im', 'openid');
1810 $multiplFields = array('url');
1811 // prevent overwritten of formatted array, reset all block from
1812 // params if it is not in valid format (since import pass valid format)
1813 foreach ($blocks as $blk) {
1814 if (array_key_exists($blk, $params) &&
1815 !is_array($params[$blk])
1817 unset($params[$blk]);
1821 $primaryPhoneLoc = NULL;
1822 foreach ($params as $key => $value) {
1823 $fieldName = $locTypeId = $typeId = NULL;
1824 list($fieldName, $locTypeId, $typeId) = CRM_Utils_System
::explode('-', $key, 3);
1826 //store original location type id
1827 $actualLocTypeId = $locTypeId;
1829 if ($locTypeId == 'Primary') {
1831 if(in_array( $fieldName, $blocks)){
1832 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, $fieldName);
1835 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, 'address');
1837 $primaryLocationType = $locTypeId;
1840 $locTypeId = $defaultLocationId;
1844 if (is_numeric($locTypeId) &&
1845 !in_array($fieldName, $multiplFields) &&
1846 substr($fieldName, 0, 7) != 'custom_'
1848 $index = $locTypeId;
1850 if (is_numeric($typeId)) {
1851 $index .= '-' . $typeId;
1853 if (!in_array($index, $locationType)) {
1854 $locationType[$count] = $index;
1858 $loc = CRM_Utils_Array
::key($index, $locationType);
1860 $blockName = in_array( $fieldName, $blocks) ?
$fieldName : 'address';
1862 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
1864 //set is_billing true, for location type "Billing"
1865 if ($locTypeId == $billingLocationTypeId) {
1866 $data[$blockName][$loc]['is_billing'] = 1;
1870 //get the primary location type
1871 if ($locTypeId == $primaryLocationType) {
1872 $data[$blockName][$loc]['is_primary'] = 1;
1875 elseif ($locTypeId == $defaultLocationId) {
1876 $data[$blockName][$loc]['is_primary'] = 1;
1879 if ( in_array($fieldName, array('phone'))) {
1881 $data['phone'][$loc]['phone_type_id'] = $typeId;
1884 $data['phone'][$loc]['phone_type_id'] = '';
1886 $data['phone'][$loc]['phone'] = $value;
1888 //special case to handle primary phone with different phone types
1889 // in this case we make first phone type as primary
1890 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
1891 $primaryPhoneLoc = $loc;
1894 if ($loc != $primaryPhoneLoc) {
1895 unset($data['phone'][$loc]['is_primary']);
1898 elseif ($fieldName == 'phone_ext') {
1899 $data['phone'][$loc]['phone_ext'] = $value;
1901 elseif ($fieldName == 'email') {
1902 $data['email'][$loc]['email'] = $value;
1904 elseif ($fieldName == 'im') {
1905 if (isset($params[$key . '-provider_id'])) {
1906 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
1908 if (strpos($key, '-provider_id') !== FALSE) {
1909 $data['im'][$loc]['provider_id'] = $params[$key];
1912 $data['im'][$loc]['name'] = $value;
1915 elseif ($fieldName == 'openid') {
1916 $data['openid'][$loc]['openid'] = $value;
1919 if ($fieldName === 'state_province') {
1921 if (is_numeric($value) && ((int ) $value) >= 1000) {
1922 $data['address'][$loc]['state_province_id'] = $value;
1924 elseif (empty($value)) {
1925 $data['address'][$loc]['state_province_id'] = '';
1928 $data['address'][$loc]['state_province'] = $value;
1931 elseif ($fieldName === 'country') {
1933 if (is_numeric($value) && ((int ) $value) >= 1000
1935 $data['address'][$loc]['country_id'] = $value;
1937 elseif (empty($value)) {
1938 $data['address'][$loc]['country_id'] = '';
1941 $data['address'][$loc]['country'] = $value;
1944 elseif ($fieldName === 'county') {
1945 $data['address'][$loc]['county_id'] = $value;
1947 elseif ($fieldName == 'address_name') {
1948 $data['address'][$loc]['name'] = $value;
1950 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1951 $data['address'][$loc][substr($fieldName, 8)] = $value;
1954 $data['address'][$loc][$fieldName] = $value;
1959 if (substr($key, 0, 4) === 'url-') {
1960 $websiteField = explode('-', $key);
1961 if (isset($websiteField[2])) {
1962 $data['website'][$websiteField[1]]['website_type_id'] = $value;
1965 $data['website'][$websiteField[1]]['url'] = $value;
1968 elseif ($key === 'individual_suffix') {
1969 $data['suffix_id'] = $value;
1971 elseif ($key === 'individual_prefix') {
1972 $data['prefix_id'] = $value;
1974 elseif ($key === 'gender') {
1975 $data['gender_id'] = $value;
1977 //save email/postal greeting and addressee values if any, CRM-4575
1978 elseif (in_array($key, self
::$_greetingTypes, TRUE)) {
1979 $data[$key . '_id'] = $value;
1981 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($key))) {
1982 // for autocomplete transfer hidden value instead of label
1983 if ($params[$key] && isset($params[$key . '_id'])) {
1984 $value = $params[$key . '_id'];
1987 // we need to append time with date
1988 if ($params[$key] && isset($params[$key . '_time'])) {
1989 $value .= ' ' . $params[$key . '_time'];
1993 if (CRM_Utils_Array
::value('customRecordValues', $params)) {
1994 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
1995 foreach ($params['customRecordValues'] as $recId => $customFields) {
1996 if (is_array($customFields) && !empty($customFields)) {
1997 foreach ($customFields as $customFieldName) {
1998 if ($customFieldName == $key) {
2008 $type = $data['contact_type'];
2009 if ( CRM_Utils_Array
::value('contact_sub_type', $data) ) {
2010 $type = $data['contact_sub_type'];
2011 $type = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($type, CRM_Core_DAO
::VALUE_SEPARATOR
));
2012 // generally a contact even if, has multiple subtypes the parent-type is going to be one only
2013 // and since formatCustomField() would be interested in parent type, lets consider only one subtype
2014 // as the results going to be same.
2018 CRM_Core_BAO_CustomField
::formatCustomField($customFieldId,
2026 elseif ($key == 'edit') {
2030 if ($key == 'location') {
2031 foreach ($value as $locationTypeId => $field) {
2032 foreach ($field as $block => $val) {
2033 if ($block == 'address' && array_key_exists('address_name', $val)) {
2034 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2039 if($key == 'phone' && isset($params['phone_ext'])){
2040 $data[$key] = $value;
2041 foreach($value as $cnt => $phoneBlock){
2042 if($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']){
2043 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array
::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2048 $data[$key] = $value;
2054 if (!isset($data['contact_type'])) {
2055 $data['contact_type'] = 'Individual';
2058 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2059 $privacy = CRM_Core_SelectValues
::privacy();
2060 foreach ($privacy as $key => $value) {
2061 if (array_key_exists($key, $fields)) {
2062 if (array_key_exists($key, $params)) {
2063 $data[$key] = $params[$key];
2064 // dont reset it for existing contacts
2066 elseif (!$contactID) {
2072 return array($data, $contactDetails);
2076 * Function to find the get contact details
2077 * does not respect ACLs for now, which might need to be rectified at some
2078 * stage based on how its used
2080 * @param string $mail primary email address of the contact
2081 * @param string $ctype contact type
2083 * @return object $dao contact details
2086 static function &matchContactOnEmail($mail, $ctype = NULL) {
2087 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2088 $mail = $strtolower(trim($mail));
2090 SELECT civicrm_contact.id as contact_id,
2091 civicrm_contact.hash as hash,
2092 civicrm_contact.contact_type as contact_type,
2093 civicrm_contact.contact_sub_type as contact_sub_type
2094 FROM civicrm_contact
2095 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2098 if (CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
2099 'uniq_email_per_site'
2101 // try to find a match within a site (multisite).
2102 $groups = CRM_Core_BAO_Domain
::getChildGroupIds();
2103 if (!empty($groups)) {
2105 INNER JOIN civicrm_group_contact gc ON
2106 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2111 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2112 $p = array(1 => array($mail, 'String'));
2115 $query .= " AND civicrm_contact.contact_type = %3";
2116 $p[3] = array($ctype, 'String');
2119 $query .= " ORDER BY civicrm_email.is_primary DESC";
2121 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2123 if ($dao->fetch()) {
2126 return CRM_Core_DAO
::$_nullObject;
2130 * Function to find the contact details associated with an OpenID
2132 * @param string $openId openId of the contact
2133 * @param string $ctype contact type
2135 * @return object $dao contact details
2138 static function &matchContactOnOpenId($openId, $ctype = NULL) {
2139 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2140 $openId = $strtolower(trim($openId));
2142 SELECT civicrm_contact.id as contact_id,
2143 civicrm_contact.hash as hash,
2144 civicrm_contact.contact_type as contact_type,
2145 civicrm_contact.contact_sub_type as contact_sub_type
2146 FROM civicrm_contact
2147 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2148 WHERE civicrm_openid.openid = %1";
2149 $p = array(1 => array($openId, 'String'));
2152 $query .= " AND civicrm_contact.contact_type = %3";
2153 $p[3] = array($ctype, 'String');
2156 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2158 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2160 if ($dao->fetch()) {
2163 return CRM_Core_DAO
::$_nullObject;
2167 * Funtion to get primary email of the contact
2169 * @param int $contactID contact id
2171 * @return string $dao->email email address if present else null
2175 public static function getPrimaryEmail($contactID) {
2176 // fetch the primary email
2178 SELECT civicrm_email.email as email
2179 FROM civicrm_contact
2180 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2181 WHERE civicrm_email.is_primary = 1
2182 AND civicrm_contact.id = %1";
2183 $p = array(1 => array($contactID, 'Integer'));
2184 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2187 if ($dao->fetch()) {
2188 $email = $dao->email
;
2195 * Funtion to get primary OpenID of the contact
2197 * @param int $contactID contact id
2199 * @return string $dao->openid OpenID if present else null
2203 public static function getPrimaryOpenId($contactID) {
2204 // fetch the primary OpenID
2206 SELECT civicrm_openid.openid as openid
2207 FROM civicrm_contact
2208 LEFT JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2209 WHERE civicrm_contact.id = %1
2210 AND civicrm_openid.is_primary = 1";
2211 $p = array(1 => array($contactID, 'Integer'));
2212 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2215 if ($dao->fetch()) {
2216 $openId = $dao->openid
;
2223 * Given the list of params in the params array, fetch the object
2224 * and store the values in the values array
2226 * @param array $params input parameters to find object
2227 * @param array $values output values of the object
2229 * @return CRM_Contact_BAO_Contact|null the found object or null
2233 public static function getValues(&$params, &$values) {
2234 $contact = new CRM_Contact_BAO_Contact();
2236 $contact->copyValues($params);
2238 if ($contact->find(TRUE)) {
2240 CRM_Core_DAO
::storeValues($contact, $values);
2243 foreach (self
::$_commPrefs as $name) {
2244 if (isset($contact->$name)) {
2245 $privacy[$name] = $contact->$name;
2249 if (!empty($privacy)) {
2250 $values['privacy'] = $privacy;
2253 // communication Prefferance
2254 $preffComm = $comm = array();
2255 $comm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2256 $contact->preferred_communication_method
2258 foreach ($comm as $value) {
2259 $preffComm[$value] = 1;
2261 $temp = array('preferred_communication_method' => $contact->preferred_communication_method
);
2264 'preferred_communication_method' => array('newName' => 'preferred_communication_method_display',
2265 'groupName' => 'preferred_communication_method',
2268 CRM_Core_OptionGroup
::lookupValues($temp, $names, FALSE);
2270 $values['preferred_communication_method'] = $preffComm;
2271 $values['preferred_communication_method_display'] = CRM_Utils_Array
::value('preferred_communication_method_display', $temp);
2273 CRM_Contact_DAO_Contact
::addDisplayEnums($values);
2275 // get preferred languages
2276 if (!empty($contact->preferred_language
)) {
2277 $languages = CRM_Core_PseudoConstant
::languages();
2278 $values['preferred_language'] = CRM_Utils_Array
::value($contact->preferred_language
, $languages);
2281 // Calculating Year difference
2282 if ($contact->birth_date
) {
2283 $birthDate = CRM_Utils_Date
::customFormat($contact->birth_date
, '%Y%m%d');
2284 if ($birthDate < date('Ymd')) {
2285 $age = CRM_Utils_Date
::calculateAge($birthDate);
2286 $values['age']['y'] = CRM_Utils_Array
::value('years', $age);
2287 $values['age']['m'] = CRM_Utils_Array
::value('months', $age);
2290 list($values['birth_date']) = CRM_Utils_Date
::setDateDefaults($contact->birth_date
, 'birth');
2291 $values['birth_date_display'] = $contact->birth_date
;
2294 if ($contact->deceased_date
) {
2295 list($values['deceased_date']) = CRM_Utils_Date
::setDateDefaults($contact->deceased_date
, 'birth');
2296 $values['deceased_date_display'] = $contact->deceased_date
;
2299 $contact->contact_id
= $contact->id
;
2307 * Given the component name and returns
2308 * the count of participation of contact
2310 * @param string $component input component name
2311 * @param integer $contactId input contact id
2312 * @param string $tableName optional tableName if component is custom group
2314 * @return total number of count of occurence in database
2318 static function getCountComponent($component, $contactId, $tableName = NULL) {
2320 switch ($component) {
2322 return CRM_Core_BAO_EntityTag
::getContactTags($contactId, TRUE);
2325 return CRM_Contact_BAO_Relationship
::getRelationship($contactId,
2326 CRM_Contact_BAO_Relationship
::CURRENT
,
2331 return CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, "Added", NULL, TRUE);
2334 if (CRM_Core_BAO_Log
::useLoggingReport()) {
2337 return CRM_Core_BAO_Log
::getContactLogCount($contactId);
2340 return CRM_Core_BAO_Note
::getContactNoteCount($contactId);
2342 case 'contribution':
2343 return CRM_Contribute_BAO_Contribution
::contributionCount($contactId);
2346 return CRM_Member_BAO_Membership
::getContactMembershipCount($contactId, TRUE);
2349 return CRM_Event_BAO_Participant
::getContactParticipantCount($contactId);
2352 return CRM_Pledge_BAO_Pledge
::getContactPledgeCount($contactId);
2355 return CRM_Case_BAO_Case
::caseCount($contactId);
2358 return CRM_Grant_BAO_Grant
::getContactGrantCount($contactId);
2362 'contact_id' => $contactId,
2365 'context' => 'activity',
2367 return CRM_Activity_BAO_Activity
::getActivitiesCount($input);
2370 $custom = explode('_', $component);
2371 if ($custom['0'] = 'custom') {
2373 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2375 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2376 return CRM_Core_DAO
::singleValueQuery($queryString);
2382 * Function to process greetings and cache
2384 * @param object $contact contact object after save
2385 * @param boolean $useDefaults use default greeting values
2391 static function processGreetings(&$contact, $useDefaults = FALSE) {
2393 //retrieve default greetings
2394 $defaultGreetings = CRM_Core_PseudoConstant
::greetingDefaults();
2395 $contactDefaults = $defaultGreetings[$contact->contact_type
];
2398 // note that contact object not always has required greeting related
2399 // fields that are required to calculate greeting and
2400 // also other fields used in tokens etc,
2401 // hence we need to retrieve it again.
2402 $contact->find(TRUE);
2404 // store object values to an array
2405 $contactDetails = array();
2406 CRM_Core_DAO
::storeValues($contact, $contactDetails);
2407 $contactDetails = array(array($contact->id
=> $contactDetails));
2409 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2410 $updateQueryString = array();
2412 //cache email and postal greeting to greeting display
2413 if ($contact->email_greeting_custom
!= 'null' && $contact->email_greeting_custom
) {
2414 $emailGreetingString = $contact->email_greeting_custom
;
2416 elseif ($contact->email_greeting_id
!= 'null' && $contact->email_greeting_id
) {
2417 // the filter value for Individual contact type is set to 1
2419 'contact_type' => $contact->contact_type
,
2420 'greeting_type' => 'email_greeting',
2423 $emailGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2424 $emailGreetingString = $emailGreeting[$contact->email_greeting_id
];
2425 $updateQueryString[] = " email_greeting_custom = NULL ";
2429 reset($contactDefaults['email_greeting']);
2430 $emailGreetingID = key($contactDefaults['email_greeting']);
2431 $emailGreetingString = $contactDefaults['email_greeting'][$emailGreetingID];
2432 $updateQueryString[] = " email_greeting_id = $emailGreetingID ";
2433 $updateQueryString[] = " email_greeting_custom = NULL ";
2435 elseif ($contact->email_greeting_custom
) {
2436 $updateQueryString[] = " email_greeting_display = NULL ";
2440 if ($emailGreetingString) {
2441 CRM_Utils_Token
::replaceGreetingTokens($emailGreetingString,
2444 'CRM_Contact_BAO_Contact'
2446 $emailGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($emailGreetingString));
2447 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2451 if ($contact->postal_greeting_custom
!= 'null' && $contact->postal_greeting_custom
) {
2452 $postalGreetingString = $contact->postal_greeting_custom
;
2454 elseif ($contact->postal_greeting_id
!= 'null' && $contact->postal_greeting_id
) {
2456 'contact_type' => $contact->contact_type
,
2457 'greeting_type' => 'postal_greeting',
2459 $postalGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2460 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id
];
2461 $updateQueryString[] = " postal_greeting_custom = NULL ";
2465 reset($contactDefaults['postal_greeting']);
2466 $postalGreetingID = key($contactDefaults['postal_greeting']);
2467 $postalGreetingString = $contactDefaults['postal_greeting'][$postalGreetingID];
2468 $updateQueryString[] = " postal_greeting_id = $postalGreetingID ";
2469 $updateQueryString[] = " postal_greeting_custom = NULL ";
2471 elseif ($contact->postal_greeting_custom
) {
2472 $updateQueryString[] = " postal_greeting_display = NULL ";
2476 if ($postalGreetingString) {
2477 CRM_Utils_Token
::replaceGreetingTokens($postalGreetingString,
2480 'CRM_Contact_BAO_Contact'
2482 $postalGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($postalGreetingString));
2483 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2487 if ($contact->addressee_custom
!= 'null' && $contact->addressee_custom
) {
2488 $addresseeString = $contact->addressee_custom
;
2490 elseif ($contact->addressee_id
!= 'null' && $contact->addressee_id
) {
2492 'contact_type' => $contact->contact_type
,
2493 'greeting_type' => 'addressee',
2496 $addressee = CRM_Core_PseudoConstant
::greeting($filter);
2497 $addresseeString = $addressee[$contact->addressee_id
];
2498 $updateQueryString[] = " addressee_custom = NULL ";
2502 reset($contactDefaults['addressee']);
2503 $addresseeID = key($contactDefaults['addressee']);
2504 $addresseeString = $contactDefaults['addressee'][$addresseeID];
2505 $updateQueryString[] = " addressee_id = $addresseeID ";
2506 $updateQueryString[] = " addressee_custom = NULL ";
2508 elseif ($contact->addressee_custom
) {
2509 $updateQueryString[] = " addressee_display = NULL ";
2513 if ($addresseeString) {
2514 CRM_Utils_Token
::replaceGreetingTokens($addresseeString,
2517 'CRM_Contact_BAO_Contact'
2519 $addresseeString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($addresseeString));
2520 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2523 if (!empty($updateQueryString)) {
2524 $updateQueryString = implode(',', $updateQueryString);
2525 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2526 CRM_Core_DAO
::executeQuery($queryString);
2531 * Function to retrieve loc block ids w/ given condition.
2533 * @param int $contactId contact id.
2534 * @param array $criteria key => value pair which should be
2535 * fulfill by return record ids.
2536 * @param string $condOperator operator use for grouping multiple conditions.
2538 * @return array $locBlockIds loc block ids which fulfill condition.
2541 static function getLocBlockIds($contactId, $criteria = array(
2542 ), $condOperator = 'AND') {
2543 $locBlockIds = array();
2545 return $locBlockIds;
2549 'Email', 'OpenID', 'Phone', 'Address', 'IM') as $block) {
2550 $name = strtolower($block);
2551 eval("\$blockDAO = new CRM_Core_DAO_$block();");
2553 // build the condition.
2554 if (is_array($criteria)) {
2555 eval('$object = new CRM_Core_DAO_' . $block . '( );');
2556 $fields = $object->fields();
2557 $conditions = array();
2558 foreach ($criteria as $field => $value) {
2559 if (array_key_exists($field, $fields)) {
2560 $cond = "( $field = $value )";
2561 // value might be zero or null.
2562 if (!$value ||
strtolower($value) == 'null') {
2563 $cond = "( $field = 0 OR $field IS NULL )";
2565 $conditions[] = $cond;
2568 if (!empty($conditions)) {
2569 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2573 $blockDAO->contact_id
= $contactId;
2575 while ($blockDAO->fetch()) {
2576 $locBlockIds[$name][] = $blockDAO->id
;
2581 return $locBlockIds;
2585 * Function to build context menu items.
2587 * @return array of context menu for logged in user.
2590 static function contextMenu($contactId = NULL) {
2592 'view' => array('title' => ts('View Contact'),
2594 'ref' => 'view-contact',
2596 'permissions' => array('view all contacts'),
2598 'add' => array('title' => ts('Edit Contact'),
2600 'ref' => 'edit-contact',
2602 'permissions' => array('edit all contacts'),
2604 'delete' => array('title' => ts('Delete Contact'),
2606 'ref' => 'delete-contact',
2608 'permissions' => array('access deleted contacts', 'delete contacts'),
2610 'contribution' => array('title' => ts('Add Contribution'),
2612 'ref' => 'new-contribution',
2613 'key' => 'contribution',
2614 'component' => 'CiviContribute',
2615 'href' => CRM_Utils_System
::url('civicrm/contact/view/contribution',
2616 'reset=1&action=add&context=contribution'
2618 'permissions' => array(
2619 'access CiviContribute',
2620 'edit contributions',
2623 'participant' => array('title' => ts('Register for Event'),
2625 'ref' => 'new-participant',
2626 'key' => 'participant',
2627 'component' => 'CiviEvent',
2628 'href' => CRM_Utils_System
::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
2629 'permissions' => array(
2631 'edit event participants',
2634 'activity' => array('title' => ts('Record Activity'),
2636 'ref' => 'new-activity',
2637 'key' => 'activity',
2638 'permissions' => array('edit all contacts'),
2640 'pledge' => array('title' => ts('Add Pledge'),
2642 'ref' => 'new-pledge',
2644 'href' => CRM_Utils_System
::url('civicrm/contact/view/pledge',
2645 'reset=1&action=add&context=pledge'
2647 'component' => 'CiviPledge',
2648 'permissions' => array(
2649 'access CiviPledge',
2653 'membership' => array('title' => ts('Add Membership'),
2655 'ref' => 'new-membership',
2656 'key' => 'membership',
2657 'component' => 'CiviMember',
2658 'href' => CRM_Utils_System
::url('civicrm/contact/view/membership',
2659 'reset=1&action=add&context=membership'
2661 'permissions' => array(
2662 'access CiviMember',
2666 'case' => array('title' => ts('Add Case'),
2668 'ref' => 'new-case',
2670 'component' => 'CiviCase',
2671 'href' => CRM_Utils_System
::url('civicrm/case/add', 'reset=1&action=add&context=case'),
2672 'permissions' => array('add cases'),
2674 'grant' => array('title' => ts('Add Grant'),
2676 'ref' => 'new-grant',
2678 'component' => 'CiviGrant',
2679 'href' => CRM_Utils_System
::url('civicrm/contact/view/grant',
2680 'reset=1&action=add&context=grant'
2682 'permissions' => array('edit grants'),
2684 'rel' => array('title' => ts('Add Relationship'),
2686 'ref' => 'new-relationship',
2688 'href' => CRM_Utils_System
::url('civicrm/contact/view/rel',
2689 'reset=1&action=add'
2691 'permissions' => array('edit all contacts'),
2693 'note' => array('title' => ts('Add Note'),
2695 'ref' => 'new-note',
2697 'href' => CRM_Utils_System
::url('civicrm/contact/view/note',
2698 'reset=1&action=add'
2700 'permissions' => array('edit all contacts'),
2702 'email' => array('title' => ts('Send an Email'),
2704 'ref' => 'new-email',
2706 'permissions' => array('view all contacts'),
2708 'group' => array('title' => ts('Add to Group'),
2710 'ref' => 'group-add-contact',
2712 'permissions' => array('edit groups'),
2714 'tag' => array('title' => ts('Tag'),
2716 'ref' => 'tag-contact',
2718 'permissions' => array('edit all contacts'),
2722 CRM_Utils_Hook
::summaryActions($menu, $contactId);
2723 //1. check for component is active.
2724 //2. check for user permissions.
2725 //3. check for acls.
2726 //3. edit and view contact are directly accessible to user.
2728 $aclPermissionedTasks = array(
2729 'view-contact', 'edit-contact', 'new-activity',
2730 'new-email', 'group-add-contact', 'tag-contact', 'delete-contact',
2732 $corePermission = CRM_Core_Permission
::getPermission();
2734 $config = CRM_Core_Config
::singleton();
2736 $contextMenu = array();
2737 foreach ($menu as $key => $values) {
2738 $componentName = CRM_Utils_Array
::value('component', $values);
2740 // if component action - make sure component is enable.
2741 if ($componentName && !in_array($componentName, $config->enableComponents
)) {
2745 // make sure user has all required permissions.
2746 $hasAllPermissions = FALSE;
2748 $permissions = CRM_Utils_Array
::value('permissions', $values);
2749 if (!is_array($permissions) ||
empty($permissions)) {
2750 $hasAllPermissions = TRUE;
2753 // iterate for required permissions in given permissions array.
2754 if (!$hasAllPermissions) {
2755 $hasPermissions = 0;
2756 foreach ($permissions as $permission) {
2757 if (CRM_Core_Permission
::check($permission)) {
2762 if (count($permissions) == $hasPermissions) {
2763 $hasAllPermissions = TRUE;
2766 // if still user does not have required permissions, check acl.
2767 if (!$hasAllPermissions && $values['ref'] != 'delete-contact') {
2768 if (in_array($values['ref'], $aclPermissionedTasks) &&
2769 $corePermission == CRM_Core_Permission
::EDIT
2771 $hasAllPermissions = TRUE;
2773 elseif (in_array($values['ref'], array(
2775 // grant permissions for these tasks.
2776 $hasAllPermissions = TRUE;
2781 // user does not have necessary permissions.
2782 if (!$hasAllPermissions) {
2786 // build directly accessible action menu.
2787 if (in_array($values['ref'], array(
2788 'view-contact', 'edit-contact'))) {
2789 $contextMenu['primaryActions'][$key] = array(
2790 'title' => $values['title'],
2791 'ref' => $values['ref'],
2792 'key' => $values['key'],
2797 // finally get menu item for -more- action widget.
2798 $contextMenu['moreActions'][$values['weight']] = array(
2799 'title' => $values['title'],
2800 'ref' => $values['ref'],
2801 'href' => CRM_Utils_Array
::value('href', $values),
2802 'key' => $values['key'],
2806 ksort($contextMenu['moreActions']);
2808 return $contextMenu;
2812 * Function to retrieve display name of contact that address is shared
2813 * based on $masterAddressId or $contactId .
2815 * @param int $masterAddressId master id.
2816 * @param int $contactId contact id.
2818 * @return display name |null the found display name or null.
2822 static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
2823 $masterDisplayName = NULL;
2825 if (!$masterAddressId && !$contactId) {
2826 return $masterDisplayName;
2829 if ($masterAddressId) {
2831 SELECT display_name from civicrm_contact
2832 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
2833 WHERE civicrm_address.id = " . $masterAddressId;
2835 elseif ($contactId) {
2837 SELECT display_name from civicrm_contact cc, civicrm_address add1
2838 LEFT JOIN civicrm_address add2 ON ( add1.master_id = add2.id )
2839 WHERE cc.id = add2.contact_id AND add1.contact_id = " . $contactId;
2842 $masterDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
2843 return $masterDisplayName;
2847 * Get the creation/modification times for a contact
2849 * @return array('created_date' => $, 'modified_date' => $)
2851 static function getTimestamps($contactId) {
2852 $timestamps = CRM_Core_DAO
::executeQuery(
2853 'SELECT created_date, modified_date
2854 FROM civicrm_contact
2857 1 => array($contactId, 'Integer'),
2860 if ($timestamps->fetch()) {
2862 'created_date' => $timestamps->created_date
,
2863 'modified_date' => $timestamps->modified_date
,
2872 * Get a list of triggers for the contact table
2874 * @see hook_civicrm_triggerInfo
2875 * @see CRM_Core_DAO::triggerRebuild
2876 * @see http://issues.civicrm.org/jira/browse/CRM-10554
2878 static function triggerInfo(&$info, $tableName = NULL) {
2879 //during upgrade, first check for valid version and then create triggers
2880 //i.e the columns created_date and modified_date are introduced in 4.3.alpha1 so dont create triggers for older version
2881 if (CRM_Core_Config
::isUpgradeMode()) {
2882 $currentVer = CRM_Core_BAO_Domain
::version(TRUE);
2883 //if current version is less than 4.3.alpha1 dont create below triggers
2884 if (version_compare($currentVer, '4.3.alpha1') < 0) {
2889 if ($tableName == NULL ||
$tableName == self
::getTableName()) {
2891 'table' => array(self
::getTableName()),
2893 'event' => array('INSERT'),
2894 'sql' => "\nSET NEW.created_date = CURRENT_TIMESTAMP;\n",
2898 // Update timestamp when modifying closely related core tables
2899 $relatedTables = array(
2907 'table' => $relatedTables,
2909 'event' => array('INSERT', 'UPDATE'),
2910 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = NEW.contact_id;\n",
2913 'table' => $relatedTables,
2915 'event' => array('DELETE'),
2916 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = OLD.contact_id;\n",
2919 // Update timestamp when modifying related custom-data tables
2920 $customGroupTables = array();
2921 $customGroupDAO = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity('Contact');
2922 $customGroupDAO->is_multiple
= 0;
2923 $customGroupDAO->find();
2924 while ($customGroupDAO->fetch()) {
2925 $customGroupTables[] = $customGroupDAO->table_name
;
2927 if (!empty($customGroupTables)) {
2929 'table' => $customGroupTables,
2931 'event' => array('INSERT', 'UPDATE'),
2932 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = NEW.entity_id;\n",
2935 'table' => $customGroupTables,
2937 'event' => array('DELETE'),
2938 'sql' => "\nUPDATE civicrm_contact SET modified_date = CURRENT_TIMESTAMP WHERE id = OLD.entity_id;\n",
2942 // Update phone table to populate phone_numeric field
2943 if (!$tableName ||
$tableName == 'civicrm_phone') {
2944 // Define stored sql function needed for phones
2945 CRM_Core_DAO
::executeQuery(self
::DROP_STRIP_FUNCTION_43
);
2946 CRM_Core_DAO
::executeQuery(self
::CREATE_STRIP_FUNCTION_43
);
2948 'table' => array('civicrm_phone'),
2950 'event' => array('INSERT', 'UPDATE'),
2951 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
2957 * Function to check if contact is being used in civicrm_domain
2958 * based on $contactId
2960 * @param int $contactId contact id.
2962 * @return true if present else false.
2966 static function checkDomainContact($contactId) {
2969 $domainId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
2980 * Delete a contact-related object that has an 'is_primary' field
2981 * Ensures that is_primary gets assigned to another object if available
2982 * Also calls pre/post hooks
2984 * @var $type: object type
2985 * @var $id: object id
2987 public static function deleteObjectWithPrimary($type, $id) {
2988 if (!$id ||
!is_numeric($id)) {
2991 $daoName = "CRM_Core_DAO_$type";
2992 $obj = new $daoName();
2995 if ($obj->fetch()) {
2996 CRM_Utils_Hook
::pre('delete', $type, $id, CRM_Core_DAO
::$_nullArray);
2997 $contactId = $obj->contact_id
;
3003 $dao = new $daoName();
3004 $dao->contact_id
= $contactId;
3005 $dao->is_primary
= 1;
3006 // Pick another record to be primary (if one isn't already)
3007 if (!$dao->find(TRUE)) {
3008 $dao->is_primary
= 0;
3010 if ($dao->fetch()) {
3011 $dao->is_primary
= 1;
3016 CRM_Utils_Hook
::post('delete', $type, $id, $obj);