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,
233 * This method set cache key, later used in test environment
237 public function setKey($key) {
242 * This method returns the links that are given for each search row.
243 * currently the links added for each row are
250 public static function &links() {
251 list($context, $contextMenu, $key) = func_get_args();
252 $extraParams = ($key) ?
"&key={$key}" : NULL;
253 $searchContext = ($context) ?
"&context=$context" : NULL;
255 if (!(self
::$_links)) {
257 CRM_Core_Action
::VIEW
=> [
258 'name' => ts('View'),
259 'url' => 'civicrm/contact/view',
260 'class' => 'no-popup',
261 'qs' => "reset=1&cid=%%id%%{$searchContext}{$extraParams}",
262 'title' => ts('View Contact Details'),
263 'ref' => 'view-contact',
265 CRM_Core_Action
::UPDATE
=> [
266 'name' => ts('Edit'),
267 'url' => 'civicrm/contact/add',
268 'class' => 'no-popup',
269 'qs' => "reset=1&action=update&cid=%%id%%{$searchContext}{$extraParams}",
270 'title' => ts('Edit Contact Details'),
271 'ref' => 'edit-contact',
275 $config = CRM_Core_Config
::singleton();
276 //CRM-16552: mapAPIKey is not mandatory as google no longer requires an API Key
277 if ($config->mapProvider
&& ($config->mapAPIKey ||
$config->mapProvider
== 'Google')) {
278 self
::$_links[CRM_Core_Action
::MAP
] = [
280 'url' => 'civicrm/contact/map',
281 'qs' => "reset=1&cid=%%id%%{$searchContext}{$extraParams}",
282 'title' => ts('Map Contact'),
286 // Adding Context Menu Links in more action
289 foreach ($contextMenu as $key => $value) {
290 $contextVal = '&context=' . $value['key'];
291 if ($value['key'] == 'delete') {
292 $contextVal = $searchContext;
294 $url = "civicrm/contact/view/{$value['key']}";
295 $qs = "reset=1&action=add&cid=%%id%%{$contextVal}{$extraParams}";
296 if ($value['key'] == 'activity') {
297 $qs = "action=browse&selectedChild=activity&reset=1&cid=%%id%%{$extraParams}";
299 elseif ($value['key'] == 'email') {
300 $url = "civicrm/contact/view/activity";
301 $qs = "atype=3&action=add&reset=1&cid=%%id%%{$extraParams}";
304 self
::$_links[$counter++
] = [
305 'name' => $value['title'],
308 'title' => $value['title'],
309 'ref' => $value['ref'],
310 'class' => $value['class'] ??
NULL,
315 return self
::$_links;
319 * Getter for array of the parameters required for creating pager.
322 * @param array $params
324 public function getPagerParams($action, &$params) {
325 $params['status'] = ts('Contact %%StatusMessage%%');
326 $params['csvString'] = NULL;
327 $params['rowCount'] = CRM_Utils_Pager
::ROWCOUNT
;
329 $params['buttonTop'] = 'PagerTopButton';
330 $params['buttonBottom'] = 'PagerBottomButton';
334 * @param null $action
335 * @param null $output
339 public function &getColHeads($action = NULL, $output = NULL) {
340 $colHeads = self
::_getColumnHeaders();
341 $colHeads[] = ['desc' => ts('Actions'), 'name' => ts('Action')];
346 * Returns the column headers as an array of tuples:
347 * (name, sortName (key to the sort array))
349 * @param string $action
350 * The action being performed.
351 * @param string $output
352 * What should the result set include (web/email/csv).
355 * the column headers that need to be displayed
357 public function &getColumnHeaders($action = NULL, $output = NULL) {
360 // unset return property elements that we don't care
361 if (!empty($this->_returnProperties
)) {
362 $doNotCareElements = [
367 foreach ($doNotCareElements as $value) {
368 unset($this->_returnProperties
[$value]);
372 if ($output == CRM_Core_Selector_Controller
::EXPORT
) {
373 $csvHeaders = [ts('Contact ID'), ts('Contact Type')];
374 foreach ($this->getColHeads($action, $output) as $column) {
375 if (array_key_exists('name', $column)) {
376 $csvHeaders[] = $column['name'];
379 $headers = $csvHeaders;
381 elseif ($output == CRM_Core_Selector_Controller
::SCREEN
) {
382 $csvHeaders = [ts('Name')];
383 foreach ($this->getColHeads($action, $output) as $key => $column) {
384 if (array_key_exists('name', $column) &&
386 $column['name'] != ts('Name')
388 $csvHeaders[$key] = $column['name'];
391 $headers = $csvHeaders;
393 elseif ($this->_ufGroupID
) {
394 // we dont use the cached value of column headers
395 // since it potentially changed because of the profile selected
396 static $skipFields = ['group', 'tag'];
397 $direction = CRM_Utils_Sort
::ASCENDING
;
399 if (!self
::$_columnHeaders) {
400 self
::$_columnHeaders = [
403 'name' => ts('Name'),
404 'sort' => 'sort_name',
405 'direction' => CRM_Utils_Sort
::ASCENDING
,
409 $locationTypes = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
411 foreach ($this->_fields
as $name => $field) {
412 if (!empty($field['in_selector']) &&
413 !in_array($name, $skipFields)
415 if (strpos($name, '-') !== FALSE) {
416 list($fieldName, $lType, $type) = CRM_Utils_System
::explode('-', $name, 3);
418 if ($lType == 'Primary') {
419 $locationTypeName = 1;
422 $locationTypeName = $locationTypes[$lType];
425 if (in_array($fieldName, [
431 $name = "`$locationTypeName-$fieldName-$type`";
434 $name = "`$locationTypeName-$fieldName`";
438 $name = "`$locationTypeName-$fieldName`";
441 //to handle sort key for Internal contactId.CRM-2289
443 $name = 'contact_id';
446 self
::$_columnHeaders[] = [
447 'name' => $field['title'],
449 'direction' => $direction,
451 $direction = CRM_Utils_Sort
::DONTCARE
;
456 // if we dont have any valid columns, dont add the implicit ones
457 // this allows the template to check on emptiness of column headers
459 self
::$_columnHeaders = [];
462 self
::$_columnHeaders[] = ['desc' => ts('Actions'), 'name' => ts('Action')];
465 $headers = self
::$_columnHeaders;
467 elseif (!empty($this->_returnProperties
)) {
468 self
::$_columnHeaders = [
471 'name' => ts('Name'),
472 'sort' => 'sort_name',
473 'direction' => CRM_Utils_Sort
::ASCENDING
,
476 $properties = self
::makeProperties($this->_returnProperties
);
478 foreach ($properties as $prop) {
479 if (strpos($prop, '-')) {
480 list($loc, $fld, $phoneType) = CRM_Utils_System
::explode('-', $prop, 3);
481 $title = $this->_query
->_fields
[$fld]['title'];
482 if (trim($phoneType) && !is_numeric($phoneType) && strtolower($phoneType) != $fld) {
483 $title .= "-{$phoneType}";
485 // fetch Location type label from name as $loc, which will be later used in column header
486 $title .= sprintf(" (%s)",
487 CRM_Core_PseudoConstant
::getLabel(
488 'CRM_Core_DAO_Address',
490 CRM_Core_PseudoConstant
::getKey('CRM_Core_DAO_Address', 'location_type_id', $loc)
495 elseif (isset($this->_query
->_fields
[$prop]) && isset($this->_query
->_fields
[$prop]['title'])) {
496 $title = $this->_query
->_fields
[$prop]['title'];
498 elseif (isset($this->_query
->_pseudoConstantsSelect
[$prop]) && isset($this->_query
->_pseudoConstantsSelect
[$prop]['pseudoconstant']['optionGroupName'])) {
499 $title = CRM_Core_BAO_OptionGroup
::getTitleByName($this->_query
->_pseudoConstantsSelect
[$prop]['pseudoconstant']['optionGroupName']);
505 self
::$_columnHeaders[] = ['name' => $title, 'sort' => $prop];
507 self
::$_columnHeaders[] = ['name' => ts('Actions')];
508 $headers = self
::$_columnHeaders;
511 $headers = $this->getColHeads($action, $output);
518 * Returns total number of rows for the query.
523 * Total number of rows
525 public function getTotalCount($action) {
526 // Use count from cache during paging/sorting
527 if (!empty($_GET['crmPID']) ||
!empty($_GET['crmSID'])) {
528 $count = Civi
::cache('long')->get("Search Results Count $this->_key");
531 $count = $this->_query
->searchQuery(0, 0, NULL, TRUE);
532 Civi
::cache('long')->set("Search Results Count $this->_key", $count);
538 * Returns all the rows in the given offset and rowCount.
540 * @param string $action
541 * The action being performed.
543 * The row number to start from.
544 * @param int $rowCount
545 * The number of rows to return.
546 * @param string $sort
547 * The sql string that describes the sort order.
548 * @param string $output
549 * What should the result set include (web/email/csv).
552 * the total number of rows for this action
554 public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
555 if (($output == CRM_Core_Selector_Controller
::EXPORT ||
556 $output == CRM_Core_Selector_Controller
::SCREEN
558 $this->_formValues
['radio_ts'] == 'ts_sel'
560 $includeContactIds = TRUE;
563 $includeContactIds = FALSE;
566 // note the formvalues were given by CRM_Contact_Form_Search to us
567 // and contain the search criteria (parameters)
568 // note that the default action is basic
570 /** @var CRM_Core_PrevNextCache_Interface $prevNext */
571 $prevNext = Civi
::service('prevnext');
572 $cacheKey = $this->buildPrevNextCache($sort);
573 $cids = $prevNext->fetch($cacheKey, $offset, $rowCount);
574 $resultSet = empty($cids) ?
[] : $this->_query
->getCachedContacts($cids, $includeContactIds)->fetchGenerator();
577 $resultSet = $this->_query
->searchQuery($offset, $rowCount, $sort, FALSE, $includeContactIds)->fetchGenerator();
580 // process the result of the query
582 $permissions = [CRM_Core_Permission
::getPermission()];
583 if (CRM_Core_Permission
::check('delete contacts')) {
584 $permissions[] = CRM_Core_Permission
::DELETE
;
586 $mask = CRM_Core_Action
::mask($permissions);
588 // mask value to hide map link if there are not lat/long
589 $mapMask = $mask & 4095;
591 if ($this->_searchContext
== 'smog') {
592 $gc = CRM_Core_SelectValues
::groupContactStatus();
595 if ($this->_ufGroupID
) {
596 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
599 static $skipFields = ['group', 'tag'];
600 foreach ($this->_fields
as $key => $field) {
601 if (!empty($field['in_selector']) &&
602 !in_array($key, $skipFields)
604 if (strpos($key, '-') !== FALSE) {
605 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $key, 3);
607 if ($id == 'Primary') {
608 $locationTypeName = 1;
610 elseif ($fieldName == 'url') {
611 $locationTypeName = "website-{$id}";
614 $locationTypeName = $locationTypes[$id] ??
NULL;
615 if (!$locationTypeName) {
620 $locationTypeName = str_replace(' ', '_', $locationTypeName);
621 if (in_array($fieldName, [
627 $names[] = "{$locationTypeName}-{$fieldName}-{$type}";
630 $names[] = "{$locationTypeName}-{$fieldName}";
634 $names[] = "{$locationTypeName}-{$fieldName}";
638 $names[] = $field['name'];
645 elseif (!empty($this->_returnProperties
)) {
646 $names = self
::makeProperties($this->_returnProperties
);
649 $names = self
::$_properties;
652 $links = self
::links($this->_context
, $this->_contextMenu
, $this->_key
);
654 //check explicitly added contact to a Smart Group.
655 $groupID = $this->_formValues
['group'] ??
NULL;
657 $pseudoconstants = [];
658 // for CRM-3157 purposes
659 if (in_array('world_region', $names)) {
660 $pseudoconstants['world_region'] = [
661 'dbName' => 'worldregion_id',
662 'values' => CRM_Core_PseudoConstant
::worldRegion(),
666 foreach ($resultSet as $result) {
668 $this->_query
->convertToPseudoNames($result);
669 // the columns we are interested in
670 foreach ($names as $property) {
671 if ($property == 'status') {
674 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($property)) {
675 $row[$property] = CRM_Core_BAO_CustomField
::displayValue(
681 elseif (strpos($property, '-im')) {
682 $row[$property] = $result->$property;
683 if (!empty($result->$property)) {
684 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
685 $providerId = $property . "-provider_id";
686 $providerName = $imProviders[$result->$providerId];
687 $row[$property] = $result->$property . " ({$providerName})";
690 elseif (in_array($property, [
695 $greeting = $property . '_display';
696 $row[$property] = $result->$greeting;
698 elseif (isset($pseudoconstants[$property])) {
699 $row[$property] = CRM_Utils_Array
::value(
700 $result->{$pseudoconstants[$property]['dbName']},
701 $pseudoconstants[$property]['values']
704 elseif (strpos($property, '-url') !== FALSE) {
706 $websiteKey = str_replace('-url', '', $property);
707 $propertyArray = explode('-', $property);
708 $websiteFld = $websiteKey . '-' . array_pop($propertyArray);
709 if (!empty($result->$websiteFld)) {
710 $websiteTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Website', 'website_type_id');
711 $websiteType = $websiteTypes[$result->{"$websiteKey-website_type_id"}];
712 $websiteValue = $result->$websiteFld;
713 $websiteUrl = "<a href=\"{$websiteValue}\">{$websiteValue} ({$websiteType})</a>";
715 $row[$property] = $websiteUrl;
717 elseif (strpos($property, '-email') !== FALSE) {
718 list($locType) = explode("-email", $property);
719 $onholdProperty = "{$locType}-on_hold";
721 $row[$property] = $result->$property ??
NULL;
722 if (!empty($row[$property]) && !empty($result->$onholdProperty)) {
723 $row[$property] .= " (On Hold)";
727 $row[$property] = $result->$property ??
NULL;
731 if (!empty($result->postal_code_suffix
)) {
732 $row['postal_code'] .= "-" . $result->postal_code_suffix
;
735 if ($output != CRM_Core_Selector_Controller
::EXPORT
&&
736 $this->_searchContext
== 'smog'
738 if (empty($result->status
) &&
741 $contactID = $result->contact_id
;
744 'contact_id' => $contactID,
745 'group_id' => $groupID,
749 CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_GroupContact', $gcParams, $gcDefaults);
751 if (empty($gcDefaults)) {
752 $row['status'] = ts('Smart');
755 $row['status'] = $gc[$gcDefaults['status']];
759 $row['status'] = NULL;
763 $row['status'] = $gc[$result->status
];
767 if ($output != CRM_Core_Selector_Controller
::EXPORT
) {
768 $row['checkbox'] = CRM_Core_Form
::CB_PREFIX
. $result->contact_id
;
770 if (!empty($this->_formValues
['deleted_contacts']) && CRM_Core_Permission
::check('access deleted contacts')
774 'name' => ts('View'),
775 'url' => 'civicrm/contact/view',
776 'qs' => 'reset=1&cid=%%id%%',
777 'class' => 'no-popup',
778 'title' => ts('View Contact Details'),
781 'name' => ts('Restore'),
782 'url' => 'civicrm/contact/view/delete',
783 'qs' => 'reset=1&cid=%%id%%&restore=1',
784 'title' => ts('Restore Contact'),
787 if (CRM_Core_Permission
::check('delete contacts')) {
789 'name' => ts('Delete Permanently'),
790 'url' => 'civicrm/contact/view/delete',
791 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1',
792 'title' => ts('Permanently Delete Contact'),
795 $row['action'] = CRM_Core_Action
::formLink(
798 ['id' => $result->contact_id
],
801 'contact.selector.row',
806 elseif ((is_numeric(CRM_Utils_Array
::value('geo_code_1', $row))) ||
807 (!empty($row['city']) && !empty($row['state_province']))
809 $row['action'] = CRM_Core_Action
::formLink(
812 ['id' => $result->contact_id
],
815 'contact.selector.row',
821 $row['action'] = CRM_Core_Action
::formLink(
824 ['id' => $result->contact_id
],
827 'contact.selector.row',
833 // allow components to add more actions
834 CRM_Core_Component
::searchAction($row, $result->contact_id
);
836 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils
::getImage($result->contact_sub_type ?
$result->contact_sub_type
: $result->contact_type
,
841 $row['contact_type_orig'] = $result->contact_sub_type ?
$result->contact_sub_type
: $result->contact_type
;
842 $row['contact_id'] = $result->contact_id
;
843 $row['sort_name'] = $result->sort_name
;
844 // Surely this if should be if NOT - otherwise it's just wierd.
845 if (array_key_exists('id', $row)) {
846 $row['id'] = $result->contact_id
;
850 $rows[$row['contact_id']] = $row;
857 * @param CRM_Utils_Sort $sort
861 public function buildPrevNextCache($sort) {
862 $cacheKey = 'civicrm search ' . $this->_key
;
864 // We should clear the cache in following conditions:
865 // 1. when starting from scratch, i.e new search
866 // 2. if records are sorted
868 // get current page requested
869 $pageNum = CRM_Utils_Request
::retrieve('crmPID', 'Integer');
871 // get the current sort order
872 $currentSortID = CRM_Utils_Request
::retrieve('crmSID', 'String');
874 $session = CRM_Core_Session
::singleton();
876 // get previous sort id
877 $previousSortID = $session->get('previousSortID');
879 // check for current != previous to ensure cache is not reset if paging is done without changing
881 if (!$pageNum ||
(!empty($currentSortID) && $currentSortID != $previousSortID)) {
882 Civi
::service('prevnext')->deleteItem(NULL, $cacheKey, 'civicrm_contact');
883 // this means it's fresh search, so set pageNum=1
889 // set the current sort as previous sort
890 if (!empty($currentSortID)) {
891 $session->set('previousSortID', $currentSortID);
894 $pageSize = CRM_Utils_Request
::retrieve('crmRowCount', 'Integer', CRM_Core_DAO
::$_nullObject, FALSE, 50);
895 $firstRecord = ($pageNum - 1) * $pageSize;
897 //for alphabetic pagination selection save
898 $sortByCharacter = CRM_Utils_Request
::retrieve('sortByCharacter', 'String');
900 //for text field pagination selection save
901 $countRow = Civi
::service('prevnext')->getCount($cacheKey);
902 // $sortByCharacter triggers a refresh in the prevNext cache
903 if ($sortByCharacter && $sortByCharacter != 'all') {
904 $this->fillupPrevNextCache($sort, $cacheKey, 0, max(self
::CACHE_SIZE
, $pageSize));
906 elseif (($firstRecord +
$pageSize) >= $countRow) {
907 $this->fillupPrevNextCache($sort, $cacheKey, $countRow, max(self
::CACHE_SIZE
, $pageSize) +
$firstRecord - $countRow);
915 public function addActions(&$rows) {
917 $basicPermissions = CRM_Core_Permission
::check('delete contacts') ?
[CRM_Core_Permission
::DELETE
] : [];
919 // get permissions on an individual level (CRM-12645)
920 // @todo look at storing this to the session as this is called twice during search results render.
921 $can_edit_list = CRM_Contact_BAO_Contact_Permission
::allowList(array_keys($rows), CRM_Core_Permission
::EDIT
);
923 $links_template = self
::links($this->_context
, $this->_contextMenu
, $this->_key
);
925 foreach ($rows as $id => & $row) {
926 $links = $links_template;
927 if (in_array($id, $can_edit_list)) {
928 $mask = CRM_Core_Action
::mask(array_merge([CRM_Core_Permission
::EDIT
], $basicPermissions));
931 $mask = CRM_Core_Action
::mask(array_merge([CRM_Core_Permission
::VIEW
], $basicPermissions));
934 if ((!is_numeric(CRM_Utils_Array
::value('geo_code_1', $row))) &&
935 (empty($row['city']) ||
empty($row['state_province']))
937 $mask = $mask & 4095;
940 if (!empty($this->_formValues
['deleted_contacts']) && CRM_Core_Permission
::check('access deleted contacts')
944 'name' => ts('View'),
945 'url' => 'civicrm/contact/view',
946 'qs' => 'reset=1&cid=%%id%%',
947 'class' => 'no-popup',
948 'title' => ts('View Contact Details'),
951 'name' => ts('Restore'),
952 'url' => 'civicrm/contact/view/delete',
953 'qs' => 'reset=1&cid=%%id%%&restore=1',
954 'title' => ts('Restore Contact'),
957 if (CRM_Core_Permission
::check('delete contacts')) {
959 'name' => ts('Delete Permanently'),
960 'url' => 'civicrm/contact/view/delete',
961 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1',
962 'title' => ts('Permanently Delete Contact'),
965 $row['action'] = CRM_Core_Action
::formLink(
968 ['id' => $row['contact_id']],
971 'contact.selector.actions',
977 $row['action'] = CRM_Core_Action
::formLink(
980 ['id' => $row['contact_id']],
983 'contact.selector.actions',
989 // allow components to add more actions
990 CRM_Core_Component
::searchAction($row, $row['contact_id']);
992 if (!empty($row['contact_type_orig'])) {
993 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils
::getImage($row['contact_type_orig'],
994 FALSE, $row['contact_id']);
1002 public function removeActions(&$rows) {
1003 foreach ($rows as $rid => & $rValue) {
1004 unset($rValue['contact_type']);
1005 unset($rValue['action']);
1010 * @param CRM_Utils_Sort $sort
1011 * @param string $cacheKey
1015 * @throws \CRM_Core_Exception
1017 public function fillupPrevNextCache($sort, $cacheKey, $start = 0, $end = self
::CACHE_SIZE
) {
1019 // For custom searches, use the contactIDs method
1020 if (is_a($this, 'CRM_Contact_Selector_Custom')) {
1021 $sql = $this->_search
->contactIDs($start, $end, $sort, TRUE);
1022 $coreSearch = FALSE;
1024 // For core searches use the searchQuery method
1026 $sql = $this->_query
->getSearchSQL($start, $end, $sort, FALSE, $this->_query
->_includeContactIds
,
1031 // due to limitations in our search query writer, the above query does not work
1032 // in cases where the query is being sorted on a non-contact table
1033 // this results in a fatal error :(
1034 // see below for the gross hack of trapping the error and not filling
1035 // the prev next cache in this situation
1036 // the other alternative of running the FULL query will just be incredibly inefficient
1037 // and slow things down way too much on large data sets / complex queries
1039 $selectSQL = CRM_Core_DAO
::composeQuery("SELECT DISTINCT %1, contact_a.id, contact_a.sort_name", [1 => [$cacheKey, 'String']]);
1041 $sql = str_ireplace(['SELECT contact_a.id as contact_id', 'SELECT contact_a.id as id'], $selectSQL, $sql);
1042 $sql = str_ireplace('ORDER BY `contact_id`', 'ORDER BY `id`', $sql, $sql);
1045 Civi
::service('prevnext')->fillWithSql($cacheKey, $sql);
1047 catch (\Exception
$e) {
1049 // in the case of error, try rebuilding cache using full sql which is used for search selector display
1050 // this fixes the bugs reported in CRM-13996 & CRM-14438
1051 $this->rebuildPreNextCache($start, $end, $sort, $cacheKey);
1054 CRM_Core_Error
::deprecatedFunctionWarning('Custom searches should return sql capable of filling the prevnext cache.');
1055 // This will always show for CiviRules :-( as a) it orders by 'rule_label'
1056 // which is not available in the query & b) it uses contact not contact_a
1058 // CRM_Core_Session::setStatus(ts('Query Failed'));
1063 if (Civi
::service('prevnext') instanceof CRM_Core_PrevNextCache_Sql
) {
1064 // SQL-backed prevnext cache uses an extra record for pruning the cache.
1065 // Also ensure that caches stay alive for 2 days as per previous code
1066 Civi
::cache('prevNextCache')->set($cacheKey, $cacheKey, 60 * 60 * 24 * CRM_Core_PrevNextCache_Sql
::cacheDays
);
1071 * called to rebuild prev next cache using full sql in case of core search ( excluding custom search)
1074 * Start for limit clause.
1076 * End for limit clause.
1077 * @param CRM_Utils_Sort $sort
1078 * @param string $cacheKey
1081 public function rebuildPreNextCache($start, $end, $sort, $cacheKey) {
1082 // generate full SQL
1083 $sql = $this->_query
->searchQuery($start, $end, $sort, FALSE, $this->_query
->_includeContactIds
,
1084 FALSE, FALSE, TRUE);
1086 $dao = CRM_Core_DAO
::executeQuery($sql);
1088 // build insert query, note that currently we build cache for 500 (self::CACHE_SIZE) contact records at a time, hence below approach
1090 while ($dao->fetch()) {
1092 'entity_table' => 'civicrm_contact',
1093 'entity_id1' => $dao->contact_id
,
1094 'entity_id2' => $dao->contact_id
,
1095 'data' => $dao->sort_name
,
1099 Civi
::service('prevnext')->fillWithArray($cacheKey, $rows);
1105 public function getQILL() {
1106 return $this->_query
->qill();
1110 * Name of export file.
1112 * @param string $output
1118 public function getExportFileName($output = 'csv') {
1119 return ts('CiviCRM Contact Search');
1123 * Get colunmn headers for search selector.
1127 private static function &_getColumnHeaders() {
1128 if (!isset(self
::$_columnHeaders)) {
1129 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1130 'address_options', TRUE, NULL, TRUE
1133 self
::$_columnHeaders = [
1134 'contact_type' => ['desc' => ts('Contact Type')],
1136 'name' => ts('Name'),
1137 'sort' => 'sort_name',
1138 'direction' => CRM_Utils_Sort
::ASCENDING
,
1143 'street_address' => ['name' => ts('Address')],
1145 'name' => ts('City'),
1147 'direction' => CRM_Utils_Sort
::DONTCARE
,
1149 'state_province' => [
1150 'name' => ts('State'),
1151 'sort' => 'state_province',
1152 'direction' => CRM_Utils_Sort
::DONTCARE
,
1155 'name' => ts('Postal'),
1156 'sort' => 'postal_code',
1157 'direction' => CRM_Utils_Sort
::DONTCARE
,
1160 'name' => ts('Country'),
1161 'sort' => 'country',
1162 'direction' => CRM_Utils_Sort
::DONTCARE
,
1166 foreach ($defaultAddress as $columnName => $column) {
1167 if (!empty($addressOptions[$columnName])) {
1168 self
::$_columnHeaders[$columnName] = $column;
1172 self
::$_columnHeaders['email'] = [
1173 'name' => ts('Email'),
1175 'direction' => CRM_Utils_Sort
::DONTCARE
,
1178 self
::$_columnHeaders['phone'] = ['name' => ts('Phone')];
1180 return self
::$_columnHeaders;
1184 * @return CRM_Contact_BAO_Query
1186 public function getQuery() {
1187 return $this->_query
;
1191 * @return CRM_Contact_DAO_Contact
1193 public function alphabetQuery() {
1194 return $this->_query
->alphabetQuery();
1198 * @param array $params
1199 * @param int $sortID
1200 * @param null $displayRelationshipType
1201 * @param string $queryOperator
1203 * @return CRM_Contact_DAO_Contact
1205 public function contactIDQuery($params, $sortID, $displayRelationshipType = NULL, $queryOperator = 'AND') {
1206 $sortOrder = &$this->getSortOrder($this->_action
);
1207 $sort = new CRM_Utils_Sort($sortOrder, $sortID);
1209 // rectify params to what proximity search expects if there is a value for prox_distance
1210 // CRM-7021 CRM-7905
1211 if (!empty($params)) {
1212 CRM_Contact_BAO_ProximityQuery
::fixInputParams($params);
1215 if (!$displayRelationshipType) {
1216 $query = new CRM_Contact_BAO_Query($params,
1217 CRM_Contact_BAO_Query
::NO_RETURN_PROPERTIES
,
1218 NULL, FALSE, FALSE, 1,
1219 FALSE, TRUE, TRUE, NULL,
1224 $query = new CRM_Contact_BAO_Query($params,
1225 CRM_Contact_BAO_Query
::NO_RETURN_PROPERTIES
,
1226 NULL, FALSE, FALSE, 1,
1227 FALSE, TRUE, TRUE, $displayRelationshipType,
1231 return $query->searchQuery(0, 0, $sort);
1235 * @param $returnProperties
1239 public function &makeProperties(&$returnProperties) {
1241 foreach ($returnProperties as $name => $value) {
1242 if ($name != 'location') {
1243 // special handling for group and tag
1244 if (in_array($name, ['group', 'tag'])) {
1248 // special handling for notes
1249 if (in_array($name, ['note', 'note_subject', 'note_body'])) {
1253 $properties[] = $name;
1256 // extract all the location stuff
1257 foreach ($value as $n => $v) {
1258 foreach ($v as $n1 => $v1) {
1259 if (!strpos('_id', $n1) && $n1 != 'location_type') {
1260 $n = str_replace(' ', '_', $n);
1261 $properties[] = "{$n}-{$n1}";