Merge pull request #4768 from rohankatkar/CRM-10331Fix
[civicrm-core.git] / CRM / Contact / BAO / Contact / Utils.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35 class CRM_Contact_BAO_Contact_Utils {
36
37 /**
38 * Given a contact type, get the contact image
39 *
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
44 *
45 * @return string
46 * @access public
47 * @static
48 */
49 static function getImage($contactType, $urlOnly = FALSE, $contactId = NULL, $addProfileOverlay = TRUE) {
50 static $imageInfo = array();
51
52 $contactType = explode(CRM_Core_DAO::VALUE_SEPARATOR, trim($contactType, CRM_Core_DAO::VALUE_SEPARATOR));
53 $contactType = $contactType[0];
54
55 if (!array_key_exists($contactType, $imageInfo)) {
56 $imageInfo[$contactType] = array();
57
58 $typeInfo = array();
59 $params = array('name' => $contactType);
60 CRM_Contact_BAO_ContactType::retrieve($params, $typeInfo);
61
62 if (!empty($typeInfo['image_URL'])) {
63 $imageUrl = $typeInfo['image_URL'];
64 $config = CRM_Core_Config::singleton();
65
66 if (!preg_match("/^(\/|(http(s)?:)).+$/i", $imageUrl)) {
67 $imageUrl = $config->resourceBase . $imageUrl;
68 }
69 $imageInfo[$contactType]['image'] = "<div class=\"icon crm-icon {$typeInfo['name']}-icon\" style=\"background: url('{$imageUrl}')\" title=\"{$contactType}\"></div>";
70 $imageInfo[$contactType]['url'] = $imageUrl;
71 }
72 else {
73 $isSubtype = (array_key_exists('parent_id', $typeInfo) &&
74 $typeInfo['parent_id']
75 ) ? TRUE : FALSE;
76
77 if ($isSubtype) {
78 $type = CRM_Contact_BAO_ContactType::getBasicType($typeInfo['name']) . '-subtype';
79 }
80 else {
81 $type = CRM_Utils_Array::value('name', $typeInfo);
82 }
83
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>";
87 }
88 else{
89 $imageInfo[$contactType]['image'] = "<div class=\"icon crm-icon {$type}-icon\" title=\"{$contactType}\"></div>";
90 }
91 $imageInfo[$contactType]['url'] = NULL;
92 }
93 }
94
95 if ($addProfileOverlay) {
96 static $summaryOverlayProfileId = NULL;
97 if (!$summaryOverlayProfileId) {
98 $summaryOverlayProfileId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', 'summary_overlay', 'id', 'name');
99 }
100
101 $profileURL = CRM_Utils_System::url('civicrm/profile/view',
102 "reset=1&gid={$summaryOverlayProfileId}&id={$contactId}&snippet=4"
103 );
104
105 $imageInfo[$contactType]['summary-link'] = '<a href="' . $profileURL . '" class="crm-summary-link">' . $imageInfo[$contactType]['image'] . '</a>';
106 }
107 else {
108 $imageInfo[$contactType]['summary-link'] = $imageInfo[$contactType]['image'];
109 }
110
111 return $urlOnly ? $imageInfo[$contactType]['url'] : $imageInfo[$contactType]['summary-link'];
112 }
113
114 /**
115 * Function check for mix contact ids(individual+household etc...)
116 *
117 * @param array $contactIds array of contact ids
118 *
119 * @return boolen true or false true if mix contact array else fale
120 *
121 * @access public
122 * @static
123 */
124 public static function checkContactType(&$contactIds) {
125 if (empty($contactIds)) {
126 return FALSE;
127 }
128
129 $idString = implode(',', $contactIds);
130 $query = "
131 SELECT count( DISTINCT contact_type )
132 FROM civicrm_contact
133 WHERE id IN ( $idString )
134 ";
135 $count = CRM_Core_DAO::singleValueQuery($query,
136 CRM_Core_DAO::$_nullArray
137 );
138 return $count > 1 ? TRUE : FALSE;
139 }
140
141 /**
142 * Generate a checksum for a $entityId of type $entityType
143 *
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
148 *
149 * @param string $entityType
150 * @param null $hashSize
151 *
152 * @return array ( $cs, $ts, $live )
153 * @static
154 * @access public
155 */
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
160 if (!$entityId) {
161 return 'invalidChecksum';
162 }
163
164 if (!$hash) {
165 if ($entityType == 'contact') {
166 $hash = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
167 $entityId, 'hash'
168 );
169 }
170 elseif ($entityType == 'mailing') {
171 $hash = CRM_Core_DAO::getFieldValue('CRM_Mailing_DAO_Mailing',
172 $entityId, 'hash'
173 );
174 }
175 }
176
177 if (!$hash) {
178 $hash = md5(uniqid(rand(), TRUE));
179 if ($hashSize) {
180 $hash = substr($hash, 0, $hashSize);
181 }
182
183 if ($entityType == 'contact') {
184 CRM_Core_DAO::setFieldValue('CRM_Contact_DAO_Contact',
185 $entityId,
186 'hash', $hash
187 );
188 }
189 elseif ($entityType == 'mailing') {
190 CRM_Core_DAO::setFieldValue('CRM_Mailing_DAO_Mailing',
191 $entityId,
192 'hash', $hash
193 );
194 }
195 }
196
197 if (!$ts) {
198 $ts = time();
199 }
200
201 if (!$live) {
202 $days = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
203 'checksum_timeout',
204 NULL,
205 7
206 );
207 $live = 24 * $days;
208 }
209
210 $cs = md5("{$hash}_{$entityId}_{$ts}_{$live}");
211 return "{$cs}_{$ts}_{$live}";
212 }
213
214 /**
215 * Make sure the checksum is valid for the passed in contactID
216 *
217 * @param int $contactID
218 * @param string $inputCheck checksum to match against
219 *
220 * @return boolean true if valid, else false
221 * @static
222 * @access public
223 */
224 static function validChecksum($contactID, $inputCheck) {
225
226 $input = CRM_Utils_System::explode('_', $inputCheck, 3);
227
228 $inputCS = CRM_Utils_Array::value(0, $input);
229 $inputTS = CRM_Utils_Array::value(1, $input);
230 $inputLF = CRM_Utils_Array::value(2, $input);
231
232 $check = self::generateChecksum($contactID, $inputTS, $inputLF);
233
234 if ($check != $inputCheck) {
235 return FALSE;
236 }
237
238 // no life limit for checksum
239 if ($inputLF == 'inf') {
240 return TRUE;
241 }
242
243 // checksum matches so now check timestamp
244 $now = time();
245 return ($inputTS + ($inputLF * 60 * 60) >= $now);
246 }
247
248 /**
249 * Get the count of contact loctions
250 *
251 * @param int $contactId contact id
252 *
253 * @return int $locationCount max locations for the contact
254 * @static
255 * @access public
256 */
257 static function maxLocations($contactId) {
258 $contactLocations = array();
259
260 // find number of location blocks for this contact and adjust value accordinly
261 // get location type from email
262 $query = "
263 ( SELECT location_type_id FROM civicrm_email WHERE contact_id = {$contactId} )
264 UNION
265 ( SELECT location_type_id FROM civicrm_phone WHERE contact_id = {$contactId} )
266 UNION
267 ( SELECT location_type_id FROM civicrm_im WHERE contact_id = {$contactId} )
268 UNION
269 ( SELECT location_type_id FROM civicrm_address WHERE contact_id = {$contactId} )
270 ";
271 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
272 return $dao->N;
273 }
274
275 /**
276 * Create Current employer relationship for a individual
277 *
278 * @param int $contactID contact id of the individual
279 * @param $organization (id or name)
280 * @param int $previousEmployerID
281 * @param bool $newContact
282 *
283 * @access public
284 * @static
285 */
286 static function createCurrentEmployerRelationship($contactID, $organization, $previousEmployerID = NULL, $newContact = FALSE) {
287 //if organization name is passed. CRM-15368,CRM-15547
288 if ($organization && !is_numeric($organization)) {
289 $organizationParams['organization_name'] = $organization;
290 $dedupeParams = CRM_Dedupe_Finder::formatParams($organizationParams, 'Organization');
291
292 $dedupeParams['check_permission'] = FALSE;
293 $dupeIDs = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Organization', 'Unsupervised');
294
295 if (is_array($dupeIDs) && !empty($dupeIDs)) {
296 // we should create relationship only w/ first org CRM-4193
297 foreach ($dupeIDs as $orgId) {
298 $organization = $orgId;
299 break;
300 }
301 }
302 else {
303 //create new organization
304 $newOrg = array(
305 'contact_type' => 'Organization',
306 'organization_name' => $organization,
307 );
308 $org = CRM_Contact_BAO_Contact::create($newOrg);
309 $organization = $org->id;
310 }
311 }
312
313 if ($organization && is_numeric($organization)) {
314 $cid = array('contact' => $contactID);
315
316 // get the relationship type id of "Employee of"
317 $relTypeId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', 'Employee of', 'id', 'name_a_b');
318 if (!$relTypeId) {
319 CRM_Core_Error::fatal(ts("You seem to have deleted the relationship type 'Employee of'"));
320 }
321
322 // create employee of relationship
323 $relationshipParams = array(
324 'is_active' => TRUE,
325 'relationship_type_id' => $relTypeId . '_a_b',
326 'contact_check' => array($organization => TRUE),
327 );
328 list($valid, $invalid, $duplicate,
329 $saved, $relationshipIds
330 ) = CRM_Contact_BAO_Relationship::create($relationshipParams, $cid);
331
332
333 // In case we change employer, clean previous employer related records.
334 if (!$previousEmployerID && !$newContact) {
335 $previousEmployerID = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id');
336 }
337 if ($previousEmployerID &&
338 $previousEmployerID != $organization
339 ) {
340 self::clearCurrentEmployer($contactID, $previousEmployerID);
341 }
342
343 // set current employer
344 self::setCurrentEmployer(array($contactID => $organization));
345
346 $relationshipParams['relationship_ids'] = $relationshipIds;
347 // handle related meberships. CRM-3792
348 self::currentEmployerRelatedMembership($contactID, $organization, $relationshipParams, $duplicate, $previousEmployerID);
349 }
350 }
351
352 /**
353 * Create related memberships for current employer
354 *
355 * @param int $contactID contact id of the individual
356 * @param int $employerID contact id of the organization.
357 * @param array $relationshipParams relationship params.
358 * @param boolean $duplicate are we triggered existing relationship.
359 *
360 * @param int $previousEmpID
361 *
362 * @throws CiviCRM_API3_Exception
363 * @access public
364 * @static
365 */
366 static function currentEmployerRelatedMembership($contactID, $employerID, $relationshipParams, $duplicate = FALSE, $previousEmpID = NULL) {
367 $ids = array();
368 $action = CRM_Core_Action::ADD;
369
370 //we do not know that triggered relationship record is active.
371 if ($duplicate) {
372 $relationship = new CRM_Contact_DAO_Relationship();
373 $relationship->contact_id_a = $contactID;
374 $relationship->contact_id_b = $employerID;
375 $relationship->relationship_type_id = $relationshipParams['relationship_type_id'];
376 if ($relationship->find(TRUE)) {
377 $action = CRM_Core_Action::UPDATE;
378 $ids['contact'] = $contactID;
379 $ids['contactTarget'] = $employerID;
380 $ids['relationship'] = $relationship->id;
381 CRM_Contact_BAO_Relationship::setIsActive($relationship->id, TRUE);
382 }
383 $relationship->free();
384 }
385
386 //need to handle related meberships. CRM-3792
387 if ($previousEmpID != $employerID) {
388 CRM_Contact_BAO_Relationship::relatedMemberships($contactID, $relationshipParams, $ids, $action);
389 }
390 }
391
392 /**
393 * Set current employer id and organization name
394 *
395 * @param array $currentEmployerParams associated array of contact id and its employer id
396 *
397 */
398 static function setCurrentEmployer($currentEmployerParams) {
399 foreach ($currentEmployerParams as $contactId => $orgId) {
400 $query = "UPDATE civicrm_contact contact_a,civicrm_contact contact_b
401 SET contact_a.employer_id=contact_b.id, contact_a.organization_name=contact_b.organization_name
402 WHERE contact_a.id ={$contactId} AND contact_b.id={$orgId}; ";
403
404 //FIXME : currently civicrm mysql_query support only single statement
405 //execution, though mysql 5.0 support multiple statement execution.
406 $dao = CRM_Core_DAO::executeQuery($query);
407 }
408 }
409
410 /**
411 * Update cached current employer name
412 *
413 * @param int $organizationId current employer id
414 *
415 */
416 static function updateCurrentEmployer($organizationId) {
417 $query = "UPDATE civicrm_contact contact_a,civicrm_contact contact_b
418 SET contact_a.organization_name=contact_b.organization_name
419 WHERE contact_a.employer_id=contact_b.id AND contact_b.id={$organizationId}; ";
420
421 $dao = CRM_Core_DAO::executeQuery($query);
422 }
423
424 /**
425 * Clear cached current employer name
426 *
427 * @param int $contactId contact id ( mostly individual contact id)
428 * @param int $employerId contact id ( mostly organization contact id)
429 *
430 */
431 static function clearCurrentEmployer($contactId, $employerId = NULL) {
432 $query = "UPDATE civicrm_contact
433 SET organization_name=NULL, employer_id = NULL
434 WHERE id={$contactId}; ";
435
436 $dao = CRM_Core_DAO::executeQuery($query);
437
438 // need to handle related meberships. CRM-3792
439 if ($employerId) {
440 //1. disable corresponding relationship.
441 //2. delete related membership.
442
443 //get the relationship type id of "Employee of"
444 $relTypeId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', 'Employee of', 'id', 'name_a_b');
445 if (!$relTypeId) {
446 CRM_Core_Error::fatal(ts("You seem to have deleted the relationship type 'Employee of'"));
447 }
448 $relMembershipParams['relationship_type_id'] = $relTypeId . '_a_b';
449 $relMembershipParams['contact_check'][$employerId] = 1;
450
451 //get relationship id.
452 if (CRM_Contact_BAO_Relationship::checkDuplicateRelationship($relMembershipParams, $contactId, $employerId)) {
453 $relationship = new CRM_Contact_DAO_Relationship();
454 $relationship->contact_id_a = $contactId;
455 $relationship->contact_id_b = $employerId;
456 $relationship->relationship_type_id = $relTypeId;
457
458 if ($relationship->find(TRUE)) {
459 CRM_Contact_BAO_Relationship::setIsActive($relationship->id, FALSE);
460 CRM_Contact_BAO_Relationship::relatedMemberships($contactId, $relMembershipParams,
461 $ids = array(
462 ), CRM_Core_Action::DELETE
463 );
464 }
465 $relationship->free();
466 }
467 }
468 }
469
470 /**
471 * Build form for related contacts / on behalf of organization.
472 *
473 * @param CRM_Core_Form $form
474 * @param $contactType string contact type
475 * @param int $countryID
476 * @param int $stateID
477 * @param $title string fieldset title
478 *
479 * @static
480 */
481 static function buildOnBehalfForm(&$form, $contactType, $countryID, $stateID, $title) {
482
483 $config = CRM_Core_Config::singleton();
484
485 $form->assign('contact_type', $contactType);
486 $form->assign('fieldSetTitle', $title);
487 $form->assign('contactEditMode', TRUE);
488
489 $attributes = CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact');
490 if ($form->_contactId) {
491 $form->assign('orgId', $form->_contactId);
492 }
493
494 switch ($contactType) {
495 case 'Organization':
496 $form->add('text', 'organization_name', ts('Organization Name'), $attributes['organization_name'], TRUE);
497 break;
498
499 case 'Household':
500 $form->add('text', 'household_name', ts('Household Name'), $attributes['household_name']);
501 break;
502
503 default:
504 // individual
505 $form->addElement('select', 'prefix_id', ts('Prefix'),
506 array('' => ts('- prefix -')) + CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'prefix_id')
507 );
508 $form->addElement('text', 'first_name', ts('First Name'),
509 $attributes['first_name']
510 );
511 $form->addElement('text', 'middle_name', ts('Middle Name'),
512 $attributes['middle_name']
513 );
514 $form->addElement('text', 'last_name', ts('Last Name'),
515 $attributes['last_name']
516 );
517 $form->addElement('select', 'suffix_id', ts('Suffix'),
518 array('' => ts('- suffix -')) + CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'suffix_id')
519 );
520 }
521
522 $addressSequence = $config->addressSequence();
523 $form->assign('addressSequence', array_fill_keys($addressSequence, 1));
524
525 //Primary Phone
526 $form->addElement('text',
527 'phone[1][phone]',
528 ts('Primary Phone'),
529 CRM_Core_DAO::getAttribute('CRM_Core_DAO_Phone',
530 'phone'
531 )
532 );
533 //Primary Email
534 $form->addElement('text',
535 'email[1][email]',
536 ts('Primary Email'),
537 CRM_Core_DAO::getAttribute('CRM_Core_DAO_Email',
538 'email'
539 )
540 );
541 //build the address block
542 CRM_Contact_Form_Edit_Address::buildQuickForm($form);
543 }
544
545 /**
546 * Clear cache employer name and employer id
547 * of all employee when employer get deleted.
548 *
549 * @param int $employerId contact id of employer ( organization id )
550 *
551 */
552 static function clearAllEmployee($employerId) {
553 $query = "
554 UPDATE civicrm_contact
555 SET organization_name=NULL, employer_id = NULL
556 WHERE employer_id={$employerId}; ";
557
558 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
559 }
560
561 /**
562 * Given an array of contact ids this function will return array with links to view contact page
563 *
564 * @param array $contactIDs associated contact id's
565 * @param bool $addViewLink
566 * @param bool $addEditLink
567 * @param int $originalId associated with the contact which is edited
568 *
569 *
570 * @return array $contactViewLinks returns array with links to contact view
571 * @static
572 * @access public
573 */
574 static function formatContactIDSToLinks($contactIDs, $addViewLink = TRUE, $addEditLink = TRUE, $originalId = NULL) {
575 $contactLinks = array();
576 if (!is_array($contactIDs) || empty($contactIDs)) {
577 return $contactLinks;
578 }
579
580 // does contact has sufficient permissions.
581 $permissions = array(
582 'view' => 'view all contacts',
583 'edit' => 'edit all contacts',
584 'merge' => 'merge duplicate contacts',
585 );
586
587 $permissionedContactIds = array();
588 foreach ($permissions as $task => $permission) {
589 // give permission.
590 if (CRM_Core_Permission::check($permission)) {
591 foreach ($contactIDs as $contactId) {
592 $permissionedContactIds[$contactId][$task] = TRUE;
593 }
594 continue;
595 }
596
597 // check permission on acl basis.
598 if (in_array($task, array(
599 'view', 'edit'))) {
600 $aclPermission = CRM_Core_Permission::VIEW;
601 if ($task == 'edit') {
602 $aclPermission = CRM_Core_Permission::EDIT;
603 }
604 foreach ($contactIDs as $contactId) {
605 if (CRM_Contact_BAO_Contact_Permission::allow($contactId, $aclPermission)) {
606 $permissionedContactIds[$contactId][$task] = TRUE;
607 }
608 }
609 }
610 }
611
612 // retrieve display names for all contacts
613 $query = '
614 SELECT c.id, c.display_name, c.contact_type, ce.email
615 FROM civicrm_contact c
616 LEFT JOIN civicrm_email ce ON ( ce.contact_id=c.id AND ce.is_primary = 1 )
617 WHERE c.id IN (' . implode(',', $contactIDs) . ' ) LIMIT 20';
618
619 $dao = CRM_Core_DAO::executeQuery($query);
620
621 $contactLinks['msg'] = NULL;
622 $i = 0;
623 while ($dao->fetch()) {
624
625 $contactLinks['rows'][$i]['display_name'] = $dao->display_name;
626 $contactLinks['rows'][$i]['primary_email'] = $dao->email;
627
628 // get the permission for current contact id.
629 $hasPermissions = CRM_Utils_Array::value($dao->id, $permissionedContactIds);
630 if (!is_array($hasPermissions) || empty($hasPermissions)) {
631 $i++;
632 continue;
633 }
634
635 // do check for view.
636 if (array_key_exists('view', $hasPermissions)) {
637 $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>';
638 if (!$contactLinks['msg']) {
639 $contactLinks['msg'] = 'view';
640 }
641 }
642 if (array_key_exists('edit', $hasPermissions)) {
643 $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>';
644 if (!$contactLinks['msg'] || $contactLinks['msg'] != 'merge') {
645 $contactLinks['msg'] = 'edit';
646 }
647 }
648 if (!empty($originalId) && array_key_exists('merge', $hasPermissions)) {
649 $rgBao = new CRM_Dedupe_BAO_RuleGroup();
650 $rgBao->contact_type = $dao->contact_type;
651 $rgBao->used = 'Supervised';
652 if ($rgBao->find(TRUE)) {
653 $rgid = $rgBao->id;
654 }
655 if ($rgid && isset($dao->id)) {
656 //get an url to merge the contact
657 $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>';
658 $contactLinks['msg'] = 'merge';
659 }
660 }
661
662 $i++;
663 }
664
665 return $contactLinks;
666 }
667
668 /**
669 * This function retrieve component related contact information.
670 *
671 * @param array $componentIds array of component Ids.
672 * @param string $componentName
673 * @param array $returnProperties array of return elements.
674 *
675 * @return array $contactDetails array of contact info.@static
676 */
677 static function contactDetails($componentIds, $componentName, $returnProperties = array()) {
678 $contactDetails = array();
679 if (empty($componentIds) ||
680 !in_array($componentName, array('CiviContribute', 'CiviMember', 'CiviEvent', 'Activity'))
681 ) {
682 return $contactDetails;
683 }
684
685 if (empty($returnProperties)) {
686 $autocompleteContactSearch = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
687 'contact_autocomplete_options'
688 );
689 $returnProperties = array_fill_keys(array_merge(array('sort_name'),
690 array_keys($autocompleteContactSearch)
691 ), 1);
692 }
693
694 $compTable = NULL;
695 if ($componentName == 'CiviContribute') {
696 $compTable = 'civicrm_contribution';
697 }
698 elseif ($componentName == 'CiviMember') {
699 $compTable = 'civicrm_membership';
700 }
701 elseif ($componentName == 'Activity') {
702 $compTable = 'civicrm_activity';
703 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
704 }
705 else {
706 $compTable = 'civicrm_participant';
707 }
708
709 $select = $from = array();
710 foreach ($returnProperties as $property => $ignore) {
711 $value = (in_array($property, array(
712 'city', 'street_address'))) ? 'address' : $property;
713 switch ($property) {
714 case 'sort_name':
715 if ($componentName == 'Activity') {
716 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
717 $select[] = "contact.$property as $property";
718 $from[$value] = "
719 INNER JOIN civicrm_activity_contact acs ON (acs.activity_id = {$compTable}.id AND acs.record_type_id = {$sourceID})
720 INNER JOIN civicrm_contact contact ON ( contact.id = acs.contact_id )";
721 }
722 else {
723 $select[] = "$property as $property";
724 $from[$value] = "INNER JOIN civicrm_contact contact ON ( contact.id = $compTable.contact_id )";
725 }
726 break;
727
728 case 'target_sort_name':
729 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
730 $select[] = "contact_target.sort_name as $property";
731 $from[$value] = "
732 INNER JOIN civicrm_activity_contact act ON (act.activity_id = {$compTable}.id AND act.record_type_id = {$targetID})
733 INNER JOIN civicrm_contact contact_target ON ( contact_target.id = act.contact_id )";
734 break;
735
736 case 'email':
737 case 'phone':
738 case 'city':
739 case 'street_address':
740 $select[] = "$property as $property";
741 // Grab target contact properties if this is for activity
742 if ($componentName == 'Activity') {
743 $from[$value] = "LEFT JOIN civicrm_{$value} {$value} ON ( contact_target.id = {$value}.contact_id AND {$value}.is_primary = 1 ) ";
744 }
745 else {
746 $from[$value] = "LEFT JOIN civicrm_{$value} {$value} ON ( contact.id = {$value}.contact_id AND {$value}.is_primary = 1 ) ";
747 }
748 break;
749
750 case 'country':
751 case 'state_province':
752 $select[] = "{$property}.name as $property";
753 if (!in_array('address', $from)) {
754 // Grab target contact properties if this is for activity
755 if ($componentName == 'Activity') {
756 $from['address'] = 'LEFT JOIN civicrm_address address ON ( contact_target.id = address.contact_id AND address.is_primary = 1) ';
757 }
758 else {
759 $from['address'] = 'LEFT JOIN civicrm_address address ON ( contact.id = address.contact_id AND address.is_primary = 1) ';
760 }
761 }
762 $from[$value] = " LEFT JOIN civicrm_{$value} {$value} ON ( address.{$value}_id = {$value}.id ) ";
763 break;
764 }
765 }
766
767 //finally retrieve contact details.
768 if (!empty($select) && !empty($from)) {
769 $fromClause = implode(' ', $from);
770 $selectClause = implode(', ', $select);
771 $whereClause = "{$compTable}.id IN (" . implode(',', $componentIds) . ')';
772
773 $query = "
774 SELECT contact.id as contactId, $compTable.id as componentId, $selectClause
775 FROM $compTable as $compTable $fromClause
776 WHERE $whereClause
777 Group By componentId";
778
779 $contact = CRM_Core_DAO::executeQuery($query);
780 while ($contact->fetch()) {
781 $contactDetails[$contact->componentId]['contact_id'] = $contact->contactId;
782 foreach ($returnProperties as $property => $ignore) {
783 $contactDetails[$contact->componentId][$property] = $contact->$property;
784 }
785 }
786 $contact->free();
787 }
788
789 return $contactDetails;
790 }
791
792 /**
793 * Function handles shared contact address processing
794 * In this function we just modify submitted values so that new address created for the user
795 * has same address as shared contact address. We copy the address so that search etc will be
796 * much efficient.
797 *
798 * @param array $address this is associated array which contains submitted form values
799 *
800 * @return void
801 * @static
802 * @access public
803 */
804 static function processSharedAddress(&$address) {
805 if (!is_array($address)) {
806 return;
807 }
808
809 // Sharing contact address during create mode is pretty straight forward.
810 // In update mode we should check following:
811 // - We should check if user has uncheck shared contact address
812 // - If yes then unset the master_id or may be just delete the address that copied master
813 // Normal update process will automatically create new address with submitted values
814
815 // 1. loop through entire subnitted address array
816 $masterAddress = array();
817 $skipFields = array('is_primary', 'location_type_id', 'is_billing', 'master_id');
818 foreach ($address as & $values) {
819 // 2. check if master id exists, if not continue
820 if (empty($values['master_id']) || empty($values['use_shared_address'])) {
821 // we should unset master id when use uncheck share address for existing address
822 $values['master_id'] = 'null';
823 continue;
824 }
825
826 // 3. get the address details for master_id
827 $masterAddress = new CRM_Core_BAO_Address();
828 $masterAddress->id = CRM_Utils_Array::value('master_id', $values);
829 $masterAddress->find(TRUE);
830
831 // 4. modify submitted params and update it with shared contact address
832 // make sure you preserve specific form values like location type, is_primary_ is_billing, master_id
833 // CRM-10336: Also empty any fields from the existing address block if they don't exist in master (otherwise they will persist)
834 foreach ($values as $field => $submittedValue) {
835 if (!in_array($field, $skipFields)){
836 if (isset($masterAddress->$field)) {
837 $values[$field] = $masterAddress->$field;
838 } else {
839 $values[$field] = '';
840 }
841 }
842 }
843 }
844 }
845
846 /**
847 * Get the list of contact name give address associated array
848 *
849 * @param array $addresses associated array of
850 *
851 * @return array $contactNames associated array of contact names@static
852 */
853 static function getAddressShareContactNames(&$addresses) {
854 $contactNames = array();
855 // get the list of master id's for address
856 $masterAddressIds = array();
857 foreach ($addresses as $key => $addressValue) {
858 if (!empty($addressValue['master_id'])) {
859 $masterAddressIds[] = $addressValue['master_id'];
860 }
861 }
862
863 if (!empty($masterAddressIds)) {
864 $query = 'SELECT ca.id, cc.display_name, cc.id as cid, cc.is_deleted
865 FROM civicrm_contact cc
866 INNER JOIN civicrm_address ca ON cc.id = ca.contact_id
867 WHERE ca.id IN ( ' . implode(',', $masterAddressIds) . ')';
868 $dao = CRM_Core_DAO::executeQuery($query);
869
870 while ($dao->fetch()) {
871 $contactViewUrl = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$dao->cid}");
872 $contactNames[$dao->id] = array(
873 'name' => "<a href='{$contactViewUrl}'>{$dao->display_name}</a>",
874 'is_deleted' => $dao->is_deleted,
875 'contact_id' => $dao->cid,
876 );
877 }
878 }
879 return $contactNames;
880 }
881
882 /**
883 * Clear the contact cache so things are kosher. We started off being super aggressive with clearing
884 * caches, but are backing off from this with every release. Compromise between ease of coding versus
885 * performance versus being accurate at that very instant
886 *
887 * @param $contactID - the contactID that was edited / deleted
888 *
889 * @return void
890 * @static
891 */
892 static function clearContactCaches($contactID = NULL) {
893 // clear acl cache if any.
894 CRM_ACL_BAO_Cache::resetCache();
895
896 if (empty($contactID)) {
897 // also clear prev/next dedupe cache - if no contactID passed in
898 CRM_Core_BAO_PrevNextCache::deleteItem();
899 }
900
901 // reset the group contact cache for this group
902 CRM_Contact_BAO_GroupContactCache::remove();
903 }
904
905 /**
906 * @param array $params
907 *
908 * @throws Exception
909 */
910 public static function updateGreeting($params) {
911 $contactType = $params['ct'];
912 $greeting = $params['gt'];
913 $valueID = $id = CRM_Utils_Array::value('id', $params);
914 $force = CRM_Utils_Array::value('force', $params);
915 $limit = CRM_Utils_Array::value('limit', $params);
916
917 // if valueID is not passed use default value
918 if (!$valueID) {
919 $valueID = $id = self::defaultGreeting($contactType, $greeting);
920 }
921
922 $filter = array(
923 'contact_type' => $contactType,
924 'greeting_type' => $greeting,
925 );
926
927 $allGreetings = CRM_Core_PseudoConstant::greeting($filter);
928 $originalGreetingString = $greetingString = CRM_Utils_Array::value($valueID, $allGreetings);
929 if (!$greetingString) {
930 CRM_Core_Error::fatal(ts('Incorrect greeting value id %1, or no default greeting for this contact type and greeting type.', array(1 => $valueID)));
931 }
932
933 // build return properties based on tokens
934 $greetingTokens = CRM_Utils_Token::getTokens($greetingString);
935 $tokens = CRM_Utils_Array::value('contact', $greetingTokens);
936 $greetingsReturnProperties = array();
937 if (is_array($tokens)) {
938 $greetingsReturnProperties = array_fill_keys(array_values($tokens), 1);
939 }
940
941 // Process ALL contacts only when force=1 or force=2 is passed. Else only contacts with NULL greeting or addressee value are updated.
942 $processAll = $processOnlyIdSet = FALSE;
943 if ($force == 1) {
944 $processAll = TRUE;
945 }
946 elseif ($force == 2) {
947 $processOnlyIdSet = TRUE;
948 }
949
950 //FIXME : apiQuery should handle these clause.
951 $filterContactFldIds = $filterIds = array();
952 $idFldName = $displayFldName = NULL;
953 if (in_array($greeting, CRM_Contact_BAO_Contact::$_greetingTypes)) {
954 $idFldName = $greeting . '_id';
955 $displayFldName = $greeting . '_display';
956 }
957
958 if ($idFldName) {
959 $queryParams = array(1 => array($contactType, 'String'));
960
961 // if $force == 1 then update all contacts else only
962 // those with NULL greeting or addressee value CRM-9476
963 if ($processAll) {
964 $sql = "SELECT DISTINCT id, $idFldName FROM civicrm_contact WHERE contact_type = %1 ";
965 }
966 else {
967 $sql = "
968 SELECT DISTINCT id, $idFldName
969 FROM civicrm_contact
970 WHERE contact_type = %1
971 AND ({$idFldName} IS NULL
972 OR ( {$idFldName} IS NOT NULL AND ({$displayFldName} IS NULL OR {$displayFldName} = '')) )";
973 }
974
975 if ($limit) {
976 $sql .= " LIMIT 0, %2";
977 $queryParams += array(2 => array($limit, 'Integer'));
978 }
979
980 $dao = CRM_Core_DAO::executeQuery($sql, $queryParams);
981 while ($dao->fetch()) {
982 $filterContactFldIds[$dao->id] = $dao->$idFldName;
983
984 if (!CRM_Utils_System::isNull($dao->$idFldName)) {
985 $filterIds[$dao->id] = $dao->$idFldName;
986 }
987 }
988 }
989
990 if (empty($filterContactFldIds)) {
991 $filterContactFldIds[] = 0;
992 }
993
994 // retrieve only required contact information
995 $extraParams[] = array('contact_type', '=', $contactType, 0, 0);
996 // we do token replacement in the replaceGreetingTokens hook
997 list($greetingDetails) = CRM_Utils_Token::getTokenDetails(array_keys($filterContactFldIds),
998 $greetingsReturnProperties,
999 FALSE, FALSE, $extraParams
1000 );
1001 // perform token replacement and build update SQL
1002 $contactIds = array();
1003 $cacheFieldQuery = "UPDATE civicrm_contact SET {$greeting}_display = CASE id ";
1004 foreach ($greetingDetails as $contactID => $contactDetails) {
1005 if (!$processAll &&
1006 !array_key_exists($contactID, $filterContactFldIds)
1007 ) {
1008 continue;
1009 }
1010
1011 if ($processOnlyIdSet && !array_key_exists($contactID, $filterIds)) {
1012 continue;
1013 }
1014
1015 if ($id) {
1016 $greetingString = $originalGreetingString;
1017 $contactIds[] = $contactID;
1018 }
1019 else {
1020 if ($greetingBuffer = CRM_Utils_Array::value($filterContactFldIds[$contactID], $allGreetings)) {
1021 $greetingString = $greetingBuffer;
1022 }
1023 }
1024
1025 self::processGreetingTemplate($greetingString, $contactDetails, $contactID, 'CRM_UpdateGreeting');
1026 $greetingString = CRM_Core_DAO::escapeString($greetingString);
1027 $cacheFieldQuery .= " WHEN {$contactID} THEN '{$greetingString}' ";
1028
1029 $allContactIds[] = $contactID;
1030 }
1031
1032 if (!empty($allContactIds)) {
1033 $cacheFieldQuery .= " ELSE {$greeting}_display
1034 END;";
1035 if (!empty($contactIds)) {
1036 // need to update greeting _id field.
1037 // reset greeting _custom
1038 $resetCustomGreeting = '';
1039 if ($valueID != 4) {
1040 $resetCustomGreeting = ", {$greeting}_custom = NULL ";
1041 }
1042
1043 $queryString = "
1044 UPDATE civicrm_contact
1045 SET {$greeting}_id = {$valueID}
1046 {$resetCustomGreeting}
1047 WHERE id IN (" . implode(',', $contactIds) . ")";
1048 CRM_Core_DAO::executeQuery($queryString);
1049 }
1050
1051 // now update cache field
1052 CRM_Core_DAO::executeQuery($cacheFieldQuery);
1053 }
1054 }
1055
1056 /**
1057 * Fetch the default greeting for a given contact type
1058 *
1059 * @param string $contactType contact type
1060 * @param string $greetingType greeting type
1061 *
1062 * @return int or null
1063 */
1064 static function defaultGreeting($contactType, $greetingType) {
1065 $contactTypeFilters = array('Individual' => 1, 'Household' => 2, 'Organization' => 3);
1066 if (!isset($contactTypeFilters[$contactType])) {
1067 return;
1068 }
1069 $filter = $contactTypeFilters[$contactType];
1070
1071 $id = CRM_Core_OptionGroup::values($greetingType, NULL, NULL, NULL,
1072 " AND is_default = 1 AND (filter = {$filter} OR filter = 0)",
1073 'value'
1074 );
1075 if (!empty($id)) {
1076 return current($id);
1077 }
1078 }
1079
1080 /**
1081 * Process a greeting template string to produce the individualised greeting text.
1082 *
1083 * This works just like message templates for mailings:
1084 * the template is processed with the token substitution mechanism,
1085 * to supply the individual contact data;
1086 * and it is also processed with Smarty,
1087 * to allow for conditionals etc. based on the contact data.
1088 *
1089 * Note: We don't pass any variables to Smarty --
1090 * all variable data is inserted into the input string
1091 * by the token substitution mechanism,
1092 * before Smarty is invoked.
1093 *
1094 * @param string $templateString the greeting template string with contact tokens + Smarty syntax
1095 *
1096 * @param $contactDetails
1097 * @param int $contactID
1098 * @param string $className
1099 *
1100 * @return void
1101 * @static
1102 */
1103 static function processGreetingTemplate(&$templateString, $contactDetails, $contactID, $className) {
1104 CRM_Utils_Token::replaceGreetingTokens($templateString, $contactDetails, $contactID, $className, TRUE);
1105
1106 $smarty = CRM_Core_Smarty::singleton();
1107 $templateString = $smarty->fetch("string:$templateString");
1108 }
1109 }