3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
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
{
42 * This defines two actions- View and Edit.
46 static $_links = NULL;
49 * We use desc to remind us what that column is, name is used in the tpl
53 static $_columnHeaders;
56 * Properties of contact we're interested in displaying
59 static $_properties = array(
82 * FormValues is the array returned by exportValues called on
83 * the HTML_QuickForm_Controller for that page.
94 protected $_contextMenu;
97 * Params is the array in a value used by the search query creator
104 * The return properties used for search
108 protected $_returnProperties;
111 * Represent the type of selector
117 protected $_searchContext;
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', CRM_Core_DAO
::$_nullObject);
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 returns the links that are given for each search row.
228 * currently the links added for each row are
235 public static function &links() {
236 list($context, $contextMenu, $key) = func_get_args();
237 $extraParams = ($key) ?
"&key={$key}" : NULL;
238 $searchContext = ($context) ?
"&context=$context" : NULL;
240 if (!(self
::$_links)) {
241 self
::$_links = array(
242 CRM_Core_Action
::VIEW
=> array(
243 'name' => ts('View'),
244 'url' => 'civicrm/contact/view',
245 'class' => 'no-popup',
246 'qs' => "reset=1&cid=%%id%%{$searchContext}{$extraParams}",
247 'title' => ts('View Contact Details'),
248 'ref' => 'view-contact',
250 CRM_Core_Action
::UPDATE
=> array(
251 'name' => ts('Edit'),
252 'url' => 'civicrm/contact/add',
253 'class' => 'no-popup',
254 'qs' => "reset=1&action=update&cid=%%id%%{$searchContext}{$extraParams}",
255 'title' => ts('Edit Contact Details'),
256 'ref' => 'edit-contact',
260 $config = CRM_Core_Config
::singleton();
261 //CRM-16552: mapAPIKey is not mandatory as google no longer requires an API Key
262 if ($config->mapProvider
&& ($config->mapAPIKey ||
$config->mapProvider
== 'Google')) {
263 self
::$_links[CRM_Core_Action
::MAP
] = array(
265 'url' => 'civicrm/contact/map',
266 'qs' => "reset=1&cid=%%id%%{$searchContext}{$extraParams}",
267 'title' => ts('Map Contact'),
271 // Adding Context Menu Links in more action
274 foreach ($contextMenu as $key => $value) {
275 $contextVal = '&context=' . $value['key'];
276 if ($value['key'] == 'delete') {
277 $contextVal = $searchContext;
279 $url = "civicrm/contact/view/{$value['key']}";
280 $qs = "reset=1&action=add&cid=%%id%%{$contextVal}{$extraParams}";
281 if ($value['key'] == 'activity') {
282 $qs = "action=browse&selectedChild=activity&reset=1&cid=%%id%%{$extraParams}";
284 elseif ($value['key'] == 'email') {
285 $url = "civicrm/contact/view/activity";
286 $qs = "atype=3&action=add&reset=1&cid=%%id%%{$extraParams}";
289 self
::$_links[$counter++
] = array(
290 'name' => $value['title'],
293 'title' => $value['title'],
294 'ref' => $value['ref'],
295 'class' => CRM_Utils_Array
::value('class', $value),
300 return self
::$_links;
304 * Getter for array of the parameters required for creating pager.
307 * @param array $params
309 public function getPagerParams($action, &$params) {
310 $params['status'] = ts('Contact %%StatusMessage%%');
311 $params['csvString'] = NULL;
312 $params['rowCount'] = CRM_Utils_Pager
::ROWCOUNT
;
314 $params['buttonTop'] = 'PagerTopButton';
315 $params['buttonBottom'] = 'PagerBottomButton';
319 * @param null $action
320 * @param null $output
324 public function &getColHeads($action = NULL, $output = NULL) {
325 $colHeads = self
::_getColumnHeaders();
326 $colHeads[] = array('desc' => ts('Actions'), 'name' => ts('Action'));
331 * Returns the column headers as an array of tuples:
332 * (name, sortName (key to the sort array))
334 * @param string $action
335 * The action being performed.
336 * @param string $output
337 * What should the result set include (web/email/csv).
340 * the column headers that need to be displayed
342 public function &getColumnHeaders($action = NULL, $output = NULL) {
345 // unset return property elements that we don't care
346 if (!empty($this->_returnProperties
)) {
347 $doNotCareElements = array(
352 foreach ($doNotCareElements as $value) {
353 unset($this->_returnProperties
[$value]);
357 if ($output == CRM_Core_Selector_Controller
::EXPORT
) {
358 $csvHeaders = array(ts('Contact ID'), ts('Contact Type'));
359 foreach ($this->getColHeads($action, $output) as $column) {
360 if (array_key_exists('name', $column)) {
361 $csvHeaders[] = $column['name'];
364 $headers = $csvHeaders;
366 elseif ($output == CRM_Core_Selector_Controller
::SCREEN
) {
367 $csvHeaders = array(ts('Name'));
368 foreach ($this->getColHeads($action, $output) as $key => $column) {
369 if (array_key_exists('name', $column) &&
371 $column['name'] != ts('Name')
373 $csvHeaders[$key] = $column['name'];
376 $headers = $csvHeaders;
378 elseif ($this->_ufGroupID
) {
379 // we dont use the cached value of column headers
380 // since it potentially changed because of the profile selected
381 static $skipFields = array('group', 'tag');
382 $direction = CRM_Utils_Sort
::ASCENDING
;
384 if (!self
::$_columnHeaders) {
385 self
::$_columnHeaders = array(
388 'name' => ts('Name'),
389 'sort' => 'sort_name',
390 'direction' => CRM_Utils_Sort
::ASCENDING
,
394 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
396 foreach ($this->_fields
as $name => $field) {
397 if (!empty($field['in_selector']) &&
398 !in_array($name, $skipFields)
400 if (strpos($name, '-') !== FALSE) {
401 list($fieldName, $lType, $type) = CRM_Utils_System
::explode('-', $name, 3);
403 if ($lType == 'Primary') {
404 $locationTypeName = 1;
407 $locationTypeName = $locationTypes[$lType];
410 if (in_array($fieldName, array(
416 $name = "`$locationTypeName-$fieldName-$type`";
419 $name = "`$locationTypeName-$fieldName`";
423 $name = "`$locationTypeName-$fieldName`";
426 //to handle sort key for Internal contactId.CRM-2289
428 $name = 'contact_id';
431 self
::$_columnHeaders[] = array(
432 'name' => $field['title'],
434 'direction' => $direction,
436 $direction = CRM_Utils_Sort
::DONTCARE
;
441 // if we dont have any valid columns, dont add the implicit ones
442 // this allows the template to check on emptiness of column headers
444 self
::$_columnHeaders = array();
447 self
::$_columnHeaders[] = array('desc' => ts('Actions'), 'name' => ts('Action'));
450 $headers = self
::$_columnHeaders;
452 elseif (!empty($this->_returnProperties
)) {
453 self
::$_columnHeaders = array(
456 'name' => ts('Name'),
457 'sort' => 'sort_name',
458 'direction' => CRM_Utils_Sort
::ASCENDING
,
461 $properties = self
::makeProperties($this->_returnProperties
);
463 foreach ($properties as $prop) {
464 if (strpos($prop, '-')) {
465 list($loc, $fld, $phoneType) = CRM_Utils_System
::explode('-', $prop, 3);
466 $title = $this->_query
->_fields
[$fld]['title'];
467 if (trim($phoneType) && !is_numeric($phoneType) && strtolower($phoneType) != $fld) {
468 $title .= "-{$phoneType}";
472 elseif (isset($this->_query
->_fields
[$prop]) && isset($this->_query
->_fields
[$prop]['title'])) {
473 $title = $this->_query
->_fields
[$prop]['title'];
479 self
::$_columnHeaders[] = array('name' => $title, 'sort' => $prop);
481 self
::$_columnHeaders[] = array('name' => ts('Actions'));
482 $headers = self
::$_columnHeaders;
485 $headers = $this->getColHeads($action, $output);
492 * Returns total number of rows for the query.
497 * Total number of rows
499 public function getTotalCount($action) {
500 // Use count from cache during paging/sorting
501 if (!empty($_GET['crmPID']) ||
!empty($_GET['crmSID'])) {
502 $count = CRM_Core_BAO_Cache
::getItem('Search Results Count', $this->_key
);
505 $count = $this->_query
->searchQuery(0, 0, NULL, TRUE);
506 CRM_Core_BAO_Cache
::setItem($count, 'Search Results Count', $this->_key
);
512 * Returns all the rows in the given offset and rowCount.
514 * @param string $action
515 * The action being performed.
517 * The row number to start from.
518 * @param int $rowCount
519 * The number of rows to return.
520 * @param string $sort
521 * The sql string that describes the sort order.
522 * @param string $output
523 * What should the result set include (web/email/csv).
526 * the total number of rows for this action
528 public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
529 $config = CRM_Core_Config
::singleton();
531 if (($output == CRM_Core_Selector_Controller
::EXPORT ||
532 $output == CRM_Core_Selector_Controller
::SCREEN
534 $this->_formValues
['radio_ts'] == 'ts_sel'
536 $includeContactIds = TRUE;
539 $includeContactIds = FALSE;
542 // note the formvalues were given by CRM_Contact_Form_Search to us
543 // and contain the search criteria (parameters)
544 // note that the default action is basic
546 $cacheKey = $this->buildPrevNextCache($sort);
547 $result = $this->_query
->getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds);
550 $result = $this->_query
->searchQuery($offset, $rowCount, $sort, FALSE, $includeContactIds);
553 // process the result of the query
555 $permissions = array(CRM_Core_Permission
::getPermission());
556 if (CRM_Core_Permission
::check('delete contacts')) {
557 $permissions[] = CRM_Core_Permission
::DELETE
;
559 $mask = CRM_Core_Action
::mask($permissions);
561 // mask value to hide map link if there are not lat/long
562 $mapMask = $mask & 4095;
564 if ($this->_searchContext
== 'smog') {
565 $gc = CRM_Core_SelectValues
::groupContactStatus();
568 if ($this->_ufGroupID
) {
569 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
572 static $skipFields = array('group', 'tag');
573 foreach ($this->_fields
as $key => $field) {
574 if (!empty($field['in_selector']) &&
575 !in_array($key, $skipFields)
577 if (strpos($key, '-') !== FALSE) {
578 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $key, 3);
580 if ($id == 'Primary') {
581 $locationTypeName = 1;
583 elseif ($fieldName == 'url') {
584 $locationTypeName = "website-{$id}";
587 $locationTypeName = CRM_Utils_Array
::value($id, $locationTypes);
588 if (!$locationTypeName) {
593 $locationTypeName = str_replace(' ', '_', $locationTypeName);
594 if (in_array($fieldName, array(
600 $names[] = "{$locationTypeName}-{$fieldName}-{$type}";
603 $names[] = "{$locationTypeName}-{$fieldName}";
607 $names[] = "{$locationTypeName}-{$fieldName}";
611 $names[] = $field['name'];
618 elseif (!empty($this->_returnProperties
)) {
619 $names = self
::makeProperties($this->_returnProperties
);
622 $names = self
::$_properties;
625 $multipleSelectFields = array('preferred_communication_method' => 1);
627 $links = self
::links($this->_context
, $this->_contextMenu
, $this->_key
);
629 //check explicitly added contact to a Smart Group.
630 $groupID = CRM_Utils_Array
::value('group', $this->_formValues
);
632 $pseudoconstants = array();
633 // for CRM-3157 purposes
634 if (in_array('world_region', $names)) {
635 $pseudoconstants['world_region'] = array(
636 'dbName' => 'worldregion_id',
637 'values' => CRM_Core_PseudoConstant
::worldRegion(),
642 while ($result->fetch()) {
644 $this->_query
->convertToPseudoNames($result);
646 // the columns we are interested in
647 foreach ($names as $property) {
648 if ($property == 'status') {
651 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($property)) {
652 $row[$property] = CRM_Core_BAO_CustomField
::getDisplayValue(
660 $multipleSelectFields &&
661 array_key_exists($property, $multipleSelectFields)
664 $paramsNew = array($key => $result->$property);
665 $name = array($key => array('newName' => $key, 'groupName' => $key));
667 CRM_Core_OptionGroup
::lookupValues($paramsNew, $name, FALSE);
668 $row[$key] = $paramsNew[$key];
670 elseif (strpos($property, '-im')) {
671 $row[$property] = $result->$property;
672 if (!empty($result->$property)) {
673 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
674 $providerId = $property . "-provider_id";
675 $providerName = $imProviders[$result->$providerId];
676 $row[$property] = $result->$property . " ({$providerName})";
679 elseif (in_array($property, array(
684 $greeting = $property . '_display';
685 $row[$property] = $result->$greeting;
687 elseif (isset($pseudoconstants[$property])) {
688 $row[$property] = CRM_Utils_Array
::value(
689 $result->{$pseudoconstants[$property]['dbName']},
690 $pseudoconstants[$property]['values']
693 elseif (strpos($property, '-url') !== FALSE) {
695 $websiteKey = str_replace('-url', '', $property);
696 $propertyArray = explode('-', $property);
697 $websiteFld = $websiteKey . '-' . array_pop($propertyArray);
698 if (!empty($result->$websiteFld)) {
699 $websiteTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Website', 'website_type_id');
700 $websiteType = $websiteTypes[$result->{"$websiteKey-website_type_id"}];
701 $websiteValue = $result->$websiteFld;
702 $websiteUrl = "<a href=\"{$websiteValue}\">{$websiteValue} ({$websiteType})</a>";
704 $row[$property] = $websiteUrl;
707 $row[$property] = isset($result->$property) ?
$result->$property : NULL;
711 if (!empty($result->postal_code_suffix
)) {
712 $row['postal_code'] .= "-" . $result->postal_code_suffix
;
715 if ($output != CRM_Core_Selector_Controller
::EXPORT
&&
716 $this->_searchContext
== 'smog'
718 if (empty($result->status
) &&
721 $contactID = $result->contact_id
;
724 'contact_id' => $contactID,
725 'group_id' => $groupID,
728 $gcDefaults = array();
729 CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_GroupContact', $gcParams, $gcDefaults);
731 if (empty($gcDefaults)) {
732 $row['status'] = ts('Smart');
735 $row['status'] = $gc[$gcDefaults['status']];
739 $row['status'] = NULL;
743 $row['status'] = $gc[$result->status
];
747 if ($output != CRM_Core_Selector_Controller
::EXPORT
) {
748 $row['checkbox'] = CRM_Core_Form
::CB_PREFIX
. $result->contact_id
;
750 if (!empty($this->_formValues
['deleted_contacts']) && CRM_Core_Permission
::check('access deleted contacts')
754 'name' => ts('View'),
755 'url' => 'civicrm/contact/view',
756 'qs' => 'reset=1&cid=%%id%%',
757 'class' => 'no-popup',
758 'title' => ts('View Contact Details'),
761 'name' => ts('Restore'),
762 'url' => 'civicrm/contact/view/delete',
763 'qs' => 'reset=1&cid=%%id%%&restore=1',
764 'title' => ts('Restore Contact'),
767 if (CRM_Core_Permission
::check('delete contacts')) {
769 'name' => ts('Delete Permanently'),
770 'url' => 'civicrm/contact/view/delete',
771 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1',
772 'title' => ts('Permanently Delete Contact'),
775 $row['action'] = CRM_Core_Action
::formLink(
778 array('id' => $result->contact_id
),
781 'contact.selector.row',
786 elseif ((is_numeric(CRM_Utils_Array
::value('geo_code_1', $row))) ||
787 (!empty($row['city']) &&
788 CRM_Utils_Array
::value('state_province', $row)
791 $row['action'] = CRM_Core_Action
::formLink(
794 array('id' => $result->contact_id
),
797 'contact.selector.row',
803 $row['action'] = CRM_Core_Action
::formLink(
806 array('id' => $result->contact_id
),
809 'contact.selector.row',
815 // allow components to add more actions
816 CRM_Core_Component
::searchAction($row, $result->contact_id
);
818 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils
::getImage($result->contact_sub_type ?
$result->contact_sub_type
: $result->contact_type
,
823 $row['contact_type_orig'] = $result->contact_sub_type ?
$result->contact_sub_type
: $result->contact_type
;
824 $row['contact_sub_type'] = $result->contact_sub_type ? CRM_Contact_BAO_ContactType
::contactTypePairs(FALSE, $result->contact_sub_type
, ', ') : $result->contact_sub_type
;
825 $row['contact_id'] = $result->contact_id
;
826 $row['sort_name'] = $result->sort_name
;
827 if (array_key_exists('id', $row)) {
828 $row['id'] = $result->contact_id
;
833 if (in_array($row['contact_id'], $seenIDs) === FALSE) {
834 $seenIDs[] = $row['contact_id'];
843 * @param CRM_Utils_Sort $sort
847 public function buildPrevNextCache($sort) {
848 $cacheKey = 'civicrm search ' . $this->_key
;
850 // We should clear the cache in following conditions:
851 // 1. when starting from scratch, i.e new search
852 // 2. if records are sorted
854 // get current page requested
855 $pageNum = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
857 // get the current sort order
858 $currentSortID = CRM_Utils_Request
::retrieve('crmSID', 'String', CRM_Core_DAO
::$_nullObject);
860 $session = CRM_Core_Session
::singleton();
862 // get previous sort id
863 $previousSortID = $session->get('previousSortID');
865 // check for current != previous to ensure cache is not reset if paging is done without changing
867 if (!$pageNum ||
(!empty($currentSortID) && $currentSortID != $previousSortID)) {
868 CRM_Core_BAO_PrevNextCache
::deleteItem(NULL, $cacheKey, 'civicrm_contact');
869 // this means it's fresh search, so set pageNum=1
875 // set the current sort as previous sort
876 if (!empty($currentSortID)) {
877 $session->set('previousSortID', $currentSortID);
880 $pageSize = CRM_Utils_Request
::retrieve('crmRowCount', 'Integer', CRM_Core_DAO
::$_nullObject, FALSE, 50);
881 $firstRecord = ($pageNum - 1) * $pageSize;
883 //for alphabetic pagination selection save
884 $sortByCharacter = CRM_Utils_Request
::retrieve('sortByCharacter', 'String', CRM_Core_DAO
::$_nullObject);
886 //for text field pagination selection save
887 $countRow = CRM_Core_BAO_PrevNextCache
::getCount($cacheKey, NULL, "entity_table = 'civicrm_contact'");
888 // $sortByCharacter triggers a refresh in the prevNext cache
889 if ($sortByCharacter && $sortByCharacter != 'all') {
890 $cacheKey .= "_alphabet";
891 $this->fillupPrevNextCache($sort, $cacheKey);
893 elseif ($firstRecord >= $countRow) {
894 $this->fillupPrevNextCache($sort, $cacheKey, $countRow, 500 +
$firstRecord - $countRow);
902 public function addActions(&$rows) {
903 $config = CRM_Core_Config
::singleton();
905 $permissions = array(CRM_Core_Permission
::getPermission());
906 if (CRM_Core_Permission
::check('delete contacts')) {
907 $permissions[] = CRM_Core_Permission
::DELETE
;
909 $mask = CRM_Core_Action
::mask($permissions);
910 // mask value to hide map link if there are not lat/long
911 $mapMask = $mask & 4095;
913 // mask value to hide map link if there are not lat/long
914 $mapMask = $mask & 4095;
916 $links = self
::links($this->_context
, $this->_contextMenu
, $this->_key
);
918 foreach ($rows as $id => & $row) {
919 if (!empty($this->_formValues
['deleted_contacts']) && CRM_Core_Permission
::check('access deleted contacts')
923 'name' => ts('View'),
924 'url' => 'civicrm/contact/view',
925 'qs' => 'reset=1&cid=%%id%%',
926 'class' => 'no-popup',
927 'title' => ts('View Contact Details'),
930 'name' => ts('Restore'),
931 'url' => 'civicrm/contact/view/delete',
932 'qs' => 'reset=1&cid=%%id%%&restore=1',
933 'title' => ts('Restore Contact'),
936 if (CRM_Core_Permission
::check('delete contacts')) {
938 'name' => ts('Delete Permanently'),
939 'url' => 'civicrm/contact/view/delete',
940 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1',
941 'title' => ts('Permanently Delete Contact'),
944 $row['action'] = CRM_Core_Action
::formLink(
947 array('id' => $row['contact_id']),
950 'contact.selector.actions',
955 elseif ((is_numeric(CRM_Utils_Array
::value('geo_code_1', $row))) ||
956 (!empty($row['city']) &&
957 CRM_Utils_Array
::value('state_province', $row)
960 $row['action'] = CRM_Core_Action
::formLink(
963 array('id' => $row['contact_id']),
966 'contact.selector.actions',
972 $row['action'] = CRM_Core_Action
::formLink(
975 array('id' => $row['contact_id']),
978 'contact.selector.actions',
984 // allow components to add more actions
985 CRM_Core_Component
::searchAction($row, $row['contact_id']);
987 if (!empty($row['contact_type_orig'])) {
988 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils
::getImage($row['contact_type_orig'],
989 FALSE, $row['contact_id']);
997 public function removeActions(&$rows) {
998 foreach ($rows as $rid => & $rValue) {
999 unset($rValue['contact_type']);
1000 unset($rValue['action']);
1005 * @param CRM_Utils_Sort $sort
1006 * @param string $cacheKey
1010 public function fillupPrevNextCache($sort, $cacheKey, $start = 0, $end = 500) {
1012 // For custom searches, use the contactIDs method
1013 if (is_a($this, 'CRM_Contact_Selector_Custom')) {
1014 $sql = $this->_search
->contactIDs($start, $end, $sort, TRUE);
1015 $replaceSQL = "SELECT contact_a.id as contact_id";
1016 $coreSearch = FALSE;
1018 // For core searches use the searchQuery method
1020 $sql = $this->_query
->searchQuery($start, $end, $sort, FALSE, $this->_query
->_includeContactIds
,
1022 $replaceSQL = "SELECT contact_a.id as id";
1026 // due to limitations in our search query writer, the above query does not work
1027 // in cases where the query is being sorted on a non-contact table
1028 // this results in a fatal error :(
1029 // see below for the gross hack of trapping the error and not filling
1030 // the prev next cache in this situation
1031 // the other alternative of running the FULL query will just be incredibly inefficient
1032 // and slow things down way too much on large data sets / complex queries
1035 INSERT INTO civicrm_prevnext_cache ( entity_table, entity_id1, entity_id2, cacheKey, data )
1036 SELECT DISTINCT 'civicrm_contact', contact_a.id, contact_a.id, '$cacheKey', contact_a.display_name
1039 $sql = str_replace($replaceSQL, $insertSQL, $sql);
1041 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1042 $result = CRM_Core_DAO
::executeQuery($sql);
1045 if (is_a($result, 'DB_Error')) {
1046 // check if we get error during core search
1048 // in the case of error, try rebuilding cache using full sql which is used for search selector display
1049 // this fixes the bugs reported in CRM-13996 & CRM-14438
1050 $this->rebuildPreNextCache($start, $end, $sort, $cacheKey);
1053 // return if above query fails
1058 // also record an entry in the cache key table, so we can delete it periodically
1059 CRM_Core_BAO_Cache
::setItem($cacheKey, 'CiviCRM Search PrevNextCache', $cacheKey);
1063 * called to rebuild prev next cache using full sql in case of core search ( excluding custom search)
1066 * Start for limit clause.
1068 * End for limit clause.
1069 * @param CRM_Utils_Sort $sort
1070 * @param string $cacheKey
1073 public function rebuildPreNextCache($start, $end, $sort, $cacheKey) {
1074 // generate full SQL
1075 $sql = $this->_query
->searchQuery($start, $end, $sort, FALSE, $this->_query
->_includeContactIds
,
1076 FALSE, FALSE, TRUE);
1078 $dao = CRM_Core_DAO
::executeQuery($sql);
1080 // build insert query, note that currently we build cache for 500 contact records at a time, hence below approach
1081 $insertValues = array();
1082 while ($dao->fetch()) {
1083 $insertValues[] = "('civicrm_contact', {$dao->contact_id}, {$dao->contact_id}, '{$cacheKey}', '" . CRM_Core_DAO
::escapeString($dao->sort_name
) . "')";
1086 //update pre/next cache using single insert query
1087 if (!empty($insertValues)) {
1088 $sql = 'INSERT INTO civicrm_prevnext_cache ( entity_table, entity_id1, entity_id2, cacheKey, data ) VALUES
1089 ' . implode(',', $insertValues);
1091 $result = CRM_Core_DAO
::executeQuery($sql);
1098 public function getQILL() {
1099 return $this->_query
->qill();
1103 * Name of export file.
1105 * @param string $output
1111 public function getExportFileName($output = 'csv') {
1112 return ts('CiviCRM Contact Search');
1116 * Get colunmn headers for search selector.
1120 private static function &_getColumnHeaders() {
1121 if (!isset(self
::$_columnHeaders)) {
1122 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1123 'address_options', TRUE, NULL, TRUE
1126 self
::$_columnHeaders = array(
1127 'contact_type' => array('desc' => ts('Contact Type')),
1128 'sort_name' => array(
1129 'name' => ts('Name'),
1130 'sort' => 'sort_name',
1131 'direction' => CRM_Utils_Sort
::ASCENDING
,
1135 $defaultAddress = array(
1136 'street_address' => array('name' => ts('Address')),
1138 'name' => ts('City'),
1140 'direction' => CRM_Utils_Sort
::DONTCARE
,
1142 'state_province' => array(
1143 'name' => ts('State'),
1144 'sort' => 'state_province',
1145 'direction' => CRM_Utils_Sort
::DONTCARE
,
1147 'postal_code' => array(
1148 'name' => ts('Postal'),
1149 'sort' => 'postal_code',
1150 'direction' => CRM_Utils_Sort
::DONTCARE
,
1153 'name' => ts('Country'),
1154 'sort' => 'country',
1155 'direction' => CRM_Utils_Sort
::DONTCARE
,
1159 foreach ($defaultAddress as $columnName => $column) {
1160 if (!empty($addressOptions[$columnName])) {
1161 self
::$_columnHeaders[$columnName] = $column;
1165 self
::$_columnHeaders['email'] = array(
1166 'name' => ts('Email'),
1168 'direction' => CRM_Utils_Sort
::DONTCARE
,
1171 self
::$_columnHeaders['phone'] = array('name' => ts('Phone'));
1173 return self
::$_columnHeaders;
1177 * @return CRM_Contact_BAO_Query
1179 public function &getQuery() {
1180 return $this->_query
;
1184 * @return CRM_Contact_DAO_Contact
1186 public function alphabetQuery() {
1187 return $this->_query
->searchQuery(NULL, NULL, NULL, FALSE, FALSE, TRUE);
1191 * @param array $params
1193 * @param int $sortID
1194 * @param null $displayRelationshipType
1195 * @param string $queryOperator
1197 * @return CRM_Contact_DAO_Contact
1199 public function contactIDQuery($params, $action, $sortID, $displayRelationshipType = NULL, $queryOperator = 'AND') {
1200 $sortOrder = &$this->getSortOrder($this->_action
);
1201 $sort = new CRM_Utils_Sort($sortOrder, $sortID);
1203 // rectify params to what proximity search expects if there is a value for prox_distance
1204 // CRM-7021 CRM-7905
1205 if (!empty($params)) {
1206 CRM_Contact_BAO_ProximityQuery
::fixInputParams($params);
1209 if (!$displayRelationshipType) {
1210 $query = new CRM_Contact_BAO_Query($params,
1211 $this->_returnProperties
,
1212 NULL, FALSE, FALSE, 1,
1213 FALSE, TRUE, TRUE, NULL,
1218 $query = new CRM_Contact_BAO_Query($params, $this->_returnProperties
,
1219 NULL, FALSE, FALSE, 1,
1220 FALSE, TRUE, TRUE, $displayRelationshipType,
1224 $value = $query->searchQuery(0, 0, $sort,
1225 FALSE, FALSE, FALSE,
1232 * @param $returnProperties
1236 public function &makeProperties(&$returnProperties) {
1237 $properties = array();
1238 foreach ($returnProperties as $name => $value) {
1239 if ($name != 'location') {
1240 // special handling for group and tag
1241 if (in_array($name, array('group', 'tag'))) {
1245 // special handling for notes
1246 if (in_array($name, array('note', 'note_subject', 'note_body'))) {
1250 $properties[] = $name;
1253 // extract all the location stuff
1254 foreach ($value as $n => $v) {
1255 foreach ($v as $n1 => $v1) {
1256 if (!strpos('_id', $n1) && $n1 != 'location_type') {
1257 $properties[] = "{$n}-{$n1}";