3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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 contact type
41 * @param boolean $urlOnly if we need to return only image url
42 * @param int $contactId contact id
43 * @param boolean $addProfileOverlay if profile overlay class should be added
49 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 array of contact ids
119 * @return boolen true or false true if mix contact array else fale
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
145 * @param int $ts timestamp that checksum was generated
146 * @param int $live life of this checksum in hours/ 'inf' for infinite
147 * @param string $hash contact hash, if sent, prevents a query in inner loop
149 * @param string $entityType
150 * @param null $hashSize
152 * @return array ( $cs, $ts, $live )
156 static function generateChecksum($entityId, $ts = NULL, $live = NULL, $hash = NULL, $entityType = 'contact', $hashSize = NULL) {
157 // return a warning message if we dont get a entityId
158 // this typically happens when we do a message preview
159 // or an anon mailing view - CRM-8298
161 return 'invalidChecksum';
165 if ($entityType == 'contact') {
166 $hash = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
170 elseif ($entityType == 'mailing') {
171 $hash = CRM_Core_DAO
::getFieldValue('CRM_Mailing_DAO_Mailing',
178 $hash = md5(uniqid(rand(), TRUE));
180 $hash = substr($hash, 0, $hashSize);
183 if ($entityType == 'contact') {
184 CRM_Core_DAO
::setFieldValue('CRM_Contact_DAO_Contact',
189 elseif ($entityType == 'mailing') {
190 CRM_Core_DAO
::setFieldValue('CRM_Mailing_DAO_Mailing',
202 $days = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
210 $cs = md5("{$hash}_{$entityId}_{$ts}_{$live}");
211 return "{$cs}_{$ts}_{$live}";
215 * Make sure the checksum is valid for the passed in contactID
217 * @param int $contactID
218 * @param string $inputCheck checksum to match against
220 * @return boolean true if valid, else false
224 static function validChecksum($contactID, $inputCheck) {
226 $input = CRM_Utils_System
::explode('_', $inputCheck, 3);
228 $inputCS = CRM_Utils_Array
::value(0, $input);
229 $inputTS = CRM_Utils_Array
::value(1, $input);
230 $inputLF = CRM_Utils_Array
::value(2, $input);
232 $check = self
::generateChecksum($contactID, $inputTS, $inputLF);
234 if ($check != $inputCheck) {
238 // no life limit for checksum
239 if ($inputLF == 'inf') {
243 // checksum matches so now check timestamp
245 return ($inputTS +
($inputLF * 60 * 60) >= $now);
249 * Function to get the count of contact loctions
251 * @param int $contactId contact id
253 * @return int $locationCount max locations for the contact
257 static function maxLocations($contactId) {
258 $contactLocations = array();
260 // find number of location blocks for this contact and adjust value accordinly
261 // get location type from email
263 ( SELECT location_type_id FROM civicrm_email WHERE contact_id = {$contactId} )
265 ( SELECT location_type_id FROM civicrm_phone WHERE contact_id = {$contactId} )
267 ( SELECT location_type_id FROM civicrm_im WHERE contact_id = {$contactId} )
269 ( SELECT location_type_id FROM civicrm_address WHERE contact_id = {$contactId} )
271 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
276 * Create Current employer relationship for a individual
278 * @param int $contactID contact id of the individual
279 * @param $organizationId
280 * @param null $previousEmployerID
282 * @internal param string $organization it can be name or id of organization
287 static function createCurrentEmployerRelationship($contactID, $organizationId, $previousEmployerID = NULL, $newContact = FALSE) {
288 if ($organizationId && is_numeric($organizationId)) {
289 $cid = array('contact' => $contactID);
291 // get the relationship type id of "Employee of"
292 $relTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType', 'Employee of', 'id', 'name_a_b');
294 CRM_Core_Error
::fatal(ts("You seem to have deleted the relationship type 'Employee of'"));
297 // create employee of relationship
298 $relationshipParams = array(
300 'relationship_type_id' => $relTypeId . '_a_b',
301 'contact_check' => array($organizationId => TRUE),
303 list($valid, $invalid, $duplicate,
304 $saved, $relationshipIds
305 ) = CRM_Contact_BAO_Relationship
::create($relationshipParams, $cid);
308 // In case we change employer, clean previous employer related records.
309 if (!$previousEmployerID && !$newContact) {
310 $previousEmployerID = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id');
312 if ($previousEmployerID &&
313 $previousEmployerID != $organizationId
315 self
::clearCurrentEmployer($contactID, $previousEmployerID);
318 // set current employer
319 self
::setCurrentEmployer(array($contactID => $organizationId));
321 $relationshipParams['relationship_ids'] = $relationshipIds;
322 // handle related meberships. CRM-3792
323 self
::currentEmployerRelatedMembership($contactID, $organizationId, $relationshipParams, $duplicate, $previousEmployerID);
328 * create related memberships for current employer
330 * @param int $contactID contact id of the individual
331 * @param int $employerID contact id of the organization.
332 * @param array $relationshipParams relationship params.
333 * @param boolean $duplicate are we triggered existing relationship.
335 * @param null $previousEmpID
337 * @throws CiviCRM_API3_Exception
341 static function currentEmployerRelatedMembership($contactID, $employerID, $relationshipParams, $duplicate = FALSE, $previousEmpID = NULL) {
343 $action = CRM_Core_Action
::ADD
;
345 //we do not know that triggered relationship record is active.
347 $relationship = new CRM_Contact_DAO_Relationship();
348 $relationship->contact_id_a
= $contactID;
349 $relationship->contact_id_b
= $employerID;
350 $relationship->relationship_type_id
= $relationshipParams['relationship_type_id'];
351 if ($relationship->find(TRUE)) {
352 $action = CRM_Core_Action
::UPDATE
;
353 $ids['contact'] = $contactID;
354 $ids['contactTarget'] = $employerID;
355 $ids['relationship'] = $relationship->id
;
356 CRM_Contact_BAO_Relationship
::setIsActive($relationship->id
, TRUE);
358 $relationship->free();
361 //need to handle related meberships. CRM-3792
362 if ($previousEmpID != $employerID) {
363 CRM_Contact_BAO_Relationship
::relatedMemberships($contactID, $relationshipParams, $ids, $action);
368 * Function to set current employer id and organization name
370 * @param array $currentEmployerParams associated array of contact id and its employer id
373 static function setCurrentEmployer($currentEmployerParams) {
374 foreach ($currentEmployerParams as $contactId => $orgId) {
375 $query = "UPDATE civicrm_contact contact_a,civicrm_contact contact_b
376 SET contact_a.employer_id=contact_b.id, contact_a.organization_name=contact_b.organization_name
377 WHERE contact_a.id ={$contactId} AND contact_b.id={$orgId}; ";
379 //FIXME : currently civicrm mysql_query support only single statement
380 //execution, though mysql 5.0 support multiple statement execution.
381 $dao = CRM_Core_DAO
::executeQuery($query);
386 * Function to update cached current employer name
388 * @param int $organizationId current employer id
391 static function updateCurrentEmployer($organizationId) {
392 $query = "UPDATE civicrm_contact contact_a,civicrm_contact contact_b
393 SET contact_a.organization_name=contact_b.organization_name
394 WHERE contact_a.employer_id=contact_b.id AND contact_b.id={$organizationId}; ";
396 $dao = CRM_Core_DAO
::executeQuery($query);
400 * Function to clear cached current employer name
402 * @param int $contactId contact id ( mostly individual contact id)
403 * @param int $employerId contact id ( mostly organization contact id)
406 static function clearCurrentEmployer($contactId, $employerId = NULL) {
407 $query = "UPDATE civicrm_contact
408 SET organization_name=NULL, employer_id = NULL
409 WHERE id={$contactId}; ";
411 $dao = CRM_Core_DAO
::executeQuery($query);
413 // need to handle related meberships. CRM-3792
415 //1. disable corresponding relationship.
416 //2. delete related membership.
418 //get the relationship type id of "Employee of"
419 $relTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType', 'Employee of', 'id', 'name_a_b');
421 CRM_Core_Error
::fatal(ts("You seem to have deleted the relationship type 'Employee of'"));
423 $relMembershipParams['relationship_type_id'] = $relTypeId . '_a_b';
424 $relMembershipParams['contact_check'][$employerId] = 1;
426 //get relationship id.
427 if (CRM_Contact_BAO_Relationship
::checkDuplicateRelationship($relMembershipParams, $contactId, $employerId)) {
428 $relationship = new CRM_Contact_DAO_Relationship();
429 $relationship->contact_id_a
= $contactId;
430 $relationship->contact_id_b
= $employerId;
431 $relationship->relationship_type_id
= $relTypeId;
433 if ($relationship->find(TRUE)) {
434 CRM_Contact_BAO_Relationship
::setIsActive($relationship->id
, FALSE);
435 CRM_Contact_BAO_Relationship
::relatedMemberships($contactId, $relMembershipParams,
437 ), CRM_Core_Action
::DELETE
440 $relationship->free();
446 * Function to build form for related contacts / on behalf of organization.
448 * @param $form object invoking Object
449 * @param $contactType string contact type
452 * @param $title string fieldset title
454 * @internal param int $maxLocationBlocks number of location blocks
458 static function buildOnBehalfForm(&$form, $contactType, $countryID, $stateID, $title) {
460 $config = CRM_Core_Config
::singleton();
462 $form->assign('contact_type', $contactType);
463 $form->assign('fieldSetTitle', $title);
464 $form->assign('contactEditMode', TRUE);
466 $attributes = CRM_Core_DAO
::getAttribute('CRM_Contact_DAO_Contact');
467 if ($form->_contactId
) {
468 $form->assign('orgId', $form->_contactId
);
471 switch ($contactType) {
473 $form->add('text', 'organization_name', ts('Organization Name'), $attributes['organization_name'], TRUE);
477 $form->add('text', 'household_name', ts('Household Name'), $attributes['household_name']);
482 $form->addElement('select', 'prefix_id', ts('Prefix'),
483 array('' => ts('- prefix -')) + CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id')
485 $form->addElement('text', 'first_name', ts('First Name'),
486 $attributes['first_name']
488 $form->addElement('text', 'middle_name', ts('Middle Name'),
489 $attributes['middle_name']
491 $form->addElement('text', 'last_name', ts('Last Name'),
492 $attributes['last_name']
494 $form->addElement('select', 'suffix_id', ts('Suffix'),
495 array('' => ts('- suffix -')) + CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'suffix_id')
499 $addressSequence = $config->addressSequence();
500 $form->assign('addressSequence', array_fill_keys($addressSequence, 1));
503 $form->addElement('text',
506 CRM_Core_DAO
::getAttribute('CRM_Core_DAO_Phone',
511 $form->addElement('text',
514 CRM_Core_DAO
::getAttribute('CRM_Core_DAO_Email',
518 //build the address block
519 CRM_Contact_Form_Edit_Address
::buildQuickForm($form);
523 * Function to clear cache employer name and employer id
524 * of all employee when employer get deleted.
526 * @param int $employerId contact id of employer ( organization id )
529 static function clearAllEmployee($employerId) {
531 UPDATE civicrm_contact
532 SET organization_name=NULL, employer_id = NULL
533 WHERE employer_id={$employerId}; ";
535 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
539 * Given an array of contact ids this function will return array with links to view contact page
541 * @param array $contactIDs associated contact id's
542 * @param bool $addViewLink
543 * @param bool $addEditLink
544 * @param int $originalId associated with the contact which is edited
547 * @return array $contactViewLinks returns array with links to contact view
551 static function formatContactIDSToLinks($contactIDs, $addViewLink = TRUE, $addEditLink = TRUE, $originalId = NULL) {
552 $contactLinks = array();
553 if (!is_array($contactIDs) ||
empty($contactIDs)) {
554 return $contactLinks;
557 // does contact has sufficient permissions.
558 $permissions = array(
559 'view' => 'view all contacts',
560 'edit' => 'edit all contacts',
561 'merge' => 'merge duplicate contacts',
564 $permissionedContactIds = array();
565 foreach ($permissions as $task => $permission) {
567 if (CRM_Core_Permission
::check($permission)) {
568 foreach ($contactIDs as $contactId) {
569 $permissionedContactIds[$contactId][$task] = TRUE;
574 // check permission on acl basis.
575 if (in_array($task, array(
577 $aclPermission = CRM_Core_Permission
::VIEW
;
578 if ($task == 'edit') {
579 $aclPermission = CRM_Core_Permission
::EDIT
;
581 foreach ($contactIDs as $contactId) {
582 if (CRM_Contact_BAO_Contact_Permission
::allow($contactId, $aclPermission)) {
583 $permissionedContactIds[$contactId][$task] = TRUE;
589 // retrieve display names for all contacts
591 SELECT c.id, c.display_name, c.contact_type, ce.email
592 FROM civicrm_contact c
593 LEFT JOIN civicrm_email ce ON ( ce.contact_id=c.id AND ce.is_primary = 1 )
594 WHERE c.id IN (' . implode(',', $contactIDs) . ' ) LIMIT 20';
596 $dao = CRM_Core_DAO
::executeQuery($query);
598 $contactLinks['msg'] = NULL;
600 while ($dao->fetch()) {
602 $contactLinks['rows'][$i]['display_name'] = $dao->display_name
;
603 $contactLinks['rows'][$i]['primary_email'] = $dao->email
;
605 // get the permission for current contact id.
606 $hasPermissions = CRM_Utils_Array
::value($dao->id
, $permissionedContactIds);
607 if (!is_array($hasPermissions) ||
empty($hasPermissions)) {
612 // do check for view.
613 if (array_key_exists('view', $hasPermissions)) {
614 $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>';
615 if (!$contactLinks['msg']) {
616 $contactLinks['msg'] = 'view';
619 if (array_key_exists('edit', $hasPermissions)) {
620 $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>';
621 if (!$contactLinks['msg'] ||
$contactLinks['msg'] != 'merge') {
622 $contactLinks['msg'] = 'edit';
625 if (!empty($originalId) && array_key_exists('merge', $hasPermissions)) {
626 $rgBao = new CRM_Dedupe_BAO_RuleGroup();
627 $rgBao->contact_type
= $dao->contact_type
;
628 $rgBao->used
= 'Supervised';
629 if ($rgBao->find(TRUE)) {
632 if ($rgid && isset($dao->id
)) {
633 //get an url to merge the contact
634 $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>';
635 $contactLinks['msg'] = 'merge';
642 return $contactLinks;
646 * This function retrieve component related contact information.
648 * @param array $componentIds array of component Ids.
649 * @param $componentName
650 * @param array $returnProperties array of return elements.
652 * @return array $contactDetails array of contact info.@static
654 static function contactDetails($componentIds, $componentName, $returnProperties = array(
656 $contactDetails = array();
657 if (empty($componentIds) ||
658 !in_array($componentName, array('CiviContribute', 'CiviMember', 'CiviEvent', 'Activity'))
660 return $contactDetails;
663 if (empty($returnProperties)) {
664 $autocompleteContactSearch = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
665 'contact_autocomplete_options'
667 $returnProperties = array_fill_keys(array_merge(array('sort_name'),
668 array_keys($autocompleteContactSearch)
673 if ($componentName == 'CiviContribute') {
674 $compTable = 'civicrm_contribution';
676 elseif ($componentName == 'CiviMember') {
677 $compTable = 'civicrm_membership';
679 elseif ($componentName == 'Activity') {
680 $compTable = 'civicrm_activity';
681 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
684 $compTable = 'civicrm_participant';
687 $select = $from = array();
688 foreach ($returnProperties as $property => $ignore) {
689 $value = (in_array($property, array(
690 'city', 'street_address'))) ?
'address' : $property;
693 if ($componentName == 'Activity') {
694 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
695 $select[] = "contact.$property as $property";
697 INNER JOIN civicrm_activity_contact acs ON (acs.activity_id = {$compTable}.id AND acs.record_type_id = {$sourceID})
698 INNER JOIN civicrm_contact contact ON ( contact.id = acs.contact_id )";
701 $select[] = "$property as $property";
702 $from[$value] = "INNER JOIN civicrm_contact contact ON ( contact.id = $compTable.contact_id )";
706 case 'target_sort_name':
707 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
708 $select[] = "contact_target.sort_name as $property";
710 INNER JOIN civicrm_activity_contact act ON (act.activity_id = {$compTable}.id AND act.record_type_id = {$targetID})
711 INNER JOIN civicrm_contact contact_target ON ( contact_target.id = act.contact_id )";
717 case 'street_address':
718 $select[] = "$property as $property";
719 // Grab target contact properties if this is for activity
720 if ($componentName == 'Activity') {
721 $from[$value] = "LEFT JOIN civicrm_{$value} {$value} ON ( contact_target.id = {$value}.contact_id AND {$value}.is_primary = 1 ) ";
724 $from[$value] = "LEFT JOIN civicrm_{$value} {$value} ON ( contact.id = {$value}.contact_id AND {$value}.is_primary = 1 ) ";
729 case 'state_province':
730 $select[] = "{$property}.name as $property";
731 if (!in_array('address', $from)) {
732 // Grab target contact properties if this is for activity
733 if ($componentName == 'Activity') {
734 $from['address'] = 'LEFT JOIN civicrm_address address ON ( contact_target.id = address.contact_id AND address.is_primary = 1) ';
737 $from['address'] = 'LEFT JOIN civicrm_address address ON ( contact.id = address.contact_id AND address.is_primary = 1) ';
740 $from[$value] = " LEFT JOIN civicrm_{$value} {$value} ON ( address.{$value}_id = {$value}.id ) ";
745 //finally retrieve contact details.
746 if (!empty($select) && !empty($from)) {
747 $fromClause = implode(' ', $from);
748 $selectClause = implode(', ', $select);
749 $whereClause = "{$compTable}.id IN (" . implode(',', $componentIds) . ')';
752 SELECT contact.id as contactId, $compTable.id as componentId, $selectClause
753 FROM $compTable as $compTable $fromClause
755 Group By componentId";
757 $contact = CRM_Core_DAO
::executeQuery($query);
758 while ($contact->fetch()) {
759 $contactDetails[$contact->componentId
]['contact_id'] = $contact->contactId
;
760 foreach ($returnProperties as $property => $ignore) {
761 $contactDetails[$contact->componentId
][$property] = $contact->$property;
767 return $contactDetails;
771 * Function handles shared contact address processing
772 * In this function we just modify submitted values so that new address created for the user
773 * has same address as shared contact address. We copy the address so that search etc will be
776 * @param array $address this is associated array which contains submitted form values
782 static function processSharedAddress(&$address) {
783 if (!is_array($address)) {
787 // Sharing contact address during create mode is pretty straight forward.
788 // In update mode we should check following:
789 // - We should check if user has uncheck shared contact address
790 // - If yes then unset the master_id or may be just delete the address that copied master
791 // Normal update process will automatically create new address with submitted values
793 // 1. loop through entire subnitted address array
794 $masterAddress = array();
795 $skipFields = array('is_primary', 'location_type_id', 'is_billing', 'master_id');
796 foreach ($address as & $values) {
797 // 2. check if master id exists, if not continue
798 if (empty($values['master_id']) ||
empty($values['use_shared_address'])) {
799 // we should unset master id when use uncheck share address for existing address
800 $values['master_id'] = 'null';
804 // 3. get the address details for master_id
805 $masterAddress = new CRM_Core_BAO_Address();
806 $masterAddress->id
= CRM_Utils_Array
::value('master_id', $values);
807 $masterAddress->find(TRUE);
809 // 4. modify submitted params and update it with shared contact address
810 // make sure you preserve specific form values like location type, is_primary_ is_billing, master_id
811 // CRM-10336: Also empty any fields from the existing address block if they don't exist in master (otherwise they will persist)
812 foreach ($values as $field => $submittedValue) {
813 if (!in_array($field, $skipFields)){
814 if (isset($masterAddress->$field)) {
815 $values[$field] = $masterAddress->$field;
817 $values[$field] = '';
825 * Function to get the list of contact name give address associated array
827 * @param array $addresses associated array of
829 * @return array $contactNames associated array of contact names@static
831 static function getAddressShareContactNames(&$addresses) {
832 $contactNames = array();
833 // get the list of master id's for address
834 $masterAddressIds = array();
835 foreach ($addresses as $key => $addressValue) {
836 if (!empty($addressValue['master_id'])) {
837 $masterAddressIds[] = $addressValue['master_id'];
841 if (!empty($masterAddressIds)) {
842 $query = 'SELECT ca.id, cc.display_name, cc.id as cid, cc.is_deleted
843 FROM civicrm_contact cc
844 INNER JOIN civicrm_address ca ON cc.id = ca.contact_id
845 WHERE ca.id IN ( ' . implode(',', $masterAddressIds) . ')';
846 $dao = CRM_Core_DAO
::executeQuery($query);
848 while ($dao->fetch()) {
849 $contactViewUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$dao->cid}");
850 $contactNames[$dao->id
] = array(
851 'name' => "<a href='{$contactViewUrl}'>{$dao->display_name}</a>",
852 'is_deleted' => $dao->is_deleted
,
856 return $contactNames;
860 * Clear the contact cache so things are kosher. We started off being super aggressive with clearing
861 * caches, but are backing off from this with every release. Compromise between ease of coding versus
862 * performance versus being accurate at that very instant
864 * @param $contactID - the contactID that was edited / deleted
869 static function clearContactCaches($contactID = NULL) {
870 // clear acl cache if any.
871 CRM_ACL_BAO_Cache
::resetCache();
873 if (empty($contactID)) {
874 // also clear prev/next dedupe cache - if no contactID passed in
875 CRM_Core_BAO_PrevNextCache
::deleteItem();
878 // reset the group contact cache for this group
879 CRM_Contact_BAO_GroupContactCache
::remove();
887 public static function updateGreeting($params) {
888 $contactType = $params['ct'];
889 $greeting = $params['gt'];
890 $valueID = $id = CRM_Utils_Array
::value('id', $params);
891 $force = CRM_Utils_Array
::value('force', $params);
892 $limit = CRM_Utils_Array
::value('limit', $params);
894 // if valueID is not passed use default value
896 $valueID = $id = self
::defaultGreeting($contactType, $greeting);
900 'contact_type' => $contactType,
901 'greeting_type' => $greeting,
904 $allGreetings = CRM_Core_PseudoConstant
::greeting($filter);
905 $originalGreetingString = $greetingString = CRM_Utils_Array
::value($valueID, $allGreetings);
906 if (!$greetingString) {
907 CRM_Core_Error
::fatal(ts('Incorrect greeting value id %1, or no default greeting for this contact type and greeting type.', array(1 => $valueID)));
910 // build return properties based on tokens
911 $greetingTokens = CRM_Utils_Token
::getTokens($greetingString);
912 $tokens = CRM_Utils_Array
::value('contact', $greetingTokens);
913 $greetingsReturnProperties = array();
914 if (is_array($tokens)) {
915 $greetingsReturnProperties = array_fill_keys(array_values($tokens), 1);
918 // Process ALL contacts only when force=1 or force=2 is passed. Else only contacts with NULL greeting or addressee value are updated.
919 $processAll = $processOnlyIdSet = FALSE;
923 elseif ($force == 2) {
924 $processOnlyIdSet = TRUE;
927 //FIXME : apiQuery should handle these clause.
928 $filterContactFldIds = $filterIds = array();
929 $idFldName = $displayFldName = NULL;
930 if (in_array($greeting, CRM_Contact_BAO_Contact
::$_greetingTypes)) {
931 $idFldName = $greeting . '_id';
932 $displayFldName = $greeting . '_display';
936 $queryParams = array(1 => array($contactType, 'String'));
938 // if $force == 1 then update all contacts else only
939 // those with NULL greeting or addressee value CRM-9476
941 $sql = "SELECT DISTINCT id, $idFldName FROM civicrm_contact WHERE contact_type = %1 ";
945 SELECT DISTINCT id, $idFldName
947 WHERE contact_type = %1
948 AND ({$idFldName} IS NULL
949 OR ( {$idFldName} IS NOT NULL AND ({$displayFldName} IS NULL OR {$displayFldName} = '')) )";
953 $sql .= " LIMIT 0, %2";
954 $queryParams +
= array(2 => array($limit, 'Integer'));
957 $dao = CRM_Core_DAO
::executeQuery($sql, $queryParams);
958 while ($dao->fetch()) {
959 $filterContactFldIds[$dao->id
] = $dao->$idFldName;
961 if (!CRM_Utils_System
::isNull($dao->$idFldName)) {
962 $filterIds[$dao->id
] = $dao->$idFldName;
967 if (empty($filterContactFldIds)) {
968 $filterContactFldIds[] = 0;
971 // retrieve only required contact information
972 $extraParams[] = array('contact_type', '=', $contactType, 0, 0);
973 // we do token replacement in the replaceGreetingTokens hook
974 list($greetingDetails) = CRM_Utils_Token
::getTokenDetails(array_keys($filterContactFldIds),
975 $greetingsReturnProperties,
976 FALSE, FALSE, $extraParams
978 // perform token replacement and build update SQL
979 $contactIds = array();
980 $cacheFieldQuery = "UPDATE civicrm_contact SET {$greeting}_display = CASE id ";
981 foreach ($greetingDetails as $contactID => $contactDetails) {
983 !array_key_exists($contactID, $filterContactFldIds)
988 if ($processOnlyIdSet && !array_key_exists($contactID, $filterIds)) {
993 $greetingString = $originalGreetingString;
994 $contactIds[] = $contactID;
997 if ($greetingBuffer = CRM_Utils_Array
::value($filterContactFldIds[$contactID], $allGreetings)) {
998 $greetingString = $greetingBuffer;
1002 self
::processGreetingTemplate($greetingString, $contactDetails, $contactID, 'CRM_UpdateGreeting');
1003 $greetingString = CRM_Core_DAO
::escapeString($greetingString);
1004 $cacheFieldQuery .= " WHEN {$contactID} THEN '{$greetingString}' ";
1006 $allContactIds[] = $contactID;
1009 if (!empty($allContactIds)) {
1010 $cacheFieldQuery .= " ELSE {$greeting}_display
1012 if (!empty($contactIds)) {
1013 // need to update greeting _id field.
1014 // reset greeting _custom
1015 $resetCustomGreeting = '';
1016 if ($valueID != 4) {
1017 $resetCustomGreeting = ", {$greeting}_custom = NULL ";
1021 UPDATE civicrm_contact
1022 SET {$greeting}_id = {$valueID}
1023 {$resetCustomGreeting}
1024 WHERE id IN (" . implode(',', $contactIds) . ")";
1025 CRM_Core_DAO
::executeQuery($queryString);
1028 // now update cache field
1029 CRM_Core_DAO
::executeQuery($cacheFieldQuery);
1034 * Fetch the default greeting for a given contact type
1036 * @param string $contactType contact type
1037 * @param string $greetingType greeting type
1039 * @return int or null
1041 static function defaultGreeting($contactType, $greetingType) {
1042 $contactTypeFilters = array('Individual' => 1, 'Household' => 2, 'Organization' => 3);
1043 if (!isset($contactTypeFilters[$contactType])) {
1046 $filter = $contactTypeFilters[$contactType];
1048 $id = CRM_Core_OptionGroup
::values($greetingType, NULL, NULL, NULL,
1049 " AND is_default = 1 AND (filter = {$filter} OR filter = 0)",
1053 return current($id);
1058 * Process a greeting template string to produce the individualised greeting text.
1060 * This works just like message templates for mailings:
1061 * the template is processed with the token substitution mechanism,
1062 * to supply the individual contact data;
1063 * and it is also processed with Smarty,
1064 * to allow for conditionals etc. based on the contact data.
1066 * Note: We don't pass any variables to Smarty --
1067 * all variable data is inserted into the input string
1068 * by the token substitution mechanism,
1069 * before Smarty is invoked.
1071 * @param string $templateString the greeting template string with contact tokens + Smarty syntax
1073 * @param $contactDetails
1080 static function processGreetingTemplate(&$templateString, $contactDetails, $contactID, $className) {
1081 CRM_Utils_Token
::replaceGreetingTokens($templateString, $contactDetails, $contactID, $className, TRUE);
1083 $smarty = CRM_Core_Smarty
::singleton();
1084 $templateString = $smarty->fetch("string:$templateString");