3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
33 class CRM_Contact_BAO_Contact_Utils
{
36 * Given a contact type, get the contact image.
38 * @param string $contactType
40 * @param bool $urlOnly
41 * If we need to return only image url.
42 * @param int $contactId
44 * @param bool $addProfileOverlay
45 * If profile overlay class should be added.
49 public static function getImage($contactType, $urlOnly = FALSE, $contactId = NULL, $addProfileOverlay = TRUE) {
50 static $imageInfo = array();
52 $contactType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($contactType, CRM_Core_DAO
::VALUE_SEPARATOR
));
53 $contactType = $contactType[0];
55 if (!array_key_exists($contactType, $imageInfo)) {
56 $imageInfo[$contactType] = array();
59 $params = array('name' => $contactType);
60 CRM_Contact_BAO_ContactType
::retrieve($params, $typeInfo);
62 if (!empty($typeInfo['image_URL'])) {
63 $imageUrl = $typeInfo['image_URL'];
64 $config = CRM_Core_Config
::singleton();
66 if (!preg_match("/^(\/|(http(s)?:)).+$/i", $imageUrl)) {
67 $imageUrl = $config->resourceBase
. $imageUrl;
69 $imageInfo[$contactType]['image'] = "<div class=\"icon crm-icon {$typeInfo['name']}-icon\" style=\"background: url('{$imageUrl}')\" title=\"{$contactType}\"></div>";
70 $imageInfo[$contactType]['url'] = $imageUrl;
73 $isSubtype = (array_key_exists('parent_id', $typeInfo) &&
74 $typeInfo['parent_id']
78 $type = CRM_Contact_BAO_ContactType
::getBasicType($typeInfo['name']) . '-subtype';
81 $type = CRM_Utils_Array
::value('name', $typeInfo);
84 // do not add title since it hides contact name
85 if ($addProfileOverlay) {
86 $imageInfo[$contactType]['image'] = "<div class=\"icon crm-icon {$type}-icon\"></div>";
89 $imageInfo[$contactType]['image'] = "<div class=\"icon crm-icon {$type}-icon\" title=\"{$contactType}\"></div>";
91 $imageInfo[$contactType]['url'] = NULL;
95 if ($addProfileOverlay) {
96 static $summaryOverlayProfileId = NULL;
97 if (!$summaryOverlayProfileId) {
98 $summaryOverlayProfileId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', 'summary_overlay', 'id', 'name');
101 $profileURL = CRM_Utils_System
::url('civicrm/profile/view',
102 "reset=1&gid={$summaryOverlayProfileId}&id={$contactId}&snippet=4"
105 $imageInfo[$contactType]['summary-link'] = '<a href="' . $profileURL . '" class="crm-summary-link">' . $imageInfo[$contactType]['image'] . '</a>';
108 $imageInfo[$contactType]['summary-link'] = $imageInfo[$contactType]['image'];
111 return $urlOnly ?
$imageInfo[$contactType]['url'] : $imageInfo[$contactType]['summary-link'];
115 * Function check for mix contact ids(individual+household etc...)
117 * @param array $contactIds
118 * Array of contact ids.
121 * true if mix contact array else false
124 public static function checkContactType(&$contactIds) {
125 if (empty($contactIds)) {
129 $idString = implode(',', $contactIds);
131 SELECT count( DISTINCT contact_type )
133 WHERE id IN ( $idString )
135 $count = CRM_Core_DAO
::singleValueQuery($query,
136 CRM_Core_DAO
::$_nullArray
138 return $count > 1 ?
TRUE : FALSE;
142 * Generate a checksum for a $entityId of type $entityType
144 * @param int $entityId
146 * Timestamp that checksum was generated.
148 * Life of this checksum in hours/ 'inf' for infinite.
149 * @param string $hash
150 * Contact hash, if sent, prevents a query in inner loop.
152 * @param string $entityType
153 * @param null $hashSize
156 * ( $cs, $ts, $live )
158 public static function generateChecksum($entityId, $ts = NULL, $live = NULL, $hash = NULL, $entityType = 'contact', $hashSize = NULL) {
159 // return a warning message if we dont get a entityId
160 // this typically happens when we do a message preview
161 // or an anon mailing view - CRM-8298
163 return 'invalidChecksum';
167 if ($entityType == 'contact') {
168 $hash = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
172 elseif ($entityType == 'mailing') {
173 $hash = CRM_Core_DAO
::getFieldValue('CRM_Mailing_DAO_Mailing',
180 $hash = md5(uniqid(rand(), TRUE));
182 $hash = substr($hash, 0, $hashSize);
185 if ($entityType == 'contact') {
186 CRM_Core_DAO
::setFieldValue('CRM_Contact_DAO_Contact',
191 elseif ($entityType == 'mailing') {
192 CRM_Core_DAO
::setFieldValue('CRM_Mailing_DAO_Mailing',
204 $days = Civi
::settings()->get('checksum_timeout');
208 $cs = md5("{$hash}_{$entityId}_{$ts}_{$live}");
209 return "{$cs}_{$ts}_{$live}";
213 * Make sure the checksum is valid for the passed in contactID.
215 * @param int $contactID
216 * @param string $inputCheck
217 * Checksum to match against.
220 * true if valid, else false
222 public static function validChecksum($contactID, $inputCheck) {
224 $input = CRM_Utils_System
::explode('_', $inputCheck, 3);
226 $inputCS = CRM_Utils_Array
::value(0, $input);
227 $inputTS = CRM_Utils_Array
::value(1, $input);
228 $inputLF = CRM_Utils_Array
::value(2, $input);
230 $check = self
::generateChecksum($contactID, $inputTS, $inputLF);
232 if ($check != $inputCheck) {
236 // no life limit for checksum
237 if ($inputLF == 'inf') {
241 // checksum matches so now check timestamp
243 return ($inputTS +
($inputLF * 60 * 60) >= $now);
247 * Get the count of contact loctions.
249 * @param int $contactId
253 * max locations for the contact
255 public static function maxLocations($contactId) {
256 $contactLocations = array();
258 // find number of location blocks for this contact and adjust value accordinly
259 // get location type from email
261 ( SELECT location_type_id FROM civicrm_email WHERE contact_id = {$contactId} )
263 ( SELECT location_type_id FROM civicrm_phone WHERE contact_id = {$contactId} )
265 ( SELECT location_type_id FROM civicrm_im WHERE contact_id = {$contactId} )
267 ( SELECT location_type_id FROM civicrm_address WHERE contact_id = {$contactId} )
269 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
274 * Create Current employer relationship for a individual.
276 * @param int $contactID
277 * Contact id of the individual.
278 * @param $organization
280 * @param int $previousEmployerID
281 * @param bool $newContact
284 public static function createCurrentEmployerRelationship($contactID, $organization, $previousEmployerID = NULL, $newContact = FALSE) {
285 //if organization name is passed. CRM-15368,CRM-15547
286 if ($organization && !is_numeric($organization)) {
287 $organizationParams['organization_name'] = $organization;
288 $dedupeParams = CRM_Dedupe_Finder
::formatParams($organizationParams, 'Organization');
290 $dedupeParams['check_permission'] = FALSE;
291 $dupeIDs = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, 'Organization', 'Unsupervised');
293 if (is_array($dupeIDs) && !empty($dupeIDs)) {
294 // we should create relationship only w/ first org CRM-4193
295 foreach ($dupeIDs as $orgId) {
296 $organization = $orgId;
301 //create new organization
303 'contact_type' => 'Organization',
304 'organization_name' => $organization,
306 $org = CRM_Contact_BAO_Contact
::create($newOrg);
307 $organization = $org->id
;
311 if ($organization && is_numeric($organization)) {
312 $cid = array('contact' => $contactID);
314 // get the relationship type id of "Employee of"
315 $relTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType', 'Employee of', 'id', 'name_a_b');
317 CRM_Core_Error
::fatal(ts("You seem to have deleted the relationship type 'Employee of'"));
320 // create employee of relationship
321 $relationshipParams = array(
323 'relationship_type_id' => $relTypeId . '_a_b',
324 'contact_check' => array($organization => TRUE),
326 list($valid, $invalid, $duplicate, $saved, $relationshipIds)
327 = CRM_Contact_BAO_Relationship
::legacyCreateMultiple($relationshipParams, $cid);
329 // In case we change employer, clean previous employer related records.
330 if (!$previousEmployerID && !$newContact) {
331 $previousEmployerID = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id');
333 if ($previousEmployerID &&
334 $previousEmployerID != $organization
336 self
::clearCurrentEmployer($contactID, $previousEmployerID);
339 // set current employer
340 self
::setCurrentEmployer(array($contactID => $organization));
342 $relationshipParams['relationship_ids'] = $relationshipIds;
343 // Handle related memberships. CRM-3792
344 self
::currentEmployerRelatedMembership($contactID, $organization, $relationshipParams, $duplicate, $previousEmployerID);
349 * Create related memberships for current employer.
351 * @param int $contactID
352 * Contact id of the individual.
353 * @param int $employerID
354 * Contact id of the organization.
355 * @param array $relationshipParams
356 * Relationship params.
357 * @param bool $duplicate
358 * Are we triggered existing relationship.
360 * @param int $previousEmpID
362 * @throws CiviCRM_API3_Exception
364 public static function currentEmployerRelatedMembership($contactID, $employerID, $relationshipParams, $duplicate = FALSE, $previousEmpID = NULL) {
366 $action = CRM_Core_Action
::ADD
;
368 //we do not know that triggered relationship record is active.
370 $relationship = new CRM_Contact_DAO_Relationship();
371 $relationship->contact_id_a
= $contactID;
372 $relationship->contact_id_b
= $employerID;
373 $relationship->relationship_type_id
= $relationshipParams['relationship_type_id'];
374 if ($relationship->find(TRUE)) {
375 $action = CRM_Core_Action
::UPDATE
;
376 $ids['contact'] = $contactID;
377 $ids['contactTarget'] = $employerID;
378 $ids['relationship'] = $relationship->id
;
379 CRM_Contact_BAO_Relationship
::setIsActive($relationship->id
, TRUE);
381 $relationship->free();
384 //need to handle related meberships. CRM-3792
385 if ($previousEmpID != $employerID) {
386 CRM_Contact_BAO_Relationship
::relatedMemberships($contactID, $relationshipParams, $ids, $action);
391 * Set current employer id and organization name.
393 * @param array $currentEmployerParams
394 * Associated array of contact id and its employer id.
396 public static function setCurrentEmployer($currentEmployerParams) {
397 foreach ($currentEmployerParams as $contactId => $orgId) {
398 $query = "UPDATE civicrm_contact contact_a,civicrm_contact contact_b
399 SET contact_a.employer_id=contact_b.id, contact_a.organization_name=contact_b.organization_name
400 WHERE contact_a.id ={$contactId} AND contact_b.id={$orgId}; ";
402 //FIXME : currently civicrm mysql_query support only single statement
403 //execution, though mysql 5.0 support multiple statement execution.
404 $dao = CRM_Core_DAO
::executeQuery($query);
409 * Update cached current employer name.
411 * @param int $organizationId
412 * Current employer id.
414 public static function updateCurrentEmployer($organizationId) {
415 $query = "UPDATE civicrm_contact contact_a,civicrm_contact contact_b
416 SET contact_a.organization_name=contact_b.organization_name
417 WHERE contact_a.employer_id=contact_b.id AND contact_b.id={$organizationId}; ";
419 $dao = CRM_Core_DAO
::executeQuery($query);
423 * Clear cached current employer name.
425 * @param int $contactId
426 * Contact id ( mostly individual contact id).
427 * @param int $employerId
428 * Contact id ( mostly organization contact id).
430 public static function clearCurrentEmployer($contactId, $employerId = NULL) {
431 $query = "UPDATE civicrm_contact
432 SET organization_name=NULL, employer_id = NULL
433 WHERE id={$contactId}; ";
435 $dao = CRM_Core_DAO
::executeQuery($query);
437 // need to handle related meberships. CRM-3792
439 //1. disable corresponding relationship.
440 //2. delete related membership.
442 //get the relationship type id of "Employee of"
443 $relTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType', 'Employee of', 'id', 'name_a_b');
445 CRM_Core_Error
::fatal(ts("You seem to have deleted the relationship type 'Employee of'"));
447 $relMembershipParams['relationship_type_id'] = $relTypeId . '_a_b';
448 $relMembershipParams['contact_check'][$employerId] = 1;
450 //get relationship id.
451 if (CRM_Contact_BAO_Relationship
::checkDuplicateRelationship($relMembershipParams, $contactId, $employerId)) {
452 $relationship = new CRM_Contact_DAO_Relationship();
453 $relationship->contact_id_a
= $contactId;
454 $relationship->contact_id_b
= $employerId;
455 $relationship->relationship_type_id
= $relTypeId;
457 if ($relationship->find(TRUE)) {
458 CRM_Contact_BAO_Relationship
::setIsActive($relationship->id
, FALSE);
459 CRM_Contact_BAO_Relationship
::relatedMemberships($contactId, $relMembershipParams,
461 CRM_Core_Action
::DELETE
464 $relationship->free();
470 * Build form for related contacts / on behalf of organization.
472 * @param CRM_Core_Form $form
473 * @param string $contactType
475 * @param int $countryID
476 * @param int $stateID
477 * @param string $title
481 public static function buildOnBehalfForm(&$form, $contactType, $countryID, $stateID, $title) {
483 $config = CRM_Core_Config
::singleton();
485 $form->assign('contact_type', $contactType);
486 $form->assign('fieldSetTitle', $title);
487 $form->assign('contactEditMode', TRUE);
489 $attributes = CRM_Core_DAO
::getAttribute('CRM_Contact_DAO_Contact');
490 if ($form->_contactId
) {
491 $form->assign('orgId', $form->_contactId
);
494 switch ($contactType) {
496 $form->add('text', 'organization_name', ts('Organization Name'), $attributes['organization_name'], TRUE);
500 $form->add('text', 'household_name', ts('Household Name'), $attributes['household_name']);
505 $form->addElement('select', 'prefix_id', ts('Prefix'),
506 array('' => ts('- prefix -')) + CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id')
508 $form->addElement('text', 'first_name', ts('First Name'),
509 $attributes['first_name']
511 $form->addElement('text', 'middle_name', ts('Middle Name'),
512 $attributes['middle_name']
514 $form->addElement('text', 'last_name', ts('Last Name'),
515 $attributes['last_name']
517 $form->addElement('select', 'suffix_id', ts('Suffix'),
518 array('' => ts('- suffix -')) + CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'suffix_id')
522 $addressSequence = $config->addressSequence();
523 $form->assign('addressSequence', array_fill_keys($addressSequence, 1));
526 $form->addElement('text',
529 CRM_Core_DAO
::getAttribute('CRM_Core_DAO_Phone',
534 $form->addElement('text',
537 CRM_Core_DAO
::getAttribute('CRM_Core_DAO_Email',
541 //build the address block
542 CRM_Contact_Form_Edit_Address
::buildQuickForm($form);
546 * Clear cache employer name and employer id
547 * of all employee when employer get deleted.
549 * @param int $employerId
550 * Contact id of employer ( organization id ).
552 public static function clearAllEmployee($employerId) {
554 UPDATE civicrm_contact
555 SET organization_name=NULL, employer_id = NULL
556 WHERE employer_id={$employerId}; ";
558 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
562 * Given an array of contact ids this function will return array with links to view contact page.
564 * @param array $contactIDs
565 * Associated contact id's.
566 * @param bool $addViewLink
567 * @param bool $addEditLink
568 * @param int $originalId
569 * Associated with the contact which is edited.
573 * returns array with links to contact view
575 public static function formatContactIDSToLinks($contactIDs, $addViewLink = TRUE, $addEditLink = TRUE, $originalId = NULL) {
576 $contactLinks = array();
577 if (!is_array($contactIDs) ||
empty($contactIDs)) {
578 return $contactLinks;
581 // does contact has sufficient permissions.
582 $permissions = array(
583 'view' => 'view all contacts',
584 'edit' => 'edit all contacts',
585 'merge' => 'merge duplicate contacts',
588 $permissionedContactIds = array();
589 foreach ($permissions as $task => $permission) {
591 if (CRM_Core_Permission
::check($permission)) {
592 foreach ($contactIDs as $contactId) {
593 $permissionedContactIds[$contactId][$task] = TRUE;
598 // check permission on acl basis.
599 if (in_array($task, array(
603 $aclPermission = CRM_Core_Permission
::VIEW
;
604 if ($task == 'edit') {
605 $aclPermission = CRM_Core_Permission
::EDIT
;
607 foreach ($contactIDs as $contactId) {
608 if (CRM_Contact_BAO_Contact_Permission
::allow($contactId, $aclPermission)) {
609 $permissionedContactIds[$contactId][$task] = TRUE;
615 // retrieve display names for all contacts
617 SELECT c.id, c.display_name, c.contact_type, ce.email
618 FROM civicrm_contact c
619 LEFT JOIN civicrm_email ce ON ( ce.contact_id=c.id AND ce.is_primary = 1 )
620 WHERE c.id IN (' . implode(',', $contactIDs) . ' ) LIMIT 20';
622 $dao = CRM_Core_DAO
::executeQuery($query);
624 $contactLinks['msg'] = NULL;
626 while ($dao->fetch()) {
628 $contactLinks['rows'][$i]['display_name'] = $dao->display_name
;
629 $contactLinks['rows'][$i]['primary_email'] = $dao->email
;
631 // get the permission for current contact id.
632 $hasPermissions = CRM_Utils_Array
::value($dao->id
, $permissionedContactIds);
633 if (!is_array($hasPermissions) ||
empty($hasPermissions)) {
638 // do check for view.
639 if (array_key_exists('view', $hasPermissions)) {
640 $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>';
641 if (!$contactLinks['msg']) {
642 $contactLinks['msg'] = 'view';
645 if (array_key_exists('edit', $hasPermissions)) {
646 $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>';
647 if (!$contactLinks['msg'] ||
$contactLinks['msg'] != 'merge') {
648 $contactLinks['msg'] = 'edit';
651 if (!empty($originalId) && array_key_exists('merge', $hasPermissions)) {
652 $rgBao = new CRM_Dedupe_BAO_RuleGroup();
653 $rgBao->contact_type
= $dao->contact_type
;
654 $rgBao->used
= 'Supervised';
655 if ($rgBao->find(TRUE)) {
658 if ($rgid && isset($dao->id
)) {
659 //get an url to merge the contact
660 $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>';
661 $contactLinks['msg'] = 'merge';
668 return $contactLinks;
672 * This function retrieve component related contact information.
674 * @param array $componentIds
675 * Array of component Ids.
676 * @param string $componentName
677 * @param array $returnProperties
678 * Array of return elements.
681 * array of contact info.
683 public static function contactDetails($componentIds, $componentName, $returnProperties = array()) {
684 $contactDetails = array();
685 if (empty($componentIds) ||
686 !in_array($componentName, array('CiviContribute', 'CiviMember', 'CiviEvent', 'Activity'))
688 return $contactDetails;
691 if (empty($returnProperties)) {
692 $autocompleteContactSearch = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
693 'contact_autocomplete_options'
695 $returnProperties = array_fill_keys(array_merge(array('sort_name'),
696 array_keys($autocompleteContactSearch)
701 if ($componentName == 'CiviContribute') {
702 $compTable = 'civicrm_contribution';
704 elseif ($componentName == 'CiviMember') {
705 $compTable = 'civicrm_membership';
707 elseif ($componentName == 'Activity') {
708 $compTable = 'civicrm_activity';
709 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
712 $compTable = 'civicrm_participant';
715 $select = $from = array();
716 foreach ($returnProperties as $property => $ignore) {
717 $value = (in_array($property, array(
720 ))) ?
'address' : $property;
723 if ($componentName == 'Activity') {
724 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
725 $select[] = "contact.$property as $property";
727 INNER JOIN civicrm_activity_contact acs ON (acs.activity_id = {$compTable}.id AND acs.record_type_id = {$sourceID})
728 INNER JOIN civicrm_contact contact ON ( contact.id = acs.contact_id )";
731 $select[] = "$property as $property";
732 $from[$value] = "INNER JOIN civicrm_contact contact ON ( contact.id = $compTable.contact_id )";
736 case 'target_sort_name':
737 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
738 $select[] = "contact_target.sort_name as $property";
740 INNER JOIN civicrm_activity_contact act ON (act.activity_id = {$compTable}.id AND act.record_type_id = {$targetID})
741 INNER JOIN civicrm_contact contact_target ON ( contact_target.id = act.contact_id )";
747 case 'street_address':
748 $select[] = "$property as $property";
749 // Grab target contact properties if this is for activity
750 if ($componentName == 'Activity') {
751 $from[$value] = "LEFT JOIN civicrm_{$value} {$value} ON ( contact_target.id = {$value}.contact_id AND {$value}.is_primary = 1 ) ";
754 $from[$value] = "LEFT JOIN civicrm_{$value} {$value} ON ( contact.id = {$value}.contact_id AND {$value}.is_primary = 1 ) ";
759 case 'state_province':
760 $select[] = "{$property}.name as $property";
761 if (!in_array('address', $from)) {
762 // Grab target contact properties if this is for activity
763 if ($componentName == 'Activity') {
764 $from['address'] = 'LEFT JOIN civicrm_address address ON ( contact_target.id = address.contact_id AND address.is_primary = 1) ';
767 $from['address'] = 'LEFT JOIN civicrm_address address ON ( contact.id = address.contact_id AND address.is_primary = 1) ';
770 $from[$value] = " LEFT JOIN civicrm_{$value} {$value} ON ( address.{$value}_id = {$value}.id ) ";
775 //finally retrieve contact details.
776 if (!empty($select) && !empty($from)) {
777 $fromClause = implode(' ', $from);
778 $selectClause = implode(', ', $select);
779 $whereClause = "{$compTable}.id IN (" . implode(',', $componentIds) . ')';
782 SELECT contact.id as contactId, $compTable.id as componentId, $selectClause
783 FROM $compTable as $compTable $fromClause
785 Group By componentId";
787 $contact = CRM_Core_DAO
::executeQuery($query);
788 while ($contact->fetch()) {
789 $contactDetails[$contact->componentId
]['contact_id'] = $contact->contactId
;
790 foreach ($returnProperties as $property => $ignore) {
791 $contactDetails[$contact->componentId
][$property] = $contact->$property;
797 return $contactDetails;
801 * Function handles shared contact address processing.
802 * In this function we just modify submitted values so that new address created for the user
803 * has same address as shared contact address. We copy the address so that search etc will be
806 * @param array $address
807 * This is associated array which contains submitted form values.
809 public static function processSharedAddress(&$address) {
810 if (!is_array($address)) {
814 // Sharing contact address during create mode is pretty straight forward.
815 // In update mode we should check following:
816 // - We should check if user has uncheck shared contact address
817 // - If yes then unset the master_id or may be just delete the address that copied master
818 // Normal update process will automatically create new address with submitted values
820 // 1. loop through entire subnitted address array
821 $masterAddress = array();
822 $skipFields = array('is_primary', 'location_type_id', 'is_billing', 'master_id');
823 foreach ($address as & $values) {
824 // 2. check if master id exists, if not continue
825 if (empty($values['master_id']) ||
empty($values['use_shared_address'])) {
826 // we should unset master id when use uncheck share address for existing address
827 $values['master_id'] = 'null';
831 // 3. get the address details for master_id
832 $masterAddress = new CRM_Core_BAO_Address();
833 $masterAddress->id
= CRM_Utils_Array
::value('master_id', $values);
834 $masterAddress->find(TRUE);
836 // 4. modify submitted params and update it with shared contact address
837 // make sure you preserve specific form values like location type, is_primary_ is_billing, master_id
838 // CRM-10336: Also empty any fields from the existing address block if they don't exist in master (otherwise they will persist)
839 foreach ($values as $field => $submittedValue) {
840 if (!in_array($field, $skipFields)) {
841 if (isset($masterAddress->$field)) {
842 $values[$field] = $masterAddress->$field;
845 $values[$field] = '';
850 //5. modify the params to include county_id if it exist in master contact.
851 // CRM-16152: This is a hack since QF does not submit disabled field.
852 if (!empty($masterAddress->county_id
) && empty($values['county_id'])) {
853 $values['county_id'] = $masterAddress->county_id
;
859 * Get the list of contact name give address associated array.
861 * @param array $addresses
862 * Associated array of.
865 * associated array of contact names
867 public static function getAddressShareContactNames(&$addresses) {
868 $contactNames = array();
869 // get the list of master id's for address
870 $masterAddressIds = array();
871 foreach ($addresses as $key => $addressValue) {
872 if (!empty($addressValue['master_id'])) {
873 $masterAddressIds[] = $addressValue['master_id'];
877 if (!empty($masterAddressIds)) {
878 $query = 'SELECT ca.id, cc.display_name, cc.id as cid, cc.is_deleted
879 FROM civicrm_contact cc
880 INNER JOIN civicrm_address ca ON cc.id = ca.contact_id
881 WHERE ca.id IN ( ' . implode(',', $masterAddressIds) . ')';
882 $dao = CRM_Core_DAO
::executeQuery($query);
884 while ($dao->fetch()) {
885 $contactViewUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$dao->cid}");
886 $contactNames[$dao->id
] = array(
887 'name' => "<a href='{$contactViewUrl}'>{$dao->display_name}</a>",
888 'is_deleted' => $dao->is_deleted
,
889 'contact_id' => $dao->cid
,
893 return $contactNames;
897 * Clear the contact cache so things are kosher. We started off being super aggressive with clearing
898 * caches, but are backing off from this with every release. Compromise between ease of coding versus
899 * performance versus being accurate at that very instant
902 * The contactID that was edited / deleted.
904 public static function clearContactCaches($contactID = NULL) {
905 // clear acl cache if any.
906 CRM_ACL_BAO_Cache
::resetCache();
908 if (empty($contactID)) {
909 // also clear prev/next dedupe cache - if no contactID passed in
910 CRM_Core_BAO_PrevNextCache
::deleteItem();
913 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheRefresh();
917 * @param array $params
921 public static function updateGreeting($params) {
922 $contactType = $params['ct'];
923 $greeting = $params['gt'];
924 $valueID = $id = CRM_Utils_Array
::value('id', $params);
925 $force = CRM_Utils_Array
::value('force', $params);
926 $limit = CRM_Utils_Array
::value('limit', $params);
928 // if valueID is not passed use default value
930 $valueID = $id = self
::defaultGreeting($contactType, $greeting);
934 'contact_type' => $contactType,
935 'greeting_type' => $greeting,
938 $allGreetings = CRM_Core_PseudoConstant
::greeting($filter);
939 $originalGreetingString = $greetingString = CRM_Utils_Array
::value($valueID, $allGreetings);
940 if (!$greetingString) {
941 CRM_Core_Error
::fatal(ts('Incorrect greeting value id %1, or no default greeting for this contact type and greeting type.', array(1 => $valueID)));
944 // build return properties based on tokens
945 $greetingTokens = CRM_Utils_Token
::getTokens($greetingString);
946 $tokens = CRM_Utils_Array
::value('contact', $greetingTokens);
947 $greetingsReturnProperties = array();
948 if (is_array($tokens)) {
949 $greetingsReturnProperties = array_fill_keys(array_values($tokens), 1);
952 // Process ALL contacts only when force=1 or force=2 is passed. Else only contacts with NULL greeting or addressee value are updated.
953 $processAll = $processOnlyIdSet = FALSE;
957 elseif ($force == 2) {
958 $processOnlyIdSet = TRUE;
961 //FIXME : apiQuery should handle these clause.
962 $filterContactFldIds = $filterIds = array();
963 $idFldName = $displayFldName = NULL;
964 if (in_array($greeting, CRM_Contact_BAO_Contact
::$_greetingTypes)) {
965 $idFldName = $greeting . '_id';
966 $displayFldName = $greeting . '_display';
970 $queryParams = array(1 => array($contactType, 'String'));
972 // if $force == 1 then update all contacts else only
973 // those with NULL greeting or addressee value CRM-9476
975 $sql = "SELECT DISTINCT id, $idFldName FROM civicrm_contact WHERE contact_type = %1 ";
979 SELECT DISTINCT id, $idFldName
981 WHERE contact_type = %1
982 AND ({$idFldName} IS NULL
983 OR ( {$idFldName} IS NOT NULL AND ({$displayFldName} IS NULL OR {$displayFldName} = '')) )";
987 $sql .= " LIMIT 0, %2";
988 $queryParams +
= array(2 => array($limit, 'Integer'));
991 $dao = CRM_Core_DAO
::executeQuery($sql, $queryParams);
992 while ($dao->fetch()) {
993 $filterContactFldIds[$dao->id
] = $dao->$idFldName;
995 if (!CRM_Utils_System
::isNull($dao->$idFldName)) {
996 $filterIds[$dao->id
] = $dao->$idFldName;
1001 if (empty($filterContactFldIds)) {
1002 $filterContactFldIds[] = 0;
1005 // retrieve only required contact information
1006 $extraParams[] = array('contact_type', '=', $contactType, 0, 0);
1007 // we do token replacement in the replaceGreetingTokens hook
1008 list($greetingDetails) = CRM_Utils_Token
::getTokenDetails(array_keys($filterContactFldIds),
1009 $greetingsReturnProperties,
1010 FALSE, FALSE, $extraParams
1012 // perform token replacement and build update SQL
1013 $contactIds = array();
1014 $cacheFieldQuery = "UPDATE civicrm_contact SET {$greeting}_display = CASE id ";
1015 foreach ($greetingDetails as $contactID => $contactDetails) {
1017 !array_key_exists($contactID, $filterContactFldIds)
1022 if ($processOnlyIdSet && !array_key_exists($contactID, $filterIds)) {
1027 $greetingString = $originalGreetingString;
1028 $contactIds[] = $contactID;
1031 if ($greetingBuffer = CRM_Utils_Array
::value($filterContactFldIds[$contactID], $allGreetings)) {
1032 $greetingString = $greetingBuffer;
1036 self
::processGreetingTemplate($greetingString, $contactDetails, $contactID, 'CRM_UpdateGreeting');
1037 $greetingString = CRM_Core_DAO
::escapeString($greetingString);
1038 $cacheFieldQuery .= " WHEN {$contactID} THEN '{$greetingString}' ";
1040 $allContactIds[] = $contactID;
1043 if (!empty($allContactIds)) {
1044 $cacheFieldQuery .= " ELSE {$greeting}_display
1046 if (!empty($contactIds)) {
1047 // need to update greeting _id field.
1048 // reset greeting _custom
1049 $resetCustomGreeting = '';
1050 if ($valueID != 4) {
1051 $resetCustomGreeting = ", {$greeting}_custom = NULL ";
1055 UPDATE civicrm_contact
1056 SET {$greeting}_id = {$valueID}
1057 {$resetCustomGreeting}
1058 WHERE id IN (" . implode(',', $contactIds) . ")";
1059 CRM_Core_DAO
::executeQuery($queryString);
1062 // now update cache field
1063 CRM_Core_DAO
::executeQuery($cacheFieldQuery);
1068 * Fetch the default greeting for a given contact type.
1070 * @param string $contactType
1072 * @param string $greetingType
1077 public static function defaultGreeting($contactType, $greetingType) {
1078 $contactTypeFilters = array(
1081 'Organization' => 3,
1083 if (!isset($contactTypeFilters[$contactType])) {
1086 $filter = $contactTypeFilters[$contactType];
1088 $id = CRM_Core_OptionGroup
::values($greetingType, NULL, NULL, NULL,
1089 " AND is_default = 1 AND (filter = {$filter} OR filter = 0)",
1093 return current($id);
1098 * Process a greeting template string to produce the individualised greeting text.
1100 * This works just like message templates for mailings:
1101 * the template is processed with the token substitution mechanism,
1102 * to supply the individual contact data;
1103 * and it is also processed with Smarty,
1104 * to allow for conditionals etc. based on the contact data.
1106 * Note: We don't pass any variables to Smarty --
1107 * all variable data is inserted into the input string
1108 * by the token substitution mechanism,
1109 * before Smarty is invoked.
1111 * @param string $templateString
1112 * The greeting template string with contact tokens + Smarty syntax.
1114 * @param array $contactDetails
1115 * @param int $contactID
1116 * @param string $className
1118 public static function processGreetingTemplate(&$templateString, $contactDetails, $contactID, $className) {
1119 CRM_Utils_Token
::replaceGreetingTokens($templateString, $contactDetails, $contactID, $className, TRUE);
1121 $smarty = CRM_Core_Smarty
::singleton();
1122 $templateString = $smarty->fetch("string:$templateString");
1126 * Determine if a contact ID is real/valid.
1128 * @param int $contactId
1129 * The hypothetical contact ID
1132 public static function isContactId($contactId) {
1134 // ensure that this is a valid contact id (for session inconsistency rules)
1135 $cid = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',