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