3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
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 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)) {
257 self
::$_links = array(
258 CRM_Core_Action
::VIEW
=> array(
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
=> array(
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
] = array(
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++
] = array(
306 'name' => $value['title'],
309 'title' => $value['title'],
310 'ref' => $value['ref'],
311 'class' => CRM_Utils_Array
::value('class', $value),
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[] = array('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 = array(
368 foreach ($doNotCareElements as $value) {
369 unset($this->_returnProperties
[$value]);
373 if ($output == CRM_Core_Selector_Controller
::EXPORT
) {
374 $csvHeaders = array(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 = array(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 = array('group', 'tag');
398 $direction = CRM_Utils_Sort
::ASCENDING
;
400 if (!self
::$_columnHeaders) {
401 self
::$_columnHeaders = array(
404 'name' => ts('Name'),
405 'sort' => 'sort_name',
406 'direction' => CRM_Utils_Sort
::ASCENDING
,
410 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
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, array(
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[] = array(
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 = array();
463 self
::$_columnHeaders[] = array('desc' => ts('Actions'), 'name' => ts('Action'));
466 $headers = self
::$_columnHeaders;
468 elseif (!empty($this->_returnProperties
)) {
469 self
::$_columnHeaders = array(
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}";
488 elseif (isset($this->_query
->_fields
[$prop]) && isset($this->_query
->_fields
[$prop]['title'])) {
489 $title = $this->_query
->_fields
[$prop]['title'];
495 self
::$_columnHeaders[] = array('name' => $title, 'sort' => $prop);
497 self
::$_columnHeaders[] = array('name' => ts('Actions'));
498 $headers = self
::$_columnHeaders;
501 $headers = $this->getColHeads($action, $output);
508 * Returns total number of rows for the query.
513 * Total number of rows
515 public function getTotalCount($action) {
516 // Use count from cache during paging/sorting
517 if (!empty($_GET['crmPID']) ||
!empty($_GET['crmSID'])) {
518 $count = CRM_Core_BAO_Cache
::getItem('Search Results Count', $this->_key
);
521 $count = $this->_query
->searchQuery(0, 0, NULL, TRUE);
522 CRM_Core_BAO_Cache
::setItem($count, 'Search Results Count', $this->_key
);
528 * Returns all the rows in the given offset and rowCount.
530 * @param string $action
531 * The action being performed.
533 * The row number to start from.
534 * @param int $rowCount
535 * The number of rows to return.
536 * @param string $sort
537 * The sql string that describes the sort order.
538 * @param string $output
539 * What should the result set include (web/email/csv).
542 * the total number of rows for this action
544 public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
546 if (($output == CRM_Core_Selector_Controller
::EXPORT ||
547 $output == CRM_Core_Selector_Controller
::SCREEN
549 $this->_formValues
['radio_ts'] == 'ts_sel'
551 $includeContactIds = TRUE;
554 $includeContactIds = FALSE;
557 // note the formvalues were given by CRM_Contact_Form_Search to us
558 // and contain the search criteria (parameters)
559 // note that the default action is basic
561 $cacheKey = $this->buildPrevNextCache($sort);
562 $result = $this->_query
->getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds);
565 $result = $this->_query
->searchQuery($offset, $rowCount, $sort, FALSE, $includeContactIds);
568 // process the result of the query
570 $permissions = array(CRM_Core_Permission
::getPermission());
571 if (CRM_Core_Permission
::check('delete contacts')) {
572 $permissions[] = CRM_Core_Permission
::DELETE
;
574 $mask = CRM_Core_Action
::mask($permissions);
576 // mask value to hide map link if there are not lat/long
577 $mapMask = $mask & 4095;
579 if ($this->_searchContext
== 'smog') {
580 $gc = CRM_Core_SelectValues
::groupContactStatus();
583 if ($this->_ufGroupID
) {
584 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
587 static $skipFields = array('group', 'tag');
588 foreach ($this->_fields
as $key => $field) {
589 if (!empty($field['in_selector']) &&
590 !in_array($key, $skipFields)
592 if (strpos($key, '-') !== FALSE) {
593 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $key, 3);
595 if ($id == 'Primary') {
596 $locationTypeName = 1;
598 elseif ($fieldName == 'url') {
599 $locationTypeName = "website-{$id}";
602 $locationTypeName = CRM_Utils_Array
::value($id, $locationTypes);
603 if (!$locationTypeName) {
608 $locationTypeName = str_replace(' ', '_', $locationTypeName);
609 if (in_array($fieldName, array(
615 $names[] = "{$locationTypeName}-{$fieldName}-{$type}";
618 $names[] = "{$locationTypeName}-{$fieldName}";
622 $names[] = "{$locationTypeName}-{$fieldName}";
626 $names[] = $field['name'];
633 elseif (!empty($this->_returnProperties
)) {
634 $names = self
::makeProperties($this->_returnProperties
);
637 $names = self
::$_properties;
640 $multipleSelectFields = array('preferred_communication_method' => 1);
642 $links = self
::links($this->_context
, $this->_contextMenu
, $this->_key
);
644 //check explicitly added contact to a Smart Group.
645 $groupID = CRM_Utils_Array
::value('group', $this->_formValues
);
647 $pseudoconstants = array();
648 // for CRM-3157 purposes
649 if (in_array('world_region', $names)) {
650 $pseudoconstants['world_region'] = array(
651 'dbName' => 'worldregion_id',
652 'values' => CRM_Core_PseudoConstant
::worldRegion(),
656 while ($result->fetch()) {
658 $this->_query
->convertToPseudoNames($result);
660 // the columns we are interested in
661 foreach ($names as $property) {
662 if ($property == 'status') {
665 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($property)) {
666 $row[$property] = CRM_Core_BAO_CustomField
::displayValue(
673 $multipleSelectFields &&
674 array_key_exists($property, $multipleSelectFields)
677 $paramsNew = array($key => $result->$property);
678 $name = array($key => array('newName' => $key, 'groupName' => $key));
680 CRM_Core_OptionGroup
::lookupValues($paramsNew, $name, FALSE);
681 $row[$key] = $paramsNew[$key];
683 elseif (strpos($property, '-im')) {
684 $row[$property] = $result->$property;
685 if (!empty($result->$property)) {
686 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
687 $providerId = $property . "-provider_id";
688 $providerName = $imProviders[$result->$providerId];
689 $row[$property] = $result->$property . " ({$providerName})";
692 elseif (in_array($property, array(
697 $greeting = $property . '_display';
698 $row[$property] = $result->$greeting;
700 elseif (isset($pseudoconstants[$property])) {
701 $row[$property] = CRM_Utils_Array
::value(
702 $result->{$pseudoconstants[$property]['dbName']},
703 $pseudoconstants[$property]['values']
706 elseif (strpos($property, '-url') !== FALSE) {
708 $websiteKey = str_replace('-url', '', $property);
709 $propertyArray = explode('-', $property);
710 $websiteFld = $websiteKey . '-' . array_pop($propertyArray);
711 if (!empty($result->$websiteFld)) {
712 $websiteTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Website', 'website_type_id');
713 $websiteType = $websiteTypes[$result->{"$websiteKey-website_type_id"}];
714 $websiteValue = $result->$websiteFld;
715 $websiteUrl = "<a href=\"{$websiteValue}\">{$websiteValue} ({$websiteType})</a>";
717 $row[$property] = $websiteUrl;
720 $row[$property] = isset($result->$property) ?
$result->$property : NULL;
724 if (!empty($result->postal_code_suffix
)) {
725 $row['postal_code'] .= "-" . $result->postal_code_suffix
;
728 if ($output != CRM_Core_Selector_Controller
::EXPORT
&&
729 $this->_searchContext
== 'smog'
731 if (empty($result->status
) &&
734 $contactID = $result->contact_id
;
737 'contact_id' => $contactID,
738 'group_id' => $groupID,
741 $gcDefaults = array();
742 CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_GroupContact', $gcParams, $gcDefaults);
744 if (empty($gcDefaults)) {
745 $row['status'] = ts('Smart');
748 $row['status'] = $gc[$gcDefaults['status']];
752 $row['status'] = NULL;
756 $row['status'] = $gc[$result->status
];
760 if ($output != CRM_Core_Selector_Controller
::EXPORT
) {
761 $row['checkbox'] = CRM_Core_Form
::CB_PREFIX
. $result->contact_id
;
763 if (!empty($this->_formValues
['deleted_contacts']) && CRM_Core_Permission
::check('access deleted contacts')
767 'name' => ts('View'),
768 'url' => 'civicrm/contact/view',
769 'qs' => 'reset=1&cid=%%id%%',
770 'class' => 'no-popup',
771 'title' => ts('View Contact Details'),
774 'name' => ts('Restore'),
775 'url' => 'civicrm/contact/view/delete',
776 'qs' => 'reset=1&cid=%%id%%&restore=1',
777 'title' => ts('Restore Contact'),
780 if (CRM_Core_Permission
::check('delete contacts')) {
782 'name' => ts('Delete Permanently'),
783 'url' => 'civicrm/contact/view/delete',
784 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1',
785 'title' => ts('Permanently Delete Contact'),
788 $row['action'] = CRM_Core_Action
::formLink(
791 array('id' => $result->contact_id
),
794 'contact.selector.row',
799 elseif ((is_numeric(CRM_Utils_Array
::value('geo_code_1', $row))) ||
800 (!empty($row['city']) &&
801 CRM_Utils_Array
::value('state_province', $row)
804 $row['action'] = CRM_Core_Action
::formLink(
807 array('id' => $result->contact_id
),
810 'contact.selector.row',
816 $row['action'] = CRM_Core_Action
::formLink(
819 array('id' => $result->contact_id
),
822 'contact.selector.row',
828 // allow components to add more actions
829 CRM_Core_Component
::searchAction($row, $result->contact_id
);
831 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils
::getImage($result->contact_sub_type ?
$result->contact_sub_type
: $result->contact_type
,
836 $row['contact_type_orig'] = $result->contact_sub_type ?
$result->contact_sub_type
: $result->contact_type
;
837 $row['contact_sub_type'] = $result->contact_sub_type ? CRM_Contact_BAO_ContactType
::contactTypePairs(FALSE, $result->contact_sub_type
, ', ') : $result->contact_sub_type
;
838 $row['contact_id'] = $result->contact_id
;
839 $row['sort_name'] = $result->sort_name
;
840 // Surely this if should be if NOT - otherwise it's just wierd.
841 if (array_key_exists('id', $row)) {
842 $row['id'] = $result->contact_id
;
846 $rows[$row['contact_id']] = $row;
853 * @param CRM_Utils_Sort $sort
857 public function buildPrevNextCache($sort) {
858 $cacheKey = 'civicrm search ' . $this->_key
;
860 // We should clear the cache in following conditions:
861 // 1. when starting from scratch, i.e new search
862 // 2. if records are sorted
864 // get current page requested
865 $pageNum = CRM_Utils_Request
::retrieve('crmPID', 'Integer');
867 // get the current sort order
868 $currentSortID = CRM_Utils_Request
::retrieve('crmSID', 'String');
870 $session = CRM_Core_Session
::singleton();
872 // get previous sort id
873 $previousSortID = $session->get('previousSortID');
875 // check for current != previous to ensure cache is not reset if paging is done without changing
877 if (!$pageNum ||
(!empty($currentSortID) && $currentSortID != $previousSortID)) {
878 CRM_Core_BAO_PrevNextCache
::deleteItem(NULL, $cacheKey, 'civicrm_contact');
879 // this means it's fresh search, so set pageNum=1
885 // set the current sort as previous sort
886 if (!empty($currentSortID)) {
887 $session->set('previousSortID', $currentSortID);
890 $pageSize = CRM_Utils_Request
::retrieve('crmRowCount', 'Integer', CRM_Core_DAO
::$_nullObject, FALSE, 50);
891 $firstRecord = ($pageNum - 1) * $pageSize;
893 //for alphabetic pagination selection save
894 $sortByCharacter = CRM_Utils_Request
::retrieve('sortByCharacter', 'String');
896 //for text field pagination selection save
897 $countRow = CRM_Core_BAO_PrevNextCache
::getCount($cacheKey, NULL, "entity_table = 'civicrm_contact'");
898 // $sortByCharacter triggers a refresh in the prevNext cache
899 if ($sortByCharacter && $sortByCharacter != 'all') {
900 $cacheKey .= "_alphabet";
901 $this->fillupPrevNextCache($sort, $cacheKey, 0, max(self
::CACHE_SIZE
, $pageSize));
903 elseif (($firstRecord +
$pageSize) >= $countRow) {
904 $this->fillupPrevNextCache($sort, $cacheKey, $countRow, max(self
::CACHE_SIZE
, $pageSize) +
$firstRecord - $countRow);
912 public function addActions(&$rows) {
914 $basicPermissions = CRM_Core_Permission
::check('delete contacts') ?
array(CRM_Core_Permission
::DELETE
) : array();
916 // get permissions on an individual level (CRM-12645)
917 // @todo look at storing this to the session as this is called twice during search results render.
918 $can_edit_list = CRM_Contact_BAO_Contact_Permission
::allowList(array_keys($rows), CRM_Core_Permission
::EDIT
);
920 $links_template = self
::links($this->_context
, $this->_contextMenu
, $this->_key
);
922 foreach ($rows as $id => & $row) {
923 $links = $links_template;
924 if (in_array($id, $can_edit_list)) {
925 $mask = CRM_Core_Action
::mask(array_merge(array(CRM_Core_Permission
::EDIT
), $basicPermissions));
928 $mask = CRM_Core_Action
::mask(array_merge(array(CRM_Core_Permission
::VIEW
), $basicPermissions));
931 if ((!is_numeric(CRM_Utils_Array
::value('geo_code_1', $row))) &&
932 (empty($row['city']) ||
933 !CRM_Utils_Array
::value('state_province', $row)
936 $mask = $mask & 4095;
939 if (!empty($this->_formValues
['deleted_contacts']) && CRM_Core_Permission
::check('access deleted contacts')
943 'name' => ts('View'),
944 'url' => 'civicrm/contact/view',
945 'qs' => 'reset=1&cid=%%id%%',
946 'class' => 'no-popup',
947 'title' => ts('View Contact Details'),
950 'name' => ts('Restore'),
951 'url' => 'civicrm/contact/view/delete',
952 'qs' => 'reset=1&cid=%%id%%&restore=1',
953 'title' => ts('Restore Contact'),
956 if (CRM_Core_Permission
::check('delete contacts')) {
958 'name' => ts('Delete Permanently'),
959 'url' => 'civicrm/contact/view/delete',
960 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1',
961 'title' => ts('Permanently Delete Contact'),
964 $row['action'] = CRM_Core_Action
::formLink(
967 array('id' => $row['contact_id']),
970 'contact.selector.actions',
976 $row['action'] = CRM_Core_Action
::formLink(
979 array('id' => $row['contact_id']),
982 'contact.selector.actions',
988 // allow components to add more actions
989 CRM_Core_Component
::searchAction($row, $row['contact_id']);
991 if (!empty($row['contact_type_orig'])) {
992 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils
::getImage($row['contact_type_orig'],
993 FALSE, $row['contact_id']);
1001 public function removeActions(&$rows) {
1002 foreach ($rows as $rid => & $rValue) {
1003 unset($rValue['contact_type']);
1004 unset($rValue['action']);
1009 * @param CRM_Utils_Sort $sort
1010 * @param string $cacheKey
1014 public function fillupPrevNextCache($sort, $cacheKey, $start = 0, $end = self
::CACHE_SIZE
) {
1016 // For custom searches, use the contactIDs method
1017 if (is_a($this, 'CRM_Contact_Selector_Custom')) {
1018 $sql = $this->_search
->contactIDs($start, $end, $sort, TRUE);
1019 $replaceSQL = "SELECT contact_a.id as contact_id";
1020 $coreSearch = FALSE;
1022 // For core searches use the searchQuery method
1024 $sql = $this->_query
->searchQuery($start, $end, $sort, FALSE, $this->_query
->_includeContactIds
,
1026 $replaceSQL = "SELECT contact_a.id as id";
1030 // due to limitations in our search query writer, the above query does not work
1031 // in cases where the query is being sorted on a non-contact table
1032 // this results in a fatal error :(
1033 // see below for the gross hack of trapping the error and not filling
1034 // the prev next cache in this situation
1035 // the other alternative of running the FULL query will just be incredibly inefficient
1036 // and slow things down way too much on large data sets / complex queries
1039 INSERT INTO civicrm_prevnext_cache ( entity_table, entity_id1, entity_id2, cacheKey, data )
1040 SELECT DISTINCT 'civicrm_contact', contact_a.id, contact_a.id, '$cacheKey', contact_a.display_name
1043 $sql = str_replace($replaceSQL, $insertSQL, $sql);
1045 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1046 $result = CRM_Core_DAO
::executeQuery($sql);
1049 if (is_a($result, 'DB_Error')) {
1050 // check if we get error during core search
1052 // in the case of error, try rebuilding cache using full sql which is used for search selector display
1053 // this fixes the bugs reported in CRM-13996 & CRM-14438
1054 $this->rebuildPreNextCache($start, $end, $sort, $cacheKey);
1057 // return if above query fails
1062 // also record an entry in the cache key table, so we can delete it periodically
1063 CRM_Core_BAO_Cache
::setItem($cacheKey, 'CiviCRM Search PrevNextCache', $cacheKey);
1067 * called to rebuild prev next cache using full sql in case of core search ( excluding custom search)
1070 * Start for limit clause.
1072 * End for limit clause.
1073 * @param CRM_Utils_Sort $sort
1074 * @param string $cacheKey
1077 public function rebuildPreNextCache($start, $end, $sort, $cacheKey) {
1078 // generate full SQL
1079 $sql = $this->_query
->searchQuery($start, $end, $sort, FALSE, $this->_query
->_includeContactIds
,
1080 FALSE, FALSE, TRUE);
1082 $dao = CRM_Core_DAO
::executeQuery($sql);
1084 // build insert query, note that currently we build cache for 500 (self::CACHE_SIZE) contact records at a time, hence below approach
1085 $insertValues = array();
1086 while ($dao->fetch()) {
1087 $insertValues[] = "('civicrm_contact', {$dao->contact_id}, {$dao->contact_id}, '{$cacheKey}', '" . CRM_Core_DAO
::escapeString($dao->sort_name
) . "')";
1090 //update pre/next cache using single insert query
1091 if (!empty($insertValues)) {
1092 $sql = 'INSERT INTO civicrm_prevnext_cache ( entity_table, entity_id1, entity_id2, cacheKey, data ) VALUES
1093 ' . implode(',', $insertValues);
1095 $result = CRM_Core_DAO
::executeQuery($sql);
1102 public function getQILL() {
1103 return $this->_query
->qill();
1107 * Name of export file.
1109 * @param string $output
1115 public function getExportFileName($output = 'csv') {
1116 return ts('CiviCRM Contact Search');
1120 * Get colunmn headers for search selector.
1124 private static function &_getColumnHeaders() {
1125 if (!isset(self
::$_columnHeaders)) {
1126 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1127 'address_options', TRUE, NULL, TRUE
1130 self
::$_columnHeaders = array(
1131 'contact_type' => array('desc' => ts('Contact Type')),
1132 'sort_name' => array(
1133 'name' => ts('Name'),
1134 'sort' => 'sort_name',
1135 'direction' => CRM_Utils_Sort
::ASCENDING
,
1139 $defaultAddress = array(
1140 'street_address' => array('name' => ts('Address')),
1142 'name' => ts('City'),
1144 'direction' => CRM_Utils_Sort
::DONTCARE
,
1146 'state_province' => array(
1147 'name' => ts('State'),
1148 'sort' => 'state_province',
1149 'direction' => CRM_Utils_Sort
::DONTCARE
,
1151 'postal_code' => array(
1152 'name' => ts('Postal'),
1153 'sort' => 'postal_code',
1154 'direction' => CRM_Utils_Sort
::DONTCARE
,
1157 'name' => ts('Country'),
1158 'sort' => 'country',
1159 'direction' => CRM_Utils_Sort
::DONTCARE
,
1163 foreach ($defaultAddress as $columnName => $column) {
1164 if (!empty($addressOptions[$columnName])) {
1165 self
::$_columnHeaders[$columnName] = $column;
1169 self
::$_columnHeaders['email'] = array(
1170 'name' => ts('Email'),
1172 'direction' => CRM_Utils_Sort
::DONTCARE
,
1175 self
::$_columnHeaders['phone'] = array('name' => ts('Phone'));
1177 return self
::$_columnHeaders;
1181 * @return CRM_Contact_BAO_Query
1183 public function getQuery() {
1184 return $this->_query
;
1188 * @return CRM_Contact_DAO_Contact
1190 public function alphabetQuery() {
1191 return $this->_query
->searchQuery(NULL, NULL, NULL, FALSE, FALSE, TRUE);
1195 * @param array $params
1197 * @param int $sortID
1198 * @param null $displayRelationshipType
1199 * @param string $queryOperator
1201 * @return CRM_Contact_DAO_Contact
1203 public function contactIDQuery($params, $action, $sortID, $displayRelationshipType = NULL, $queryOperator = 'AND') {
1204 $sortOrder = &$this->getSortOrder($this->_action
);
1205 $sort = new CRM_Utils_Sort($sortOrder, $sortID);
1207 // rectify params to what proximity search expects if there is a value for prox_distance
1208 // CRM-7021 CRM-7905
1209 if (!empty($params)) {
1210 CRM_Contact_BAO_ProximityQuery
::fixInputParams($params);
1213 if (!$displayRelationshipType) {
1214 $query = new CRM_Contact_BAO_Query($params,
1215 CRM_Contact_BAO_Query
::NO_RETURN_PROPERTIES
,
1216 NULL, FALSE, FALSE, 1,
1217 FALSE, TRUE, TRUE, NULL,
1222 $query = new CRM_Contact_BAO_Query($params,
1223 CRM_Contact_BAO_Query
::NO_RETURN_PROPERTIES
,
1224 NULL, FALSE, FALSE, 1,
1225 FALSE, TRUE, TRUE, $displayRelationshipType,
1229 $value = $query->searchQuery(0, 0, $sort,
1230 FALSE, FALSE, FALSE,
1237 * @param $returnProperties
1241 public function &makeProperties(&$returnProperties) {
1242 $properties = array();
1243 foreach ($returnProperties as $name => $value) {
1244 if ($name != 'location') {
1245 // special handling for group and tag
1246 if (in_array($name, array('group', 'tag'))) {
1250 // special handling for notes
1251 if (in_array($name, array('note', 'note_subject', 'note_body'))) {
1255 $properties[] = $name;
1258 // extract all the location stuff
1259 foreach ($value as $n => $v) {
1260 foreach ($v as $n1 => $v1) {
1261 if (!strpos('_id', $n1) && $n1 != 'location_type') {
1262 $properties[] = "{$n}-{$n1}";