3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
35 class CRM_Contact_BAO_Contact_Utils
{
38 * Given a contact type, get the contact image
40 * @param string $contactType
42 * @param bool $urlOnly
43 * If we need to return only image url.
44 * @param int $contactId
46 * @param bool $addProfileOverlay
47 * If profile overlay class should be added.
51 public static function getImage($contactType, $urlOnly = FALSE, $contactId = NULL, $addProfileOverlay = TRUE) {
52 static $imageInfo = array();
54 $contactType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($contactType, CRM_Core_DAO
::VALUE_SEPARATOR
));
55 $contactType = $contactType[0];
57 if (!array_key_exists($contactType, $imageInfo)) {
58 $imageInfo[$contactType] = array();
61 $params = array('name' => $contactType);
62 CRM_Contact_BAO_ContactType
::retrieve($params, $typeInfo);
64 if (!empty($typeInfo['image_URL'])) {
65 $imageUrl = $typeInfo['image_URL'];
66 $config = CRM_Core_Config
::singleton();
68 if (!preg_match("/^(\/|(http(s)?:)).+$/i", $imageUrl)) {
69 $imageUrl = $config->resourceBase
. $imageUrl;
71 $imageInfo[$contactType]['image'] = "<div class=\"icon crm-icon {$typeInfo['name']}-icon\" style=\"background: url('{$imageUrl}')\" title=\"{$contactType}\"></div>";
72 $imageInfo[$contactType]['url'] = $imageUrl;
75 $isSubtype = (array_key_exists('parent_id', $typeInfo) &&
76 $typeInfo['parent_id']
80 $type = CRM_Contact_BAO_ContactType
::getBasicType($typeInfo['name']) . '-subtype';
83 $type = CRM_Utils_Array
::value('name', $typeInfo);
86 // do not add title since it hides contact name
87 if ($addProfileOverlay) {
88 $imageInfo[$contactType]['image'] = "<div class=\"icon crm-icon {$type}-icon\"></div>";
91 $imageInfo[$contactType]['image'] = "<div class=\"icon crm-icon {$type}-icon\" title=\"{$contactType}\"></div>";
93 $imageInfo[$contactType]['url'] = NULL;
97 if ($addProfileOverlay) {
98 static $summaryOverlayProfileId = NULL;
99 if (!$summaryOverlayProfileId) {
100 $summaryOverlayProfileId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', 'summary_overlay', 'id', 'name');
103 $profileURL = CRM_Utils_System
::url('civicrm/profile/view',
104 "reset=1&gid={$summaryOverlayProfileId}&id={$contactId}&snippet=4"
107 $imageInfo[$contactType]['summary-link'] = '<a href="' . $profileURL . '" class="crm-summary-link">' . $imageInfo[$contactType]['image'] . '</a>';
110 $imageInfo[$contactType]['summary-link'] = $imageInfo[$contactType]['image'];
113 return $urlOnly ?
$imageInfo[$contactType]['url'] : $imageInfo[$contactType]['summary-link'];
117 * Function check for mix contact ids(individual+household etc...)
119 * @param array $contactIds
120 * Array of contact ids.
123 * true if mix contact array else false
126 public static function checkContactType(&$contactIds) {
127 if (empty($contactIds)) {
131 $idString = implode(',', $contactIds);
133 SELECT count( DISTINCT contact_type )
135 WHERE id IN ( $idString )
137 $count = CRM_Core_DAO
::singleValueQuery($query,
138 CRM_Core_DAO
::$_nullArray
140 return $count > 1 ?
TRUE : FALSE;
144 * Generate a checksum for a $entityId of type $entityType
146 * @param int $entityId
148 * Timestamp that checksum was generated.
150 * Life of this checksum in hours/ 'inf' for infinite.
151 * @param string $hash
152 * Contact hash, if sent, prevents a query in inner loop.
154 * @param string $entityType
155 * @param null $hashSize
158 * ( $cs, $ts, $live )
160 public static function generateChecksum($entityId, $ts = NULL, $live = NULL, $hash = NULL, $entityType = 'contact', $hashSize = NULL) {
161 // return a warning message if we dont get a entityId
162 // this typically happens when we do a message preview
163 // or an anon mailing view - CRM-8298
165 return 'invalidChecksum';
169 if ($entityType == 'contact') {
170 $hash = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
174 elseif ($entityType == 'mailing') {
175 $hash = CRM_Core_DAO
::getFieldValue('CRM_Mailing_DAO_Mailing',
182 $hash = md5(uniqid(rand(), TRUE));
184 $hash = substr($hash, 0, $hashSize);
187 if ($entityType == 'contact') {
188 CRM_Core_DAO
::setFieldValue('CRM_Contact_DAO_Contact',
193 elseif ($entityType == 'mailing') {
194 CRM_Core_DAO
::setFieldValue('CRM_Mailing_DAO_Mailing',
206 $days = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
214 $cs = md5("{$hash}_{$entityId}_{$ts}_{$live}");
215 return "{$cs}_{$ts}_{$live}";
219 * Make sure the checksum is valid for the passed in contactID.
221 * @param int $contactID
222 * @param string $inputCheck
223 * Checksum to match against.
226 * true if valid, else false
228 public static function validChecksum($contactID, $inputCheck) {
230 $input = CRM_Utils_System
::explode('_', $inputCheck, 3);
232 $inputCS = CRM_Utils_Array
::value(0, $input);
233 $inputTS = CRM_Utils_Array
::value(1, $input);
234 $inputLF = CRM_Utils_Array
::value(2, $input);
236 $check = self
::generateChecksum($contactID, $inputTS, $inputLF);
238 if ($check != $inputCheck) {
242 // no life limit for checksum
243 if ($inputLF == 'inf') {
247 // checksum matches so now check timestamp
249 return ($inputTS +
($inputLF * 60 * 60) >= $now);
253 * Get the count of contact loctions.
255 * @param int $contactId
259 * max locations for the contact
261 public static function maxLocations($contactId) {
262 $contactLocations = array();
264 // find number of location blocks for this contact and adjust value accordinly
265 // get location type from email
267 ( SELECT location_type_id FROM civicrm_email WHERE contact_id = {$contactId} )
269 ( SELECT location_type_id FROM civicrm_phone WHERE contact_id = {$contactId} )
271 ( SELECT location_type_id FROM civicrm_im WHERE contact_id = {$contactId} )
273 ( SELECT location_type_id FROM civicrm_address WHERE contact_id = {$contactId} )
275 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
280 * Create Current employer relationship for a individual.
282 * @param int $contactID
283 * Contact id of the individual.
284 * @param $organization
286 * @param int $previousEmployerID
287 * @param bool $newContact
290 public static function createCurrentEmployerRelationship($contactID, $organization, $previousEmployerID = NULL, $newContact = FALSE) {
291 //if organization name is passed. CRM-15368,CRM-15547
292 if ($organization && !is_numeric($organization)) {
293 $organizationParams['organization_name'] = $organization;
294 $dedupeParams = CRM_Dedupe_Finder
::formatParams($organizationParams, 'Organization');
296 $dedupeParams['check_permission'] = FALSE;
297 $dupeIDs = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, 'Organization', 'Unsupervised');
299 if (is_array($dupeIDs) && !empty($dupeIDs)) {
300 // we should create relationship only w/ first org CRM-4193
301 foreach ($dupeIDs as $orgId) {
302 $organization = $orgId;
307 //create new organization
309 'contact_type' => 'Organization',
310 'organization_name' => $organization,
312 $org = CRM_Contact_BAO_Contact
::create($newOrg);
313 $organization = $org->id
;
317 if ($organization && is_numeric($organization)) {
318 $cid = array('contact' => $contactID);
320 // get the relationship type id of "Employee of"
321 $relTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType', 'Employee of', 'id', 'name_a_b');
323 CRM_Core_Error
::fatal(ts("You seem to have deleted the relationship type 'Employee of'"));
326 // create employee of relationship
327 $relationshipParams = array(
329 'relationship_type_id' => $relTypeId . '_a_b',
330 'contact_check' => array($organization => TRUE),
332 list($valid, $invalid, $duplicate, $saved, $relationshipIds)
333 = CRM_Contact_BAO_Relationship
::createMultiple($relationshipParams, $cid);
335 // In case we change employer, clean previous employer related records.
336 if (!$previousEmployerID && !$newContact) {
337 $previousEmployerID = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id');
339 if ($previousEmployerID &&
340 $previousEmployerID != $organization
342 self
::clearCurrentEmployer($contactID, $previousEmployerID);
345 // set current employer
346 self
::setCurrentEmployer(array($contactID => $organization));
348 $relationshipParams['relationship_ids'] = $relationshipIds;
349 // handle related meberships. CRM-3792
350 self
::currentEmployerRelatedMembership($contactID, $organization, $relationshipParams, $duplicate, $previousEmployerID);
355 * Create related memberships for current employer.
357 * @param int $contactID
358 * Contact id of the individual.
359 * @param int $employerID
360 * Contact id of the organization.
361 * @param array $relationshipParams
362 * Relationship params.
363 * @param bool $duplicate
364 * Are we triggered existing relationship.
366 * @param int $previousEmpID
368 * @throws CiviCRM_API3_Exception
370 public static function currentEmployerRelatedMembership($contactID, $employerID, $relationshipParams, $duplicate = FALSE, $previousEmpID = NULL) {
372 $action = CRM_Core_Action
::ADD
;
374 //we do not know that triggered relationship record is active.
376 $relationship = new CRM_Contact_DAO_Relationship();
377 $relationship->contact_id_a
= $contactID;
378 $relationship->contact_id_b
= $employerID;
379 $relationship->relationship_type_id
= $relationshipParams['relationship_type_id'];
380 if ($relationship->find(TRUE)) {
381 $action = CRM_Core_Action
::UPDATE
;
382 $ids['contact'] = $contactID;
383 $ids['contactTarget'] = $employerID;
384 $ids['relationship'] = $relationship->id
;
385 CRM_Contact_BAO_Relationship
::setIsActive($relationship->id
, TRUE);
387 $relationship->free();
390 //need to handle related meberships. CRM-3792
391 if ($previousEmpID != $employerID) {
392 CRM_Contact_BAO_Relationship
::relatedMemberships($contactID, $relationshipParams, $ids, $action);
397 * Set current employer id and organization name.
399 * @param array $currentEmployerParams
400 * Associated array of contact id and its employer id.
402 public static function setCurrentEmployer($currentEmployerParams) {
403 foreach ($currentEmployerParams as $contactId => $orgId) {
404 $query = "UPDATE civicrm_contact contact_a,civicrm_contact contact_b
405 SET contact_a.employer_id=contact_b.id, contact_a.organization_name=contact_b.organization_name
406 WHERE contact_a.id ={$contactId} AND contact_b.id={$orgId}; ";
408 //FIXME : currently civicrm mysql_query support only single statement
409 //execution, though mysql 5.0 support multiple statement execution.
410 $dao = CRM_Core_DAO
::executeQuery($query);
415 * Update cached current employer name.
417 * @param int $organizationId
418 * Current employer id.
420 public static function updateCurrentEmployer($organizationId) {
421 $query = "UPDATE civicrm_contact contact_a,civicrm_contact contact_b
422 SET contact_a.organization_name=contact_b.organization_name
423 WHERE contact_a.employer_id=contact_b.id AND contact_b.id={$organizationId}; ";
425 $dao = CRM_Core_DAO
::executeQuery($query);
429 * Clear cached current employer name.
431 * @param int $contactId
432 * Contact id ( mostly individual contact id).
433 * @param int $employerId
434 * Contact id ( mostly organization contact id).
436 public static function clearCurrentEmployer($contactId, $employerId = NULL) {
437 $query = "UPDATE civicrm_contact
438 SET organization_name=NULL, employer_id = NULL
439 WHERE id={$contactId}; ";
441 $dao = CRM_Core_DAO
::executeQuery($query);
443 // need to handle related meberships. CRM-3792
445 //1. disable corresponding relationship.
446 //2. delete related membership.
448 //get the relationship type id of "Employee of"
449 $relTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType', 'Employee of', 'id', 'name_a_b');
451 CRM_Core_Error
::fatal(ts("You seem to have deleted the relationship type 'Employee of'"));
453 $relMembershipParams['relationship_type_id'] = $relTypeId . '_a_b';
454 $relMembershipParams['contact_check'][$employerId] = 1;
456 //get relationship id.
457 if (CRM_Contact_BAO_Relationship
::checkDuplicateRelationship($relMembershipParams, $contactId, $employerId)) {
458 $relationship = new CRM_Contact_DAO_Relationship();
459 $relationship->contact_id_a
= $contactId;
460 $relationship->contact_id_b
= $employerId;
461 $relationship->relationship_type_id
= $relTypeId;
463 if ($relationship->find(TRUE)) {
464 CRM_Contact_BAO_Relationship
::setIsActive($relationship->id
, FALSE);
465 CRM_Contact_BAO_Relationship
::relatedMemberships($contactId, $relMembershipParams,
467 CRM_Core_Action
::DELETE
470 $relationship->free();
476 * Build form for related contacts / on behalf of organization.
478 * @param CRM_Core_Form $form
479 * @param string $contactType
481 * @param int $countryID
482 * @param int $stateID
483 * @param string $title
487 public static function buildOnBehalfForm(&$form, $contactType, $countryID, $stateID, $title) {
489 $config = CRM_Core_Config
::singleton();
491 $form->assign('contact_type', $contactType);
492 $form->assign('fieldSetTitle', $title);
493 $form->assign('contactEditMode', TRUE);
495 $attributes = CRM_Core_DAO
::getAttribute('CRM_Contact_DAO_Contact');
496 if ($form->_contactId
) {
497 $form->assign('orgId', $form->_contactId
);
500 switch ($contactType) {
502 $form->add('text', 'organization_name', ts('Organization Name'), $attributes['organization_name'], TRUE);
506 $form->add('text', 'household_name', ts('Household Name'), $attributes['household_name']);
511 $form->addElement('select', 'prefix_id', ts('Prefix'),
512 array('' => ts('- prefix -')) + CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id')
514 $form->addElement('text', 'first_name', ts('First Name'),
515 $attributes['first_name']
517 $form->addElement('text', 'middle_name', ts('Middle Name'),
518 $attributes['middle_name']
520 $form->addElement('text', 'last_name', ts('Last Name'),
521 $attributes['last_name']
523 $form->addElement('select', 'suffix_id', ts('Suffix'),
524 array('' => ts('- suffix -')) + CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'suffix_id')
528 $addressSequence = $config->addressSequence();
529 $form->assign('addressSequence', array_fill_keys($addressSequence, 1));
532 $form->addElement('text',
535 CRM_Core_DAO
::getAttribute('CRM_Core_DAO_Phone',
540 $form->addElement('text',
543 CRM_Core_DAO
::getAttribute('CRM_Core_DAO_Email',
547 //build the address block
548 CRM_Contact_Form_Edit_Address
::buildQuickForm($form);
552 * Clear cache employer name and employer id
553 * of all employee when employer get deleted.
555 * @param int $employerId
556 * Contact id of employer ( organization id ).
558 public static function clearAllEmployee($employerId) {
560 UPDATE civicrm_contact
561 SET organization_name=NULL, employer_id = NULL
562 WHERE employer_id={$employerId}; ";
564 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
568 * Given an array of contact ids this function will return array with links to view contact page.
570 * @param array $contactIDs
571 * Associated contact id's.
572 * @param bool $addViewLink
573 * @param bool $addEditLink
574 * @param int $originalId
575 * Associated with the contact which is edited.
579 * returns array with links to contact view
581 public static function formatContactIDSToLinks($contactIDs, $addViewLink = TRUE, $addEditLink = TRUE, $originalId = NULL) {
582 $contactLinks = array();
583 if (!is_array($contactIDs) ||
empty($contactIDs)) {
584 return $contactLinks;
587 // does contact has sufficient permissions.
588 $permissions = array(
589 'view' => 'view all contacts',
590 'edit' => 'edit all contacts',
591 'merge' => 'merge duplicate contacts',
594 $permissionedContactIds = array();
595 foreach ($permissions as $task => $permission) {
597 if (CRM_Core_Permission
::check($permission)) {
598 foreach ($contactIDs as $contactId) {
599 $permissionedContactIds[$contactId][$task] = TRUE;
604 // check permission on acl basis.
605 if (in_array($task, array(
609 $aclPermission = CRM_Core_Permission
::VIEW
;
610 if ($task == 'edit') {
611 $aclPermission = CRM_Core_Permission
::EDIT
;
613 foreach ($contactIDs as $contactId) {
614 if (CRM_Contact_BAO_Contact_Permission
::allow($contactId, $aclPermission)) {
615 $permissionedContactIds[$contactId][$task] = TRUE;
621 // retrieve display names for all contacts
623 SELECT c.id, c.display_name, c.contact_type, ce.email
624 FROM civicrm_contact c
625 LEFT JOIN civicrm_email ce ON ( ce.contact_id=c.id AND ce.is_primary = 1 )
626 WHERE c.id IN (' . implode(',', $contactIDs) . ' ) LIMIT 20';
628 $dao = CRM_Core_DAO
::executeQuery($query);
630 $contactLinks['msg'] = NULL;
632 while ($dao->fetch()) {
634 $contactLinks['rows'][$i]['display_name'] = $dao->display_name
;
635 $contactLinks['rows'][$i]['primary_email'] = $dao->email
;
637 // get the permission for current contact id.
638 $hasPermissions = CRM_Utils_Array
::value($dao->id
, $permissionedContactIds);
639 if (!is_array($hasPermissions) ||
empty($hasPermissions)) {
644 // do check for view.
645 if (array_key_exists('view', $hasPermissions)) {
646 $contactLinks['rows'][$i]['view'] = '<a class="action-item" href="' . CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&cid=' . $dao->id
) . '" target="_blank">' . ts('View') . '</a>';
647 if (!$contactLinks['msg']) {
648 $contactLinks['msg'] = 'view';
651 if (array_key_exists('edit', $hasPermissions)) {
652 $contactLinks['rows'][$i]['edit'] = '<a class="action-item" href="' . CRM_Utils_System
::url('civicrm/contact/add', 'reset=1&action=update&cid=' . $dao->id
) . '" target="_blank">' . ts('Edit') . '</a>';
653 if (!$contactLinks['msg'] ||
$contactLinks['msg'] != 'merge') {
654 $contactLinks['msg'] = 'edit';
657 if (!empty($originalId) && array_key_exists('merge', $hasPermissions)) {
658 $rgBao = new CRM_Dedupe_BAO_RuleGroup();
659 $rgBao->contact_type
= $dao->contact_type
;
660 $rgBao->used
= 'Supervised';
661 if ($rgBao->find(TRUE)) {
664 if ($rgid && isset($dao->id
)) {
665 //get an url to merge the contact
666 $contactLinks['rows'][$i]['merge'] = '<a class="action-item" href="' . CRM_Utils_System
::url('civicrm/contact/merge', "reset=1&cid=" . $originalId . '&oid=' . $dao->id
. '&action=update&rgid=' . $rgid) . '">' . ts('Merge') . '</a>';
667 $contactLinks['msg'] = 'merge';
674 return $contactLinks;
678 * This function retrieve component related contact information.
680 * @param array $componentIds
681 * Array of component Ids.
682 * @param string $componentName
683 * @param array $returnProperties
684 * Array of return elements.
687 * array of contact info.
689 public static function contactDetails($componentIds, $componentName, $returnProperties = array()) {
690 $contactDetails = array();
691 if (empty($componentIds) ||
692 !in_array($componentName, array('CiviContribute', 'CiviMember', 'CiviEvent', 'Activity'))
694 return $contactDetails;
697 if (empty($returnProperties)) {
698 $autocompleteContactSearch = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
699 'contact_autocomplete_options'
701 $returnProperties = array_fill_keys(array_merge(array('sort_name'),
702 array_keys($autocompleteContactSearch)
707 if ($componentName == 'CiviContribute') {
708 $compTable = 'civicrm_contribution';
710 elseif ($componentName == 'CiviMember') {
711 $compTable = 'civicrm_membership';
713 elseif ($componentName == 'Activity') {
714 $compTable = 'civicrm_activity';
715 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
718 $compTable = 'civicrm_participant';
721 $select = $from = array();
722 foreach ($returnProperties as $property => $ignore) {
723 $value = (in_array($property, array(
726 ))) ?
'address' : $property;
729 if ($componentName == 'Activity') {
730 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
731 $select[] = "contact.$property as $property";
733 INNER JOIN civicrm_activity_contact acs ON (acs.activity_id = {$compTable}.id AND acs.record_type_id = {$sourceID})
734 INNER JOIN civicrm_contact contact ON ( contact.id = acs.contact_id )";
737 $select[] = "$property as $property";
738 $from[$value] = "INNER JOIN civicrm_contact contact ON ( contact.id = $compTable.contact_id )";
742 case 'target_sort_name':
743 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
744 $select[] = "contact_target.sort_name as $property";
746 INNER JOIN civicrm_activity_contact act ON (act.activity_id = {$compTable}.id AND act.record_type_id = {$targetID})
747 INNER JOIN civicrm_contact contact_target ON ( contact_target.id = act.contact_id )";
753 case 'street_address':
754 $select[] = "$property as $property";
755 // Grab target contact properties if this is for activity
756 if ($componentName == 'Activity') {
757 $from[$value] = "LEFT JOIN civicrm_{$value} {$value} ON ( contact_target.id = {$value}.contact_id AND {$value}.is_primary = 1 ) ";
760 $from[$value] = "LEFT JOIN civicrm_{$value} {$value} ON ( contact.id = {$value}.contact_id AND {$value}.is_primary = 1 ) ";
765 case 'state_province':
766 $select[] = "{$property}.name as $property";
767 if (!in_array('address', $from)) {
768 // Grab target contact properties if this is for activity
769 if ($componentName == 'Activity') {
770 $from['address'] = 'LEFT JOIN civicrm_address address ON ( contact_target.id = address.contact_id AND address.is_primary = 1) ';
773 $from['address'] = 'LEFT JOIN civicrm_address address ON ( contact.id = address.contact_id AND address.is_primary = 1) ';
776 $from[$value] = " LEFT JOIN civicrm_{$value} {$value} ON ( address.{$value}_id = {$value}.id ) ";
781 //finally retrieve contact details.
782 if (!empty($select) && !empty($from)) {
783 $fromClause = implode(' ', $from);
784 $selectClause = implode(', ', $select);
785 $whereClause = "{$compTable}.id IN (" . implode(',', $componentIds) . ')';
788 SELECT contact.id as contactId, $compTable.id as componentId, $selectClause
789 FROM $compTable as $compTable $fromClause
791 Group By componentId";
793 $contact = CRM_Core_DAO
::executeQuery($query);
794 while ($contact->fetch()) {
795 $contactDetails[$contact->componentId
]['contact_id'] = $contact->contactId
;
796 foreach ($returnProperties as $property => $ignore) {
797 $contactDetails[$contact->componentId
][$property] = $contact->$property;
803 return $contactDetails;
807 * Function handles shared contact address processing.
808 * In this function we just modify submitted values so that new address created for the user
809 * has same address as shared contact address. We copy the address so that search etc will be
812 * @param array $address
813 * This is associated array which contains submitted form values.
817 public static function processSharedAddress(&$address) {
818 if (!is_array($address)) {
822 // Sharing contact address during create mode is pretty straight forward.
823 // In update mode we should check following:
824 // - We should check if user has uncheck shared contact address
825 // - If yes then unset the master_id or may be just delete the address that copied master
826 // Normal update process will automatically create new address with submitted values
828 // 1. loop through entire subnitted address array
829 $masterAddress = array();
830 $skipFields = array('is_primary', 'location_type_id', 'is_billing', 'master_id');
831 foreach ($address as & $values) {
832 // 2. check if master id exists, if not continue
833 if (empty($values['master_id']) ||
empty($values['use_shared_address'])) {
834 // we should unset master id when use uncheck share address for existing address
835 $values['master_id'] = 'null';
839 // 3. get the address details for master_id
840 $masterAddress = new CRM_Core_BAO_Address();
841 $masterAddress->id
= CRM_Utils_Array
::value('master_id', $values);
842 $masterAddress->find(TRUE);
844 // 4. modify submitted params and update it with shared contact address
845 // make sure you preserve specific form values like location type, is_primary_ is_billing, master_id
846 // CRM-10336: Also empty any fields from the existing address block if they don't exist in master (otherwise they will persist)
847 foreach ($values as $field => $submittedValue) {
848 if (!in_array($field, $skipFields)) {
849 if (isset($masterAddress->$field)) {
850 $values[$field] = $masterAddress->$field;
853 $values[$field] = '';
861 * Get the list of contact name give address associated array.
863 * @param array $addresses
864 * Associated array of.
867 * associated array of contact names
869 public static function getAddressShareContactNames(&$addresses) {
870 $contactNames = array();
871 // get the list of master id's for address
872 $masterAddressIds = array();
873 foreach ($addresses as $key => $addressValue) {
874 if (!empty($addressValue['master_id'])) {
875 $masterAddressIds[] = $addressValue['master_id'];
879 if (!empty($masterAddressIds)) {
880 $query = 'SELECT ca.id, cc.display_name, cc.id as cid, cc.is_deleted
881 FROM civicrm_contact cc
882 INNER JOIN civicrm_address ca ON cc.id = ca.contact_id
883 WHERE ca.id IN ( ' . implode(',', $masterAddressIds) . ')';
884 $dao = CRM_Core_DAO
::executeQuery($query);
886 while ($dao->fetch()) {
887 $contactViewUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$dao->cid}");
888 $contactNames[$dao->id
] = array(
889 'name' => "<a href='{$contactViewUrl}'>{$dao->display_name}</a>",
890 'is_deleted' => $dao->is_deleted
,
891 'contact_id' => $dao->cid
,
895 return $contactNames;
899 * Clear the contact cache so things are kosher. We started off being super aggressive with clearing
900 * caches, but are backing off from this with every release. Compromise between ease of coding versus
901 * performance versus being accurate at that very instant
904 * The contactID that was edited / deleted.
908 public static function clearContactCaches($contactID = NULL) {
909 // clear acl cache if any.
910 CRM_ACL_BAO_Cache
::resetCache();
912 if (empty($contactID)) {
913 // also clear prev/next dedupe cache - if no contactID passed in
914 CRM_Core_BAO_PrevNextCache
::deleteItem();
917 // reset the group contact cache for this group
918 CRM_Contact_BAO_GroupContactCache
::remove();
922 * @param array $params
926 public static function updateGreeting($params) {
927 $contactType = $params['ct'];
928 $greeting = $params['gt'];
929 $valueID = $id = CRM_Utils_Array
::value('id', $params);
930 $force = CRM_Utils_Array
::value('force', $params);
931 $limit = CRM_Utils_Array
::value('limit', $params);
933 // if valueID is not passed use default value
935 $valueID = $id = self
::defaultGreeting($contactType, $greeting);
939 'contact_type' => $contactType,
940 'greeting_type' => $greeting,
943 $allGreetings = CRM_Core_PseudoConstant
::greeting($filter);
944 $originalGreetingString = $greetingString = CRM_Utils_Array
::value($valueID, $allGreetings);
945 if (!$greetingString) {
946 CRM_Core_Error
::fatal(ts('Incorrect greeting value id %1, or no default greeting for this contact type and greeting type.', array(1 => $valueID)));
949 // build return properties based on tokens
950 $greetingTokens = CRM_Utils_Token
::getTokens($greetingString);
951 $tokens = CRM_Utils_Array
::value('contact', $greetingTokens);
952 $greetingsReturnProperties = array();
953 if (is_array($tokens)) {
954 $greetingsReturnProperties = array_fill_keys(array_values($tokens), 1);
957 // Process ALL contacts only when force=1 or force=2 is passed. Else only contacts with NULL greeting or addressee value are updated.
958 $processAll = $processOnlyIdSet = FALSE;
962 elseif ($force == 2) {
963 $processOnlyIdSet = TRUE;
966 //FIXME : apiQuery should handle these clause.
967 $filterContactFldIds = $filterIds = array();
968 $idFldName = $displayFldName = NULL;
969 if (in_array($greeting, CRM_Contact_BAO_Contact
::$_greetingTypes)) {
970 $idFldName = $greeting . '_id';
971 $displayFldName = $greeting . '_display';
975 $queryParams = array(1 => array($contactType, 'String'));
977 // if $force == 1 then update all contacts else only
978 // those with NULL greeting or addressee value CRM-9476
980 $sql = "SELECT DISTINCT id, $idFldName FROM civicrm_contact WHERE contact_type = %1 ";
984 SELECT DISTINCT id, $idFldName
986 WHERE contact_type = %1
987 AND ({$idFldName} IS NULL
988 OR ( {$idFldName} IS NOT NULL AND ({$displayFldName} IS NULL OR {$displayFldName} = '')) )";
992 $sql .= " LIMIT 0, %2";
993 $queryParams +
= array(2 => array($limit, 'Integer'));
996 $dao = CRM_Core_DAO
::executeQuery($sql, $queryParams);
997 while ($dao->fetch()) {
998 $filterContactFldIds[$dao->id
] = $dao->$idFldName;
1000 if (!CRM_Utils_System
::isNull($dao->$idFldName)) {
1001 $filterIds[$dao->id
] = $dao->$idFldName;
1006 if (empty($filterContactFldIds)) {
1007 $filterContactFldIds[] = 0;
1010 // retrieve only required contact information
1011 $extraParams[] = array('contact_type', '=', $contactType, 0, 0);
1012 // we do token replacement in the replaceGreetingTokens hook
1013 list($greetingDetails) = CRM_Utils_Token
::getTokenDetails(array_keys($filterContactFldIds),
1014 $greetingsReturnProperties,
1015 FALSE, FALSE, $extraParams
1017 // perform token replacement and build update SQL
1018 $contactIds = array();
1019 $cacheFieldQuery = "UPDATE civicrm_contact SET {$greeting}_display = CASE id ";
1020 foreach ($greetingDetails as $contactID => $contactDetails) {
1022 !array_key_exists($contactID, $filterContactFldIds)
1027 if ($processOnlyIdSet && !array_key_exists($contactID, $filterIds)) {
1032 $greetingString = $originalGreetingString;
1033 $contactIds[] = $contactID;
1036 if ($greetingBuffer = CRM_Utils_Array
::value($filterContactFldIds[$contactID], $allGreetings)) {
1037 $greetingString = $greetingBuffer;
1041 self
::processGreetingTemplate($greetingString, $contactDetails, $contactID, 'CRM_UpdateGreeting');
1042 $greetingString = CRM_Core_DAO
::escapeString($greetingString);
1043 $cacheFieldQuery .= " WHEN {$contactID} THEN '{$greetingString}' ";
1045 $allContactIds[] = $contactID;
1048 if (!empty($allContactIds)) {
1049 $cacheFieldQuery .= " ELSE {$greeting}_display
1051 if (!empty($contactIds)) {
1052 // need to update greeting _id field.
1053 // reset greeting _custom
1054 $resetCustomGreeting = '';
1055 if ($valueID != 4) {
1056 $resetCustomGreeting = ", {$greeting}_custom = NULL ";
1060 UPDATE civicrm_contact
1061 SET {$greeting}_id = {$valueID}
1062 {$resetCustomGreeting}
1063 WHERE id IN (" . implode(',', $contactIds) . ")";
1064 CRM_Core_DAO
::executeQuery($queryString);
1067 // now update cache field
1068 CRM_Core_DAO
::executeQuery($cacheFieldQuery);
1073 * Fetch the default greeting for a given contact type.
1075 * @param string $contactType
1077 * @param string $greetingType
1082 public static function defaultGreeting($contactType, $greetingType) {
1083 $contactTypeFilters = array(
1086 'Organization' => 3,
1088 if (!isset($contactTypeFilters[$contactType])) {
1091 $filter = $contactTypeFilters[$contactType];
1093 $id = CRM_Core_OptionGroup
::values($greetingType, NULL, NULL, NULL,
1094 " AND is_default = 1 AND (filter = {$filter} OR filter = 0)",
1098 return current($id);
1103 * Process a greeting template string to produce the individualised greeting text.
1105 * This works just like message templates for mailings:
1106 * the template is processed with the token substitution mechanism,
1107 * to supply the individual contact data;
1108 * and it is also processed with Smarty,
1109 * to allow for conditionals etc. based on the contact data.
1111 * Note: We don't pass any variables to Smarty --
1112 * all variable data is inserted into the input string
1113 * by the token substitution mechanism,
1114 * before Smarty is invoked.
1116 * @param string $templateString
1117 * The greeting template string with contact tokens + Smarty syntax.
1119 * @param $contactDetails
1120 * @param int $contactID
1121 * @param string $className
1125 public static function processGreetingTemplate(&$templateString, $contactDetails, $contactID, $className) {
1126 CRM_Utils_Token
::replaceGreetingTokens($templateString, $contactDetails, $contactID, $className, TRUE);
1128 $smarty = CRM_Core_Smarty
::singleton();
1129 $templateString = $smarty->fetch("string:$templateString");