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
= CRM_Utils_Array
::value('uf_group_id', $this->_formValues
);
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;
200 $displayRelationshipType = CRM_Utils_Array
::value('display_relationship_type', $this->_formValues
);
201 $operator = CRM_Utils_Array
::value('operator', $this->_formValues
, 'AND');
203 // rectify params to what proximity search expects if there is a value for prox_distance
205 if (!empty($this->_params
)) {
206 CRM_Contact_BAO_ProximityQuery
::fixInputParams($this->_params
);
209 $this->_query
= new CRM_Contact_BAO_Query(
211 $this->_returnProperties
,
215 CRM_Contact_BAO_Query
::MODE_CONTACTS
,
217 $searchDescendentGroups,
219 $displayRelationshipType,
223 $this->_options
= &$this->_query
->_options
;
227 * This method set cache key, later used in test environment
231 public function setKey($key) {
236 * This method returns the links that are given for each search row.
237 * currently the links added for each row are
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;
249 if (!(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',
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',
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
] = [
274 'url' => 'civicrm/contact/map',
275 'qs' => "reset=1&cid=%%id%%{$searchContext}{$extraParams}",
276 'title' => ts('Map Contact'),
280 // Adding Context Menu Links in more action
283 foreach ($contextMenu as $key => $value) {
284 $contextVal = '&context=' . $value['key'];
285 if ($value['key'] == 'delete') {
286 $contextVal = $searchContext;
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}";
293 elseif ($value['key'] == 'email') {
294 $url = "civicrm/contact/view/activity";
295 $qs = "atype=3&action=add&reset=1&cid=%%id%%{$extraParams}";
298 self
::$_links[$counter++
] = [
299 'name' => $value['title'],
302 'title' => $value['title'],
303 'ref' => $value['ref'],
304 'class' => CRM_Utils_Array
::value('class', $value),
309 return self
::$_links;
313 * Getter for array of the parameters required for creating pager.
316 * @param array $params
318 public function getPagerParams($action, &$params) {
319 $params['status'] = ts('Contact %%StatusMessage%%');
320 $params['csvString'] = NULL;
321 $params['rowCount'] = CRM_Utils_Pager
::ROWCOUNT
;
323 $params['buttonTop'] = 'PagerTopButton';
324 $params['buttonBottom'] = 'PagerBottomButton';
328 * @param null $action
329 * @param null $output
333 public function &getColHeads($action = NULL, $output = NULL) {
334 $colHeads = self
::_getColumnHeaders();
335 $colHeads[] = ['desc' => ts('Actions'), 'name' => ts('Action')];
340 * Returns the column headers as an array of tuples:
341 * (name, sortName (key to the sort array))
343 * @param string $action
344 * The action being performed.
345 * @param string $output
346 * What should the result set include (web/email/csv).
349 * the column headers that need to be displayed
351 public function &getColumnHeaders($action = NULL, $output = NULL) {
354 // unset return property elements that we don't care
355 if (!empty($this->_returnProperties
)) {
356 $doNotCareElements = [
361 foreach ($doNotCareElements as $value) {
362 unset($this->_returnProperties
[$value]);
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'];
373 $headers = $csvHeaders;
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) &&
380 $column['name'] != ts('Name')
382 $csvHeaders[$key] = $column['name'];
385 $headers = $csvHeaders;
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
;
393 if (!self
::$_columnHeaders) {
394 self
::$_columnHeaders = [
397 'name' => ts('Name'),
398 'sort' => 'sort_name',
399 'direction' => CRM_Utils_Sort
::ASCENDING
,
403 $locationTypes = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
405 foreach ($this->_fields
as $name => $field) {
406 if (!empty($field['in_selector']) &&
407 !in_array($name, $skipFields)
409 if (strpos($name, '-') !== FALSE) {
410 list($fieldName, $lType, $type) = CRM_Utils_System
::explode('-', $name, 3);
412 if ($lType == 'Primary') {
413 $locationTypeName = 1;
416 $locationTypeName = $locationTypes[$lType];
419 if (in_array($fieldName, [
425 $name = "`$locationTypeName-$fieldName-$type`";
428 $name = "`$locationTypeName-$fieldName`";
432 $name = "`$locationTypeName-$fieldName`";
435 //to handle sort key for Internal contactId.CRM-2289
437 $name = 'contact_id';
440 self
::$_columnHeaders[] = [
441 'name' => $field['title'],
443 'direction' => $direction,
445 $direction = CRM_Utils_Sort
::DONTCARE
;
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
453 self
::$_columnHeaders = [];
456 self
::$_columnHeaders[] = ['desc' => ts('Actions'), 'name' => ts('Action')];
459 $headers = self
::$_columnHeaders;
461 elseif (!empty($this->_returnProperties
)) {
462 self
::$_columnHeaders = [
465 'name' => ts('Name'),
466 'sort' => 'sort_name',
467 'direction' => CRM_Utils_Sort
::ASCENDING
,
470 $properties = self
::makeProperties($this->_returnProperties
);
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}";
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',
484 CRM_Core_PseudoConstant
::getKey('CRM_Core_DAO_Address', 'location_type_id', $loc)
489 elseif (isset($this->_query
->_fields
[$prop]) && isset($this->_query
->_fields
[$prop]['title'])) {
490 $title = $this->_query
->_fields
[$prop]['title'];
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']);
499 self
::$_columnHeaders[] = ['name' => $title, 'sort' => $prop];
501 self
::$_columnHeaders[] = ['name' => ts('Actions')];
502 $headers = self
::$_columnHeaders;
505 $headers = $this->getColHeads($action, $output);
512 * Returns total number of rows for the query.
517 * Total number of rows
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");
525 $count = $this->_query
->searchQuery(0, 0, NULL, TRUE);
526 Civi
::cache('long')->set("Search Results Count $this->_key", $count);
532 * Returns all the rows in the given offset and rowCount.
534 * @param string $action
535 * The action being performed.
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).
546 * the total number of rows for this action
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
552 $this->_formValues
['radio_ts'] == 'ts_sel'
554 $includeContactIds = TRUE;
557 $includeContactIds = FALSE;
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
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();
571 $resultSet = $this->_query
->searchQuery($offset, $rowCount, $sort, FALSE, $includeContactIds)->fetchGenerator();
574 // process the result of the query
576 $permissions = [CRM_Core_Permission
::getPermission()];
577 if (CRM_Core_Permission
::check('delete contacts')) {
578 $permissions[] = CRM_Core_Permission
::DELETE
;
580 $mask = CRM_Core_Action
::mask($permissions);
582 // mask value to hide map link if there are not lat/long
583 $mapMask = $mask & 4095;
585 if ($this->_searchContext
== 'smog') {
586 $gc = CRM_Core_SelectValues
::groupContactStatus();
589 if ($this->_ufGroupID
) {
590 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
593 static $skipFields = ['group', 'tag'];
594 foreach ($this->_fields
as $key => $field) {
595 if (!empty($field['in_selector']) &&
596 !in_array($key, $skipFields)
598 if (strpos($key, '-') !== FALSE) {
599 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $key, 3);
601 if ($id == 'Primary') {
602 $locationTypeName = 1;
604 elseif ($fieldName == 'url') {
605 $locationTypeName = "website-{$id}";
608 $locationTypeName = CRM_Utils_Array
::value($id, $locationTypes);
609 if (!$locationTypeName) {
614 $locationTypeName = str_replace(' ', '_', $locationTypeName);
615 if (in_array($fieldName, [
621 $names[] = "{$locationTypeName}-{$fieldName}-{$type}";
624 $names[] = "{$locationTypeName}-{$fieldName}";
628 $names[] = "{$locationTypeName}-{$fieldName}";
632 $names[] = $field['name'];
639 elseif (!empty($this->_returnProperties
)) {
640 $names = self
::makeProperties($this->_returnProperties
);
643 $names = self
::$_properties;
646 $links = self
::links($this->_context
, $this->_contextMenu
, $this->_key
);
648 //check explicitly added contact to a Smart Group.
649 $groupID = CRM_Utils_Array
::value('group', $this->_formValues
);
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(),
660 foreach ($resultSet as $result) {
662 $this->_query
->convertToPseudoNames($result);
663 // the columns we are interested in
664 foreach ($names as $property) {
665 if ($property == 'status') {
668 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($property)) {
669 $row[$property] = CRM_Core_BAO_CustomField
::displayValue(
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})";
684 elseif (in_array($property, [
689 $greeting = $property . '_display';
690 $row[$property] = $result->$greeting;
692 elseif (isset($pseudoconstants[$property])) {
693 $row[$property] = CRM_Utils_Array
::value(
694 $result->{$pseudoconstants[$property]['dbName']},
695 $pseudoconstants[$property]['values']
698 elseif (strpos($property, '-url') !== FALSE) {
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>";
709 $row[$property] = $websiteUrl;
712 $row[$property] = isset($result->$property) ?
$result->$property : NULL;
716 if (!empty($result->postal_code_suffix
)) {
717 $row['postal_code'] .= "-" . $result->postal_code_suffix
;
720 if ($output != CRM_Core_Selector_Controller
::EXPORT
&&
721 $this->_searchContext
== 'smog'
723 if (empty($result->status
) &&
726 $contactID = $result->contact_id
;
729 'contact_id' => $contactID,
730 'group_id' => $groupID,
734 CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_GroupContact', $gcParams, $gcDefaults);
736 if (empty($gcDefaults)) {
737 $row['status'] = ts('Smart');
740 $row['status'] = $gc[$gcDefaults['status']];
744 $row['status'] = NULL;
748 $row['status'] = $gc[$result->status
];
752 if ($output != CRM_Core_Selector_Controller
::EXPORT
) {
753 $row['checkbox'] = CRM_Core_Form
::CB_PREFIX
. $result->contact_id
;
755 if (!empty($this->_formValues
['deleted_contacts']) && CRM_Core_Permission
::check('access deleted contacts')
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'),
766 'name' => ts('Restore'),
767 'url' => 'civicrm/contact/view/delete',
768 'qs' => 'reset=1&cid=%%id%%&restore=1',
769 'title' => ts('Restore Contact'),
772 if (CRM_Core_Permission
::check('delete contacts')) {
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'),
780 $row['action'] = CRM_Core_Action
::formLink(
783 ['id' => $result->contact_id
],
786 'contact.selector.row',
791 elseif ((is_numeric(CRM_Utils_Array
::value('geo_code_1', $row))) ||
792 (!empty($row['city']) &&
793 CRM_Utils_Array
::value('state_province', $row)
796 $row['action'] = CRM_Core_Action
::formLink(
799 ['id' => $result->contact_id
],
802 'contact.selector.row',
808 $row['action'] = CRM_Core_Action
::formLink(
811 ['id' => $result->contact_id
],
814 'contact.selector.row',
820 // allow components to add more actions
821 CRM_Core_Component
::searchAction($row, $result->contact_id
);
823 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils
::getImage($result->contact_sub_type ?
$result->contact_sub_type
: $result->contact_type
,
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
;
837 $rows[$row['contact_id']] = $row;
844 * @param CRM_Utils_Sort $sort
848 public function buildPrevNextCache($sort) {
849 $cacheKey = 'civicrm search ' . $this->_key
;
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
855 // get current page requested
856 $pageNum = CRM_Utils_Request
::retrieve('crmPID', 'Integer');
858 // get the current sort order
859 $currentSortID = CRM_Utils_Request
::retrieve('crmSID', 'String');
861 $session = CRM_Core_Session
::singleton();
863 // get previous sort id
864 $previousSortID = $session->get('previousSortID');
866 // check for current != previous to ensure cache is not reset if paging is done without changing
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
876 // set the current sort as previous sort
877 if (!empty($currentSortID)) {
878 $session->set('previousSortID', $currentSortID);
881 $pageSize = CRM_Utils_Request
::retrieve('crmRowCount', 'Integer', CRM_Core_DAO
::$_nullObject, FALSE, 50);
882 $firstRecord = ($pageNum - 1) * $pageSize;
884 //for alphabetic pagination selection save
885 $sortByCharacter = CRM_Utils_Request
::retrieve('sortByCharacter', 'String');
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));
893 elseif (($firstRecord +
$pageSize) >= $countRow) {
894 $this->fillupPrevNextCache($sort, $cacheKey, $countRow, max(self
::CACHE_SIZE
, $pageSize) +
$firstRecord - $countRow);
902 public function addActions(&$rows) {
904 $basicPermissions = CRM_Core_Permission
::check('delete contacts') ?
[CRM_Core_Permission
::DELETE
] : [];
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
);
910 $links_template = self
::links($this->_context
, $this->_contextMenu
, $this->_key
);
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));
918 $mask = CRM_Core_Action
::mask(array_merge([CRM_Core_Permission
::VIEW
], $basicPermissions));
921 if ((!is_numeric(CRM_Utils_Array
::value('geo_code_1', $row))) &&
922 (empty($row['city']) ||
923 !CRM_Utils_Array
::value('state_province', $row)
926 $mask = $mask & 4095;
929 if (!empty($this->_formValues
['deleted_contacts']) && CRM_Core_Permission
::check('access deleted contacts')
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'),
940 'name' => ts('Restore'),
941 'url' => 'civicrm/contact/view/delete',
942 'qs' => 'reset=1&cid=%%id%%&restore=1',
943 'title' => ts('Restore Contact'),
946 if (CRM_Core_Permission
::check('delete contacts')) {
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'),
954 $row['action'] = CRM_Core_Action
::formLink(
957 ['id' => $row['contact_id']],
960 'contact.selector.actions',
966 $row['action'] = CRM_Core_Action
::formLink(
969 ['id' => $row['contact_id']],
972 'contact.selector.actions',
978 // allow components to add more actions
979 CRM_Core_Component
::searchAction($row, $row['contact_id']);
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']);
991 public function removeActions(&$rows) {
992 foreach ($rows as $rid => & $rValue) {
993 unset($rValue['contact_type']);
994 unset($rValue['action']);
999 * @param CRM_Utils_Sort $sort
1000 * @param string $cacheKey
1004 public function fillupPrevNextCache($sort, $cacheKey, $start = 0, $end = self
::CACHE_SIZE
) {
1006 // For custom searches, use the contactIDs method
1007 if (is_a($this, 'CRM_Contact_Selector_Custom')) {
1008 $sql = $this->_search
->contactIDs($start, $end, $sort, TRUE);
1009 $coreSearch = FALSE;
1011 // For core searches use the searchQuery method
1013 $sql = $this->_query
->getSearchSQL($start, $end, $sort, FALSE, $this->_query
->_includeContactIds
,
1018 // due to limitations in our search query writer, the above query does not work
1019 // in cases where the query is being sorted on a non-contact table
1020 // this results in a fatal error :(
1021 // see below for the gross hack of trapping the error and not filling
1022 // the prev next cache in this situation
1023 // the other alternative of running the FULL query will just be incredibly inefficient
1024 // and slow things down way too much on large data sets / complex queries
1026 $selectSQL = "SELECT DISTINCT %1, contact_a.id, contact_a.sort_name";
1028 $sql = str_ireplace(["SELECT contact_a.id as contact_id", "SELECT contact_a.id as id"], $selectSQL, $sql);
1030 Civi
::service('prevnext')->fillWithSql($cacheKey, $sql, [1 => [$cacheKey, 'String']]);
1032 catch (CRM_Core_Exception
$e) {
1034 // in the case of error, try rebuilding cache using full sql which is used for search selector display
1035 // this fixes the bugs reported in CRM-13996 & CRM-14438
1036 $this->rebuildPreNextCache($start, $end, $sort, $cacheKey);
1039 // This will always show for CiviRules :-( as a) it orders by 'rule_label'
1040 // which is not available in the query & b) it uses contact not contact_a
1042 // CRM_Core_Session::setStatus(ts('Query Failed'));
1047 if (Civi
::service('prevnext') instanceof CRM_Core_PrevNextCache_Sql
) {
1048 // SQL-backed prevnext cache uses an extra record for pruning the cache.
1049 // Also ensure that caches stay alive for 2 days as per previous code
1050 Civi
::cache('prevNextCache')->set($cacheKey, $cacheKey, 60 * 60 * 24 * CRM_Core_PrevNextCache_Sql
::cacheDays
);
1055 * called to rebuild prev next cache using full sql in case of core search ( excluding custom search)
1058 * Start for limit clause.
1060 * End for limit clause.
1061 * @param CRM_Utils_Sort $sort
1062 * @param string $cacheKey
1065 public function rebuildPreNextCache($start, $end, $sort, $cacheKey) {
1066 // generate full SQL
1067 $sql = $this->_query
->searchQuery($start, $end, $sort, FALSE, $this->_query
->_includeContactIds
,
1068 FALSE, FALSE, TRUE);
1070 $dao = CRM_Core_DAO
::executeQuery($sql);
1072 // build insert query, note that currently we build cache for 500 (self::CACHE_SIZE) contact records at a time, hence below approach
1074 while ($dao->fetch()) {
1076 'entity_table' => 'civicrm_contact',
1077 'entity_id1' => $dao->contact_id
,
1078 'entity_id2' => $dao->contact_id
,
1079 'data' => $dao->sort_name
,
1083 Civi
::service('prevnext')->fillWithArray($cacheKey, $rows);
1089 public function getQILL() {
1090 return $this->_query
->qill();
1094 * Name of export file.
1096 * @param string $output
1102 public function getExportFileName($output = 'csv') {
1103 return ts('CiviCRM Contact Search');
1107 * Get colunmn headers for search selector.
1111 private static function &_getColumnHeaders() {
1112 if (!isset(self
::$_columnHeaders)) {
1113 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1114 'address_options', TRUE, NULL, TRUE
1117 self
::$_columnHeaders = [
1118 'contact_type' => ['desc' => ts('Contact Type')],
1120 'name' => ts('Name'),
1121 'sort' => 'sort_name',
1122 'direction' => CRM_Utils_Sort
::ASCENDING
,
1127 'street_address' => ['name' => ts('Address')],
1129 'name' => ts('City'),
1131 'direction' => CRM_Utils_Sort
::DONTCARE
,
1133 'state_province' => [
1134 'name' => ts('State'),
1135 'sort' => 'state_province',
1136 'direction' => CRM_Utils_Sort
::DONTCARE
,
1139 'name' => ts('Postal'),
1140 'sort' => 'postal_code',
1141 'direction' => CRM_Utils_Sort
::DONTCARE
,
1144 'name' => ts('Country'),
1145 'sort' => 'country',
1146 'direction' => CRM_Utils_Sort
::DONTCARE
,
1150 foreach ($defaultAddress as $columnName => $column) {
1151 if (!empty($addressOptions[$columnName])) {
1152 self
::$_columnHeaders[$columnName] = $column;
1156 self
::$_columnHeaders['email'] = [
1157 'name' => ts('Email'),
1159 'direction' => CRM_Utils_Sort
::DONTCARE
,
1162 self
::$_columnHeaders['phone'] = ['name' => ts('Phone')];
1164 return self
::$_columnHeaders;
1168 * @return CRM_Contact_BAO_Query
1170 public function getQuery() {
1171 return $this->_query
;
1175 * @return CRM_Contact_DAO_Contact
1177 public function alphabetQuery() {
1178 return $this->_query
->alphabetQuery();
1182 * @param array $params
1183 * @param int $sortID
1184 * @param null $displayRelationshipType
1185 * @param string $queryOperator
1187 * @return CRM_Contact_DAO_Contact
1189 public function contactIDQuery($params, $sortID, $displayRelationshipType = NULL, $queryOperator = 'AND') {
1190 $sortOrder = &$this->getSortOrder($this->_action
);
1191 $sort = new CRM_Utils_Sort($sortOrder, $sortID);
1193 // rectify params to what proximity search expects if there is a value for prox_distance
1194 // CRM-7021 CRM-7905
1195 if (!empty($params)) {
1196 CRM_Contact_BAO_ProximityQuery
::fixInputParams($params);
1199 if (!$displayRelationshipType) {
1200 $query = new CRM_Contact_BAO_Query($params,
1201 CRM_Contact_BAO_Query
::NO_RETURN_PROPERTIES
,
1202 NULL, FALSE, FALSE, 1,
1203 FALSE, TRUE, TRUE, NULL,
1208 $query = new CRM_Contact_BAO_Query($params,
1209 CRM_Contact_BAO_Query
::NO_RETURN_PROPERTIES
,
1210 NULL, FALSE, FALSE, 1,
1211 FALSE, TRUE, TRUE, $displayRelationshipType,
1215 return $query->searchQuery(0, 0, $sort);
1219 * @param $returnProperties
1223 public function &makeProperties(&$returnProperties) {
1225 foreach ($returnProperties as $name => $value) {
1226 if ($name != 'location') {
1227 // special handling for group and tag
1228 if (in_array($name, ['group', 'tag'])) {
1232 // special handling for notes
1233 if (in_array($name, ['note', 'note_subject', 'note_body'])) {
1237 $properties[] = $name;
1240 // extract all the location stuff
1241 foreach ($value as $n => $v) {
1242 foreach ($v as $n1 => $v1) {
1243 if (!strpos('_id', $n1) && $n1 != 'location_type') {
1244 $n = str_replace(' ', '_', $n);
1245 $properties[] = "{$n}-{$n1}";