3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * Class is to retrieve and display a range of contacts that match the given criteria.
21 * It is specifically for results of advanced search options.
23 class CRM_Contact_Selector
extends CRM_Core_Selector_Base
implements CRM_Core_Selector_API
{
25 const CACHE_SIZE
= 500;
28 * This defines two actions- View and Edit.
32 public static $_links = NULL;
35 * We use desc to remind us what that column is, name is used in the tpl
39 public static $_columnHeaders;
42 * Properties of contact we're interested in displaying
45 public static $_properties = [
69 * FormValues is the array returned by exportValues called on
70 * the HTML_QuickForm_Controller for that page.
81 protected $_contextMenu;
84 * Params is the array in a value used by the search query creator
91 * The return properties used for search
95 protected $_returnProperties;
98 * Represent the type of selector
104 protected $_searchContext;
107 * Query object for this selector.
109 * @var CRM_Contact_BAO_Query
114 * Get the query object for this selector.
116 * @return CRM_Contact_BAO_Query
118 public function getQueryObject() {
119 return $this->_query
;
127 protected $_ufGroupID;
130 * The public visible fields to be shown to the user
139 * @param $customSearchClass
140 * @param array $formValues
141 * Array of form values imported.
142 * @param array $params
143 * Array of parameters for query.
144 * @param null $returnProperties
145 * @param \const|int $action - action of search basic or advanced.
147 * @param bool $includeContactIds
148 * @param bool $searchDescendentGroups
149 * @param string $searchContext
150 * @param null $contextMenu
152 * @return CRM_Contact_Selector
154 public function __construct(
158 $returnProperties = NULL,
159 $action = CRM_Core_Action
::NONE
,
160 $includeContactIds = FALSE,
161 $searchDescendentGroups = TRUE,
162 $searchContext = 'search',
165 //don't build query constructor, if form is not submitted
166 $force = CRM_Utils_Request
::retrieve('force', 'Boolean');
167 if (empty($formValues) && !$force) {
171 // submitted form values
172 $this->_formValues
= &$formValues;
173 $this->_params
= &$params;
174 $this->_returnProperties
= &$returnProperties;
175 $this->_contextMenu
= &$contextMenu;
176 $this->_context
= $searchContext;
179 $this->_action
= $action;
181 $this->_searchContext
= $searchContext;
183 $this->_ufGroupID
= $this->_formValues
['uf_group_id'] ??
NULL;
185 if ($this->_ufGroupID
) {
186 $this->_fields
= CRM_Core_BAO_UFGroup
::getListingFields(CRM_Core_Action
::VIEW
,
187 CRM_Core_BAO_UFGroup
::PUBLIC_VISIBILITY |
188 CRM_Core_BAO_UFGroup
::LISTINGS_VISIBILITY
,
189 FALSE, $this->_ufGroupID
191 self
::$_columnHeaders = NULL;
193 $this->_customFields
= CRM_Core_BAO_CustomField
::getFieldsForImport('Individual');
195 $this->_returnProperties
= CRM_Contact_BAO_Contact
::makeHierReturnProperties($this->_fields
);
196 $this->_returnProperties
['contact_type'] = 1;
197 $this->_returnProperties
['contact_sub_type'] = 1;
198 $this->_returnProperties
['sort_name'] = 1;
199 if (!empty($this->_returnProperties
['location']) && is_array($this->_returnProperties
['location'])) {
200 foreach ($this->_returnProperties
['location'] as $key => $property) {
201 if (!empty($property['email'])) {
202 $this->_returnProperties
['location'][$key]['on_hold'] = 1;
208 $displayRelationshipType = $this->_formValues
['display_relationship_type'] ??
NULL;
209 $operator = CRM_Utils_Array
::value('operator', $this->_formValues
, 'AND');
211 // rectify params to what proximity search expects if there is a value for prox_distance
213 if (!empty($this->_params
)) {
214 CRM_Contact_BAO_ProximityQuery
::fixInputParams($this->_params
);
217 $this->_query
= new CRM_Contact_BAO_Query(
219 $this->_returnProperties
,
223 CRM_Contact_BAO_Query
::MODE_CONTACTS
,
225 $searchDescendentGroups,
227 $displayRelationshipType,
231 $this->_options
= &$this->_query
->_options
;
235 * This method set cache key, later used in test environment
239 public function setKey($key) {
244 * This method returns the links that are given for each search row.
245 * currently the links added for each row are
252 public static function &links() {
253 list($context, $contextMenu, $key) = func_get_args();
254 $extraParams = ($key) ?
"&key={$key}" : NULL;
255 $searchContext = ($context) ?
"&context=$context" : NULL;
257 if (!(self
::$_links)) {
259 CRM_Core_Action
::VIEW
=> [
260 'name' => ts('View'),
261 'url' => 'civicrm/contact/view',
262 'class' => 'no-popup',
263 'qs' => "reset=1&cid=%%id%%{$searchContext}{$extraParams}",
264 'title' => ts('View Contact Details'),
265 'ref' => 'view-contact',
267 CRM_Core_Action
::UPDATE
=> [
268 'name' => ts('Edit'),
269 'url' => 'civicrm/contact/add',
270 'class' => 'no-popup',
271 'qs' => "reset=1&action=update&cid=%%id%%{$searchContext}{$extraParams}",
272 'title' => ts('Edit Contact Details'),
273 'ref' => 'edit-contact',
277 $config = CRM_Core_Config
::singleton();
278 //CRM-16552: mapAPIKey is not mandatory as google no longer requires an API Key
279 if ($config->mapProvider
&& ($config->mapAPIKey ||
$config->mapProvider
== 'Google')) {
280 self
::$_links[CRM_Core_Action
::MAP
] = [
282 'url' => 'civicrm/contact/map',
283 'qs' => "reset=1&cid=%%id%%{$searchContext}{$extraParams}",
284 'title' => ts('Map Contact'),
288 // Adding Context Menu Links in more action
291 foreach ($contextMenu as $key => $value) {
292 $contextVal = '&context=' . $value['key'];
293 if ($value['key'] == 'delete') {
294 $contextVal = $searchContext;
296 $url = "civicrm/contact/view/{$value['key']}";
297 $qs = "reset=1&action=add&cid=%%id%%{$contextVal}{$extraParams}";
298 if ($value['key'] == 'activity') {
299 $qs = "action=browse&selectedChild=activity&reset=1&cid=%%id%%{$extraParams}";
301 elseif ($value['key'] == 'email') {
302 $url = "civicrm/contact/view/activity";
303 $qs = "atype=3&action=add&reset=1&cid=%%id%%{$extraParams}";
306 self
::$_links[$counter++
] = [
307 'name' => $value['title'],
310 'title' => $value['title'],
311 'ref' => $value['ref'],
312 'class' => $value['class'] ??
NULL,
317 return self
::$_links;
321 * Getter for array of the parameters required for creating pager.
324 * @param array $params
326 public function getPagerParams($action, &$params) {
327 $params['status'] = ts('Contact %%StatusMessage%%');
328 $params['csvString'] = NULL;
329 $params['rowCount'] = CRM_Utils_Pager
::ROWCOUNT
;
331 $params['buttonTop'] = 'PagerTopButton';
332 $params['buttonBottom'] = 'PagerBottomButton';
336 * @param null $action
337 * @param null $output
341 public function &getColHeads($action = NULL, $output = NULL) {
342 $colHeads = self
::_getColumnHeaders();
343 $colHeads[] = ['desc' => ts('Actions'), 'name' => ts('Action')];
348 * Returns the column headers as an array of tuples:
349 * (name, sortName (key to the sort array))
351 * @param string $action
352 * The action being performed.
353 * @param string $output
354 * What should the result set include (web/email/csv).
357 * the column headers that need to be displayed
359 public function &getColumnHeaders($action = NULL, $output = NULL) {
362 // unset return property elements that we don't care
363 if (!empty($this->_returnProperties
)) {
364 $doNotCareElements = [
369 foreach ($doNotCareElements as $value) {
370 unset($this->_returnProperties
[$value]);
374 if ($output == CRM_Core_Selector_Controller
::EXPORT
) {
375 $csvHeaders = [ts('Contact ID'), ts('Contact Type')];
376 foreach ($this->getColHeads($action, $output) as $column) {
377 if (array_key_exists('name', $column)) {
378 $csvHeaders[] = $column['name'];
381 $headers = $csvHeaders;
383 elseif ($output == CRM_Core_Selector_Controller
::SCREEN
) {
384 $csvHeaders = [ts('Name')];
385 foreach ($this->getColHeads($action, $output) as $key => $column) {
386 if (array_key_exists('name', $column) &&
388 $column['name'] != ts('Name')
390 $csvHeaders[$key] = $column['name'];
393 $headers = $csvHeaders;
395 elseif ($this->_ufGroupID
) {
396 // we dont use the cached value of column headers
397 // since it potentially changed because of the profile selected
398 static $skipFields = ['group', 'tag'];
399 $direction = CRM_Utils_Sort
::ASCENDING
;
401 if (!self
::$_columnHeaders) {
402 self
::$_columnHeaders = [
405 'name' => ts('Name'),
406 'sort' => 'sort_name',
407 'direction' => CRM_Utils_Sort
::ASCENDING
,
411 $locationTypes = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
413 foreach ($this->_fields
as $name => $field) {
414 if (!empty($field['in_selector']) &&
415 !in_array($name, $skipFields)
417 if (strpos($name, '-') !== FALSE) {
418 list($fieldName, $lType, $type) = CRM_Utils_System
::explode('-', $name, 3);
420 if ($lType == 'Primary') {
421 $locationTypeName = 1;
424 $locationTypeName = $locationTypes[$lType];
427 if (in_array($fieldName, [
433 $name = "`$locationTypeName-$fieldName-$type`";
436 $name = "`$locationTypeName-$fieldName`";
440 $name = "`$locationTypeName-$fieldName`";
443 //to handle sort key for Internal contactId.CRM-2289
445 $name = 'contact_id';
448 self
::$_columnHeaders[] = [
449 'name' => $field['title'],
451 'direction' => $direction,
453 $direction = CRM_Utils_Sort
::DONTCARE
;
458 // if we dont have any valid columns, dont add the implicit ones
459 // this allows the template to check on emptiness of column headers
461 self
::$_columnHeaders = [];
464 self
::$_columnHeaders[] = ['desc' => ts('Actions'), 'name' => ts('Action')];
467 $headers = self
::$_columnHeaders;
469 elseif (!empty($this->_returnProperties
)) {
470 self
::$_columnHeaders = [
473 'name' => ts('Name'),
474 'sort' => 'sort_name',
475 'direction' => CRM_Utils_Sort
::ASCENDING
,
478 $properties = self
::makeProperties($this->_returnProperties
);
480 foreach ($properties as $prop) {
481 if (strpos($prop, '-')) {
482 list($loc, $fld, $phoneType) = CRM_Utils_System
::explode('-', $prop, 3);
483 $title = $this->_query
->_fields
[$fld]['title'];
484 if (trim($phoneType) && !is_numeric($phoneType) && strtolower($phoneType) != $fld) {
485 $title .= "-{$phoneType}";
487 // fetch Location type label from name as $loc, which will be later used in column header
488 $title .= sprintf(" (%s)",
489 CRM_Core_PseudoConstant
::getLabel(
490 'CRM_Core_DAO_Address',
492 CRM_Core_PseudoConstant
::getKey('CRM_Core_DAO_Address', 'location_type_id', $loc)
497 elseif (isset($this->_query
->_fields
[$prop]) && isset($this->_query
->_fields
[$prop]['title'])) {
498 $title = $this->_query
->_fields
[$prop]['title'];
500 elseif (isset($this->_query
->_pseudoConstantsSelect
[$prop]) && isset($this->_query
->_pseudoConstantsSelect
[$prop]['pseudoconstant']['optionGroupName'])) {
501 $title = CRM_Core_BAO_OptionGroup
::getTitleByName($this->_query
->_pseudoConstantsSelect
[$prop]['pseudoconstant']['optionGroupName']);
507 self
::$_columnHeaders[] = ['name' => $title, 'sort' => $prop];
509 self
::$_columnHeaders[] = ['name' => ts('Actions')];
510 $headers = self
::$_columnHeaders;
513 $headers = $this->getColHeads($action, $output);
520 * Returns total number of rows for the query.
525 * Total number of rows
527 public function getTotalCount($action) {
528 // Use count from cache during paging/sorting
529 if (!empty($_GET['crmPID']) ||
!empty($_GET['crmSID'])) {
530 $count = Civi
::cache('long')->get("Search Results Count $this->_key");
533 $count = $this->_query
->searchQuery(0, 0, NULL, TRUE);
534 Civi
::cache('long')->set("Search Results Count $this->_key", $count);
540 * Returns all the rows in the given offset and rowCount.
542 * @param string $action
543 * The action being performed.
545 * The row number to start from.
546 * @param int $rowCount
547 * The number of rows to return.
548 * @param string $sort
549 * The sql string that describes the sort order.
550 * @param string $output
551 * What should the result set include (web/email/csv).
554 * the total number of rows for this action
556 public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
557 if (($output == CRM_Core_Selector_Controller
::EXPORT ||
558 $output == CRM_Core_Selector_Controller
::SCREEN
560 $this->_formValues
['radio_ts'] == 'ts_sel'
562 $includeContactIds = TRUE;
565 $includeContactIds = FALSE;
568 // note the formvalues were given by CRM_Contact_Form_Search to us
569 // and contain the search criteria (parameters)
570 // note that the default action is basic
572 /** @var CRM_Core_PrevNextCache_Interface $prevNext */
573 $prevNext = Civi
::service('prevnext');
574 $cacheKey = $this->buildPrevNextCache($sort);
575 $cids = $prevNext->fetch($cacheKey, $offset, $rowCount);
576 $resultSet = empty($cids) ?
[] : $this->_query
->getCachedContacts($cids, $includeContactIds)->fetchGenerator();
579 $resultSet = $this->_query
->searchQuery($offset, $rowCount, $sort, FALSE, $includeContactIds)->fetchGenerator();
582 // process the result of the query
584 $permissions = [CRM_Core_Permission
::getPermission()];
585 if (CRM_Core_Permission
::check('delete contacts')) {
586 $permissions[] = CRM_Core_Permission
::DELETE
;
588 $mask = CRM_Core_Action
::mask($permissions);
590 // mask value to hide map link if there are not lat/long
591 $mapMask = $mask & 4095;
593 if ($this->_searchContext
== 'smog') {
594 $gc = CRM_Core_SelectValues
::groupContactStatus();
597 if ($this->_ufGroupID
) {
598 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
601 static $skipFields = ['group', 'tag'];
602 foreach ($this->_fields
as $key => $field) {
603 if (!empty($field['in_selector']) &&
604 !in_array($key, $skipFields)
606 if (strpos($key, '-') !== FALSE) {
607 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $key, 3);
609 if ($id == 'Primary') {
610 $locationTypeName = 1;
612 elseif ($fieldName == 'url') {
613 $locationTypeName = "website-{$id}";
616 $locationTypeName = $locationTypes[$id] ??
NULL;
617 if (!$locationTypeName) {
622 $locationTypeName = str_replace(' ', '_', $locationTypeName);
623 if (in_array($fieldName, [
629 $names[] = "{$locationTypeName}-{$fieldName}-{$type}";
632 $names[] = "{$locationTypeName}-{$fieldName}";
636 $names[] = "{$locationTypeName}-{$fieldName}";
640 $names[] = $field['name'];
647 elseif (!empty($this->_returnProperties
)) {
648 $names = self
::makeProperties($this->_returnProperties
);
651 $names = self
::$_properties;
654 $links = self
::links($this->_context
, $this->_contextMenu
, $this->_key
);
656 //check explicitly added contact to a Smart Group.
657 $groupID = $this->_formValues
['group'] ??
NULL;
659 $pseudoconstants = [];
660 // for CRM-3157 purposes
661 if (in_array('world_region', $names)) {
662 $pseudoconstants['world_region'] = [
663 'dbName' => 'worldregion_id',
664 'values' => CRM_Core_PseudoConstant
::worldRegion(),
668 foreach ($resultSet as $result) {
670 $this->_query
->convertToPseudoNames($result);
671 // the columns we are interested in
672 foreach ($names as $property) {
673 if ($property == 'status') {
676 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($property)) {
677 $row[$property] = CRM_Core_BAO_CustomField
::displayValue(
683 elseif (strpos($property, '-im')) {
684 $row[$property] = $result->$property;
685 if (!empty($result->$property)) {
686 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
687 $providerId = $property . "-provider_id";
688 $providerName = $imProviders[$result->$providerId];
689 $row[$property] = $result->$property . " ({$providerName})";
692 elseif (in_array($property, [
697 $greeting = $property . '_display';
698 $row[$property] = $result->$greeting;
700 elseif (isset($pseudoconstants[$property])) {
701 $row[$property] = CRM_Utils_Array
::value(
702 $result->{$pseudoconstants[$property]['dbName']},
703 $pseudoconstants[$property]['values']
706 elseif (strpos($property, '-url') !== FALSE) {
708 $websiteKey = str_replace('-url', '', $property);
709 $propertyArray = explode('-', $property);
710 $websiteFld = $websiteKey . '-' . array_pop($propertyArray);
711 if (!empty($result->$websiteFld)) {
712 $websiteTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Website', 'website_type_id');
713 $websiteType = $websiteTypes[$result->{"$websiteKey-website_type_id"}];
714 $websiteValue = $result->$websiteFld;
715 $websiteUrl = "<a href=\"{$websiteValue}\">{$websiteValue} ({$websiteType})</a>";
717 $row[$property] = $websiteUrl;
719 elseif (strpos($property, '-email') !== FALSE) {
720 list($locType) = explode("-email", $property);
721 $onholdProperty = "{$locType}-on_hold";
723 $row[$property] = $result->$property ??
NULL;
724 if (!empty($row[$property]) && !empty($result->$onholdProperty)) {
725 $row[$property] .= " (On Hold)";
729 $row[$property] = $result->$property ??
NULL;
733 if (!empty($result->postal_code_suffix
)) {
734 $row['postal_code'] .= "-" . $result->postal_code_suffix
;
737 if ($output != CRM_Core_Selector_Controller
::EXPORT
&&
738 $this->_searchContext
== 'smog'
740 if (empty($result->status
) &&
743 $contactID = $result->contact_id
;
746 'contact_id' => $contactID,
747 'group_id' => $groupID,
751 CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_GroupContact', $gcParams, $gcDefaults);
753 if (empty($gcDefaults)) {
754 $row['status'] = ts('Smart');
757 $row['status'] = $gc[$gcDefaults['status']];
761 $row['status'] = NULL;
765 $row['status'] = $gc[$result->status
];
769 if ($output != CRM_Core_Selector_Controller
::EXPORT
) {
770 $row['checkbox'] = CRM_Core_Form
::CB_PREFIX
. $result->contact_id
;
772 if (!empty($this->_formValues
['deleted_contacts']) && CRM_Core_Permission
::check('access deleted contacts')
776 'name' => ts('View'),
777 'url' => 'civicrm/contact/view',
778 'qs' => 'reset=1&cid=%%id%%',
779 'class' => 'no-popup',
780 'title' => ts('View Contact Details'),
783 'name' => ts('Restore'),
784 'url' => 'civicrm/contact/view/delete',
785 'qs' => 'reset=1&cid=%%id%%&restore=1',
786 'title' => ts('Restore Contact'),
789 if (CRM_Core_Permission
::check('delete contacts')) {
791 'name' => ts('Delete Permanently'),
792 'url' => 'civicrm/contact/view/delete',
793 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1',
794 'title' => ts('Permanently Delete Contact'),
797 $row['action'] = CRM_Core_Action
::formLink(
800 ['id' => $result->contact_id
],
803 'contact.selector.row',
808 elseif ((is_numeric(CRM_Utils_Array
::value('geo_code_1', $row))) ||
809 (!empty($row['city']) && !empty($row['state_province']))
811 $row['action'] = CRM_Core_Action
::formLink(
814 ['id' => $result->contact_id
],
817 'contact.selector.row',
823 $row['action'] = CRM_Core_Action
::formLink(
826 ['id' => $result->contact_id
],
829 'contact.selector.row',
835 // allow components to add more actions
836 CRM_Core_Component
::searchAction($row, $result->contact_id
);
838 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils
::getImage($result->contact_sub_type ?
$result->contact_sub_type
: $result->contact_type
,
843 $row['contact_type_orig'] = $result->contact_sub_type ?
$result->contact_sub_type
: $result->contact_type
;
844 $row['contact_id'] = $result->contact_id
;
845 $row['sort_name'] = $result->sort_name
;
846 // Surely this if should be if NOT - otherwise it's just wierd.
847 if (array_key_exists('id', $row)) {
848 $row['id'] = $result->contact_id
;
852 $rows[$row['contact_id']] = $row;
859 * @param CRM_Utils_Sort $sort
863 public function buildPrevNextCache($sort) {
864 $cacheKey = 'civicrm search ' . $this->_key
;
866 // We should clear the cache in following conditions:
867 // 1. when starting from scratch, i.e new search
868 // 2. if records are sorted
870 // get current page requested
871 $pageNum = CRM_Utils_Request
::retrieve('crmPID', 'Integer');
873 // get the current sort order
874 $currentSortID = CRM_Utils_Request
::retrieve('crmSID', 'String');
876 $session = CRM_Core_Session
::singleton();
878 // get previous sort id
879 $previousSortID = $session->get('previousSortID');
881 // check for current != previous to ensure cache is not reset if paging is done without changing
883 if (!$pageNum ||
(!empty($currentSortID) && $currentSortID != $previousSortID)) {
884 Civi
::service('prevnext')->deleteItem(NULL, $cacheKey, 'civicrm_contact');
885 // this means it's fresh search, so set pageNum=1
891 // set the current sort as previous sort
892 if (!empty($currentSortID)) {
893 $session->set('previousSortID', $currentSortID);
896 $pageSize = CRM_Utils_Request
::retrieve('crmRowCount', 'Integer', CRM_Core_DAO
::$_nullObject, FALSE, 50);
897 $firstRecord = ($pageNum - 1) * $pageSize;
899 //for alphabetic pagination selection save
900 $sortByCharacter = CRM_Utils_Request
::retrieve('sortByCharacter', 'String');
902 //for text field pagination selection save
903 $countRow = Civi
::service('prevnext')->getCount($cacheKey);
904 // $sortByCharacter triggers a refresh in the prevNext cache
905 if ($sortByCharacter && $sortByCharacter != 'all') {
906 $this->fillupPrevNextCache($sort, $cacheKey, 0, max(self
::CACHE_SIZE
, $pageSize));
908 elseif (($firstRecord +
$pageSize) >= $countRow) {
909 $this->fillupPrevNextCache($sort, $cacheKey, $countRow, max(self
::CACHE_SIZE
, $pageSize) +
$firstRecord - $countRow);
917 public function addActions(&$rows) {
919 $basicPermissions = CRM_Core_Permission
::check('delete contacts') ?
[CRM_Core_Permission
::DELETE
] : [];
921 // get permissions on an individual level (CRM-12645)
922 // @todo look at storing this to the session as this is called twice during search results render.
923 $can_edit_list = CRM_Contact_BAO_Contact_Permission
::allowList(array_keys($rows), CRM_Core_Permission
::EDIT
);
925 $links_template = self
::links($this->_context
, $this->_contextMenu
, $this->_key
);
927 foreach ($rows as $id => & $row) {
928 $links = $links_template;
929 if (in_array($id, $can_edit_list)) {
930 $mask = CRM_Core_Action
::mask(array_merge([CRM_Core_Permission
::EDIT
], $basicPermissions));
933 $mask = CRM_Core_Action
::mask(array_merge([CRM_Core_Permission
::VIEW
], $basicPermissions));
936 if ((!is_numeric(CRM_Utils_Array
::value('geo_code_1', $row))) &&
937 (empty($row['city']) ||
empty($row['state_province']))
939 $mask = $mask & 4095;
942 if (!empty($this->_formValues
['deleted_contacts']) && CRM_Core_Permission
::check('access deleted contacts')
946 'name' => ts('View'),
947 'url' => 'civicrm/contact/view',
948 'qs' => 'reset=1&cid=%%id%%',
949 'class' => 'no-popup',
950 'title' => ts('View Contact Details'),
953 'name' => ts('Restore'),
954 'url' => 'civicrm/contact/view/delete',
955 'qs' => 'reset=1&cid=%%id%%&restore=1',
956 'title' => ts('Restore Contact'),
959 if (CRM_Core_Permission
::check('delete contacts')) {
961 'name' => ts('Delete Permanently'),
962 'url' => 'civicrm/contact/view/delete',
963 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1',
964 'title' => ts('Permanently Delete Contact'),
967 $row['action'] = CRM_Core_Action
::formLink(
970 ['id' => $row['contact_id']],
973 'contact.selector.actions',
979 $row['action'] = CRM_Core_Action
::formLink(
982 ['id' => $row['contact_id']],
985 'contact.selector.actions',
991 // allow components to add more actions
992 CRM_Core_Component
::searchAction($row, $row['contact_id']);
994 if (!empty($row['contact_type_orig'])) {
995 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils
::getImage($row['contact_type_orig'],
996 FALSE, $row['contact_id']);
1004 public function removeActions(&$rows) {
1005 foreach ($rows as $rid => & $rValue) {
1006 unset($rValue['contact_type']);
1007 unset($rValue['action']);
1012 * @param CRM_Utils_Sort $sort
1013 * @param string $cacheKey
1017 * @throws \CRM_Core_Exception
1019 public function fillupPrevNextCache($sort, $cacheKey, $start = 0, $end = self
::CACHE_SIZE
) {
1021 // For custom searches, use the contactIDs method
1022 if (is_a($this, 'CRM_Contact_Selector_Custom')) {
1023 $sql = $this->_search
->contactIDs($start, $end, $sort, TRUE);
1024 $coreSearch = FALSE;
1026 // For core searches use the searchQuery method
1028 $sql = $this->_query
->getSearchSQL($start, $end, $sort, FALSE, $this->_query
->_includeContactIds
,
1033 // due to limitations in our search query writer, the above query does not work
1034 // in cases where the query is being sorted on a non-contact table
1035 // this results in a fatal error :(
1036 // see below for the gross hack of trapping the error and not filling
1037 // the prev next cache in this situation
1038 // the other alternative of running the FULL query will just be incredibly inefficient
1039 // and slow things down way too much on large data sets / complex queries
1041 $selectSQL = CRM_Core_DAO
::composeQuery("SELECT DISTINCT %1, contact_a.id, contact_a.sort_name", [1 => [$cacheKey, 'String']]);
1043 $sql = str_ireplace(['SELECT contact_a.id as contact_id', 'SELECT contact_a.id as id'], $selectSQL, $sql);
1044 $sql = str_ireplace('ORDER BY `contact_id`', 'ORDER BY `id`', $sql, $sql);
1047 Civi
::service('prevnext')->fillWithSql($cacheKey, $sql);
1049 catch (CRM_Core_Exception
$e) {
1051 // in the case of error, try rebuilding cache using full sql which is used for search selector display
1052 // this fixes the bugs reported in CRM-13996 & CRM-14438
1053 $this->rebuildPreNextCache($start, $end, $sort, $cacheKey);
1056 CRM_Core_Error
::deprecatedFunctionWarning('Custom searches should return sql capable of filling the prevnext cache.');
1057 // This will always show for CiviRules :-( as a) it orders by 'rule_label'
1058 // which is not available in the query & b) it uses contact not contact_a
1060 // CRM_Core_Session::setStatus(ts('Query Failed'));
1065 if (Civi
::service('prevnext') instanceof CRM_Core_PrevNextCache_Sql
) {
1066 // SQL-backed prevnext cache uses an extra record for pruning the cache.
1067 // Also ensure that caches stay alive for 2 days as per previous code
1068 Civi
::cache('prevNextCache')->set($cacheKey, $cacheKey, 60 * 60 * 24 * CRM_Core_PrevNextCache_Sql
::cacheDays
);
1073 * called to rebuild prev next cache using full sql in case of core search ( excluding custom search)
1076 * Start for limit clause.
1078 * End for limit clause.
1079 * @param CRM_Utils_Sort $sort
1080 * @param string $cacheKey
1083 public function rebuildPreNextCache($start, $end, $sort, $cacheKey) {
1084 // generate full SQL
1085 $sql = $this->_query
->searchQuery($start, $end, $sort, FALSE, $this->_query
->_includeContactIds
,
1086 FALSE, FALSE, TRUE);
1088 $dao = CRM_Core_DAO
::executeQuery($sql);
1090 // build insert query, note that currently we build cache for 500 (self::CACHE_SIZE) contact records at a time, hence below approach
1092 while ($dao->fetch()) {
1094 'entity_table' => 'civicrm_contact',
1095 'entity_id1' => $dao->contact_id
,
1096 'entity_id2' => $dao->contact_id
,
1097 'data' => $dao->sort_name
,
1101 Civi
::service('prevnext')->fillWithArray($cacheKey, $rows);
1107 public function getQILL() {
1108 return $this->_query
->qill();
1112 * Name of export file.
1114 * @param string $output
1120 public function getExportFileName($output = 'csv') {
1121 return ts('CiviCRM Contact Search');
1125 * Get colunmn headers for search selector.
1129 private static function &_getColumnHeaders() {
1130 if (!isset(self
::$_columnHeaders)) {
1131 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1132 'address_options', TRUE, NULL, TRUE
1135 self
::$_columnHeaders = [
1136 'contact_type' => ['desc' => ts('Contact Type')],
1138 'name' => ts('Name'),
1139 'sort' => 'sort_name',
1140 'direction' => CRM_Utils_Sort
::ASCENDING
,
1145 'street_address' => ['name' => ts('Address')],
1147 'name' => ts('City'),
1149 'direction' => CRM_Utils_Sort
::DONTCARE
,
1151 'state_province' => [
1152 'name' => ts('State'),
1153 'sort' => 'state_province',
1154 'direction' => CRM_Utils_Sort
::DONTCARE
,
1157 'name' => ts('Postal'),
1158 'sort' => 'postal_code',
1159 'direction' => CRM_Utils_Sort
::DONTCARE
,
1162 'name' => ts('Country'),
1163 'sort' => 'country',
1164 'direction' => CRM_Utils_Sort
::DONTCARE
,
1168 foreach ($defaultAddress as $columnName => $column) {
1169 if (!empty($addressOptions[$columnName])) {
1170 self
::$_columnHeaders[$columnName] = $column;
1174 self
::$_columnHeaders['email'] = [
1175 'name' => ts('Email'),
1177 'direction' => CRM_Utils_Sort
::DONTCARE
,
1180 self
::$_columnHeaders['phone'] = ['name' => ts('Phone')];
1182 return self
::$_columnHeaders;
1186 * @return CRM_Contact_BAO_Query
1188 public function getQuery() {
1189 return $this->_query
;
1193 * @return CRM_Contact_DAO_Contact
1195 public function alphabetQuery() {
1196 return $this->_query
->alphabetQuery();
1200 * @param array $params
1201 * @param int $sortID
1202 * @param null $displayRelationshipType
1203 * @param string $queryOperator
1205 * @return CRM_Contact_DAO_Contact
1207 public function contactIDQuery($params, $sortID, $displayRelationshipType = NULL, $queryOperator = 'AND') {
1208 $sortOrder = &$this->getSortOrder($this->_action
);
1209 $sort = new CRM_Utils_Sort($sortOrder, $sortID);
1211 // rectify params to what proximity search expects if there is a value for prox_distance
1212 // CRM-7021 CRM-7905
1213 if (!empty($params)) {
1214 CRM_Contact_BAO_ProximityQuery
::fixInputParams($params);
1217 if (!$displayRelationshipType) {
1218 $query = new CRM_Contact_BAO_Query($params,
1219 CRM_Contact_BAO_Query
::NO_RETURN_PROPERTIES
,
1220 NULL, FALSE, FALSE, 1,
1221 FALSE, TRUE, TRUE, NULL,
1226 $query = new CRM_Contact_BAO_Query($params,
1227 CRM_Contact_BAO_Query
::NO_RETURN_PROPERTIES
,
1228 NULL, FALSE, FALSE, 1,
1229 FALSE, TRUE, TRUE, $displayRelationshipType,
1233 return $query->searchQuery(0, 0, $sort);
1237 * @param $returnProperties
1241 public function &makeProperties(&$returnProperties) {
1243 foreach ($returnProperties as $name => $value) {
1244 if ($name != 'location') {
1245 // special handling for group and tag
1246 if (in_array($name, ['group', 'tag'])) {
1250 // special handling for notes
1251 if (in_array($name, ['note', 'note_subject', 'note_body'])) {
1255 $properties[] = $name;
1258 // extract all the location stuff
1259 foreach ($value as $n => $v) {
1260 foreach ($v as $n1 => $v1) {
1261 if (!strpos('_id', $n1) && $n1 != 'location_type') {
1262 $n = str_replace(' ', '_', $n);
1263 $properties[] = "{$n}-{$n1}";