3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
37 * This class is used to retrieve and display a range of
38 * contacts that match the given criteria (specifically for
39 * results of advanced search options.
42 class CRM_Contact_Selector
extends CRM_Core_Selector_Base
implements CRM_Core_Selector_API
{
45 * This defines two actions- View and Edit.
50 static $_links = NULL;
53 * We use desc to remind us what that column is, name is used in the tpl
58 static $_columnHeaders;
61 * Properties of contact we're interested in displaying
65 static $_properties = array(
66 'contact_id', 'contact_type', 'contact_sub_type',
67 'sort_name', 'street_address',
68 'city', 'state_province', 'postal_code', 'country',
69 'geo_code_1', 'geo_code_2', 'is_deceased',
70 'email', 'on_hold', 'phone', 'status',
71 'do_not_email', 'do_not_phone', 'do_not_mail',
75 * FormValues is the array returned by exportValues called on
76 * the HTML_QuickForm_Controller for that page.
87 protected $_contextMenu;
90 * Params is the array in a value used by the search query creator
97 * The return properties used for search
101 protected $_returnProperties;
104 * Represent the type of selector
110 protected $_searchContext;
119 protected $_ufGroupID;
122 * The public visible fields to be shown to the user
131 * @param $customSearchClass
132 * @param array $formValues
133 * Array of form values imported.
134 * @param array $params
135 * Array of parameters for query.
136 * @param null $returnProperties
137 * @param \const|int $action - action of search basic or advanced.
139 * @param bool $includeContactIds
140 * @param bool $searchDescendentGroups
141 * @param string $searchContext
142 * @param null $contextMenu
144 * @return CRM_Contact_Selector
146 function __construct(
150 $returnProperties = NULL,
151 $action = CRM_Core_Action
::NONE
,
152 $includeContactIds = FALSE,
153 $searchDescendentGroups = TRUE,
154 $searchContext = 'search',
157 //don't build query constructor, if form is not submitted
158 $force = CRM_Utils_Request
::retrieve('force', 'Boolean', CRM_Core_DAO
::$_nullObject);
159 if (empty($formValues) && !$force) {
163 // submitted form values
164 $this->_formValues
= &$formValues;
165 $this->_params
= &$params;
166 $this->_returnProperties
= &$returnProperties;
167 $this->_contextMenu
= &$contextMenu;
168 $this->_context
= $searchContext;
171 $this->_action
= $action;
173 $this->_searchContext
= $searchContext;
175 $this->_ufGroupID
= CRM_Utils_Array
::value('uf_group_id', $this->_formValues
);
177 if ($this->_ufGroupID
) {
178 $this->_fields
= CRM_Core_BAO_UFGroup
::getListingFields(CRM_Core_Action
::VIEW
,
179 CRM_Core_BAO_UFGroup
::PUBLIC_VISIBILITY |
180 CRM_Core_BAO_UFGroup
::LISTINGS_VISIBILITY
,
181 FALSE, $this->_ufGroupID
183 self
::$_columnHeaders = NULL;
185 $this->_customFields
= CRM_Core_BAO_CustomField
::getFieldsForImport('Individual');
187 $this->_returnProperties
= CRM_Contact_BAO_Contact
::makeHierReturnProperties($this->_fields
);
188 $this->_returnProperties
['contact_type'] = 1;
189 $this->_returnProperties
['contact_sub_type'] = 1;
190 $this->_returnProperties
['sort_name'] = 1;
193 $displayRelationshipType = CRM_Utils_Array
::value('display_relationship_type', $this->_formValues
);
194 $operator = CRM_Utils_Array
::value('operator', $this->_formValues
, 'AND');
196 // rectify params to what proximity search expects if there is a value for prox_distance
198 if (!empty($this->_params
)) {
199 CRM_Contact_BAO_ProximityQuery
::fixInputParams($this->_params
);
202 $this->_query
= new CRM_Contact_BAO_Query(
204 $this->_returnProperties
,
208 CRM_Contact_BAO_Query
::MODE_CONTACTS
,
210 $searchDescendentGroups,
212 $displayRelationshipType,
216 $this->_options
= &$this->_query
->_options
;
220 * This method returns the links that are given for each search row.
221 * currently the links added for each row are
229 public static function &links() {
230 list($context, $contextMenu, $key) = func_get_args();
231 $extraParams = ($key) ?
"&key={$key}" : NULL;
232 $searchContext = ($context) ?
"&context=$context" : NULL;
234 if (!(self
::$_links)) {
235 self
::$_links = array(
236 CRM_Core_Action
::VIEW
=> array(
237 'name' => ts('View'),
238 'url' => 'civicrm/contact/view',
239 'class' => 'no-popup',
240 'qs' => "reset=1&cid=%%id%%{$searchContext}{$extraParams}",
241 'title' => ts('View Contact Details'),
242 'ref' => 'view-contact',
244 CRM_Core_Action
::UPDATE
=> array(
245 'name' => ts('Edit'),
246 'url' => 'civicrm/contact/add',
247 'class' => 'no-popup',
248 'qs' => "reset=1&action=update&cid=%%id%%{$searchContext}{$extraParams}",
249 'title' => ts('Edit Contact Details'),
250 'ref' => 'edit-contact',
254 $config = CRM_Core_Config
::singleton();
255 if ($config->mapAPIKey
&& $config->mapProvider
) {
256 self
::$_links[CRM_Core_Action
::MAP
] = array(
258 'url' => 'civicrm/contact/map',
259 'qs' => "reset=1&cid=%%id%%{$searchContext}{$extraParams}",
260 'title' => ts('Map Contact'),
264 // Adding Context Menu Links in more action
267 foreach ($contextMenu as $key => $value) {
268 $contextVal = '&context=' . $value['key'];
269 if ($value['key'] == 'delete') {
270 $contextVal = $searchContext;
272 $url = "civicrm/contact/view/{$value['key']}";
273 $qs = "reset=1&action=add&cid=%%id%%{$contextVal}{$extraParams}";
274 if ($value['key'] == 'activity') {
275 $qs = "action=browse&selectedChild=activity&reset=1&cid=%%id%%{$extraParams}";
277 elseif ($value['key'] == 'email') {
278 $url = "civicrm/contact/view/activity";
279 $qs = "atype=3&action=add&reset=1&cid=%%id%%{$extraParams}";
282 self
::$_links[$counter++
] = array(
283 'name' => $value['title'],
286 'title' => $value['title'],
287 'ref' => $value['ref'],
288 'class' => CRM_Utils_Array
::value('class', $value),
293 return self
::$_links;
297 * Getter for array of the parameters required for creating pager.
300 * @param array $params
303 public function getPagerParams($action, &$params) {
304 $params['status'] = ts('Contact %%StatusMessage%%');
305 $params['csvString'] = NULL;
306 $params['rowCount'] = CRM_Utils_Pager
::ROWCOUNT
;
308 $params['buttonTop'] = 'PagerTopButton';
309 $params['buttonBottom'] = 'PagerBottomButton';
313 * @param null $action
314 * @param null $output
318 public function &getColHeads($action = NULL, $output = NULL) {
319 $colHeads = self
::_getColumnHeaders();
320 $colHeads[] = array('desc' => ts('Actions'), 'name' => ts('Action'));
325 * Returns the column headers as an array of tuples:
326 * (name, sortName (key to the sort array))
328 * @param string $action
329 * The action being performed.
330 * @param enum $output
331 * What should the result set include (web/email/csv).
333 * @return array the column headers that need to be displayed
335 public function &getColumnHeaders($action = NULL, $output = NULL) {
338 // unset return property elements that we don't care
339 if (!empty($this->_returnProperties
)) {
340 $doNotCareElements = array(
345 foreach ( $doNotCareElements as $value) {
346 unset($this->_returnProperties
[$value]);
350 if ($output == CRM_Core_Selector_Controller
::EXPORT
) {
351 $csvHeaders = array(ts('Contact ID'), ts('Contact Type'));
352 foreach ($this->getColHeads($action, $output) as $column) {
353 if (array_key_exists('name', $column)) {
354 $csvHeaders[] = $column['name'];
357 $headers = $csvHeaders;
359 elseif ($output == CRM_Core_Selector_Controller
::SCREEN
) {
360 $csvHeaders = array(ts('Name'));
361 foreach ($this->getColHeads($action, $output) as $key => $column) {
362 if (array_key_exists('name', $column) &&
364 $column['name'] != ts('Name')
366 $csvHeaders[$key] = $column['name'];
369 $headers = $csvHeaders;
371 elseif ($this->_ufGroupID
) {
372 // we dont use the cached value of column headers
373 // since it potentially changed because of the profile selected
374 static $skipFields = array('group', 'tag');
375 $direction = CRM_Utils_Sort
::ASCENDING
;
377 if (!self
::$_columnHeaders) {
378 self
::$_columnHeaders = array(array('name' => ''),
380 'name' => ts('Name'),
381 'sort' => 'sort_name',
382 'direction' => CRM_Utils_Sort
::ASCENDING
,
386 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
388 foreach ($this->_fields
as $name => $field) {
389 if (!empty($field['in_selector']) &&
390 !in_array($name, $skipFields)
392 if (strpos($name, '-') !== FALSE) {
393 list($fieldName, $lType, $type) = CRM_Utils_System
::explode('-', $name, 3);
395 if ($lType == 'Primary') {
396 $locationTypeName = 1;
399 $locationTypeName = $locationTypes[$lType];
402 if (in_array($fieldName, array(
403 'phone', 'im', 'email'))) {
405 $name = "`$locationTypeName-$fieldName-$type`";
408 $name = "`$locationTypeName-$fieldName`";
412 $name = "`$locationTypeName-$fieldName`";
415 //to handle sort key for Internal contactId.CRM-2289
417 $name = 'contact_id';
420 self
::$_columnHeaders[] = array(
421 'name' => $field['title'],
423 'direction' => $direction,
425 $direction = CRM_Utils_Sort
::DONTCARE
;
430 // if we dont have any valid columns, dont add the implicit ones
431 // this allows the template to check on emptiness of column headers
433 self
::$_columnHeaders = array();
436 self
::$_columnHeaders[] = array('desc' => ts('Actions'), 'name' => ts('Action'));
439 $headers = self
::$_columnHeaders;
441 elseif (!empty($this->_returnProperties
)) {
442 self
::$_columnHeaders = array(array('name' => ''),
444 'name' => ts('Name'),
445 'sort' => 'sort_name',
446 'direction' => CRM_Utils_Sort
::ASCENDING
,
449 $properties = self
::makeProperties($this->_returnProperties
);
451 foreach ($properties as $prop) {
452 if (strpos($prop, '-')) {
453 list($loc, $fld, $phoneType) = CRM_Utils_System
::explode('-', $prop, 3);
454 $title = $this->_query
->_fields
[$fld]['title'];
455 if (trim($phoneType) && !is_numeric($phoneType) && strtolower($phoneType) != $fld) {
456 $title .= "-{$phoneType}";
460 elseif (isset($this->_query
->_fields
[$prop]) && isset($this->_query
->_fields
[$prop]['title'])) {
461 $title = $this->_query
->_fields
[$prop]['title'];
467 self
::$_columnHeaders[] = array('name' => $title, 'sort' => $prop);
469 self
::$_columnHeaders[] = array('name' => ts('Actions'));
470 $headers = self
::$_columnHeaders;
473 $headers = $this->getColHeads($action, $output);
480 * Returns total number of rows for the query.
484 * @return int Total number of rows
486 public function getTotalCount($action) {
487 // Use count from cache during paging/sorting
488 if (!empty($_GET['crmPID']) ||
!empty($_GET['crmSID'])) {
489 $count = CRM_Core_BAO_Cache
::getItem('Search Results Count', $this->_key
);
492 $count = $this->_query
->searchQuery(0, 0, NULL, TRUE);
493 CRM_Core_BAO_Cache
::setItem($count, 'Search Results Count', $this->_key
);
499 * Returns all the rows in the given offset and rowCount
501 * @param enum $action
502 * The action being performed.
504 * The row number to start from.
505 * @param int $rowCount
506 * The number of rows to return.
507 * @param string $sort
508 * The sql string that describes the sort order.
509 * @param enum $output
510 * What should the result set include (web/email/csv).
512 * @return int the total number of rows for this action
514 public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
515 $config = CRM_Core_Config
::singleton();
517 if (($output == CRM_Core_Selector_Controller
::EXPORT ||
518 $output == CRM_Core_Selector_Controller
::SCREEN
520 $this->_formValues
['radio_ts'] == 'ts_sel'
522 $includeContactIds = TRUE;
525 $includeContactIds = FALSE;
528 // note the formvalues were given by CRM_Contact_Form_Search to us
529 // and contain the search criteria (parameters)
530 // note that the default action is basic
532 $cacheKey = $this->buildPrevNextCache($sort);
533 $result = $this->_query
->getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds);
536 $result = $this->_query
->searchQuery($offset, $rowCount, $sort, FALSE, $includeContactIds);
539 // process the result of the query
541 $permissions = array(CRM_Core_Permission
::getPermission());
542 if (CRM_Core_Permission
::check('delete contacts')) {
543 $permissions[] = CRM_Core_Permission
::DELETE
;
545 $mask = CRM_Core_Action
::mask($permissions);
547 // mask value to hide map link if there are not lat/long
548 $mapMask = $mask & 4095;
550 if ($this->_searchContext
== 'smog') {
551 $gc = CRM_Core_SelectValues
::groupContactStatus();
554 if ($this->_ufGroupID
) {
555 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
558 static $skipFields = array('group', 'tag');
559 foreach ($this->_fields
as $key => $field) {
560 if (!empty($field['in_selector']) &&
561 !in_array($key, $skipFields)
563 if (strpos($key, '-') !== FALSE) {
564 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $key, 3);
566 if ($id == 'Primary') {
567 $locationTypeName = 1;
570 $locationTypeName = CRM_Utils_Array
::value($id, $locationTypes);
571 if (!$locationTypeName) {
576 $locationTypeName = str_replace(' ', '_', $locationTypeName);
577 if (in_array($fieldName, array(
578 'phone', 'im', 'email'))) {
580 $names[] = "{$locationTypeName}-{$fieldName}-{$type}";
583 $names[] = "{$locationTypeName}-{$fieldName}";
587 $names[] = "{$locationTypeName}-{$fieldName}";
591 $names[] = $field['name'];
598 elseif (!empty($this->_returnProperties
)) {
599 $names = self
::makeProperties($this->_returnProperties
);
602 $names = self
::$_properties;
605 $multipleSelectFields = array('preferred_communication_method' => 1);
607 $links = self
::links($this->_context
, $this->_contextMenu
, $this->_key
);
609 //check explicitly added contact to a Smart Group.
610 $groupID = CRM_Utils_Array
::key('1', $this->_formValues
['group']);
612 $pseudoconstants = array();
613 // for CRM-3157 purposes
614 if (in_array('world_region', $names)) {
615 $pseudoconstants['world_region'] = array(
616 'dbName' => 'world_region_id',
617 'values' => CRM_Core_PseudoConstant
::worldRegion()
622 while ($result->fetch()) {
624 $this->_query
->convertToPseudoNames($result);
626 // the columns we are interested in
627 foreach ($names as $property) {
628 if ($property == 'status') {
631 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($property)) {
632 $row[$property] = CRM_Core_BAO_CustomField
::getDisplayValue(
640 $multipleSelectFields &&
641 array_key_exists($property, $multipleSelectFields)
644 $paramsNew = array($key => $result->$property);
645 $name = array($key => array('newName' => $key, 'groupName' => $key));
647 CRM_Core_OptionGroup
::lookupValues($paramsNew, $name, FALSE);
648 $row[$key] = $paramsNew[$key];
650 elseif (strpos($property, '-im')) {
651 $row[$property] = $result->$property;
652 if (!empty($result->$property)) {
653 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
654 $providerId = $property . "-provider_id";
655 $providerName = $imProviders[$result->$providerId];
656 $row[$property] = $result->$property . " ({$providerName})";
659 elseif (in_array($property, array(
660 'addressee', 'email_greeting', 'postal_greeting'))) {
661 $greeting = $property . '_display';
662 $row[$property] = $result->$greeting;
664 elseif (isset($pseudoconstants[$property])) {
665 $row[$property] = CRM_Utils_Array
::value(
666 $result->{$pseudoconstants[$property]['dbName']},
667 $pseudoconstants[$property]['values']
670 elseif (strpos($property, '-url') !== FALSE) {
672 $websiteKey = 'website-1';
673 $propertyArray = explode('-', $property);
674 $websiteFld = $websiteKey . '-' . array_pop($propertyArray);
675 if (!empty($result->$websiteFld)) {
676 $websiteTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Website', 'website_type_id');
677 $websiteType = $websiteTypes[$result->{"$websiteKey-website_type_id"}];
678 $websiteValue = $result->$websiteFld;
679 $websiteUrl = "<a href=\"{$websiteValue}\">{$websiteValue} ({$websiteType})</a>";
681 $row[$property] = $websiteUrl;
684 $row[$property] = isset($result->$property) ?
$result->$property : NULL;
688 if (!empty($result->postal_code_suffix
)) {
689 $row['postal_code'] .= "-" . $result->postal_code_suffix
;
692 if ($output != CRM_Core_Selector_Controller
::EXPORT
&&
693 $this->_searchContext
== 'smog'
695 if (empty($result->status
) &&
698 $contactID = $result->contact_id
;
701 'contact_id' => $contactID,
702 'group_id' => $groupID,
705 $gcDefaults = array();
706 CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_GroupContact', $gcParams, $gcDefaults);
708 if (empty($gcDefaults)) {
709 $row['status'] = ts('Smart');
712 $row['status'] = $gc[$gcDefaults['status']];
716 $row['status'] = NULL;
720 $row['status'] = $gc[$result->status
];
724 if ($output != CRM_Core_Selector_Controller
::EXPORT
) {
725 $row['checkbox'] = CRM_Core_Form
::CB_PREFIX
. $result->contact_id
;
727 if (!empty($this->_formValues
['deleted_contacts']) && CRM_Core_Permission
::check('access deleted contacts')
731 'name' => ts('View'),
732 'url' => 'civicrm/contact/view',
733 'qs' => 'reset=1&cid=%%id%%',
734 'class' => 'no-popup',
735 'title' => ts('View Contact Details'),
738 'name' => ts('Restore'),
739 'url' => 'civicrm/contact/view/delete',
740 'qs' => 'reset=1&cid=%%id%%&restore=1',
741 'title' => ts('Restore Contact'),
744 if (CRM_Core_Permission
::check('delete contacts')) {
746 'name' => ts('Delete Permanently'),
747 'url' => 'civicrm/contact/view/delete',
748 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1',
749 'title' => ts('Permanently Delete Contact'),
752 $row['action'] = CRM_Core_Action
::formLink(
755 array('id' => $result->contact_id
),
758 'contact.selector.row',
763 elseif ((is_numeric(CRM_Utils_Array
::value('geo_code_1', $row))) ||
764 ($config->mapGeoCoding
&& !empty($row['city']) &&
765 CRM_Utils_Array
::value('state_province', $row)
768 $row['action'] = CRM_Core_Action
::formLink(
771 array('id' => $result->contact_id
),
774 'contact.selector.row',
780 $row['action'] = CRM_Core_Action
::formLink(
783 array('id' => $result->contact_id
),
786 'contact.selector.row',
792 // allow components to add more actions
793 CRM_Core_Component
::searchAction($row, $result->contact_id
);
795 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils
::getImage($result->contact_sub_type ?
796 $result->contact_sub_type
: $result->contact_type
,
801 $row['contact_type_orig'] = $result->contact_sub_type ?
$result->contact_sub_type
: $result->contact_type
;
802 $row['contact_sub_type'] = $result->contact_sub_type ?
803 CRM_Contact_BAO_ContactType
::contactTypePairs(FALSE, $result->contact_sub_type
, ', ') : $result->contact_sub_type
;
804 $row['contact_id'] = $result->contact_id
;
805 $row['sort_name'] = $result->sort_name
;
806 if (array_key_exists('id', $row)) {
807 $row['id'] = $result->contact_id
;
812 if (in_array($row['contact_id'], $seenIDs) === FALSE) {
813 $seenIDs[] = $row['contact_id'];
822 * @param CRM_Utils_Sort $sort
826 public function buildPrevNextCache($sort) {
827 $cacheKey = 'civicrm search ' . $this->_key
;
829 // We should clear the cache in following conditions:
830 // 1. when starting from scratch, i.e new search
831 // 2. if records are sorted
833 // get current page requested
834 $pageNum = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
836 // get the current sort order
837 $currentSortID = CRM_Utils_Request
::retrieve('crmSID', 'String', CRM_Core_DAO
::$_nullObject);
839 $session = CRM_Core_Session
::singleton();
841 // get previous sort id
842 $previousSortID = $session->get('previousSortID');
844 // check for current != previous to ensure cache is not reset if paging is done without changing
846 if (!$pageNum ||
(!empty($currentSortID) && $currentSortID != $previousSortID) ) {
847 CRM_Core_BAO_PrevNextCache
::deleteItem(NULL, $cacheKey, 'civicrm_contact');
848 // this means it's fresh search, so set pageNum=1
854 // set the current sort as previous sort
855 if (!empty($currentSortID)) {
856 $session->set('previousSortID', $currentSortID);
859 $pageSize = CRM_Utils_Request
::retrieve('crmRowCount', 'Integer', CRM_Core_DAO
::$_nullObject, FALSE, 50);
860 $firstRecord = ($pageNum - 1) * $pageSize;
862 //for alphabetic pagination selection save
863 $sortByCharacter = CRM_Utils_Request
::retrieve('sortByCharacter', 'String', CRM_Core_DAO
::$_nullObject);
865 //for text field pagination selection save
866 $countRow = CRM_Core_BAO_PrevNextCache
::getCount($cacheKey, NULL, "entity_table = 'civicrm_contact'");
868 // $sortByCharacter triggers a refresh in the prevNext cache
869 if ($sortByCharacter && $sortByCharacter != 'all') {
870 $cacheKey .= "_alphabet";
871 $this->fillupPrevNextCache($sort, $cacheKey);
873 elseif ($firstRecord >= $countRow) {
874 $this->fillupPrevNextCache($sort, $cacheKey, $countRow, 500);
882 public function addActions(&$rows) {
883 $config = CRM_Core_Config
::singleton();
885 $permissions = array(CRM_Core_Permission
::getPermission());
886 if (CRM_Core_Permission
::check('delete contacts')) {
887 $permissions[] = CRM_Core_Permission
::DELETE
;
889 $mask = CRM_Core_Action
::mask($permissions);
890 // mask value to hide map link if there are not lat/long
891 $mapMask = $mask & 4095;
893 // mask value to hide map link if there are not lat/long
894 $mapMask = $mask & 4095;
896 $links = self
::links($this->_context
, $this->_contextMenu
, $this->_key
);
899 foreach ($rows as $id => & $row) {
900 if (!empty($this->_formValues
['deleted_contacts']) && CRM_Core_Permission
::check('access deleted contacts')
904 'name' => ts('View'),
905 'url' => 'civicrm/contact/view',
906 'qs' => 'reset=1&cid=%%id%%',
907 'class' => 'no-popup',
908 'title' => ts('View Contact Details'),
911 'name' => ts('Restore'),
912 'url' => 'civicrm/contact/view/delete',
913 'qs' => 'reset=1&cid=%%id%%&restore=1',
914 'title' => ts('Restore Contact'),
917 if (CRM_Core_Permission
::check('delete contacts')) {
919 'name' => ts('Delete Permanently'),
920 'url' => 'civicrm/contact/view/delete',
921 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1',
922 'title' => ts('Permanently Delete Contact'),
925 $row['action'] = CRM_Core_Action
::formLink(
928 array('id' => $row['contact_id']),
931 'contact.selector.actions',
936 elseif ((is_numeric(CRM_Utils_Array
::value('geo_code_1', $row))) ||
937 ($config->mapGeoCoding
&& !empty($row['city']) &&
938 CRM_Utils_Array
::value('state_province', $row)
941 $row['action'] = CRM_Core_Action
::formLink(
944 array('id' => $row['contact_id']),
947 'contact.selector.actions',
953 $row['action'] = CRM_Core_Action
::formLink(
956 array('id' => $row['contact_id']),
959 'contact.selector.actions',
965 // allow components to add more actions
966 CRM_Core_Component
::searchAction($row, $row['contact_id']);
968 if (!empty($row['contact_type_orig'])) {
969 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils
::getImage($row['contact_type_orig'],
970 FALSE, $row['contact_id']);
978 public function removeActions(&$rows) {
979 foreach ($rows as $rid => & $rValue) {
980 unset($rValue['contact_type']);
981 unset($rValue['action']);
986 * @param CRM_Utils_Sort $sort
987 * @param string $cacheKey
991 public function fillupPrevNextCache($sort, $cacheKey, $start = 0, $end = 500) {
993 // For custom searches, use the contactIDs method
994 if (is_a($this, 'CRM_Contact_Selector_Custom')) {
995 $sql = $this->_search
->contactIDs($start, $end, $sort, TRUE);
996 $replaceSQL = "SELECT contact_a.id as contact_id";
999 // For core searches use the searchQuery method
1001 $sql = $this->_query
->searchQuery($start, $end, $sort, FALSE, $this->_query
->_includeContactIds
,
1003 $replaceSQL = "SELECT contact_a.id as id";
1007 // due to limitations in our search query writer, the above query does not work
1008 // in cases where the query is being sorted on a non-contact table
1009 // this results in a fatal error :(
1010 // see below for the gross hack of trapping the error and not filling
1011 // the prev next cache in this situation
1012 // the other alternative of running the FULL query will just be incredibly inefficient
1013 // and slow things down way too much on large data sets / complex queries
1016 INSERT INTO civicrm_prevnext_cache ( entity_table, entity_id1, entity_id2, cacheKey, data )
1017 SELECT DISTINCT 'civicrm_contact', contact_a.id, contact_a.id, '$cacheKey', contact_a.display_name
1020 $sql = str_replace($replaceSQL, $insertSQL, $sql);
1022 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1023 $result = CRM_Core_DAO
::executeQuery($sql);
1026 if (is_a($result, 'DB_Error')) {
1027 // check if we get error during core search
1029 // in the case of error, try rebuilding cache using full sql which is used for search selector display
1030 // this fixes the bugs reported in CRM-13996 & CRM-14438
1031 $this->rebuildPreNextCache($start, $end, $sort, $cacheKey);
1034 // return if above query fails
1039 // also record an entry in the cache key table, so we can delete it periodically
1040 CRM_Core_BAO_Cache
::setItem($cacheKey, 'CiviCRM Search PrevNextCache', $cacheKey);
1044 * This function is called to rebuild prev next cache using full sql in case of core search ( excluding custom search)
1047 * Start for limit clause.
1049 * End for limit clause.
1050 * @param CRM_Utils_Sort $sort
1051 * @param string $cacheKey
1056 public function rebuildPreNextCache($start, $end, $sort, $cacheKey) {
1057 // generate full SQL
1058 $sql = $this->_query
->searchQuery($start, $end, $sort, FALSE, $this->_query
->_includeContactIds
,
1059 FALSE, FALSE, TRUE);
1061 $dao = CRM_Core_DAO
::executeQuery($sql);
1063 // build insert query, note that currently we build cache for 500 contact records at a time, hence below approach
1064 $insertValues = array();
1065 while($dao->fetch()) {
1066 $insertValues[] = "('civicrm_contact', {$dao->contact_id}, {$dao->contact_id}, '{$cacheKey}', '" . CRM_Core_DAO
::escapeString($dao->sort_name
) . "')";
1069 //update pre/next cache using single insert query
1070 if (!empty($insertValues)) {
1071 $sql = 'INSERT INTO civicrm_prevnext_cache ( entity_table, entity_id1, entity_id2, cacheKey, data ) VALUES
1072 '.implode(',', $insertValues);
1074 $result = CRM_Core_DAO
::executeQuery($sql);
1079 * Given the current formValues, gets the query in local
1083 reference) $formValues submitted formValues
1085 * @return array $qill which contains an array of strings
1088 // the current internationalisation is bad, but should more or less work
1089 // for most of "European" languages
1090 public function getQILL() {
1091 return $this->_query
->qill();
1095 * Name of export file.
1097 * @param string $output
1100 * @return string name of the file
1102 public function getExportFileName($output = 'csv') {
1103 return ts('CiviCRM Contact Search');
1107 * Get colunmn headers for search selector
1110 * @return array $_columnHeaders
1112 private static function &_getColumnHeaders() {
1113 if (!isset(self
::$_columnHeaders)) {
1114 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1115 'address_options', TRUE, NULL, TRUE
1118 self
::$_columnHeaders = array(
1119 'contact_type' => array('desc' => ts('Contact Type')),
1120 'sort_name' => array(
1121 'name' => ts('Name'),
1122 'sort' => 'sort_name',
1123 'direction' => CRM_Utils_Sort
::ASCENDING
,
1127 $defaultAddress = array(
1128 'street_address' => array('name' => ts('Address')),
1130 'name' => ts('City'),
1132 'direction' => CRM_Utils_Sort
::DONTCARE
,
1134 'state_province' => array(
1135 'name' => ts('State'),
1136 'sort' => 'state_province',
1137 'direction' => CRM_Utils_Sort
::DONTCARE
,
1139 'postal_code' => array(
1140 'name' => ts('Postal'),
1141 'sort' => 'postal_code',
1142 'direction' => CRM_Utils_Sort
::DONTCARE
,
1145 'name' => ts('Country'),
1146 'sort' => 'country',
1147 'direction' => CRM_Utils_Sort
::DONTCARE
,
1151 foreach ($defaultAddress as $columnName => $column) {
1152 if (!empty($addressOptions[$columnName])) {
1153 self
::$_columnHeaders[$columnName] = $column;
1157 self
::$_columnHeaders['email'] = array(
1158 'name' => ts('Email'),
1160 'direction' => CRM_Utils_Sort
::DONTCARE
,
1163 self
::$_columnHeaders['phone'] = array('name' => ts('Phone'));
1165 return self
::$_columnHeaders;
1169 * @return CRM_Contact_BAO_Query
1171 public function &getQuery() {
1172 return $this->_query
;
1176 * @return CRM_Contact_DAO_Contact
1178 public function alphabetQuery() {
1179 return $this->_query
->searchQuery(NULL, NULL, NULL, FALSE, FALSE, TRUE);
1183 * @param array $params
1185 * @param int $sortID
1186 * @param null $displayRelationshipType
1187 * @param string $queryOperator
1189 * @return CRM_Contact_DAO_Contact
1191 public function contactIDQuery($params, $action, $sortID, $displayRelationshipType = NULL, $queryOperator = 'AND') {
1192 $sortOrder = &$this->getSortOrder($this->_action
);
1193 $sort = new CRM_Utils_Sort($sortOrder, $sortID);
1195 // rectify params to what proximity search expects if there is a value for prox_distance
1196 // CRM-7021 CRM-7905
1197 if (!empty($params)) {
1198 CRM_Contact_BAO_ProximityQuery
::fixInputParams($params);
1201 if (!$displayRelationshipType) {
1202 $query = new CRM_Contact_BAO_Query($params,
1203 $this->_returnProperties
,
1204 NULL, FALSE, FALSE, 1,
1205 FALSE, TRUE, TRUE, NULL,
1210 $query = new CRM_Contact_BAO_Query($params, $this->_returnProperties
,
1211 NULL, FALSE, FALSE, 1,
1212 FALSE, TRUE, TRUE, $displayRelationshipType,
1216 $value = $query->searchQuery(0, 0, $sort,
1217 FALSE, FALSE, FALSE,
1224 * @param $returnProperties
1228 public function &makeProperties(&$returnProperties) {
1229 $properties = array();
1230 foreach ($returnProperties as $name => $value) {
1231 if ($name != 'location') {
1232 // special handling for group and tag
1233 if (in_array($name, array('group', 'tag'))) {
1237 // special handling for notes
1238 if (in_array($name, array('note', 'note_subject', 'note_body'))) {
1242 $properties[] = $name;
1245 // extract all the location stuff
1246 foreach ($value as $n => $v) {
1247 foreach ($v as $n1 => $v1) {
1248 if (!strpos('_id', $n1) && $n1 != 'location_type') {
1249 $properties[] = "{$n}-{$n1}";