Merge pull request #16001 from agileware/CIVICRM-1383
[civicrm-core.git] / CRM / Contact / Selector.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * Class is to retrieve and display a range of contacts that match the given criteria.
20 *
21 * It is specifically for results of advanced search options.
22 */
23 class CRM_Contact_Selector extends CRM_Core_Selector_Base implements CRM_Core_Selector_API {
24
25 const CACHE_SIZE = 500;
26
27 /**
28 * This defines two actions- View and Edit.
29 *
30 * @var array
31 */
32 public static $_links = NULL;
33
34 /**
35 * We use desc to remind us what that column is, name is used in the tpl
36 *
37 * @var array
38 */
39 public static $_columnHeaders;
40
41 /**
42 * Properties of contact we're interested in displaying
43 * @var array
44 */
45 public static $_properties = [
46 'contact_id',
47 'contact_type',
48 'contact_sub_type',
49 'sort_name',
50 'street_address',
51 'city',
52 'state_province',
53 'postal_code',
54 'country',
55 'geo_code_1',
56 'geo_code_2',
57 'is_deceased',
58 'email',
59 'on_hold',
60 'phone',
61 'status',
62 'do_not_email',
63 'do_not_phone',
64 'do_not_mail',
65 ];
66
67 /**
68 * FormValues is the array returned by exportValues called on
69 * the HTML_QuickForm_Controller for that page.
70 *
71 * @var array
72 */
73 public $_formValues;
74
75 /**
76 * The contextMenu
77 *
78 * @var array
79 */
80 protected $_contextMenu;
81
82 /**
83 * Params is the array in a value used by the search query creator
84 *
85 * @var array
86 */
87 public $_params;
88
89 /**
90 * The return properties used for search
91 *
92 * @var array
93 */
94 protected $_returnProperties;
95
96 /**
97 * Represent the type of selector
98 *
99 * @var int
100 */
101 protected $_action;
102
103 protected $_searchContext;
104
105 /**
106 * Query object for this selector.
107 *
108 * @var CRM_Contact_BAO_Query
109 */
110 protected $_query;
111
112 /**
113 * Get the query object for this selector.
114 *
115 * @return CRM_Contact_BAO_Query
116 */
117 public function getQueryObject() {
118 return $this->_query;
119 }
120
121 /**
122 * Group id
123 *
124 * @var int
125 */
126 protected $_ufGroupID;
127
128 /**
129 * The public visible fields to be shown to the user
130 *
131 * @var array
132 */
133 protected $_fields;
134
135 /**
136 * Class constructor.
137 *
138 * @param $customSearchClass
139 * @param array $formValues
140 * Array of form values imported.
141 * @param array $params
142 * Array of parameters for query.
143 * @param null $returnProperties
144 * @param \const|int $action - action of search basic or advanced.
145 *
146 * @param bool $includeContactIds
147 * @param bool $searchDescendentGroups
148 * @param string $searchContext
149 * @param null $contextMenu
150 *
151 * @return CRM_Contact_Selector
152 */
153 public function __construct(
154 $customSearchClass,
155 $formValues = NULL,
156 $params = NULL,
157 $returnProperties = NULL,
158 $action = CRM_Core_Action::NONE,
159 $includeContactIds = FALSE,
160 $searchDescendentGroups = TRUE,
161 $searchContext = 'search',
162 $contextMenu = NULL
163 ) {
164 //don't build query constructor, if form is not submitted
165 $force = CRM_Utils_Request::retrieve('force', 'Boolean');
166 if (empty($formValues) && !$force) {
167 return;
168 }
169
170 // submitted form values
171 $this->_formValues = &$formValues;
172 $this->_params = &$params;
173 $this->_returnProperties = &$returnProperties;
174 $this->_contextMenu = &$contextMenu;
175 $this->_context = $searchContext;
176
177 // type of selector
178 $this->_action = $action;
179
180 $this->_searchContext = $searchContext;
181
182 $this->_ufGroupID = CRM_Utils_Array::value('uf_group_id', $this->_formValues);
183
184 if ($this->_ufGroupID) {
185 $this->_fields = CRM_Core_BAO_UFGroup::getListingFields(CRM_Core_Action::VIEW,
186 CRM_Core_BAO_UFGroup::PUBLIC_VISIBILITY |
187 CRM_Core_BAO_UFGroup::LISTINGS_VISIBILITY,
188 FALSE, $this->_ufGroupID
189 );
190 self::$_columnHeaders = NULL;
191
192 $this->_customFields = CRM_Core_BAO_CustomField::getFieldsForImport('Individual');
193
194 $this->_returnProperties = CRM_Contact_BAO_Contact::makeHierReturnProperties($this->_fields);
195 $this->_returnProperties['contact_type'] = 1;
196 $this->_returnProperties['contact_sub_type'] = 1;
197 $this->_returnProperties['sort_name'] = 1;
198 }
199
200 $displayRelationshipType = CRM_Utils_Array::value('display_relationship_type', $this->_formValues);
201 $operator = CRM_Utils_Array::value('operator', $this->_formValues, 'AND');
202
203 // rectify params to what proximity search expects if there is a value for prox_distance
204 // CRM-7021
205 if (!empty($this->_params)) {
206 CRM_Contact_BAO_ProximityQuery::fixInputParams($this->_params);
207 }
208
209 $this->_query = new CRM_Contact_BAO_Query(
210 $this->_params,
211 $this->_returnProperties,
212 NULL,
213 $includeContactIds,
214 FALSE,
215 CRM_Contact_BAO_Query::MODE_CONTACTS,
216 FALSE,
217 $searchDescendentGroups,
218 FALSE,
219 $displayRelationshipType,
220 $operator
221 );
222
223 $this->_options = &$this->_query->_options;
224 }
225
226 /**
227 * This method set cache key, later used in test environment
228 *
229 * @param string $key
230 */
231 public function setKey($key) {
232 $this->_key = $key;
233 }
234
235 /**
236 * This method returns the links that are given for each search row.
237 * currently the links added for each row are
238 *
239 * - View
240 * - Edit
241 *
242 * @return array
243 */
244 public static function &links() {
245 list($context, $contextMenu, $key) = func_get_args();
246 $extraParams = ($key) ? "&key={$key}" : NULL;
247 $searchContext = ($context) ? "&context=$context" : NULL;
248
249 if (!(self::$_links)) {
250 self::$_links = [
251 CRM_Core_Action::VIEW => [
252 'name' => ts('View'),
253 'url' => 'civicrm/contact/view',
254 'class' => 'no-popup',
255 'qs' => "reset=1&cid=%%id%%{$searchContext}{$extraParams}",
256 'title' => ts('View Contact Details'),
257 'ref' => 'view-contact',
258 ],
259 CRM_Core_Action::UPDATE => [
260 'name' => ts('Edit'),
261 'url' => 'civicrm/contact/add',
262 'class' => 'no-popup',
263 'qs' => "reset=1&action=update&cid=%%id%%{$searchContext}{$extraParams}",
264 'title' => ts('Edit Contact Details'),
265 'ref' => 'edit-contact',
266 ],
267 ];
268
269 $config = CRM_Core_Config::singleton();
270 //CRM-16552: mapAPIKey is not mandatory as google no longer requires an API Key
271 if ($config->mapProvider && ($config->mapAPIKey || $config->mapProvider == 'Google')) {
272 self::$_links[CRM_Core_Action::MAP] = [
273 'name' => ts('Map'),
274 'url' => 'civicrm/contact/map',
275 'qs' => "reset=1&cid=%%id%%{$searchContext}{$extraParams}",
276 'title' => ts('Map Contact'),
277 ];
278 }
279
280 // Adding Context Menu Links in more action
281 if ($contextMenu) {
282 $counter = 7000;
283 foreach ($contextMenu as $key => $value) {
284 $contextVal = '&context=' . $value['key'];
285 if ($value['key'] == 'delete') {
286 $contextVal = $searchContext;
287 }
288 $url = "civicrm/contact/view/{$value['key']}";
289 $qs = "reset=1&action=add&cid=%%id%%{$contextVal}{$extraParams}";
290 if ($value['key'] == 'activity') {
291 $qs = "action=browse&selectedChild=activity&reset=1&cid=%%id%%{$extraParams}";
292 }
293 elseif ($value['key'] == 'email') {
294 $url = "civicrm/contact/view/activity";
295 $qs = "atype=3&action=add&reset=1&cid=%%id%%{$extraParams}";
296 }
297
298 self::$_links[$counter++] = [
299 'name' => $value['title'],
300 'url' => $url,
301 'qs' => $qs,
302 'title' => $value['title'],
303 'ref' => $value['ref'],
304 'class' => CRM_Utils_Array::value('class', $value),
305 ];
306 }
307 }
308 }
309 return self::$_links;
310 }
311
312 /**
313 * Getter for array of the parameters required for creating pager.
314 *
315 * @param $action
316 * @param array $params
317 */
318 public function getPagerParams($action, &$params) {
319 $params['status'] = ts('Contact %%StatusMessage%%');
320 $params['csvString'] = NULL;
321 $params['rowCount'] = CRM_Utils_Pager::ROWCOUNT;
322
323 $params['buttonTop'] = 'PagerTopButton';
324 $params['buttonBottom'] = 'PagerBottomButton';
325 }
326
327 /**
328 * @param null $action
329 * @param null $output
330 *
331 * @return array
332 */
333 public function &getColHeads($action = NULL, $output = NULL) {
334 $colHeads = self::_getColumnHeaders();
335 $colHeads[] = ['desc' => ts('Actions'), 'name' => ts('Action')];
336 return $colHeads;
337 }
338
339 /**
340 * Returns the column headers as an array of tuples:
341 * (name, sortName (key to the sort array))
342 *
343 * @param string $action
344 * The action being performed.
345 * @param string $output
346 * What should the result set include (web/email/csv).
347 *
348 * @return array
349 * the column headers that need to be displayed
350 */
351 public function &getColumnHeaders($action = NULL, $output = NULL) {
352 $headers = NULL;
353
354 // unset return property elements that we don't care
355 if (!empty($this->_returnProperties)) {
356 $doNotCareElements = [
357 'contact_type',
358 'contact_sub_type',
359 'sort_name',
360 ];
361 foreach ($doNotCareElements as $value) {
362 unset($this->_returnProperties[$value]);
363 }
364 }
365
366 if ($output == CRM_Core_Selector_Controller::EXPORT) {
367 $csvHeaders = [ts('Contact ID'), ts('Contact Type')];
368 foreach ($this->getColHeads($action, $output) as $column) {
369 if (array_key_exists('name', $column)) {
370 $csvHeaders[] = $column['name'];
371 }
372 }
373 $headers = $csvHeaders;
374 }
375 elseif ($output == CRM_Core_Selector_Controller::SCREEN) {
376 $csvHeaders = [ts('Name')];
377 foreach ($this->getColHeads($action, $output) as $key => $column) {
378 if (array_key_exists('name', $column) &&
379 $column['name'] &&
380 $column['name'] != ts('Name')
381 ) {
382 $csvHeaders[$key] = $column['name'];
383 }
384 }
385 $headers = $csvHeaders;
386 }
387 elseif ($this->_ufGroupID) {
388 // we dont use the cached value of column headers
389 // since it potentially changed because of the profile selected
390 static $skipFields = ['group', 'tag'];
391 $direction = CRM_Utils_Sort::ASCENDING;
392 $empty = TRUE;
393 if (!self::$_columnHeaders) {
394 self::$_columnHeaders = [
395 ['name' => ''],
396 [
397 'name' => ts('Name'),
398 'sort' => 'sort_name',
399 'direction' => CRM_Utils_Sort::ASCENDING,
400 ],
401 ];
402
403 $locationTypes = CRM_Core_DAO_Address::buildOptions('location_type_id', 'validate');
404
405 foreach ($this->_fields as $name => $field) {
406 if (!empty($field['in_selector']) &&
407 !in_array($name, $skipFields)
408 ) {
409 if (strpos($name, '-') !== FALSE) {
410 list($fieldName, $lType, $type) = CRM_Utils_System::explode('-', $name, 3);
411
412 if ($lType == 'Primary') {
413 $locationTypeName = 1;
414 }
415 else {
416 $locationTypeName = $locationTypes[$lType];
417 }
418
419 if (in_array($fieldName, [
420 'phone',
421 'im',
422 'email',
423 ])) {
424 if ($type) {
425 $name = "`$locationTypeName-$fieldName-$type`";
426 }
427 else {
428 $name = "`$locationTypeName-$fieldName`";
429 }
430 }
431 else {
432 $name = "`$locationTypeName-$fieldName`";
433 }
434 }
435 //to handle sort key for Internal contactId.CRM-2289
436 if ($name == 'id') {
437 $name = 'contact_id';
438 }
439
440 self::$_columnHeaders[] = [
441 'name' => $field['title'],
442 'sort' => $name,
443 'direction' => $direction,
444 ];
445 $direction = CRM_Utils_Sort::DONTCARE;
446 $empty = FALSE;
447 }
448 }
449
450 // if we dont have any valid columns, dont add the implicit ones
451 // this allows the template to check on emptiness of column headers
452 if ($empty) {
453 self::$_columnHeaders = [];
454 }
455 else {
456 self::$_columnHeaders[] = ['desc' => ts('Actions'), 'name' => ts('Action')];
457 }
458 }
459 $headers = self::$_columnHeaders;
460 }
461 elseif (!empty($this->_returnProperties)) {
462 self::$_columnHeaders = [
463 ['name' => ''],
464 [
465 'name' => ts('Name'),
466 'sort' => 'sort_name',
467 'direction' => CRM_Utils_Sort::ASCENDING,
468 ],
469 ];
470 $properties = self::makeProperties($this->_returnProperties);
471
472 foreach ($properties as $prop) {
473 if (strpos($prop, '-')) {
474 list($loc, $fld, $phoneType) = CRM_Utils_System::explode('-', $prop, 3);
475 $title = $this->_query->_fields[$fld]['title'];
476 if (trim($phoneType) && !is_numeric($phoneType) && strtolower($phoneType) != $fld) {
477 $title .= "-{$phoneType}";
478 }
479 // fetch Location type label from name as $loc, which will be later used in column header
480 $title .= sprintf(" (%s)",
481 CRM_Core_PseudoConstant::getLabel(
482 'CRM_Core_DAO_Address',
483 'location_type_id',
484 CRM_Core_PseudoConstant::getKey('CRM_Core_DAO_Address', 'location_type_id', $loc)
485 )
486 );
487
488 }
489 elseif (isset($this->_query->_fields[$prop]) && isset($this->_query->_fields[$prop]['title'])) {
490 $title = $this->_query->_fields[$prop]['title'];
491 }
492 elseif (isset($this->_query->_pseudoConstantsSelect[$prop]) && isset($this->_query->_pseudoConstantsSelect[$prop]['pseudoconstant']['optionGroupName'])) {
493 $title = CRM_Core_BAO_OptionGroup::getTitleByName($this->_query->_pseudoConstantsSelect[$prop]['pseudoconstant']['optionGroupName']);
494 }
495 else {
496 $title = '';
497 }
498
499 self::$_columnHeaders[] = ['name' => $title, 'sort' => $prop];
500 }
501 self::$_columnHeaders[] = ['name' => ts('Actions')];
502 $headers = self::$_columnHeaders;
503 }
504 else {
505 $headers = $this->getColHeads($action, $output);
506 }
507
508 return $headers;
509 }
510
511 /**
512 * Returns total number of rows for the query.
513 *
514 * @param int $action
515 *
516 * @return int
517 * Total number of rows
518 */
519 public function getTotalCount($action) {
520 // Use count from cache during paging/sorting
521 if (!empty($_GET['crmPID']) || !empty($_GET['crmSID'])) {
522 $count = Civi::cache('long')->get("Search Results Count $this->_key");
523 }
524 if (empty($count)) {
525 $count = $this->_query->searchQuery(0, 0, NULL, TRUE);
526 Civi::cache('long')->set("Search Results Count $this->_key", $count);
527 }
528 return $count;
529 }
530
531 /**
532 * Returns all the rows in the given offset and rowCount.
533 *
534 * @param string $action
535 * The action being performed.
536 * @param int $offset
537 * The row number to start from.
538 * @param int $rowCount
539 * The number of rows to return.
540 * @param string $sort
541 * The sql string that describes the sort order.
542 * @param string $output
543 * What should the result set include (web/email/csv).
544 *
545 * @return int
546 * the total number of rows for this action
547 */
548 public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
549 if (($output == CRM_Core_Selector_Controller::EXPORT ||
550 $output == CRM_Core_Selector_Controller::SCREEN
551 ) &&
552 $this->_formValues['radio_ts'] == 'ts_sel'
553 ) {
554 $includeContactIds = TRUE;
555 }
556 else {
557 $includeContactIds = FALSE;
558 }
559
560 // note the formvalues were given by CRM_Contact_Form_Search to us
561 // and contain the search criteria (parameters)
562 // note that the default action is basic
563 if ($rowCount) {
564 /** @var CRM_Core_PrevNextCache_Interface $prevNext */
565 $prevNext = Civi::service('prevnext');
566 $cacheKey = $this->buildPrevNextCache($sort);
567 $cids = $prevNext->fetch($cacheKey, $offset, $rowCount);
568 $resultSet = empty($cids) ? [] : $this->_query->getCachedContacts($cids, $includeContactIds)->fetchGenerator();
569 }
570 else {
571 $resultSet = $this->_query->searchQuery($offset, $rowCount, $sort, FALSE, $includeContactIds)->fetchGenerator();
572 }
573
574 // process the result of the query
575 $rows = [];
576 $permissions = [CRM_Core_Permission::getPermission()];
577 if (CRM_Core_Permission::check('delete contacts')) {
578 $permissions[] = CRM_Core_Permission::DELETE;
579 }
580 $mask = CRM_Core_Action::mask($permissions);
581
582 // mask value to hide map link if there are not lat/long
583 $mapMask = $mask & 4095;
584
585 if ($this->_searchContext == 'smog') {
586 $gc = CRM_Core_SelectValues::groupContactStatus();
587 }
588
589 if ($this->_ufGroupID) {
590 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
591
592 $names = [];
593 static $skipFields = ['group', 'tag'];
594 foreach ($this->_fields as $key => $field) {
595 if (!empty($field['in_selector']) &&
596 !in_array($key, $skipFields)
597 ) {
598 if (strpos($key, '-') !== FALSE) {
599 list($fieldName, $id, $type) = CRM_Utils_System::explode('-', $key, 3);
600
601 if ($id == 'Primary') {
602 $locationTypeName = 1;
603 }
604 elseif ($fieldName == 'url') {
605 $locationTypeName = "website-{$id}";
606 }
607 else {
608 $locationTypeName = CRM_Utils_Array::value($id, $locationTypes);
609 if (!$locationTypeName) {
610 continue;
611 }
612 }
613
614 $locationTypeName = str_replace(' ', '_', $locationTypeName);
615 if (in_array($fieldName, [
616 'phone',
617 'im',
618 'email',
619 ])) {
620 if ($type) {
621 $names[] = "{$locationTypeName}-{$fieldName}-{$type}";
622 }
623 else {
624 $names[] = "{$locationTypeName}-{$fieldName}";
625 }
626 }
627 else {
628 $names[] = "{$locationTypeName}-{$fieldName}";
629 }
630 }
631 else {
632 $names[] = $field['name'];
633 }
634 }
635 }
636
637 $names[] = "status";
638 }
639 elseif (!empty($this->_returnProperties)) {
640 $names = self::makeProperties($this->_returnProperties);
641 }
642 else {
643 $names = self::$_properties;
644 }
645
646 $links = self::links($this->_context, $this->_contextMenu, $this->_key);
647
648 //check explicitly added contact to a Smart Group.
649 $groupID = CRM_Utils_Array::value('group', $this->_formValues);
650
651 $pseudoconstants = [];
652 // for CRM-3157 purposes
653 if (in_array('world_region', $names)) {
654 $pseudoconstants['world_region'] = [
655 'dbName' => 'worldregion_id',
656 'values' => CRM_Core_PseudoConstant::worldRegion(),
657 ];
658 }
659
660 foreach ($resultSet as $result) {
661 $row = [];
662 $this->_query->convertToPseudoNames($result);
663 // the columns we are interested in
664 foreach ($names as $property) {
665 if ($property == 'status') {
666 continue;
667 }
668 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($property)) {
669 $row[$property] = CRM_Core_BAO_CustomField::displayValue(
670 $result->$property,
671 $cfID,
672 $result->contact_id
673 );
674 }
675 elseif (strpos($property, '-im')) {
676 $row[$property] = $result->$property;
677 if (!empty($result->$property)) {
678 $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
679 $providerId = $property . "-provider_id";
680 $providerName = $imProviders[$result->$providerId];
681 $row[$property] = $result->$property . " ({$providerName})";
682 }
683 }
684 elseif (in_array($property, [
685 'addressee',
686 'email_greeting',
687 'postal_greeting',
688 ])) {
689 $greeting = $property . '_display';
690 $row[$property] = $result->$greeting;
691 }
692 elseif (isset($pseudoconstants[$property])) {
693 $row[$property] = CRM_Utils_Array::value(
694 $result->{$pseudoconstants[$property]['dbName']},
695 $pseudoconstants[$property]['values']
696 );
697 }
698 elseif (strpos($property, '-url') !== FALSE) {
699 $websiteUrl = '';
700 $websiteKey = str_replace('-url', '', $property);
701 $propertyArray = explode('-', $property);
702 $websiteFld = $websiteKey . '-' . array_pop($propertyArray);
703 if (!empty($result->$websiteFld)) {
704 $websiteTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id');
705 $websiteType = $websiteTypes[$result->{"$websiteKey-website_type_id"}];
706 $websiteValue = $result->$websiteFld;
707 $websiteUrl = "<a href=\"{$websiteValue}\">{$websiteValue} ({$websiteType})</a>";
708 }
709 $row[$property] = $websiteUrl;
710 }
711 else {
712 $row[$property] = isset($result->$property) ? $result->$property : NULL;
713 }
714 }
715
716 if (!empty($result->postal_code_suffix)) {
717 $row['postal_code'] .= "-" . $result->postal_code_suffix;
718 }
719
720 if ($output != CRM_Core_Selector_Controller::EXPORT &&
721 $this->_searchContext == 'smog'
722 ) {
723 if (empty($result->status) &&
724 $groupID
725 ) {
726 $contactID = $result->contact_id;
727 if ($contactID) {
728 $gcParams = [
729 'contact_id' => $contactID,
730 'group_id' => $groupID,
731 ];
732
733 $gcDefaults = [];
734 CRM_Core_DAO::commonRetrieve('CRM_Contact_DAO_GroupContact', $gcParams, $gcDefaults);
735
736 if (empty($gcDefaults)) {
737 $row['status'] = ts('Smart');
738 }
739 else {
740 $row['status'] = $gc[$gcDefaults['status']];
741 }
742 }
743 else {
744 $row['status'] = NULL;
745 }
746 }
747 else {
748 $row['status'] = $gc[$result->status];
749 }
750 }
751
752 if ($output != CRM_Core_Selector_Controller::EXPORT) {
753 $row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->contact_id;
754
755 if (!empty($this->_formValues['deleted_contacts']) && CRM_Core_Permission::check('access deleted contacts')
756 ) {
757 $links = [
758 [
759 'name' => ts('View'),
760 'url' => 'civicrm/contact/view',
761 'qs' => 'reset=1&cid=%%id%%',
762 'class' => 'no-popup',
763 'title' => ts('View Contact Details'),
764 ],
765 [
766 'name' => ts('Restore'),
767 'url' => 'civicrm/contact/view/delete',
768 'qs' => 'reset=1&cid=%%id%%&restore=1',
769 'title' => ts('Restore Contact'),
770 ],
771 ];
772 if (CRM_Core_Permission::check('delete contacts')) {
773 $links[] = [
774 'name' => ts('Delete Permanently'),
775 'url' => 'civicrm/contact/view/delete',
776 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1',
777 'title' => ts('Permanently Delete Contact'),
778 ];
779 }
780 $row['action'] = CRM_Core_Action::formLink(
781 $links,
782 NULL,
783 ['id' => $result->contact_id],
784 ts('more'),
785 FALSE,
786 'contact.selector.row',
787 'Contact',
788 $result->contact_id
789 );
790 }
791 elseif ((is_numeric(CRM_Utils_Array::value('geo_code_1', $row))) ||
792 (!empty($row['city']) &&
793 CRM_Utils_Array::value('state_province', $row)
794 )
795 ) {
796 $row['action'] = CRM_Core_Action::formLink(
797 $links,
798 $mask,
799 ['id' => $result->contact_id],
800 ts('more'),
801 FALSE,
802 'contact.selector.row',
803 'Contact',
804 $result->contact_id
805 );
806 }
807 else {
808 $row['action'] = CRM_Core_Action::formLink(
809 $links,
810 $mapMask,
811 ['id' => $result->contact_id],
812 ts('more'),
813 FALSE,
814 'contact.selector.row',
815 'Contact',
816 $result->contact_id
817 );
818 }
819
820 // allow components to add more actions
821 CRM_Core_Component::searchAction($row, $result->contact_id);
822
823 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type,
824 FALSE,
825 $result->contact_id
826 );
827
828 $row['contact_type_orig'] = $result->contact_sub_type ? $result->contact_sub_type : $result->contact_type;
829 $row['contact_id'] = $result->contact_id;
830 $row['sort_name'] = $result->sort_name;
831 // Surely this if should be if NOT - otherwise it's just wierd.
832 if (array_key_exists('id', $row)) {
833 $row['id'] = $result->contact_id;
834 }
835 }
836
837 $rows[$row['contact_id']] = $row;
838 }
839
840 return $rows;
841 }
842
843 /**
844 * @param CRM_Utils_Sort $sort
845 *
846 * @return string
847 */
848 public function buildPrevNextCache($sort) {
849 $cacheKey = 'civicrm search ' . $this->_key;
850
851 // We should clear the cache in following conditions:
852 // 1. when starting from scratch, i.e new search
853 // 2. if records are sorted
854
855 // get current page requested
856 $pageNum = CRM_Utils_Request::retrieve('crmPID', 'Integer');
857
858 // get the current sort order
859 $currentSortID = CRM_Utils_Request::retrieve('crmSID', 'String');
860
861 $session = CRM_Core_Session::singleton();
862
863 // get previous sort id
864 $previousSortID = $session->get('previousSortID');
865
866 // check for current != previous to ensure cache is not reset if paging is done without changing
867 // sort criteria
868 if (!$pageNum || (!empty($currentSortID) && $currentSortID != $previousSortID)) {
869 Civi::service('prevnext')->deleteItem(NULL, $cacheKey, 'civicrm_contact');
870 // this means it's fresh search, so set pageNum=1
871 if (!$pageNum) {
872 $pageNum = 1;
873 }
874 }
875
876 // set the current sort as previous sort
877 if (!empty($currentSortID)) {
878 $session->set('previousSortID', $currentSortID);
879 }
880
881 $pageSize = CRM_Utils_Request::retrieve('crmRowCount', 'Integer', CRM_Core_DAO::$_nullObject, FALSE, 50);
882 $firstRecord = ($pageNum - 1) * $pageSize;
883
884 //for alphabetic pagination selection save
885 $sortByCharacter = CRM_Utils_Request::retrieve('sortByCharacter', 'String');
886
887 //for text field pagination selection save
888 $countRow = Civi::service('prevnext')->getCount($cacheKey);
889 // $sortByCharacter triggers a refresh in the prevNext cache
890 if ($sortByCharacter && $sortByCharacter != 'all') {
891 $this->fillupPrevNextCache($sort, $cacheKey, 0, max(self::CACHE_SIZE, $pageSize));
892 }
893 elseif (($firstRecord + $pageSize) >= $countRow) {
894 $this->fillupPrevNextCache($sort, $cacheKey, $countRow, max(self::CACHE_SIZE, $pageSize) + $firstRecord - $countRow);
895 }
896 return $cacheKey;
897 }
898
899 /**
900 * @param $rows
901 */
902 public function addActions(&$rows) {
903
904 $basicPermissions = CRM_Core_Permission::check('delete contacts') ? [CRM_Core_Permission::DELETE] : [];
905
906 // get permissions on an individual level (CRM-12645)
907 // @todo look at storing this to the session as this is called twice during search results render.
908 $can_edit_list = CRM_Contact_BAO_Contact_Permission::allowList(array_keys($rows), CRM_Core_Permission::EDIT);
909
910 $links_template = self::links($this->_context, $this->_contextMenu, $this->_key);
911
912 foreach ($rows as $id => & $row) {
913 $links = $links_template;
914 if (in_array($id, $can_edit_list)) {
915 $mask = CRM_Core_Action::mask(array_merge([CRM_Core_Permission::EDIT], $basicPermissions));
916 }
917 else {
918 $mask = CRM_Core_Action::mask(array_merge([CRM_Core_Permission::VIEW], $basicPermissions));
919 }
920
921 if ((!is_numeric(CRM_Utils_Array::value('geo_code_1', $row))) &&
922 (empty($row['city']) ||
923 !CRM_Utils_Array::value('state_province', $row)
924 )
925 ) {
926 $mask = $mask & 4095;
927 }
928
929 if (!empty($this->_formValues['deleted_contacts']) && CRM_Core_Permission::check('access deleted contacts')
930 ) {
931 $links = [
932 [
933 'name' => ts('View'),
934 'url' => 'civicrm/contact/view',
935 'qs' => 'reset=1&cid=%%id%%',
936 'class' => 'no-popup',
937 'title' => ts('View Contact Details'),
938 ],
939 [
940 'name' => ts('Restore'),
941 'url' => 'civicrm/contact/view/delete',
942 'qs' => 'reset=1&cid=%%id%%&restore=1',
943 'title' => ts('Restore Contact'),
944 ],
945 ];
946 if (CRM_Core_Permission::check('delete contacts')) {
947 $links[] = [
948 'name' => ts('Delete Permanently'),
949 'url' => 'civicrm/contact/view/delete',
950 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1',
951 'title' => ts('Permanently Delete Contact'),
952 ];
953 }
954 $row['action'] = CRM_Core_Action::formLink(
955 $links,
956 NULL,
957 ['id' => $row['contact_id']],
958 ts('more'),
959 FALSE,
960 'contact.selector.actions',
961 'Contact',
962 $row['contact_id']
963 );
964 }
965 else {
966 $row['action'] = CRM_Core_Action::formLink(
967 $links,
968 $mask,
969 ['id' => $row['contact_id']],
970 ts('more'),
971 FALSE,
972 'contact.selector.actions',
973 'Contact',
974 $row['contact_id']
975 );
976 }
977
978 // allow components to add more actions
979 CRM_Core_Component::searchAction($row, $row['contact_id']);
980
981 if (!empty($row['contact_type_orig'])) {
982 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage($row['contact_type_orig'],
983 FALSE, $row['contact_id']);
984 }
985 }
986 }
987
988 /**
989 * @param $rows
990 */
991 public function removeActions(&$rows) {
992 foreach ($rows as $rid => & $rValue) {
993 unset($rValue['contact_type']);
994 unset($rValue['action']);
995 }
996 }
997
998 /**
999 * @param CRM_Utils_Sort $sort
1000 * @param string $cacheKey
1001 * @param int $start
1002 * @param int $end
1003 *
1004 * @throws \CRM_Core_Exception
1005 */
1006 public function fillupPrevNextCache($sort, $cacheKey, $start = 0, $end = self::CACHE_SIZE) {
1007 $coreSearch = TRUE;
1008 // For custom searches, use the contactIDs method
1009 if (is_a($this, 'CRM_Contact_Selector_Custom')) {
1010 $sql = $this->_search->contactIDs($start, $end, $sort, TRUE);
1011 $coreSearch = FALSE;
1012 }
1013 // For core searches use the searchQuery method
1014 else {
1015 $sql = $this->_query->getSearchSQL($start, $end, $sort, FALSE, $this->_query->_includeContactIds,
1016 FALSE, TRUE);
1017 }
1018
1019 // CRM-9096
1020 // due to limitations in our search query writer, the above query does not work
1021 // in cases where the query is being sorted on a non-contact table
1022 // this results in a fatal error :(
1023 // see below for the gross hack of trapping the error and not filling
1024 // the prev next cache in this situation
1025 // the other alternative of running the FULL query will just be incredibly inefficient
1026 // and slow things down way too much on large data sets / complex queries
1027
1028 $selectSQL = CRM_Core_DAO::composeQuery("SELECT DISTINCT %1, contact_a.id, contact_a.sort_name", [1 => [$cacheKey, 'String']]);
1029
1030 $sql = str_ireplace(['SELECT contact_a.id as contact_id', 'SELECT contact_a.id as id'], $selectSQL, $sql);
1031 $sql = str_ireplace('ORDER BY `contact_id`', 'ORDER BY `id`', $sql, $sql);
1032
1033 try {
1034 Civi::service('prevnext')->fillWithSql($cacheKey, $sql);
1035 }
1036 catch (CRM_Core_Exception $e) {
1037 if ($coreSearch) {
1038 // in the case of error, try rebuilding cache using full sql which is used for search selector display
1039 // this fixes the bugs reported in CRM-13996 & CRM-14438
1040 $this->rebuildPreNextCache($start, $end, $sort, $cacheKey);
1041 }
1042 else {
1043 CRM_Core_Error::deprecatedFunctionWarning('Custom searches should return sql capable of filling the prevnext cache.');
1044 // This will always show for CiviRules :-( as a) it orders by 'rule_label'
1045 // which is not available in the query & b) it uses contact not contact_a
1046 // as an alias.
1047 // CRM_Core_Session::setStatus(ts('Query Failed'));
1048 return;
1049 }
1050 }
1051
1052 if (Civi::service('prevnext') instanceof CRM_Core_PrevNextCache_Sql) {
1053 // SQL-backed prevnext cache uses an extra record for pruning the cache.
1054 // Also ensure that caches stay alive for 2 days as per previous code
1055 Civi::cache('prevNextCache')->set($cacheKey, $cacheKey, 60 * 60 * 24 * CRM_Core_PrevNextCache_Sql::cacheDays);
1056 }
1057 }
1058
1059 /**
1060 * called to rebuild prev next cache using full sql in case of core search ( excluding custom search)
1061 *
1062 * @param int $start
1063 * Start for limit clause.
1064 * @param int $end
1065 * End for limit clause.
1066 * @param CRM_Utils_Sort $sort
1067 * @param string $cacheKey
1068 * Cache key.
1069 */
1070 public function rebuildPreNextCache($start, $end, $sort, $cacheKey) {
1071 // generate full SQL
1072 $sql = $this->_query->searchQuery($start, $end, $sort, FALSE, $this->_query->_includeContactIds,
1073 FALSE, FALSE, TRUE);
1074
1075 $dao = CRM_Core_DAO::executeQuery($sql);
1076
1077 // build insert query, note that currently we build cache for 500 (self::CACHE_SIZE) contact records at a time, hence below approach
1078 $rows = [];
1079 while ($dao->fetch()) {
1080 $rows[] = [
1081 'entity_table' => 'civicrm_contact',
1082 'entity_id1' => $dao->contact_id,
1083 'entity_id2' => $dao->contact_id,
1084 'data' => $dao->sort_name,
1085 ];
1086 }
1087
1088 Civi::service('prevnext')->fillWithArray($cacheKey, $rows);
1089 }
1090
1091 /**
1092 * @inheritDoc
1093 */
1094 public function getQILL() {
1095 return $this->_query->qill();
1096 }
1097
1098 /**
1099 * Name of export file.
1100 *
1101 * @param string $output
1102 * Type of output.
1103 *
1104 * @return string
1105 * name of the file
1106 */
1107 public function getExportFileName($output = 'csv') {
1108 return ts('CiviCRM Contact Search');
1109 }
1110
1111 /**
1112 * Get colunmn headers for search selector.
1113 *
1114 * @return array
1115 */
1116 private static function &_getColumnHeaders() {
1117 if (!isset(self::$_columnHeaders)) {
1118 $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
1119 'address_options', TRUE, NULL, TRUE
1120 );
1121
1122 self::$_columnHeaders = [
1123 'contact_type' => ['desc' => ts('Contact Type')],
1124 'sort_name' => [
1125 'name' => ts('Name'),
1126 'sort' => 'sort_name',
1127 'direction' => CRM_Utils_Sort::ASCENDING,
1128 ],
1129 ];
1130
1131 $defaultAddress = [
1132 'street_address' => ['name' => ts('Address')],
1133 'city' => [
1134 'name' => ts('City'),
1135 'sort' => 'city',
1136 'direction' => CRM_Utils_Sort::DONTCARE,
1137 ],
1138 'state_province' => [
1139 'name' => ts('State'),
1140 'sort' => 'state_province',
1141 'direction' => CRM_Utils_Sort::DONTCARE,
1142 ],
1143 'postal_code' => [
1144 'name' => ts('Postal'),
1145 'sort' => 'postal_code',
1146 'direction' => CRM_Utils_Sort::DONTCARE,
1147 ],
1148 'country' => [
1149 'name' => ts('Country'),
1150 'sort' => 'country',
1151 'direction' => CRM_Utils_Sort::DONTCARE,
1152 ],
1153 ];
1154
1155 foreach ($defaultAddress as $columnName => $column) {
1156 if (!empty($addressOptions[$columnName])) {
1157 self::$_columnHeaders[$columnName] = $column;
1158 }
1159 }
1160
1161 self::$_columnHeaders['email'] = [
1162 'name' => ts('Email'),
1163 'sort' => 'email',
1164 'direction' => CRM_Utils_Sort::DONTCARE,
1165 ];
1166
1167 self::$_columnHeaders['phone'] = ['name' => ts('Phone')];
1168 }
1169 return self::$_columnHeaders;
1170 }
1171
1172 /**
1173 * @return CRM_Contact_BAO_Query
1174 */
1175 public function getQuery() {
1176 return $this->_query;
1177 }
1178
1179 /**
1180 * @return CRM_Contact_DAO_Contact
1181 */
1182 public function alphabetQuery() {
1183 return $this->_query->alphabetQuery();
1184 }
1185
1186 /**
1187 * @param array $params
1188 * @param int $sortID
1189 * @param null $displayRelationshipType
1190 * @param string $queryOperator
1191 *
1192 * @return CRM_Contact_DAO_Contact
1193 */
1194 public function contactIDQuery($params, $sortID, $displayRelationshipType = NULL, $queryOperator = 'AND') {
1195 $sortOrder = &$this->getSortOrder($this->_action);
1196 $sort = new CRM_Utils_Sort($sortOrder, $sortID);
1197
1198 // rectify params to what proximity search expects if there is a value for prox_distance
1199 // CRM-7021 CRM-7905
1200 if (!empty($params)) {
1201 CRM_Contact_BAO_ProximityQuery::fixInputParams($params);
1202 }
1203
1204 if (!$displayRelationshipType) {
1205 $query = new CRM_Contact_BAO_Query($params,
1206 CRM_Contact_BAO_Query::NO_RETURN_PROPERTIES,
1207 NULL, FALSE, FALSE, 1,
1208 FALSE, TRUE, TRUE, NULL,
1209 $queryOperator
1210 );
1211 }
1212 else {
1213 $query = new CRM_Contact_BAO_Query($params,
1214 CRM_Contact_BAO_Query::NO_RETURN_PROPERTIES,
1215 NULL, FALSE, FALSE, 1,
1216 FALSE, TRUE, TRUE, $displayRelationshipType,
1217 $queryOperator
1218 );
1219 }
1220 return $query->searchQuery(0, 0, $sort);
1221 }
1222
1223 /**
1224 * @param $returnProperties
1225 *
1226 * @return array
1227 */
1228 public function &makeProperties(&$returnProperties) {
1229 $properties = [];
1230 foreach ($returnProperties as $name => $value) {
1231 if ($name != 'location') {
1232 // special handling for group and tag
1233 if (in_array($name, ['group', 'tag'])) {
1234 $name = "{$name}s";
1235 }
1236
1237 // special handling for notes
1238 if (in_array($name, ['note', 'note_subject', 'note_body'])) {
1239 $name = "notes";
1240 }
1241
1242 $properties[] = $name;
1243 }
1244 else {
1245 // extract all the location stuff
1246 foreach ($value as $n => $v) {
1247 foreach ($v as $n1 => $v1) {
1248 if (!strpos('_id', $n1) && $n1 != 'location_type') {
1249 $n = str_replace(' ', '_', $n);
1250 $properties[] = "{$n}-{$n1}";
1251 }
1252 }
1253 }
1254 }
1255 }
1256 return $properties;
1257 }
1258
1259 }