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