Merge pull request #3600 from atif-shaikh/CRM-14941
[civicrm-core.git] / CRM / Contact / BAO / Contact / Utils.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
06b69b18 4 | CiviCRM version 4.5 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
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
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35class 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
a7488080 62 if (!empty($typeInfo['image_URL'])) {
6a488035
TO
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 = "
131SELECT count( DISTINCT contact_type )
132FROM civicrm_contact
133WHERE 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 /**
c57f36a1 142 * Generate a checksum for a $entityId of type $entityType
6a488035 143 *
fd31fa4c
EM
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
6a488035
TO
151 *
152 * @return array ( $cs, $ts, $live )
153 * @static
154 * @access public
155 */
c57f36a1
PJ
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
6a488035
TO
158 // this typically happens when we do a message preview
159 // or an anon mailing view - CRM-8298
c57f36a1 160 if (!$entityId) {
6a488035
TO
161 return 'invalidChecksum';
162 }
163
164 if (!$hash) {
c57f36a1
PJ
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 }
6a488035
TO
175 }
176
177 if (!$hash) {
178 $hash = md5(uniqid(rand(), TRUE));
c57f36a1
PJ
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 }
6a488035
TO
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
c57f36a1 210 $cs = md5("{$hash}_{$entityId}_{$ts}_{$live}");
6a488035
TO
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 * Function to 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} )
264UNION
265( SELECT location_type_id FROM civicrm_phone WHERE contact_id = {$contactId} )
266UNION
267( SELECT location_type_id FROM civicrm_im WHERE contact_id = {$contactId} )
268UNION
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 *
da6b46f4
EM
278 * @param int $contactID contact id of the individual
279 * @param $organizationId
280 * @param null $previousEmployerID
281 *
282 * @internal param string $organization it can be name or id of organization
6a488035
TO
283 *
284 * @access public
285 * @static
286 */
fad0497c
CW
287 static function createCurrentEmployerRelationship($contactID, $organizationId, $previousEmployerID = NULL) {
288 if ($organizationId && is_numeric($organizationId)) {
6a488035
TO
289 $cid = array('contact' => $contactID);
290
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');
293 if (!$relTypeId) {
294 CRM_Core_Error::fatal(ts("You seem to have deleted the relationship type 'Employee of'"));
295 }
296
297 // create employee of relationship
298 $relationshipParams = array(
299 'is_active' => TRUE,
300 'relationship_type_id' => $relTypeId . '_a_b',
301 'contact_check' => array($organizationId => TRUE),
302 );
303 list($valid, $invalid, $duplicate,
304 $saved, $relationshipIds
305 ) = CRM_Contact_BAO_Relationship::create($relationshipParams, $cid);
306
307
308 // In case we change employer, clean prveovious employer related records.
90f0b591 309 if (!$previousEmployerID) {
310 $previousEmployerID = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id');
311 }
6a488035
TO
312 if ($previousEmployerID &&
313 $previousEmployerID != $organizationId
314 ) {
315 self::clearCurrentEmployer($contactID, $previousEmployerID);
316 }
317
318 // set current employer
319 self::setCurrentEmployer(array($contactID => $organizationId));
320
321 $relationshipParams['relationship_ids'] = $relationshipIds;
322 // handle related meberships. CRM-3792
90f0b591 323 self::currentEmployerRelatedMembership($contactID, $organizationId, $relationshipParams, $duplicate, $previousEmployerID);
6a488035
TO
324 }
325 }
326
327 /**
328 * create related memberships for current employer
329 *
2a6da8d7
EM
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.
334 *
335 * @param null $previousEmpID
6a488035 336 *
2a6da8d7 337 * @throws CiviCRM_API3_Exception
6a488035
TO
338 * @access public
339 * @static
340 */
90f0b591 341 static function currentEmployerRelatedMembership($contactID, $employerID, $relationshipParams, $duplicate = FALSE, $previousEmpID = NULL) {
6a488035
TO
342 $ids = array();
343 $action = CRM_Core_Action::ADD;
344
345 //we do not know that triggered relationship record is active.
346 if ($duplicate) {
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);
357 }
358 $relationship->free();
359 }
360
361 //need to handle related meberships. CRM-3792
90f0b591 362 if ($previousEmpID != $employerID) {
363 CRM_Contact_BAO_Relationship::relatedMemberships($contactID, $relationshipParams, $ids, $action);
364 }
6a488035
TO
365 }
366
367 /**
368 * Function to set current employer id and organization name
369 *
370 * @param array $currentEmployerParams associated array of contact id and its employer id
371 *
372 */
373 static function setCurrentEmployer($currentEmployerParams) {
374 foreach ($currentEmployerParams as $contactId => $orgId) {
375 $query = "UPDATE civicrm_contact contact_a,civicrm_contact contact_b
376SET contact_a.employer_id=contact_b.id, contact_a.organization_name=contact_b.organization_name
377WHERE contact_a.id ={$contactId} AND contact_b.id={$orgId}; ";
378
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);
382 }
383 }
384
385 /**
386 * Function to update cached current employer name
387 *
388 * @param int $organizationId current employer id
389 *
390 */
391 static function updateCurrentEmployer($organizationId) {
392 $query = "UPDATE civicrm_contact contact_a,civicrm_contact contact_b
393SET contact_a.organization_name=contact_b.organization_name
394WHERE contact_a.employer_id=contact_b.id AND contact_b.id={$organizationId}; ";
395
396 $dao = CRM_Core_DAO::executeQuery($query);
397 }
398
399 /**
400 * Function to clear cached current employer name
401 *
402 * @param int $contactId contact id ( mostly individual contact id)
403 * @param int $employerId contact id ( mostly organization contact id)
404 *
405 */
406 static function clearCurrentEmployer($contactId, $employerId = NULL) {
407 $query = "UPDATE civicrm_contact
408SET organization_name=NULL, employer_id = NULL
409WHERE id={$contactId}; ";
410
411 $dao = CRM_Core_DAO::executeQuery($query);
412
413 // need to handle related meberships. CRM-3792
414 if ($employerId) {
415 //1. disable corresponding relationship.
416 //2. delete related membership.
417
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');
420 if (!$relTypeId) {
421 CRM_Core_Error::fatal(ts("You seem to have deleted the relationship type 'Employee of'"));
422 }
423 $relMembershipParams['relationship_type_id'] = $relTypeId . '_a_b';
424 $relMembershipParams['contact_check'][$employerId] = 1;
425
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;
432
433 if ($relationship->find(TRUE)) {
434 CRM_Contact_BAO_Relationship::setIsActive($relationship->id, FALSE);
435 CRM_Contact_BAO_Relationship::relatedMemberships($contactId, $relMembershipParams,
436 $ids = array(
437 ), CRM_Core_Action::DELETE
438 );
439 }
440 $relationship->free();
441 }
442 }
443 }
444
445 /**
446 * Function to build form for related contacts / on behalf of organization.
447 *
448 * @param $form object invoking Object
449 * @param $contactType string contact type
2a6da8d7
EM
450 * @param $countryID
451 * @param $stateID
6a488035 452 * @param $title string fieldset title
6a488035 453 *
2a6da8d7 454 * @internal param int $maxLocationBlocks number of location blocks
6a488035 455 *
2a6da8d7 456 * @static
6a488035 457 */
0949913f 458 static function buildOnBehalfForm(&$form, $contactType, $countryID, $stateID, $title) {
6a488035
TO
459
460 $config = CRM_Core_Config::singleton();
461
462 $form->assign('contact_type', $contactType);
463 $form->assign('fieldSetTitle', $title);
0949913f 464 $form->assign('contactEditMode', TRUE);
6a488035
TO
465
466 $attributes = CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact');
467 if ($form->_contactId) {
468 $form->assign('orgId', $form->_contactId);
469 }
470
471 switch ($contactType) {
472 case 'Organization':
d5f1ee75 473 $form->add('text', 'organization_name', ts('Organization Name'), $attributes['organization_name'], TRUE);
6a488035
TO
474 break;
475
476 case 'Household':
0949913f 477 $form->add('text', 'household_name', ts('Household Name'), $attributes['household_name']);
6a488035
TO
478 break;
479
480 default:
481 // individual
482 $form->addElement('select', 'prefix_id', ts('Prefix'),
e6c4755b 483 array('' => ts('- prefix -')) + CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'prefix_id')
6a488035
TO
484 );
485 $form->addElement('text', 'first_name', ts('First Name'),
486 $attributes['first_name']
487 );
488 $form->addElement('text', 'middle_name', ts('Middle Name'),
489 $attributes['middle_name']
490 );
491 $form->addElement('text', 'last_name', ts('Last Name'),
492 $attributes['last_name']
493 );
494 $form->addElement('select', 'suffix_id', ts('Suffix'),
e6c4755b 495 array('' => ts('- suffix -')) + CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'suffix_id')
6a488035
TO
496 );
497 }
498
499 $addressSequence = $config->addressSequence();
500 $form->assign('addressSequence', array_fill_keys($addressSequence, 1));
501
502 //Primary Phone
503 $form->addElement('text',
504 'phone[1][phone]',
505 ts('Primary Phone'),
506 CRM_Core_DAO::getAttribute('CRM_Core_DAO_Phone',
507 'phone'
508 )
509 );
510 //Primary Email
511 $form->addElement('text',
512 'email[1][email]',
513 ts('Primary Email'),
514 CRM_Core_DAO::getAttribute('CRM_Core_DAO_Email',
515 'email'
516 )
517 );
518 //build the address block
519 CRM_Contact_Form_Edit_Address::buildQuickForm($form);
520
521 // also fix the state country selector
522 CRM_Contact_Form_Edit_Address::fixStateSelect($form,
523 'address[1][country_id]',
524 'address[1][state_province_id]',
525 "address[1][county_id]",
526 $countryID,
527 $stateID
528 );
529 }
530
531 /**
532 * Function to clear cache employer name and employer id
533 * of all employee when employer get deleted.
534 *
535 * @param int $employerId contact id of employer ( organization id )
536 *
537 */
538 static function clearAllEmployee($employerId) {
539 $query = "
540UPDATE civicrm_contact
541 SET organization_name=NULL, employer_id = NULL
542 WHERE employer_id={$employerId}; ";
543
544 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
545 }
546
547 /**
548 * Given an array of contact ids this function will return array with links to view contact page
549 *
550 * @param array $contactIDs associated contact id's
2a6da8d7
EM
551 * @param bool $addViewLink
552 * @param bool $addEditLink
6a488035
TO
553 * @param int $originalId associated with the contact which is edited
554 *
555 *
556 * @return array $contactViewLinks returns array with links to contact view
557 * @static
558 * @access public
559 */
560 static function formatContactIDSToLinks($contactIDs, $addViewLink = TRUE, $addEditLink = TRUE, $originalId = NULL) {
561 $contactLinks = array();
562 if (!is_array($contactIDs) || empty($contactIDs)) {
563 return $contactLinks;
564 }
565
566 // does contact has sufficient permissions.
567 $permissions = array(
568 'view' => 'view all contacts',
569 'edit' => 'edit all contacts',
570 'merge' => 'merge duplicate contacts',
571 );
572
573 $permissionedContactIds = array();
574 foreach ($permissions as $task => $permission) {
575 // give permission.
576 if (CRM_Core_Permission::check($permission)) {
577 foreach ($contactIDs as $contactId) {
578 $permissionedContactIds[$contactId][$task] = TRUE;
579 }
580 continue;
581 }
582
583 // check permission on acl basis.
584 if (in_array($task, array(
585 'view', 'edit'))) {
586 $aclPermission = CRM_Core_Permission::VIEW;
587 if ($task == 'edit') {
588 $aclPermission = CRM_Core_Permission::EDIT;
589 }
590 foreach ($contactIDs as $contactId) {
591 if (CRM_Contact_BAO_Contact_Permission::allow($contactId, $aclPermission)) {
592 $permissionedContactIds[$contactId][$task] = TRUE;
593 }
594 }
595 }
596 }
597
598 // retrieve display names for all contacts
599 $query = '
600 SELECT c.id, c.display_name, c.contact_type, ce.email
601 FROM civicrm_contact c
602LEFT JOIN civicrm_email ce ON ( ce.contact_id=c.id AND ce.is_primary = 1 )
603 WHERE c.id IN (' . implode(',', $contactIDs) . ' ) LIMIT 20';
604
605 $dao = CRM_Core_DAO::executeQuery($query);
606
607 $contactLinks['msg'] = NULL;
608 $i = 0;
609 while ($dao->fetch()) {
610
611 $contactLinks['rows'][$i]['display_name'] = $dao->display_name;
612 $contactLinks['rows'][$i]['primary_email'] = $dao->email;
613
614 // get the permission for current contact id.
615 $hasPermissions = CRM_Utils_Array::value($dao->id, $permissionedContactIds);
616 if (!is_array($hasPermissions) || empty($hasPermissions)) {
617 $i++;
618 continue;
619 }
620
621 // do check for view.
622 if (array_key_exists('view', $hasPermissions)) {
a1c7d42f 623 $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>';
6a488035
TO
624 if (!$contactLinks['msg']) {
625 $contactLinks['msg'] = 'view';
626 }
627 }
628 if (array_key_exists('edit', $hasPermissions)) {
629 $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>';
630 if (!$contactLinks['msg'] || $contactLinks['msg'] != 'merge') {
631 $contactLinks['msg'] = 'edit';
632 }
633 }
634 if (!empty($originalId) && array_key_exists('merge', $hasPermissions)) {
635 $rgBao = new CRM_Dedupe_BAO_RuleGroup();
636 $rgBao->contact_type = $dao->contact_type;
637 $rgBao->used = 'Supervised';
638 if ($rgBao->find(TRUE)) {
639 $rgid = $rgBao->id;
640 }
641 if ($rgid && isset($dao->id)) {
642 //get an url to merge the contact
643 $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>';
644 $contactLinks['msg'] = 'merge';
645 }
646 }
647
648 $i++;
649 }
650
651 return $contactLinks;
652 }
653
654 /**
655 * This function retrieve component related contact information.
656 *
2a6da8d7
EM
657 * @param array $componentIds array of component Ids.
658 * @param $componentName
659 * @param array $returnProperties array of return elements.
6a488035 660 *
2a6da8d7 661 * @return array $contactDetails array of contact info.@static
6a488035
TO
662 */
663 static function contactDetails($componentIds, $componentName, $returnProperties = array(
664 )) {
665 $contactDetails = array();
666 if (empty($componentIds) ||
667 !in_array($componentName, array('CiviContribute', 'CiviMember', 'CiviEvent', 'Activity'))
668 ) {
669 return $contactDetails;
670 }
671
672 if (empty($returnProperties)) {
673 $autocompleteContactSearch = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
674 'contact_autocomplete_options'
675 );
676 $returnProperties = array_fill_keys(array_merge(array('sort_name'),
677 array_keys($autocompleteContactSearch)
678 ), 1);
679 }
680
681 $compTable = NULL;
682 if ($componentName == 'CiviContribute') {
683 $compTable = 'civicrm_contribution';
684 }
685 elseif ($componentName == 'CiviMember') {
686 $compTable = 'civicrm_membership';
687 }
688 elseif ($componentName == 'Activity') {
689 $compTable = 'civicrm_activity';
f0385140 690 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
6a488035
TO
691 }
692 else {
693 $compTable = 'civicrm_participant';
694 }
695
696 $select = $from = array();
697 foreach ($returnProperties as $property => $ignore) {
698 $value = (in_array($property, array(
699 'city', 'street_address'))) ? 'address' : $property;
700 switch ($property) {
701 case 'sort_name':
702 if ($componentName == 'Activity') {
f0385140 703 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
704 $select[] = "contact.$property as $property";
705 $from[$value] = "
706INNER JOIN civicrm_activity_contact acs ON (acs.activity_id = {$compTable}.id AND acs.record_type_id = {$sourceID})
707INNER JOIN civicrm_contact contact ON ( contact.id = acs.contact_id )";
6a488035
TO
708 }
709 else {
710 $select[] = "$property as $property";
711 $from[$value] = "INNER JOIN civicrm_contact contact ON ( contact.id = $compTable.contact_id )";
712 }
713 break;
714
715 case 'target_sort_name':
f0385140 716 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
6a488035 717 $select[] = "contact_target.sort_name as $property";
91da6cd5 718 $from[$value] = "
f0385140 719INNER JOIN civicrm_activity_contact act ON (act.activity_id = {$compTable}.id AND act.record_type_id = {$targetID})
720INNER JOIN civicrm_contact contact_target ON ( contact_target.id = act.contact_id )";
6a488035
TO
721 break;
722
723 case 'email':
724 case 'phone':
725 case 'city':
726 case 'street_address':
727 $select[] = "$property as $property";
728 // Grab target contact properties if this is for activity
729 if ($componentName == 'Activity') {
730 $from[$value] = "LEFT JOIN civicrm_{$value} {$value} ON ( contact_target.id = {$value}.contact_id AND {$value}.is_primary = 1 ) ";
731 }
732 else {
733 $from[$value] = "LEFT JOIN civicrm_{$value} {$value} ON ( contact.id = {$value}.contact_id AND {$value}.is_primary = 1 ) ";
734 }
735 break;
736
737 case 'country':
738 case 'state_province':
739 $select[] = "{$property}.name as $property";
740 if (!in_array('address', $from)) {
741 // Grab target contact properties if this is for activity
742 if ($componentName == 'Activity') {
743 $from['address'] = 'LEFT JOIN civicrm_address address ON ( contact_target.id = address.contact_id AND address.is_primary = 1) ';
744 }
745 else {
746 $from['address'] = 'LEFT JOIN civicrm_address address ON ( contact.id = address.contact_id AND address.is_primary = 1) ';
747 }
748 }
749 $from[$value] = " LEFT JOIN civicrm_{$value} {$value} ON ( address.{$value}_id = {$value}.id ) ";
750 break;
751 }
752 }
753
754 //finally retrieve contact details.
755 if (!empty($select) && !empty($from)) {
756 $fromClause = implode(' ', $from);
757 $selectClause = implode(', ', $select);
758 $whereClause = "{$compTable}.id IN (" . implode(',', $componentIds) . ')';
759
760 $query = "
761 SELECT contact.id as contactId, $compTable.id as componentId, $selectClause
762 FROM $compTable as $compTable $fromClause
763 WHERE $whereClause
764Group By componentId";
765
766 $contact = CRM_Core_DAO::executeQuery($query);
767 while ($contact->fetch()) {
768 $contactDetails[$contact->componentId]['contact_id'] = $contact->contactId;
769 foreach ($returnProperties as $property => $ignore) {
770 $contactDetails[$contact->componentId][$property] = $contact->$property;
771 }
772 }
773 $contact->free();
774 }
775
776 return $contactDetails;
777 }
778
779 /**
780 * Function handles shared contact address processing
781 * In this function we just modify submitted values so that new address created for the user
782 * has same address as shared contact address. We copy the address so that search etc will be
783 * much efficient.
784 *
785 * @param array $address this is associated array which contains submitted form values
786 *
787 * @return void
788 * @static
789 * @access public
790 */
791 static function processSharedAddress(&$address) {
792 if (!is_array($address)) {
793 return;
794 }
795
796 // Sharing contact address during create mode is pretty straight forward.
797 // In update mode we should check following:
798 // - We should check if user has uncheck shared contact address
799 // - If yes then unset the master_id or may be just delete the address that copied master
800 // Normal update process will automatically create new address with submitted values
801
802 // 1. loop through entire subnitted address array
803 $masterAddress = array();
804 $skipFields = array('is_primary', 'location_type_id', 'is_billing', 'master_id');
805 foreach ($address as & $values) {
806 // 2. check if master id exists, if not continue
8cc574cf 807 if (empty($values['master_id']) || empty($values['use_shared_address'])) {
6a488035
TO
808 // we should unset master id when use uncheck share address for existing address
809 $values['master_id'] = 'null';
810 continue;
811 }
812
813 // 3. get the address details for master_id
814 $masterAddress = new CRM_Core_BAO_Address();
815 $masterAddress->id = CRM_Utils_Array::value('master_id', $values);
816 $masterAddress->find(TRUE);
817
818 // 4. modify submitted params and update it with shared contact address
819 // make sure you preserve specific form values like location type, is_primary_ is_billing, master_id
820 // CRM-10336: Also empty any fields from the existing address block if they don't exist in master (otherwise they will persist)
821 foreach ($values as $field => $submittedValue) {
822 if (!in_array($field, $skipFields)){
823 if (isset($masterAddress->$field)) {
824 $values[$field] = $masterAddress->$field;
825 } else {
826 $values[$field] = '';
827 }
828 }
829 }
830 }
831 }
832
833 /**
834 * Function to get the list of contact name give address associated array
835 *
836 * @param array $addresses associated array of
837 *
2a6da8d7 838 * @return array $contactNames associated array of contact names@static
6a488035
TO
839 */
840 static function getAddressShareContactNames(&$addresses) {
841 $contactNames = array();
842 // get the list of master id's for address
843 $masterAddressIds = array();
844 foreach ($addresses as $key => $addressValue) {
a7488080 845 if (!empty($addressValue['master_id'])) {
6a488035
TO
846 $masterAddressIds[] = $addressValue['master_id'];
847 }
848 }
849
850 if (!empty($masterAddressIds)) {
851 $query = 'SELECT ca.id, cc.display_name, cc.id as cid, cc.is_deleted
852 FROM civicrm_contact cc
853 INNER JOIN civicrm_address ca ON cc.id = ca.contact_id
854 WHERE ca.id IN ( ' . implode(',', $masterAddressIds) . ')';
855 $dao = CRM_Core_DAO::executeQuery($query);
856
857 while ($dao->fetch()) {
858 $contactViewUrl = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$dao->cid}");
859 $contactNames[$dao->id] = array(
860 'name' => "<a href='{$contactViewUrl}'>{$dao->display_name}</a>",
861 'is_deleted' => $dao->is_deleted,
862 );
863 }
864 }
865 return $contactNames;
866 }
867
868 /**
869 * Clear the contact cache so things are kosher. We started off being super aggressive with clearing
870 * caches, but are backing off from this with every release. Compromise between ease of coding versus
871 * performance versus being accurate at that very instant
872 *
873 * @param $contactID - the contactID that was edited / deleted
874 *
875 * @return void
876 * @static
877 */
878 static function clearContactCaches($contactID = NULL) {
879 // clear acl cache if any.
880 CRM_ACL_BAO_Cache::resetCache();
881
882 if (empty($contactID)) {
883 // also clear prev/next dedupe cache - if no contactID passed in
884 CRM_Core_BAO_PrevNextCache::deleteItem();
885 }
886
887 // reset the group contact cache for this group
888 CRM_Contact_BAO_GroupContactCache::remove();
889 }
890
86538308
EM
891 /**
892 * @param $params
893 *
894 * @throws Exception
895 */
6a488035
TO
896 public static function updateGreeting($params) {
897 $contactType = $params['ct'];
898 $greeting = $params['gt'];
899 $valueID = $id = CRM_Utils_Array::value('id', $params);
900 $force = CRM_Utils_Array::value('force', $params);
24f77640 901 $limit = CRM_Utils_Array::value('limit', $params);
6a488035
TO
902
903 // if valueID is not passed use default value
904 if (!$valueID) {
905 $valueID = $id = self::defaultGreeting($contactType, $greeting);
906 }
907
908 $filter = array(
909 'contact_type' => $contactType,
910 'greeting_type' => $greeting,
911 );
912
913 $allGreetings = CRM_Core_PseudoConstant::greeting($filter);
914 $originalGreetingString = $greetingString = CRM_Utils_Array::value($valueID, $allGreetings);
915 if (!$greetingString) {
916 CRM_Core_Error::fatal(ts('Incorrect greeting value id %1, or no default greeting for this contact type and greeting type.', array(1 => $valueID)));
917 }
918
919 // build return properties based on tokens
920 $greetingTokens = CRM_Utils_Token::getTokens($greetingString);
921 $tokens = CRM_Utils_Array::value('contact', $greetingTokens);
922 $greetingsReturnProperties = array();
923 if (is_array($tokens)) {
924 $greetingsReturnProperties = array_fill_keys(array_values($tokens), 1);
925 }
926
927 // Process ALL contacts only when force=1 or force=2 is passed. Else only contacts with NULL greeting or addressee value are updated.
928 $processAll = $processOnlyIdSet = FALSE;
929 if ($force == 1) {
930 $processAll = TRUE;
931 }
932 elseif ($force == 2) {
933 $processOnlyIdSet = TRUE;
934 }
935
936 //FIXME : apiQuery should handle these clause.
937 $filterContactFldIds = $filterIds = array();
938 $idFldName = $displayFldName = NULL;
939 if (in_array($greeting, CRM_Contact_BAO_Contact::$_greetingTypes)) {
940 $idFldName = $greeting . '_id';
941 $displayFldName = $greeting . '_display';
942 }
943
944 if ($idFldName) {
945 // if $force == 1 then update all contacts else only
946 // those with NULL greeting or addressee value CRM-9476
947 if ($processAll) {
948 $sql = "SELECT DISTINCT id, $idFldName FROM civicrm_contact WHERE contact_type = %1 ";
949 }
950 else {
a39ef8af
E
951 $sql = "
952 SELECT DISTINCT id, $idFldName
953 FROM civicrm_contact
954 WHERE contact_type = %1
955 AND ({$idFldName} IS NULL
956 OR ( {$idFldName} IS NOT NULL AND ({$displayFldName} IS NULL OR {$displayFldName} = '')) )";
6a488035
TO
957 }
958
24f77640 959 if ($limit) {
960 $sql .= " LIMIT $limit";
961 }
962
6a488035
TO
963 $dao = CRM_Core_DAO::executeQuery($sql, array(1 => array($contactType, 'String')));
964 while ($dao->fetch()) {
965 $filterContactFldIds[$dao->id] = $dao->$idFldName;
966
967 if (!CRM_Utils_System::isNull($dao->$idFldName)) {
968 $filterIds[$dao->id] = $dao->$idFldName;
969 }
970 }
971 }
972
973 if (empty($filterContactFldIds)) {
974 $filterContactFldIds[] = 0;
975 }
976
977 // retrieve only required contact information
978 $extraParams[] = array('contact_type', '=', $contactType, 0, 0);
979 // we do token replacement in the replaceGreetingTokens hook
980 list($greetingDetails) = CRM_Utils_Token::getTokenDetails(array_keys($filterContactFldIds),
981 $greetingsReturnProperties,
982 FALSE, FALSE, $extraParams
983 );
984 // perform token replacement and build update SQL
985 $contactIds = array();
986 $cacheFieldQuery = "UPDATE civicrm_contact SET {$greeting}_display = CASE id ";
987 foreach ($greetingDetails as $contactID => $contactDetails) {
988 if (!$processAll &&
989 !array_key_exists($contactID, $filterContactFldIds)
990 ) {
991 continue;
992 }
993
994 if ($processOnlyIdSet && !array_key_exists($contactID, $filterIds)) {
995 continue;
996 }
997
998 if ($id) {
999 $greetingString = $originalGreetingString;
1000 $contactIds[] = $contactID;
1001 }
1002 else {
1003 if ($greetingBuffer = CRM_Utils_Array::value($filterContactFldIds[$contactID], $allGreetings)) {
1004 $greetingString = $greetingBuffer;
1005 }
1006 }
1007
73d64eb6 1008 self::processGreetingTemplate($greetingString, $contactDetails, $contactID, 'CRM_UpdateGreeting');
6a488035
TO
1009 $greetingString = CRM_Core_DAO::escapeString($greetingString);
1010 $cacheFieldQuery .= " WHEN {$contactID} THEN '{$greetingString}' ";
1011
1012 $allContactIds[] = $contactID;
1013 }
1014
1015 if (!empty($allContactIds)) {
1016 $cacheFieldQuery .= " ELSE {$greeting}_display
1017 END;";
1018 if (!empty($contactIds)) {
1019 // need to update greeting _id field.
1020 // reset greeting _custom
1021 $resetCustomGreeting = '';
1022 if ($valueID != 4) {
1023 $resetCustomGreeting = ", {$greeting}_custom = NULL ";
1024 }
1025
1026 $queryString = "
1027UPDATE civicrm_contact
1028SET {$greeting}_id = {$valueID}
1029 {$resetCustomGreeting}
1030WHERE id IN (" . implode(',', $contactIds) . ")";
1031 CRM_Core_DAO::executeQuery($queryString);
1032 }
1033
1034 // now update cache field
1035 CRM_Core_DAO::executeQuery($cacheFieldQuery);
1036 }
1037 }
1038
1039 /**
1040 * Fetch the default greeting for a given contact type
1041 *
1042 * @param string $contactType contact type
1043 * @param string $greetingType greeting type
1044 *
1045 * @return int or null
1046 */
1047 static function defaultGreeting($contactType, $greetingType) {
1048 $contactTypeFilters = array('Individual' => 1, 'Household' => 2, 'Organization' => 3);
1049 if (!isset($contactTypeFilters[$contactType])) {
1050 return;
1051 }
1052 $filter = $contactTypeFilters[$contactType];
1053
1054 $id = CRM_Core_OptionGroup::values($greetingType, NULL, NULL, NULL,
1055 " AND is_default = 1 AND (filter = {$filter} OR filter = 0)",
1056 'value'
1057 );
1058 if (!empty($id)) {
1059 return current($id);
1060 }
1061 }
73d64eb6
OB
1062
1063 /**
1064 * Process a greeting template string to produce the individualised greeting text.
1065 *
1066 * This works just like message templates for mailings:
1067 * the template is processed with the token substitution mechanism,
1068 * to supply the individual contact data;
1069 * and it is also processed with Smarty,
1070 * to allow for conditionals etc. based on the contact data.
1071 *
1072 * Note: We don't pass any variables to Smarty --
1073 * all variable data is inserted into the input string
1074 * by the token substitution mechanism,
1075 * before Smarty is invoked.
1076 *
1077 * @param string $templateString the greeting template string with contact tokens + Smarty syntax
1078 *
2a6da8d7
EM
1079 * @param $contactDetails
1080 * @param $contactID
1081 * @param $className
1082 *
73d64eb6
OB
1083 * @return void
1084 * @static
1085 */
1086 static function processGreetingTemplate(&$templateString, $contactDetails, $contactID, $className) {
1087 CRM_Utils_Token::replaceGreetingTokens($templateString, $contactDetails, $contactID, $className, TRUE);
1088
1089 $smarty = CRM_Core_Smarty::singleton();
1090 $templateString = $smarty->fetch("string:$templateString");
1091 }
6a488035 1092}