3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2018
35 * Class is to retrieve and display a range of contacts that match the given criteria.
37 * It is specifically for results of advanced search options.
39 class CRM_Contact_Selector
extends CRM_Core_Selector_Base
implements CRM_Core_Selector_API
{
41 const CACHE_SIZE
= 500;
44 * This defines two actions- View and Edit.
48 static $_links = NULL;
51 * We use desc to remind us what that column is, name is used in the tpl
55 static $_columnHeaders;
58 * Properties of contact we're interested in displaying
61 static $_properties = array(
84 * FormValues is the array returned by exportValues called on
85 * the HTML_QuickForm_Controller for that page.
96 protected $_contextMenu;
99 * Params is the array in a value used by the search query creator
106 * The return properties used for search
110 protected $_returnProperties;
113 * Represent the type of selector
119 protected $_searchContext;
122 * Query object for this selector.
124 * @var CRM_Contact_BAO_Query
129 * Get the query object for this selector.
131 * @return CRM_Contact_BAO_Query
133 public function getQueryObject() {
134 return $this->_query
;
142 protected $_ufGroupID;
145 * The public visible fields to be shown to the user
154 * @param $customSearchClass
155 * @param array $formValues
156 * Array of form values imported.
157 * @param array $params
158 * Array of parameters for query.
159 * @param null $returnProperties
160 * @param \const|int $action - action of search basic or advanced.
162 * @param bool $includeContactIds
163 * @param bool $searchDescendentGroups
164 * @param string $searchContext
165 * @param null $contextMenu
167 * @return CRM_Contact_Selector
169 public function __construct(
173 $returnProperties = NULL,
174 $action = CRM_Core_Action
::NONE
,
175 $includeContactIds = FALSE,
176 $searchDescendentGroups = TRUE,
177 $searchContext = 'search',
180 //don't build query constructor, if form is not submitted
181 $force = CRM_Utils_Request
::retrieve('force', 'Boolean');
182 if (empty($formValues) && !$force) {
186 // submitted form values
187 $this->_formValues
= &$formValues;
188 $this->_params
= &$params;
189 $this->_returnProperties
= &$returnProperties;
190 $this->_contextMenu
= &$contextMenu;
191 $this->_context
= $searchContext;
194 $this->_action
= $action;
196 $this->_searchContext
= $searchContext;
198 $this->_ufGroupID
= CRM_Utils_Array
::value('uf_group_id', $this->_formValues
);
200 if ($this->_ufGroupID
) {
201 $this->_fields
= CRM_Core_BAO_UFGroup
::getListingFields(CRM_Core_Action
::VIEW
,
202 CRM_Core_BAO_UFGroup
::PUBLIC_VISIBILITY |
203 CRM_Core_BAO_UFGroup
::LISTINGS_VISIBILITY
,
204 FALSE, $this->_ufGroupID
206 self
::$_columnHeaders = NULL;
208 $this->_customFields
= CRM_Core_BAO_CustomField
::getFieldsForImport('Individual');
210 $this->_returnProperties
= CRM_Contact_BAO_Contact
::makeHierReturnProperties($this->_fields
);
211 $this->_returnProperties
['contact_type'] = 1;
212 $this->_returnProperties
['contact_sub_type'] = 1;
213 $this->_returnProperties
['sort_name'] = 1;
216 $displayRelationshipType = CRM_Utils_Array
::value('display_relationship_type', $this->_formValues
);
217 $operator = CRM_Utils_Array
::value('operator', $this->_formValues
, 'AND');
219 // rectify params to what proximity search expects if there is a value for prox_distance
221 if (!empty($this->_params
)) {
222 CRM_Contact_BAO_ProximityQuery
::fixInputParams($this->_params
);
225 $this->_query
= new CRM_Contact_BAO_Query(
227 $this->_returnProperties
,
231 CRM_Contact_BAO_Query
::MODE_CONTACTS
,
233 $searchDescendentGroups,
235 $displayRelationshipType,
239 $this->_options
= &$this->_query
->_options
;
243 * This method set cache key, later used in test environment
247 public function setKey($key) {
252 * This method returns the links that are given for each search row.
253 * currently the links added for each row are
260 public static function &links() {
261 list($context, $contextMenu, $key) = func_get_args();
262 $extraParams = ($key) ?
"&key={$key}" : NULL;
263 $searchContext = ($context) ?
"&context=$context" : NULL;
265 if (!(self
::$_links)) {
266 self
::$_links = array(
267 CRM_Core_Action
::VIEW
=> array(
268 'name' => ts('View'),
269 'url' => 'civicrm/contact/view',
270 'class' => 'no-popup',
271 'qs' => "reset=1&cid=%%id%%{$searchContext}{$extraParams}",
272 'title' => ts('View Contact Details'),
273 'ref' => 'view-contact',
275 CRM_Core_Action
::UPDATE
=> array(
276 'name' => ts('Edit'),
277 'url' => 'civicrm/contact/add',
278 'class' => 'no-popup',
279 'qs' => "reset=1&action=update&cid=%%id%%{$searchContext}{$extraParams}",
280 'title' => ts('Edit Contact Details'),
281 'ref' => 'edit-contact',
285 $config = CRM_Core_Config
::singleton();
286 //CRM-16552: mapAPIKey is not mandatory as google no longer requires an API Key
287 if ($config->mapProvider
&& ($config->mapAPIKey ||
$config->mapProvider
== 'Google')) {
288 self
::$_links[CRM_Core_Action
::MAP
] = array(
290 'url' => 'civicrm/contact/map',
291 'qs' => "reset=1&cid=%%id%%{$searchContext}{$extraParams}",
292 'title' => ts('Map Contact'),
296 // Adding Context Menu Links in more action
299 foreach ($contextMenu as $key => $value) {
300 $contextVal = '&context=' . $value['key'];
301 if ($value['key'] == 'delete') {
302 $contextVal = $searchContext;
304 $url = "civicrm/contact/view/{$value['key']}";
305 $qs = "reset=1&action=add&cid=%%id%%{$contextVal}{$extraParams}";
306 if ($value['key'] == 'activity') {
307 $qs = "action=browse&selectedChild=activity&reset=1&cid=%%id%%{$extraParams}";
309 elseif ($value['key'] == 'email') {
310 $url = "civicrm/contact/view/activity";
311 $qs = "atype=3&action=add&reset=1&cid=%%id%%{$extraParams}";
314 self
::$_links[$counter++
] = array(
315 'name' => $value['title'],
318 'title' => $value['title'],
319 'ref' => $value['ref'],
320 'class' => CRM_Utils_Array
::value('class', $value),
325 return self
::$_links;
329 * Getter for array of the parameters required for creating pager.
332 * @param array $params
334 public function getPagerParams($action, &$params) {
335 $params['status'] = ts('Contact %%StatusMessage%%');
336 $params['csvString'] = NULL;
337 $params['rowCount'] = CRM_Utils_Pager
::ROWCOUNT
;
339 $params['buttonTop'] = 'PagerTopButton';
340 $params['buttonBottom'] = 'PagerBottomButton';
344 * @param null $action
345 * @param null $output
349 public function &getColHeads($action = NULL, $output = NULL) {
350 $colHeads = self
::_getColumnHeaders();
351 $colHeads[] = array('desc' => ts('Actions'), 'name' => ts('Action'));
356 * Returns the column headers as an array of tuples:
357 * (name, sortName (key to the sort array))
359 * @param string $action
360 * The action being performed.
361 * @param string $output
362 * What should the result set include (web/email/csv).
365 * the column headers that need to be displayed
367 public function &getColumnHeaders($action = NULL, $output = NULL) {
370 // unset return property elements that we don't care
371 if (!empty($this->_returnProperties
)) {
372 $doNotCareElements = array(
377 foreach ($doNotCareElements as $value) {
378 unset($this->_returnProperties
[$value]);
382 if ($output == CRM_Core_Selector_Controller
::EXPORT
) {
383 $csvHeaders = array(ts('Contact ID'), ts('Contact Type'));
384 foreach ($this->getColHeads($action, $output) as $column) {
385 if (array_key_exists('name', $column)) {
386 $csvHeaders[] = $column['name'];
389 $headers = $csvHeaders;
391 elseif ($output == CRM_Core_Selector_Controller
::SCREEN
) {
392 $csvHeaders = array(ts('Name'));
393 foreach ($this->getColHeads($action, $output) as $key => $column) {
394 if (array_key_exists('name', $column) &&
396 $column['name'] != ts('Name')
398 $csvHeaders[$key] = $column['name'];
401 $headers = $csvHeaders;
403 elseif ($this->_ufGroupID
) {
404 // we dont use the cached value of column headers
405 // since it potentially changed because of the profile selected
406 static $skipFields = array('group', 'tag');
407 $direction = CRM_Utils_Sort
::ASCENDING
;
409 if (!self
::$_columnHeaders) {
410 self
::$_columnHeaders = array(
413 'name' => ts('Name'),
414 'sort' => 'sort_name',
415 'direction' => CRM_Utils_Sort
::ASCENDING
,
419 $locationTypes = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
421 foreach ($this->_fields
as $name => $field) {
422 if (!empty($field['in_selector']) &&
423 !in_array($name, $skipFields)
425 if (strpos($name, '-') !== FALSE) {
426 list($fieldName, $lType, $type) = CRM_Utils_System
::explode('-', $name, 3);
428 if ($lType == 'Primary') {
429 $locationTypeName = 1;
432 $locationTypeName = $locationTypes[$lType];
435 if (in_array($fieldName, array(
441 $name = "`$locationTypeName-$fieldName-$type`";
444 $name = "`$locationTypeName-$fieldName`";
448 $name = "`$locationTypeName-$fieldName`";
451 //to handle sort key for Internal contactId.CRM-2289
453 $name = 'contact_id';
456 self
::$_columnHeaders[] = array(
457 'name' => $field['title'],
459 'direction' => $direction,
461 $direction = CRM_Utils_Sort
::DONTCARE
;
466 // if we dont have any valid columns, dont add the implicit ones
467 // this allows the template to check on emptiness of column headers
469 self
::$_columnHeaders = array();
472 self
::$_columnHeaders[] = array('desc' => ts('Actions'), 'name' => ts('Action'));
475 $headers = self
::$_columnHeaders;
477 elseif (!empty($this->_returnProperties
)) {
478 self
::$_columnHeaders = array(
481 'name' => ts('Name'),
482 'sort' => 'sort_name',
483 'direction' => CRM_Utils_Sort
::ASCENDING
,
486 $properties = self
::makeProperties($this->_returnProperties
);
488 foreach ($properties as $prop) {
489 if (strpos($prop, '-')) {
490 list($loc, $fld, $phoneType) = CRM_Utils_System
::explode('-', $prop, 3);
491 $title = $this->_query
->_fields
[$fld]['title'];
492 if (trim($phoneType) && !is_numeric($phoneType) && strtolower($phoneType) != $fld) {
493 $title .= "-{$phoneType}";
495 // fetch Location type label from name as $loc, which will be later used in column header
496 $title .= sprintf(" (%s)",
497 CRM_Core_PseudoConstant
::getLabel(
498 'CRM_Core_DAO_Address',
500 CRM_Core_PseudoConstant
::getKey('CRM_Core_DAO_Address', 'location_type_id', $loc)
503 // use field name instead of table alias
506 elseif (isset($this->_query
->_fields
[$prop]) && isset($this->_query
->_fields
[$prop]['title'])) {
507 $title = $this->_query
->_fields
[$prop]['title'];
509 elseif (isset($this->_query
->_pseudoConstantsSelect
[$prop]) && isset($this->_query
->_pseudoConstantsSelect
[$prop]['pseudoconstant']['optionGroupName'])) {
510 $title = CRM_Core_BAO_OptionGroup
::getTitleByName($this->_query
->_pseudoConstantsSelect
[$prop]['pseudoconstant']['optionGroupName']);
516 self
::$_columnHeaders[] = array('name' => $title, 'sort' => $prop);
518 self
::$_columnHeaders[] = array('name' => ts('Actions'));
519 $headers = self
::$_columnHeaders;
522 $headers = $this->getColHeads($action, $output);
529 * Returns total number of rows for the query.
534 * Total number of rows
536 public function getTotalCount($action) {
537 // Use count from cache during paging/sorting
538 if (!empty($_GET['crmPID']) ||
!empty($_GET['crmSID'])) {
539 $count = CRM_Core_BAO_Cache
::getItem('Search Results Count', $this->_key
);
542 $count = $this->_query
->searchQuery(0, 0, NULL, TRUE);
543 CRM_Core_BAO_Cache
::setItem($count, 'Search Results Count', $this->_key
);
549 * Returns all the rows in the given offset and rowCount.
551 * @param string $action
552 * The action being performed.
554 * The row number to start from.
555 * @param int $rowCount
556 * The number of rows to return.
557 * @param string $sort
558 * The sql string that describes the sort order.
559 * @param string $output
560 * What should the result set include (web/email/csv).
563 * the total number of rows for this action
565 public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
566 if (($output == CRM_Core_Selector_Controller
::EXPORT ||
567 $output == CRM_Core_Selector_Controller
::SCREEN
569 $this->_formValues
['radio_ts'] == 'ts_sel'
571 $includeContactIds = TRUE;
574 $includeContactIds = FALSE;
577 // note the formvalues were given by CRM_Contact_Form_Search to us
578 // and contain the search criteria (parameters)
579 // note that the default action is basic
581 $cacheKey = $this->buildPrevNextCache($sort);
582 $resultSet = $this->_query
->getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds)->fetchGenerator();
585 $resultSet = $this->_query
->searchQuery($offset, $rowCount, $sort, FALSE, $includeContactIds)->fetchGenerator();
588 // process the result of the query
590 $permissions = array(CRM_Core_Permission
::getPermission());
591 if (CRM_Core_Permission
::check('delete contacts')) {
592 $permissions[] = CRM_Core_Permission
::DELETE
;
594 $mask = CRM_Core_Action
::mask($permissions);
596 // mask value to hide map link if there are not lat/long
597 $mapMask = $mask & 4095;
599 if ($this->_searchContext
== 'smog') {
600 $gc = CRM_Core_SelectValues
::groupContactStatus();
603 if ($this->_ufGroupID
) {
604 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
607 static $skipFields = array('group', 'tag');
608 foreach ($this->_fields
as $key => $field) {
609 if (!empty($field['in_selector']) &&
610 !in_array($key, $skipFields)
612 if (strpos($key, '-') !== FALSE) {
613 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $key, 3);
615 if ($id == 'Primary') {
616 $locationTypeName = 1;
618 elseif ($fieldName == 'url') {
619 $locationTypeName = "website-{$id}";
622 $locationTypeName = CRM_Utils_Array
::value($id, $locationTypes);
623 if (!$locationTypeName) {
628 $locationTypeName = str_replace(' ', '_', $locationTypeName);
629 if (in_array($fieldName, array(
635 $names[] = "{$locationTypeName}-{$fieldName}-{$type}";
638 $names[] = "{$locationTypeName}-{$fieldName}";
642 $names[] = "{$locationTypeName}-{$fieldName}";
646 $names[] = $field['name'];
653 elseif (!empty($this->_returnProperties
)) {
654 $names = self
::makeProperties($this->_returnProperties
);
657 $names = self
::$_properties;
660 $links = self
::links($this->_context
, $this->_contextMenu
, $this->_key
);
662 //check explicitly added contact to a Smart Group.
663 $groupID = CRM_Utils_Array
::value('group', $this->_formValues
);
665 $pseudoconstants = array();
666 // for CRM-3157 purposes
667 if (in_array('world_region', $names)) {
668 $pseudoconstants['world_region'] = array(
669 'dbName' => 'worldregion_id',
670 'values' => CRM_Core_PseudoConstant
::worldRegion(),
674 foreach ($resultSet as $result) {
676 $this->_query
->convertToPseudoNames($result);
677 // the columns we are interested in
678 foreach ($names as $property) {
679 if ($property == 'status') {
682 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($property)) {
683 $row[$property] = CRM_Core_BAO_CustomField
::displayValue(
689 elseif (strpos($property, '-im')) {
690 $row[$property] = $result->$property;
691 if (!empty($result->$property)) {
692 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
693 $providerId = $property . "-provider_id";
694 $providerName = $imProviders[$result->$providerId];
695 $row[$property] = $result->$property . " ({$providerName})";
698 elseif (in_array($property, array(
703 $greeting = $property . '_display';
704 $row[$property] = $result->$greeting;
706 elseif (isset($pseudoconstants[$property])) {
707 $row[$property] = CRM_Utils_Array
::value(
708 $result->{$pseudoconstants[$property]['dbName']},
709 $pseudoconstants[$property]['values']
712 elseif (strpos($property, '-url') !== FALSE) {
714 $websiteKey = str_replace('-url', '', $property);
715 $propertyArray = explode('-', $property);
716 $websiteFld = $websiteKey . '-' . array_pop($propertyArray);
717 if (!empty($result->$websiteFld)) {
718 $websiteTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Website', 'website_type_id');
719 $websiteType = $websiteTypes[$result->{"$websiteKey-website_type_id"}];
720 $websiteValue = $result->$websiteFld;
721 $websiteUrl = "<a href=\"{$websiteValue}\">{$websiteValue} ({$websiteType})</a>";
723 $row[$property] = $websiteUrl;
726 $row[$property] = isset($result->$property) ?
$result->$property : NULL;
730 if (!empty($result->postal_code_suffix
)) {
731 $row['postal_code'] .= "-" . $result->postal_code_suffix
;
734 if ($output != CRM_Core_Selector_Controller
::EXPORT
&&
735 $this->_searchContext
== 'smog'
737 if (empty($result->status
) &&
740 $contactID = $result->contact_id
;
743 'contact_id' => $contactID,
744 'group_id' => $groupID,
747 $gcDefaults = array();
748 CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_GroupContact', $gcParams, $gcDefaults);
750 if (empty($gcDefaults)) {
751 $row['status'] = ts('Smart');
754 $row['status'] = $gc[$gcDefaults['status']];
758 $row['status'] = NULL;
762 $row['status'] = $gc[$result->status
];
766 if ($output != CRM_Core_Selector_Controller
::EXPORT
) {
767 $row['checkbox'] = CRM_Core_Form
::CB_PREFIX
. $result->contact_id
;
769 if (!empty($this->_formValues
['deleted_contacts']) && CRM_Core_Permission
::check('access deleted contacts')
773 'name' => ts('View'),
774 'url' => 'civicrm/contact/view',
775 'qs' => 'reset=1&cid=%%id%%',
776 'class' => 'no-popup',
777 'title' => ts('View Contact Details'),
780 'name' => ts('Restore'),
781 'url' => 'civicrm/contact/view/delete',
782 'qs' => 'reset=1&cid=%%id%%&restore=1',
783 'title' => ts('Restore Contact'),
786 if (CRM_Core_Permission
::check('delete contacts')) {
788 'name' => ts('Delete Permanently'),
789 'url' => 'civicrm/contact/view/delete',
790 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1',
791 'title' => ts('Permanently Delete Contact'),
794 $row['action'] = CRM_Core_Action
::formLink(
797 array('id' => $result->contact_id
),
800 'contact.selector.row',
805 elseif ((is_numeric(CRM_Utils_Array
::value('geo_code_1', $row))) ||
806 (!empty($row['city']) &&
807 CRM_Utils_Array
::value('state_province', $row)
810 $row['action'] = CRM_Core_Action
::formLink(
813 array('id' => $result->contact_id
),
816 'contact.selector.row',
822 $row['action'] = CRM_Core_Action
::formLink(
825 array('id' => $result->contact_id
),
828 'contact.selector.row',
834 // allow components to add more actions
835 CRM_Core_Component
::searchAction($row, $result->contact_id
);
837 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils
::getImage($result->contact_sub_type ?
$result->contact_sub_type
: $result->contact_type
,
842 $row['contact_type_orig'] = $result->contact_sub_type ?
$result->contact_sub_type
: $result->contact_type
;
843 $row['contact_sub_type'] = $result->contact_sub_type ? CRM_Contact_BAO_ContactType
::contactTypePairs(FALSE, $result->contact_sub_type
, ', ') : $result->contact_sub_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 CRM_Core_BAO_PrevNextCache
::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 = CRM_Core_BAO_PrevNextCache
::getCount($cacheKey, NULL, "entity_table = 'civicrm_contact'");
904 // $sortByCharacter triggers a refresh in the prevNext cache
905 if ($sortByCharacter && $sortByCharacter != 'all') {
906 $cacheKey .= "_alphabet";
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') ?
array(CRM_Core_Permission
::DELETE
) : array();
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(array(CRM_Core_Permission
::EDIT
), $basicPermissions));
934 $mask = CRM_Core_Action
::mask(array_merge(array(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 array('id' => $row['contact_id']),
976 'contact.selector.actions',
982 $row['action'] = CRM_Core_Action
::formLink(
985 array('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 public function fillupPrevNextCache($sort, $cacheKey, $start = 0, $end = self
::CACHE_SIZE
) {
1022 // For custom searches, use the contactIDs method
1023 if (is_a($this, 'CRM_Contact_Selector_Custom')) {
1024 $sql = $this->_search
->contactIDs($start, $end, $sort, TRUE);
1025 $coreSearch = FALSE;
1027 // For core searches use the searchQuery method
1029 $sql = $this->_query
->searchQuery($start, $end, $sort, FALSE, $this->_query
->_includeContactIds
,
1034 // due to limitations in our search query writer, the above query does not work
1035 // in cases where the query is being sorted on a non-contact table
1036 // this results in a fatal error :(
1037 // see below for the gross hack of trapping the error and not filling
1038 // the prev next cache in this situation
1039 // the other alternative of running the FULL query will just be incredibly inefficient
1040 // and slow things down way too much on large data sets / complex queries
1043 INSERT INTO civicrm_prevnext_cache ( entity_table, entity_id1, entity_id2, cacheKey, data )
1044 SELECT DISTINCT 'civicrm_contact', contact_a.id, contact_a.id, '$cacheKey', contact_a.sort_name
1047 $sql = str_replace(array("SELECT contact_a.id as contact_id", "SELECT contact_a.id as id"), $insertSQL, $sql);
1049 $result = CRM_Core_DAO
::executeQuery($sql, [], FALSE, NULL, FALSE, TRUE, TRUE);
1050 if (is_a($result, 'DB_Error')) {
1051 throw new CRM_Core_Exception($result->message
);
1054 catch (CRM_Core_Exception
$e) {
1056 // in the case of error, try rebuilding cache using full sql which is used for search selector display
1057 // this fixes the bugs reported in CRM-13996 & CRM-14438
1058 $this->rebuildPreNextCache($start, $end, $sort, $cacheKey);
1061 // This will always show for CiviRules :-( as a) it orders by 'rule_label'
1062 // which is not available in the query & b) it uses contact not contact_a
1064 // CRM_Core_Session::setStatus(ts('Query Failed'));
1069 // also record an entry in the cache key table, so we can delete it periodically
1070 CRM_Core_BAO_Cache
::setItem($cacheKey, 'CiviCRM Search PrevNextCache', $cacheKey);
1074 * called to rebuild prev next cache using full sql in case of core search ( excluding custom search)
1077 * Start for limit clause.
1079 * End for limit clause.
1080 * @param CRM_Utils_Sort $sort
1081 * @param string $cacheKey
1084 public function rebuildPreNextCache($start, $end, $sort, $cacheKey) {
1085 // generate full SQL
1086 $sql = $this->_query
->searchQuery($start, $end, $sort, FALSE, $this->_query
->_includeContactIds
,
1087 FALSE, FALSE, TRUE);
1089 $dao = CRM_Core_DAO
::executeQuery($sql);
1091 // build insert query, note that currently we build cache for 500 (self::CACHE_SIZE) contact records at a time, hence below approach
1092 $insertValues = array();
1093 while ($dao->fetch()) {
1094 $insertValues[] = "('civicrm_contact', {$dao->contact_id}, {$dao->contact_id}, '{$cacheKey}', '" . CRM_Core_DAO
::escapeString($dao->sort_name
) . "')";
1097 //update pre/next cache using single insert query
1098 if (!empty($insertValues)) {
1099 $sql = 'INSERT INTO civicrm_prevnext_cache ( entity_table, entity_id1, entity_id2, cacheKey, data ) VALUES
1100 ' . implode(',', $insertValues);
1102 $result = CRM_Core_DAO
::executeQuery($sql);
1109 public function getQILL() {
1110 return $this->_query
->qill();
1114 * Name of export file.
1116 * @param string $output
1122 public function getExportFileName($output = 'csv') {
1123 return ts('CiviCRM Contact Search');
1127 * Get colunmn headers for search selector.
1131 private static function &_getColumnHeaders() {
1132 if (!isset(self
::$_columnHeaders)) {
1133 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1134 'address_options', TRUE, NULL, TRUE
1137 self
::$_columnHeaders = array(
1138 'contact_type' => array('desc' => ts('Contact Type')),
1139 'sort_name' => array(
1140 'name' => ts('Name'),
1141 'sort' => 'sort_name',
1142 'direction' => CRM_Utils_Sort
::ASCENDING
,
1146 $defaultAddress = array(
1147 'street_address' => array('name' => ts('Address')),
1149 'name' => ts('City'),
1151 'direction' => CRM_Utils_Sort
::DONTCARE
,
1153 'state_province' => array(
1154 'name' => ts('State'),
1155 'sort' => 'state_province',
1156 'direction' => CRM_Utils_Sort
::DONTCARE
,
1158 'postal_code' => array(
1159 'name' => ts('Postal'),
1160 'sort' => 'postal_code',
1161 'direction' => CRM_Utils_Sort
::DONTCARE
,
1164 'name' => ts('Country'),
1165 'sort' => 'country',
1166 'direction' => CRM_Utils_Sort
::DONTCARE
,
1170 foreach ($defaultAddress as $columnName => $column) {
1171 if (!empty($addressOptions[$columnName])) {
1172 self
::$_columnHeaders[$columnName] = $column;
1176 self
::$_columnHeaders['email'] = array(
1177 'name' => ts('Email'),
1179 'direction' => CRM_Utils_Sort
::DONTCARE
,
1182 self
::$_columnHeaders['phone'] = array('name' => ts('Phone'));
1184 return self
::$_columnHeaders;
1188 * @return CRM_Contact_BAO_Query
1190 public function getQuery() {
1191 return $this->_query
;
1195 * @return CRM_Contact_DAO_Contact
1197 public function alphabetQuery() {
1198 return $this->_query
->searchQuery(NULL, NULL, NULL, FALSE, FALSE, TRUE);
1202 * @param array $params
1203 * @param int $sortID
1204 * @param null $displayRelationshipType
1205 * @param string $queryOperator
1207 * @return CRM_Contact_DAO_Contact
1209 public function contactIDQuery($params, $sortID, $displayRelationshipType = NULL, $queryOperator = 'AND') {
1210 $sortOrder = &$this->getSortOrder($this->_action
);
1211 $sort = new CRM_Utils_Sort($sortOrder, $sortID);
1213 // rectify params to what proximity search expects if there is a value for prox_distance
1214 // CRM-7021 CRM-7905
1215 if (!empty($params)) {
1216 CRM_Contact_BAO_ProximityQuery
::fixInputParams($params);
1219 if (!$displayRelationshipType) {
1220 $query = new CRM_Contact_BAO_Query($params,
1221 CRM_Contact_BAO_Query
::NO_RETURN_PROPERTIES
,
1222 NULL, FALSE, FALSE, 1,
1223 FALSE, TRUE, TRUE, NULL,
1228 $query = new CRM_Contact_BAO_Query($params,
1229 CRM_Contact_BAO_Query
::NO_RETURN_PROPERTIES
,
1230 NULL, FALSE, FALSE, 1,
1231 FALSE, TRUE, TRUE, $displayRelationshipType,
1235 $value = $query->searchQuery(0, 0, $sort,
1236 FALSE, FALSE, FALSE,
1243 * @param $returnProperties
1247 public function &makeProperties(&$returnProperties) {
1248 $properties = array();
1249 foreach ($returnProperties as $name => $value) {
1250 if ($name != 'location') {
1251 // special handling for group and tag
1252 if (in_array($name, array('group', 'tag'))) {
1256 // special handling for notes
1257 if (in_array($name, array('note', 'note_subject', 'note_body'))) {
1261 $properties[] = $name;
1264 // extract all the location stuff
1265 foreach ($value as $n => $v) {
1266 foreach ($v as $n1 => $v1) {
1267 if (!strpos('_id', $n1) && $n1 != 'location_type') {
1268 $n = str_replace(' ', '_', $n);
1269 $properties[] = "{$n}-{$n1}";