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 ?
$result->contact_sub_type
: $result->contact_type
,
800 $row['contact_type_orig'] = $result->contact_sub_type ?
$result->contact_sub_type
: $result->contact_type
;
801 $row['contact_sub_type'] = $result->contact_sub_type ? CRM_Contact_BAO_ContactType
::contactTypePairs(FALSE, $result->contact_sub_type
, ', ') : $result->contact_sub_type
;
802 $row['contact_id'] = $result->contact_id
;
803 $row['sort_name'] = $result->sort_name
;
804 if (array_key_exists('id', $row)) {
805 $row['id'] = $result->contact_id
;
810 if (in_array($row['contact_id'], $seenIDs) === FALSE) {
811 $seenIDs[] = $row['contact_id'];
820 * @param CRM_Utils_Sort $sort
824 public function buildPrevNextCache($sort) {
825 $cacheKey = 'civicrm search ' . $this->_key
;
827 // We should clear the cache in following conditions:
828 // 1. when starting from scratch, i.e new search
829 // 2. if records are sorted
831 // get current page requested
832 $pageNum = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
834 // get the current sort order
835 $currentSortID = CRM_Utils_Request
::retrieve('crmSID', 'String', CRM_Core_DAO
::$_nullObject);
837 $session = CRM_Core_Session
::singleton();
839 // get previous sort id
840 $previousSortID = $session->get('previousSortID');
842 // check for current != previous to ensure cache is not reset if paging is done without changing
844 if (!$pageNum ||
(!empty($currentSortID) && $currentSortID != $previousSortID)) {
845 CRM_Core_BAO_PrevNextCache
::deleteItem(NULL, $cacheKey, 'civicrm_contact');
846 // this means it's fresh search, so set pageNum=1
852 // set the current sort as previous sort
853 if (!empty($currentSortID)) {
854 $session->set('previousSortID', $currentSortID);
857 $pageSize = CRM_Utils_Request
::retrieve('crmRowCount', 'Integer', CRM_Core_DAO
::$_nullObject, FALSE, 50);
858 $firstRecord = ($pageNum - 1) * $pageSize;
860 //for alphabetic pagination selection save
861 $sortByCharacter = CRM_Utils_Request
::retrieve('sortByCharacter', 'String', CRM_Core_DAO
::$_nullObject);
863 //for text field pagination selection save
864 $countRow = CRM_Core_BAO_PrevNextCache
::getCount($cacheKey, NULL, "entity_table = 'civicrm_contact'");
866 // $sortByCharacter triggers a refresh in the prevNext cache
867 if ($sortByCharacter && $sortByCharacter != 'all') {
868 $cacheKey .= "_alphabet";
869 $this->fillupPrevNextCache($sort, $cacheKey);
871 elseif ($firstRecord >= $countRow) {
872 $this->fillupPrevNextCache($sort, $cacheKey, $countRow, 500);
880 public function addActions(&$rows) {
881 $config = CRM_Core_Config
::singleton();
883 $permissions = array(CRM_Core_Permission
::getPermission());
884 if (CRM_Core_Permission
::check('delete contacts')) {
885 $permissions[] = CRM_Core_Permission
::DELETE
;
887 $mask = CRM_Core_Action
::mask($permissions);
888 // mask value to hide map link if there are not lat/long
889 $mapMask = $mask & 4095;
891 // mask value to hide map link if there are not lat/long
892 $mapMask = $mask & 4095;
894 $links = self
::links($this->_context
, $this->_contextMenu
, $this->_key
);
896 foreach ($rows as $id => & $row) {
897 if (!empty($this->_formValues
['deleted_contacts']) && CRM_Core_Permission
::check('access deleted contacts')
901 'name' => ts('View'),
902 'url' => 'civicrm/contact/view',
903 'qs' => 'reset=1&cid=%%id%%',
904 'class' => 'no-popup',
905 'title' => ts('View Contact Details'),
908 'name' => ts('Restore'),
909 'url' => 'civicrm/contact/view/delete',
910 'qs' => 'reset=1&cid=%%id%%&restore=1',
911 'title' => ts('Restore Contact'),
914 if (CRM_Core_Permission
::check('delete contacts')) {
916 'name' => ts('Delete Permanently'),
917 'url' => 'civicrm/contact/view/delete',
918 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1',
919 'title' => ts('Permanently Delete Contact'),
922 $row['action'] = CRM_Core_Action
::formLink(
925 array('id' => $row['contact_id']),
928 'contact.selector.actions',
933 elseif ((is_numeric(CRM_Utils_Array
::value('geo_code_1', $row))) ||
934 ($config->mapGeoCoding
&& !empty($row['city']) &&
935 CRM_Utils_Array
::value('state_province', $row)
938 $row['action'] = CRM_Core_Action
::formLink(
941 array('id' => $row['contact_id']),
944 'contact.selector.actions',
950 $row['action'] = CRM_Core_Action
::formLink(
953 array('id' => $row['contact_id']),
956 'contact.selector.actions',
962 // allow components to add more actions
963 CRM_Core_Component
::searchAction($row, $row['contact_id']);
965 if (!empty($row['contact_type_orig'])) {
966 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils
::getImage($row['contact_type_orig'],
967 FALSE, $row['contact_id']);
975 public function removeActions(&$rows) {
976 foreach ($rows as $rid => & $rValue) {
977 unset($rValue['contact_type']);
978 unset($rValue['action']);
983 * @param CRM_Utils_Sort $sort
984 * @param string $cacheKey
988 public function fillupPrevNextCache($sort, $cacheKey, $start = 0, $end = 500) {
990 // For custom searches, use the contactIDs method
991 if (is_a($this, 'CRM_Contact_Selector_Custom')) {
992 $sql = $this->_search
->contactIDs($start, $end, $sort, TRUE);
993 $replaceSQL = "SELECT contact_a.id as contact_id";
996 // For core searches use the searchQuery method
998 $sql = $this->_query
->searchQuery($start, $end, $sort, FALSE, $this->_query
->_includeContactIds
,
1000 $replaceSQL = "SELECT contact_a.id as id";
1004 // due to limitations in our search query writer, the above query does not work
1005 // in cases where the query is being sorted on a non-contact table
1006 // this results in a fatal error :(
1007 // see below for the gross hack of trapping the error and not filling
1008 // the prev next cache in this situation
1009 // the other alternative of running the FULL query will just be incredibly inefficient
1010 // and slow things down way too much on large data sets / complex queries
1013 INSERT INTO civicrm_prevnext_cache ( entity_table, entity_id1, entity_id2, cacheKey, data )
1014 SELECT DISTINCT 'civicrm_contact', contact_a.id, contact_a.id, '$cacheKey', contact_a.display_name
1017 $sql = str_replace($replaceSQL, $insertSQL, $sql);
1019 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1020 $result = CRM_Core_DAO
::executeQuery($sql);
1023 if (is_a($result, 'DB_Error')) {
1024 // check if we get error during core search
1026 // in the case of error, try rebuilding cache using full sql which is used for search selector display
1027 // this fixes the bugs reported in CRM-13996 & CRM-14438
1028 $this->rebuildPreNextCache($start, $end, $sort, $cacheKey);
1031 // return if above query fails
1036 // also record an entry in the cache key table, so we can delete it periodically
1037 CRM_Core_BAO_Cache
::setItem($cacheKey, 'CiviCRM Search PrevNextCache', $cacheKey);
1041 * This function is called to rebuild prev next cache using full sql in case of core search ( excluding custom search)
1044 * Start for limit clause.
1046 * End for limit clause.
1047 * @param CRM_Utils_Sort $sort
1048 * @param string $cacheKey
1053 public function rebuildPreNextCache($start, $end, $sort, $cacheKey) {
1054 // generate full SQL
1055 $sql = $this->_query
->searchQuery($start, $end, $sort, FALSE, $this->_query
->_includeContactIds
,
1056 FALSE, FALSE, TRUE);
1058 $dao = CRM_Core_DAO
::executeQuery($sql);
1060 // build insert query, note that currently we build cache for 500 contact records at a time, hence below approach
1061 $insertValues = array();
1062 while ($dao->fetch()) {
1063 $insertValues[] = "('civicrm_contact', {$dao->contact_id}, {$dao->contact_id}, '{$cacheKey}', '" . CRM_Core_DAO
::escapeString($dao->sort_name
) . "')";
1066 //update pre/next cache using single insert query
1067 if (!empty($insertValues)) {
1068 $sql = 'INSERT INTO civicrm_prevnext_cache ( entity_table, entity_id1, entity_id2, cacheKey, data ) VALUES
1069 ' . implode(',', $insertValues);
1071 $result = CRM_Core_DAO
::executeQuery($sql);
1076 * Given the current formValues, gets the query in local
1080 reference) $formValues submitted formValues
1082 * @return array $qill which contains an array of strings
1085 // the current internationalisation is bad, but should more or less work
1086 // for most of "European" languages
1087 public function getQILL() {
1088 return $this->_query
->qill();
1092 * Name of export file.
1094 * @param string $output
1097 * @return string name of the file
1099 public function getExportFileName($output = 'csv') {
1100 return ts('CiviCRM Contact Search');
1104 * Get colunmn headers for search selector
1107 * @return array $_columnHeaders
1109 private static function &_getColumnHeaders() {
1110 if (!isset(self
::$_columnHeaders)) {
1111 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1112 'address_options', TRUE, NULL, TRUE
1115 self
::$_columnHeaders = array(
1116 'contact_type' => array('desc' => ts('Contact Type')),
1117 'sort_name' => array(
1118 'name' => ts('Name'),
1119 'sort' => 'sort_name',
1120 'direction' => CRM_Utils_Sort
::ASCENDING
,
1124 $defaultAddress = array(
1125 'street_address' => array('name' => ts('Address')),
1127 'name' => ts('City'),
1129 'direction' => CRM_Utils_Sort
::DONTCARE
,
1131 'state_province' => array(
1132 'name' => ts('State'),
1133 'sort' => 'state_province',
1134 'direction' => CRM_Utils_Sort
::DONTCARE
,
1136 'postal_code' => array(
1137 'name' => ts('Postal'),
1138 'sort' => 'postal_code',
1139 'direction' => CRM_Utils_Sort
::DONTCARE
,
1142 'name' => ts('Country'),
1143 'sort' => 'country',
1144 'direction' => CRM_Utils_Sort
::DONTCARE
,
1148 foreach ($defaultAddress as $columnName => $column) {
1149 if (!empty($addressOptions[$columnName])) {
1150 self
::$_columnHeaders[$columnName] = $column;
1154 self
::$_columnHeaders['email'] = array(
1155 'name' => ts('Email'),
1157 'direction' => CRM_Utils_Sort
::DONTCARE
,
1160 self
::$_columnHeaders['phone'] = array('name' => ts('Phone'));
1162 return self
::$_columnHeaders;
1166 * @return CRM_Contact_BAO_Query
1168 public function &getQuery() {
1169 return $this->_query
;
1173 * @return CRM_Contact_DAO_Contact
1175 public function alphabetQuery() {
1176 return $this->_query
->searchQuery(NULL, NULL, NULL, FALSE, FALSE, TRUE);
1180 * @param array $params
1182 * @param int $sortID
1183 * @param null $displayRelationshipType
1184 * @param string $queryOperator
1186 * @return CRM_Contact_DAO_Contact
1188 public function contactIDQuery($params, $action, $sortID, $displayRelationshipType = NULL, $queryOperator = 'AND') {
1189 $sortOrder = &$this->getSortOrder($this->_action
);
1190 $sort = new CRM_Utils_Sort($sortOrder, $sortID);
1192 // rectify params to what proximity search expects if there is a value for prox_distance
1193 // CRM-7021 CRM-7905
1194 if (!empty($params)) {
1195 CRM_Contact_BAO_ProximityQuery
::fixInputParams($params);
1198 if (!$displayRelationshipType) {
1199 $query = new CRM_Contact_BAO_Query($params,
1200 $this->_returnProperties
,
1201 NULL, FALSE, FALSE, 1,
1202 FALSE, TRUE, TRUE, NULL,
1207 $query = new CRM_Contact_BAO_Query($params, $this->_returnProperties
,
1208 NULL, FALSE, FALSE, 1,
1209 FALSE, TRUE, TRUE, $displayRelationshipType,
1213 $value = $query->searchQuery(0, 0, $sort,
1214 FALSE, FALSE, FALSE,
1221 * @param $returnProperties
1225 public function &makeProperties(&$returnProperties) {
1226 $properties = array();
1227 foreach ($returnProperties as $name => $value) {
1228 if ($name != 'location') {
1229 // special handling for group and tag
1230 if (in_array($name, array('group', 'tag'))) {
1234 // special handling for notes
1235 if (in_array($name, array('note', 'note_subject', 'note_body'))) {
1239 $properties[] = $name;
1242 // extract all the location stuff
1243 foreach ($value as $n => $v) {
1244 foreach ($v as $n1 => $v1) {
1245 if (!strpos('_id', $n1) && $n1 != 'location_type') {
1246 $properties[] = "{$n}-{$n1}";