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 = [
68 * FormValues is the array returned by exportValues called on
69 * the HTML_QuickForm_Controller for that page.
80 protected $_contextMenu;
83 * Params is the array in a value used by the search query creator
90 * The return properties used for search
94 protected $_returnProperties;
97 * Represent the type of selector
103 protected $_searchContext;
106 * Query object for this selector.
108 * @var CRM_Contact_BAO_Query
113 * Get the query object for this selector.
115 * @return CRM_Contact_BAO_Query
117 public function getQueryObject() {
118 return $this->_query
;
126 protected $_ufGroupID;
129 * The public visible fields to be shown to the user
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.
146 * @param bool $includeContactIds
147 * @param bool $searchDescendentGroups
148 * @param string $searchContext
149 * @param null $contextMenu
151 * @return CRM_Contact_Selector
153 public function __construct(
157 $returnProperties = NULL,
158 $action = CRM_Core_Action
::NONE
,
159 $includeContactIds = FALSE,
160 $searchDescendentGroups = TRUE,
161 $searchContext = 'search',
164 //don't build query constructor, if form is not submitted
165 $force = CRM_Utils_Request
::retrieve('force', 'Boolean');
166 if (empty($formValues) && !$force) {
170 // submitted form values
171 $this->_formValues
= &$formValues;
172 $this->_params
= &$params;
173 $this->_returnProperties
= &$returnProperties;
174 $this->_contextMenu
= &$contextMenu;
175 $this->_context
= $searchContext;
178 $this->_action
= $action;
180 $this->_searchContext
= $searchContext;
182 $this->_ufGroupID
= $this->_formValues
['uf_group_id'] ??
NULL;
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
190 self
::$_columnHeaders = NULL;
192 $this->_customFields
= CRM_Core_BAO_CustomField
::getFieldsForImport('Individual');
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 if (!empty($this->_returnProperties
['location']) && is_array($this->_returnProperties
['location'])) {
199 foreach ($this->_returnProperties
['location'] as $key => $property) {
200 if (!empty($property['email'])) {
201 $this->_returnProperties
['location'][$key]['on_hold'] = 1;
207 $displayRelationshipType = $this->_formValues
['display_relationship_type'] ??
NULL;
208 $operator = CRM_Utils_Array
::value('operator', $this->_formValues
, 'AND');
210 // rectify params to what proximity search expects if there is a value for prox_distance
212 if (!empty($this->_params
)) {
213 CRM_Contact_BAO_ProximityQuery
::fixInputParams($this->_params
);
216 $this->_query
= new CRM_Contact_BAO_Query(
218 $this->_returnProperties
,
222 CRM_Contact_BAO_Query
::MODE_CONTACTS
,
224 $searchDescendentGroups,
226 $displayRelationshipType,
230 $this->_options
= &$this->_query
->_options
;
234 * This method set cache key, later used in test environment
238 public function setKey($key) {
243 * This method returns the links that are given for each search row.
244 * currently the links added for each row are
251 public static function &links() {
252 list($context, $contextMenu, $key) = func_get_args();
253 $extraParams = ($key) ?
"&key={$key}" : NULL;
254 $searchContext = ($context) ?
"&context=$context" : NULL;
256 if (!(self
::$_links)) {
258 CRM_Core_Action
::VIEW
=> [
259 'name' => ts('View'),
260 'url' => 'civicrm/contact/view',
261 'class' => 'no-popup',
262 'qs' => "reset=1&cid=%%id%%{$searchContext}{$extraParams}",
263 'title' => ts('View Contact Details'),
264 'ref' => 'view-contact',
266 CRM_Core_Action
::UPDATE
=> [
267 'name' => ts('Edit'),
268 'url' => 'civicrm/contact/add',
269 'class' => 'no-popup',
270 'qs' => "reset=1&action=update&cid=%%id%%{$searchContext}{$extraParams}",
271 'title' => ts('Edit Contact Details'),
272 'ref' => 'edit-contact',
276 $config = CRM_Core_Config
::singleton();
277 //CRM-16552: mapAPIKey is not mandatory as google no longer requires an API Key
278 if ($config->mapProvider
&& ($config->mapAPIKey ||
$config->mapProvider
== 'Google')) {
279 self
::$_links[CRM_Core_Action
::MAP
] = [
281 'url' => 'civicrm/contact/map',
282 'qs' => "reset=1&cid=%%id%%{$searchContext}{$extraParams}",
283 'title' => ts('Map Contact'),
287 // Adding Context Menu Links in more action
290 foreach ($contextMenu as $key => $value) {
291 $contextVal = '&context=' . $value['key'];
292 if ($value['key'] == 'delete') {
293 $contextVal = $searchContext;
295 $url = "civicrm/contact/view/{$value['key']}";
296 $qs = "reset=1&action=add&cid=%%id%%{$contextVal}{$extraParams}";
297 if ($value['key'] == 'activity') {
298 $qs = "action=browse&selectedChild=activity&reset=1&cid=%%id%%{$extraParams}";
300 elseif ($value['key'] == 'email') {
301 $url = "civicrm/contact/view/activity";
302 $qs = "atype=3&action=add&reset=1&cid=%%id%%{$extraParams}";
305 self
::$_links[$counter++
] = [
306 'name' => $value['title'],
309 'title' => $value['title'],
310 'ref' => $value['ref'],
311 'class' => $value['class'] ??
NULL,
316 return self
::$_links;
320 * Getter for array of the parameters required for creating pager.
323 * @param array $params
325 public function getPagerParams($action, &$params) {
326 $params['status'] = ts('Contact %%StatusMessage%%');
327 $params['csvString'] = NULL;
328 $params['rowCount'] = CRM_Utils_Pager
::ROWCOUNT
;
330 $params['buttonTop'] = 'PagerTopButton';
331 $params['buttonBottom'] = 'PagerBottomButton';
335 * @param null $action
336 * @param null $output
340 public function &getColHeads($action = NULL, $output = NULL) {
341 $colHeads = self
::_getColumnHeaders();
342 $colHeads[] = ['desc' => ts('Actions'), 'name' => ts('Action')];
347 * Returns the column headers as an array of tuples:
348 * (name, sortName (key to the sort array))
350 * @param string $action
351 * The action being performed.
352 * @param string $output
353 * What should the result set include (web/email/csv).
356 * the column headers that need to be displayed
358 public function &getColumnHeaders($action = NULL, $output = NULL) {
361 // unset return property elements that we don't care
362 if (!empty($this->_returnProperties
)) {
363 $doNotCareElements = [
368 foreach ($doNotCareElements as $value) {
369 unset($this->_returnProperties
[$value]);
373 if ($output == CRM_Core_Selector_Controller
::EXPORT
) {
374 $csvHeaders = [ts('Contact ID'), ts('Contact Type')];
375 foreach ($this->getColHeads($action, $output) as $column) {
376 if (array_key_exists('name', $column)) {
377 $csvHeaders[] = $column['name'];
380 $headers = $csvHeaders;
382 elseif ($output == CRM_Core_Selector_Controller
::SCREEN
) {
383 $csvHeaders = [ts('Name')];
384 foreach ($this->getColHeads($action, $output) as $key => $column) {
385 if (array_key_exists('name', $column) &&
387 $column['name'] != ts('Name')
389 $csvHeaders[$key] = $column['name'];
392 $headers = $csvHeaders;
394 elseif ($this->_ufGroupID
) {
395 // we dont use the cached value of column headers
396 // since it potentially changed because of the profile selected
397 static $skipFields = ['group', 'tag'];
398 $direction = CRM_Utils_Sort
::ASCENDING
;
400 if (!self
::$_columnHeaders) {
401 self
::$_columnHeaders = [
404 'name' => ts('Name'),
405 'sort' => 'sort_name',
406 'direction' => CRM_Utils_Sort
::ASCENDING
,
410 $locationTypes = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
412 foreach ($this->_fields
as $name => $field) {
413 if (!empty($field['in_selector']) &&
414 !in_array($name, $skipFields)
416 if (strpos($name, '-') !== FALSE) {
417 list($fieldName, $lType, $type) = CRM_Utils_System
::explode('-', $name, 3);
419 if ($lType == 'Primary') {
420 $locationTypeName = 1;
423 $locationTypeName = $locationTypes[$lType];
426 if (in_array($fieldName, [
432 $name = "`$locationTypeName-$fieldName-$type`";
435 $name = "`$locationTypeName-$fieldName`";
439 $name = "`$locationTypeName-$fieldName`";
442 //to handle sort key for Internal contactId.CRM-2289
444 $name = 'contact_id';
447 self
::$_columnHeaders[] = [
448 'name' => $field['title'],
450 'direction' => $direction,
452 $direction = CRM_Utils_Sort
::DONTCARE
;
457 // if we dont have any valid columns, dont add the implicit ones
458 // this allows the template to check on emptiness of column headers
460 self
::$_columnHeaders = [];
463 self
::$_columnHeaders[] = ['desc' => ts('Actions'), 'name' => ts('Action')];
466 $headers = self
::$_columnHeaders;
468 elseif (!empty($this->_returnProperties
)) {
469 self
::$_columnHeaders = [
472 'name' => ts('Name'),
473 'sort' => 'sort_name',
474 'direction' => CRM_Utils_Sort
::ASCENDING
,
477 $properties = self
::makeProperties($this->_returnProperties
);
479 foreach ($properties as $prop) {
480 if (strpos($prop, '-')) {
481 list($loc, $fld, $phoneType) = CRM_Utils_System
::explode('-', $prop, 3);
482 $title = $this->_query
->_fields
[$fld]['title'];
483 if (trim($phoneType) && !is_numeric($phoneType) && strtolower($phoneType) != $fld) {
484 $title .= "-{$phoneType}";
486 // fetch Location type label from name as $loc, which will be later used in column header
487 $title .= sprintf(" (%s)",
488 CRM_Core_PseudoConstant
::getLabel(
489 'CRM_Core_DAO_Address',
491 CRM_Core_PseudoConstant
::getKey('CRM_Core_DAO_Address', 'location_type_id', $loc)
496 elseif (isset($this->_query
->_fields
[$prop]) && isset($this->_query
->_fields
[$prop]['title'])) {
497 $title = $this->_query
->_fields
[$prop]['title'];
499 elseif (isset($this->_query
->_pseudoConstantsSelect
[$prop]) && isset($this->_query
->_pseudoConstantsSelect
[$prop]['pseudoconstant']['optionGroupName'])) {
500 $title = CRM_Core_BAO_OptionGroup
::getTitleByName($this->_query
->_pseudoConstantsSelect
[$prop]['pseudoconstant']['optionGroupName']);
506 self
::$_columnHeaders[] = ['name' => $title, 'sort' => $prop];
508 self
::$_columnHeaders[] = ['name' => ts('Actions')];
509 $headers = self
::$_columnHeaders;
512 $headers = $this->getColHeads($action, $output);
519 * Returns total number of rows for the query.
524 * Total number of rows
526 public function getTotalCount($action) {
527 // Use count from cache during paging/sorting
528 if (!empty($_GET['crmPID']) ||
!empty($_GET['crmSID'])) {
529 $count = Civi
::cache('long')->get("Search Results Count $this->_key");
532 $count = $this->_query
->searchQuery(0, 0, NULL, TRUE);
533 Civi
::cache('long')->set("Search Results Count $this->_key", $count);
539 * Returns all the rows in the given offset and rowCount.
541 * @param string $action
542 * The action being performed.
544 * The row number to start from.
545 * @param int $rowCount
546 * The number of rows to return.
547 * @param string $sort
548 * The sql string that describes the sort order.
549 * @param string $output
550 * What should the result set include (web/email/csv).
553 * the total number of rows for this action
555 public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
556 if (($output == CRM_Core_Selector_Controller
::EXPORT ||
557 $output == CRM_Core_Selector_Controller
::SCREEN
559 $this->_formValues
['radio_ts'] == 'ts_sel'
561 $includeContactIds = TRUE;
564 $includeContactIds = FALSE;
567 // note the formvalues were given by CRM_Contact_Form_Search to us
568 // and contain the search criteria (parameters)
569 // note that the default action is basic
571 /** @var CRM_Core_PrevNextCache_Interface $prevNext */
572 $prevNext = Civi
::service('prevnext');
573 $cacheKey = $this->buildPrevNextCache($sort);
574 $cids = $prevNext->fetch($cacheKey, $offset, $rowCount);
575 $resultSet = empty($cids) ?
[] : $this->_query
->getCachedContacts($cids, $includeContactIds)->fetchGenerator();
578 $resultSet = $this->_query
->searchQuery($offset, $rowCount, $sort, FALSE, $includeContactIds)->fetchGenerator();
581 // process the result of the query
583 $permissions = [CRM_Core_Permission
::getPermission()];
584 if (CRM_Core_Permission
::check('delete contacts')) {
585 $permissions[] = CRM_Core_Permission
::DELETE
;
587 $mask = CRM_Core_Action
::mask($permissions);
589 // mask value to hide map link if there are not lat/long
590 $mapMask = $mask & 4095;
592 if ($this->_searchContext
== 'smog') {
593 $gc = CRM_Core_SelectValues
::groupContactStatus();
596 if ($this->_ufGroupID
) {
597 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
600 static $skipFields = ['group', 'tag'];
601 foreach ($this->_fields
as $key => $field) {
602 if (!empty($field['in_selector']) &&
603 !in_array($key, $skipFields)
605 if (strpos($key, '-') !== FALSE) {
606 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $key, 3);
608 if ($id == 'Primary') {
609 $locationTypeName = 1;
611 elseif ($fieldName == 'url') {
612 $locationTypeName = "website-{$id}";
615 $locationTypeName = $locationTypes[$id] ??
NULL;
616 if (!$locationTypeName) {
621 $locationTypeName = str_replace(' ', '_', $locationTypeName);
622 if (in_array($fieldName, [
628 $names[] = "{$locationTypeName}-{$fieldName}-{$type}";
631 $names[] = "{$locationTypeName}-{$fieldName}";
635 $names[] = "{$locationTypeName}-{$fieldName}";
639 $names[] = $field['name'];
646 elseif (!empty($this->_returnProperties
)) {
647 $names = self
::makeProperties($this->_returnProperties
);
650 $names = self
::$_properties;
653 $links = self
::links($this->_context
, $this->_contextMenu
, $this->_key
);
655 //check explicitly added contact to a Smart Group.
656 $groupID = $this->_formValues
['group'] ??
NULL;
658 $pseudoconstants = [];
659 // for CRM-3157 purposes
660 if (in_array('world_region', $names)) {
661 $pseudoconstants['world_region'] = [
662 'dbName' => 'worldregion_id',
663 'values' => CRM_Core_PseudoConstant
::worldRegion(),
667 foreach ($resultSet as $result) {
669 $this->_query
->convertToPseudoNames($result);
670 // the columns we are interested in
671 foreach ($names as $property) {
672 if ($property == 'status') {
675 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($property)) {
676 $row[$property] = CRM_Core_BAO_CustomField
::displayValue(
682 elseif (strpos($property, '-im')) {
683 $row[$property] = $result->$property;
684 if (!empty($result->$property)) {
685 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
686 $providerId = $property . "-provider_id";
687 $providerName = $imProviders[$result->$providerId];
688 $row[$property] = $result->$property . " ({$providerName})";
691 elseif (in_array($property, [
696 $greeting = $property . '_display';
697 $row[$property] = $result->$greeting;
699 elseif (isset($pseudoconstants[$property])) {
700 $row[$property] = CRM_Utils_Array
::value(
701 $result->{$pseudoconstants[$property]['dbName']},
702 $pseudoconstants[$property]['values']
705 elseif (strpos($property, '-url') !== FALSE) {
707 $websiteKey = str_replace('-url', '', $property);
708 $propertyArray = explode('-', $property);
709 $websiteFld = $websiteKey . '-' . array_pop($propertyArray);
710 if (!empty($result->$websiteFld)) {
711 $websiteTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Website', 'website_type_id');
712 $websiteType = $websiteTypes[$result->{"$websiteKey-website_type_id"}];
713 $websiteValue = $result->$websiteFld;
714 $websiteUrl = "<a href=\"{$websiteValue}\">{$websiteValue} ({$websiteType})</a>";
716 $row[$property] = $websiteUrl;
718 elseif (strpos($property, '-email') !== FALSE) {
719 list($locType) = explode("-email", $property);
720 $onholdProperty = "{$locType}-on_hold";
722 $row[$property] = $result->$property ??
NULL;
723 if (!empty($row[$property]) && !empty($result->$onholdProperty)) {
724 $row[$property] .= " (On Hold)";
728 $row[$property] = $result->$property ??
NULL;
732 if (!empty($result->postal_code_suffix
)) {
733 $row['postal_code'] .= "-" . $result->postal_code_suffix
;
736 if ($output != CRM_Core_Selector_Controller
::EXPORT
&&
737 $this->_searchContext
== 'smog'
739 if (empty($result->status
) &&
742 $contactID = $result->contact_id
;
745 'contact_id' => $contactID,
746 'group_id' => $groupID,
750 CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_GroupContact', $gcParams, $gcDefaults);
752 if (empty($gcDefaults)) {
753 $row['status'] = ts('Smart');
756 $row['status'] = $gc[$gcDefaults['status']];
760 $row['status'] = NULL;
764 $row['status'] = $gc[$result->status
];
768 if ($output != CRM_Core_Selector_Controller
::EXPORT
) {
769 $row['checkbox'] = CRM_Core_Form
::CB_PREFIX
. $result->contact_id
;
771 if (!empty($this->_formValues
['deleted_contacts']) && CRM_Core_Permission
::check('access deleted contacts')
775 'name' => ts('View'),
776 'url' => 'civicrm/contact/view',
777 'qs' => 'reset=1&cid=%%id%%',
778 'class' => 'no-popup',
779 'title' => ts('View Contact Details'),
782 'name' => ts('Restore'),
783 'url' => 'civicrm/contact/view/delete',
784 'qs' => 'reset=1&cid=%%id%%&restore=1',
785 'title' => ts('Restore Contact'),
788 if (CRM_Core_Permission
::check('delete contacts')) {
790 'name' => ts('Delete Permanently'),
791 'url' => 'civicrm/contact/view/delete',
792 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1',
793 'title' => ts('Permanently Delete Contact'),
796 $row['action'] = CRM_Core_Action
::formLink(
799 ['id' => $result->contact_id
],
802 'contact.selector.row',
807 elseif ((is_numeric(CRM_Utils_Array
::value('geo_code_1', $row))) ||
808 (!empty($row['city']) &&
809 CRM_Utils_Array
::value('state_province', $row)
812 $row['action'] = CRM_Core_Action
::formLink(
815 ['id' => $result->contact_id
],
818 'contact.selector.row',
824 $row['action'] = CRM_Core_Action
::formLink(
827 ['id' => $result->contact_id
],
830 'contact.selector.row',
836 // allow components to add more actions
837 CRM_Core_Component
::searchAction($row, $result->contact_id
);
839 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils
::getImage($result->contact_sub_type ?
$result->contact_sub_type
: $result->contact_type
,
844 $row['contact_type_orig'] = $result->contact_sub_type ?
$result->contact_sub_type
: $result->contact_type
;
845 $row['contact_id'] = $result->contact_id
;
846 $row['sort_name'] = $result->sort_name
;
847 // Surely this if should be if NOT - otherwise it's just wierd.
848 if (array_key_exists('id', $row)) {
849 $row['id'] = $result->contact_id
;
853 $rows[$row['contact_id']] = $row;
860 * @param CRM_Utils_Sort $sort
864 public function buildPrevNextCache($sort) {
865 $cacheKey = 'civicrm search ' . $this->_key
;
867 // We should clear the cache in following conditions:
868 // 1. when starting from scratch, i.e new search
869 // 2. if records are sorted
871 // get current page requested
872 $pageNum = CRM_Utils_Request
::retrieve('crmPID', 'Integer');
874 // get the current sort order
875 $currentSortID = CRM_Utils_Request
::retrieve('crmSID', 'String');
877 $session = CRM_Core_Session
::singleton();
879 // get previous sort id
880 $previousSortID = $session->get('previousSortID');
882 // check for current != previous to ensure cache is not reset if paging is done without changing
884 if (!$pageNum ||
(!empty($currentSortID) && $currentSortID != $previousSortID)) {
885 Civi
::service('prevnext')->deleteItem(NULL, $cacheKey, 'civicrm_contact');
886 // this means it's fresh search, so set pageNum=1
892 // set the current sort as previous sort
893 if (!empty($currentSortID)) {
894 $session->set('previousSortID', $currentSortID);
897 $pageSize = CRM_Utils_Request
::retrieve('crmRowCount', 'Integer', CRM_Core_DAO
::$_nullObject, FALSE, 50);
898 $firstRecord = ($pageNum - 1) * $pageSize;
900 //for alphabetic pagination selection save
901 $sortByCharacter = CRM_Utils_Request
::retrieve('sortByCharacter', 'String');
903 //for text field pagination selection save
904 $countRow = Civi
::service('prevnext')->getCount($cacheKey);
905 // $sortByCharacter triggers a refresh in the prevNext cache
906 if ($sortByCharacter && $sortByCharacter != 'all') {
907 $this->fillupPrevNextCache($sort, $cacheKey, 0, max(self
::CACHE_SIZE
, $pageSize));
909 elseif (($firstRecord +
$pageSize) >= $countRow) {
910 $this->fillupPrevNextCache($sort, $cacheKey, $countRow, max(self
::CACHE_SIZE
, $pageSize) +
$firstRecord - $countRow);
918 public function addActions(&$rows) {
920 $basicPermissions = CRM_Core_Permission
::check('delete contacts') ?
[CRM_Core_Permission
::DELETE
] : [];
922 // get permissions on an individual level (CRM-12645)
923 // @todo look at storing this to the session as this is called twice during search results render.
924 $can_edit_list = CRM_Contact_BAO_Contact_Permission
::allowList(array_keys($rows), CRM_Core_Permission
::EDIT
);
926 $links_template = self
::links($this->_context
, $this->_contextMenu
, $this->_key
);
928 foreach ($rows as $id => & $row) {
929 $links = $links_template;
930 if (in_array($id, $can_edit_list)) {
931 $mask = CRM_Core_Action
::mask(array_merge([CRM_Core_Permission
::EDIT
], $basicPermissions));
934 $mask = CRM_Core_Action
::mask(array_merge([CRM_Core_Permission
::VIEW
], $basicPermissions));
937 if ((!is_numeric(CRM_Utils_Array
::value('geo_code_1', $row))) &&
938 (empty($row['city']) ||
939 !CRM_Utils_Array
::value('state_province', $row)
942 $mask = $mask & 4095;
945 if (!empty($this->_formValues
['deleted_contacts']) && CRM_Core_Permission
::check('access deleted contacts')
949 'name' => ts('View'),
950 'url' => 'civicrm/contact/view',
951 'qs' => 'reset=1&cid=%%id%%',
952 'class' => 'no-popup',
953 'title' => ts('View Contact Details'),
956 'name' => ts('Restore'),
957 'url' => 'civicrm/contact/view/delete',
958 'qs' => 'reset=1&cid=%%id%%&restore=1',
959 'title' => ts('Restore Contact'),
962 if (CRM_Core_Permission
::check('delete contacts')) {
964 'name' => ts('Delete Permanently'),
965 'url' => 'civicrm/contact/view/delete',
966 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1',
967 'title' => ts('Permanently Delete Contact'),
970 $row['action'] = CRM_Core_Action
::formLink(
973 ['id' => $row['contact_id']],
976 'contact.selector.actions',
982 $row['action'] = CRM_Core_Action
::formLink(
985 ['id' => $row['contact_id']],
988 'contact.selector.actions',
994 // allow components to add more actions
995 CRM_Core_Component
::searchAction($row, $row['contact_id']);
997 if (!empty($row['contact_type_orig'])) {
998 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils
::getImage($row['contact_type_orig'],
999 FALSE, $row['contact_id']);
1007 public function removeActions(&$rows) {
1008 foreach ($rows as $rid => & $rValue) {
1009 unset($rValue['contact_type']);
1010 unset($rValue['action']);
1015 * @param CRM_Utils_Sort $sort
1016 * @param string $cacheKey
1020 * @throws \CRM_Core_Exception
1022 public function fillupPrevNextCache($sort, $cacheKey, $start = 0, $end = self
::CACHE_SIZE
) {
1024 // For custom searches, use the contactIDs method
1025 if (is_a($this, 'CRM_Contact_Selector_Custom')) {
1026 $sql = $this->_search
->contactIDs($start, $end, $sort, TRUE);
1027 $coreSearch = FALSE;
1029 // For core searches use the searchQuery method
1031 $sql = $this->_query
->getSearchSQL($start, $end, $sort, FALSE, $this->_query
->_includeContactIds
,
1036 // due to limitations in our search query writer, the above query does not work
1037 // in cases where the query is being sorted on a non-contact table
1038 // this results in a fatal error :(
1039 // see below for the gross hack of trapping the error and not filling
1040 // the prev next cache in this situation
1041 // the other alternative of running the FULL query will just be incredibly inefficient
1042 // and slow things down way too much on large data sets / complex queries
1044 $selectSQL = CRM_Core_DAO
::composeQuery("SELECT DISTINCT %1, contact_a.id, contact_a.sort_name", [1 => [$cacheKey, 'String']]);
1046 $sql = str_ireplace(['SELECT contact_a.id as contact_id', 'SELECT contact_a.id as id'], $selectSQL, $sql);
1047 $sql = str_ireplace('ORDER BY `contact_id`', 'ORDER BY `id`', $sql, $sql);
1050 Civi
::service('prevnext')->fillWithSql($cacheKey, $sql);
1052 catch (CRM_Core_Exception
$e) {
1054 // in the case of error, try rebuilding cache using full sql which is used for search selector display
1055 // this fixes the bugs reported in CRM-13996 & CRM-14438
1056 $this->rebuildPreNextCache($start, $end, $sort, $cacheKey);
1059 CRM_Core_Error
::deprecatedFunctionWarning('Custom searches should return sql capable of filling the prevnext cache.');
1060 // This will always show for CiviRules :-( as a) it orders by 'rule_label'
1061 // which is not available in the query & b) it uses contact not contact_a
1063 // CRM_Core_Session::setStatus(ts('Query Failed'));
1068 if (Civi
::service('prevnext') instanceof CRM_Core_PrevNextCache_Sql
) {
1069 // SQL-backed prevnext cache uses an extra record for pruning the cache.
1070 // Also ensure that caches stay alive for 2 days as per previous code
1071 Civi
::cache('prevNextCache')->set($cacheKey, $cacheKey, 60 * 60 * 24 * CRM_Core_PrevNextCache_Sql
::cacheDays
);
1076 * called to rebuild prev next cache using full sql in case of core search ( excluding custom search)
1079 * Start for limit clause.
1081 * End for limit clause.
1082 * @param CRM_Utils_Sort $sort
1083 * @param string $cacheKey
1086 public function rebuildPreNextCache($start, $end, $sort, $cacheKey) {
1087 // generate full SQL
1088 $sql = $this->_query
->searchQuery($start, $end, $sort, FALSE, $this->_query
->_includeContactIds
,
1089 FALSE, FALSE, TRUE);
1091 $dao = CRM_Core_DAO
::executeQuery($sql);
1093 // build insert query, note that currently we build cache for 500 (self::CACHE_SIZE) contact records at a time, hence below approach
1095 while ($dao->fetch()) {
1097 'entity_table' => 'civicrm_contact',
1098 'entity_id1' => $dao->contact_id
,
1099 'entity_id2' => $dao->contact_id
,
1100 'data' => $dao->sort_name
,
1104 Civi
::service('prevnext')->fillWithArray($cacheKey, $rows);
1110 public function getQILL() {
1111 return $this->_query
->qill();
1115 * Name of export file.
1117 * @param string $output
1123 public function getExportFileName($output = 'csv') {
1124 return ts('CiviCRM Contact Search');
1128 * Get colunmn headers for search selector.
1132 private static function &_getColumnHeaders() {
1133 if (!isset(self
::$_columnHeaders)) {
1134 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1135 'address_options', TRUE, NULL, TRUE
1138 self
::$_columnHeaders = [
1139 'contact_type' => ['desc' => ts('Contact Type')],
1141 'name' => ts('Name'),
1142 'sort' => 'sort_name',
1143 'direction' => CRM_Utils_Sort
::ASCENDING
,
1148 'street_address' => ['name' => ts('Address')],
1150 'name' => ts('City'),
1152 'direction' => CRM_Utils_Sort
::DONTCARE
,
1154 'state_province' => [
1155 'name' => ts('State'),
1156 'sort' => 'state_province',
1157 'direction' => CRM_Utils_Sort
::DONTCARE
,
1160 'name' => ts('Postal'),
1161 'sort' => 'postal_code',
1162 'direction' => CRM_Utils_Sort
::DONTCARE
,
1165 'name' => ts('Country'),
1166 'sort' => 'country',
1167 'direction' => CRM_Utils_Sort
::DONTCARE
,
1171 foreach ($defaultAddress as $columnName => $column) {
1172 if (!empty($addressOptions[$columnName])) {
1173 self
::$_columnHeaders[$columnName] = $column;
1177 self
::$_columnHeaders['email'] = [
1178 'name' => ts('Email'),
1180 'direction' => CRM_Utils_Sort
::DONTCARE
,
1183 self
::$_columnHeaders['phone'] = ['name' => ts('Phone')];
1185 return self
::$_columnHeaders;
1189 * @return CRM_Contact_BAO_Query
1191 public function getQuery() {
1192 return $this->_query
;
1196 * @return CRM_Contact_DAO_Contact
1198 public function alphabetQuery() {
1199 return $this->_query
->alphabetQuery();
1203 * @param array $params
1204 * @param int $sortID
1205 * @param null $displayRelationshipType
1206 * @param string $queryOperator
1208 * @return CRM_Contact_DAO_Contact
1210 public function contactIDQuery($params, $sortID, $displayRelationshipType = NULL, $queryOperator = 'AND') {
1211 $sortOrder = &$this->getSortOrder($this->_action
);
1212 $sort = new CRM_Utils_Sort($sortOrder, $sortID);
1214 // rectify params to what proximity search expects if there is a value for prox_distance
1215 // CRM-7021 CRM-7905
1216 if (!empty($params)) {
1217 CRM_Contact_BAO_ProximityQuery
::fixInputParams($params);
1220 if (!$displayRelationshipType) {
1221 $query = new CRM_Contact_BAO_Query($params,
1222 CRM_Contact_BAO_Query
::NO_RETURN_PROPERTIES
,
1223 NULL, FALSE, FALSE, 1,
1224 FALSE, TRUE, TRUE, NULL,
1229 $query = new CRM_Contact_BAO_Query($params,
1230 CRM_Contact_BAO_Query
::NO_RETURN_PROPERTIES
,
1231 NULL, FALSE, FALSE, 1,
1232 FALSE, TRUE, TRUE, $displayRelationshipType,
1236 return $query->searchQuery(0, 0, $sort);
1240 * @param $returnProperties
1244 public function &makeProperties(&$returnProperties) {
1246 foreach ($returnProperties as $name => $value) {
1247 if ($name != 'location') {
1248 // special handling for group and tag
1249 if (in_array($name, ['group', 'tag'])) {
1253 // special handling for notes
1254 if (in_array($name, ['note', 'note_subject', 'note_body'])) {
1258 $properties[] = $name;
1261 // extract all the location stuff
1262 foreach ($value as $n => $v) {
1263 foreach ($v as $n1 => $v1) {
1264 if (!strpos('_id', $n1) && $n1 != 'location_type') {
1265 $n = str_replace(' ', '_', $n);
1266 $properties[] = "{$n}-{$n1}";