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 array of form values imported
133 * @param array $params array of parameters for query
134 * @param null $returnProperties
135 * @param \const|int $action - action of search basic or advanced.
137 * @param bool $includeContactIds
138 * @param bool $searchDescendentGroups
139 * @param string $searchContext
140 * @param null $contextMenu
142 * @return CRM_Contact_Selector
144 function __construct(
148 $returnProperties = NULL,
149 $action = CRM_Core_Action
::NONE
,
150 $includeContactIds = FALSE,
151 $searchDescendentGroups = TRUE,
152 $searchContext = 'search',
155 //don't build query constructor, if form is not submitted
156 $force = CRM_Utils_Request
::retrieve('force', 'Boolean', CRM_Core_DAO
::$_nullObject);
157 if (empty($formValues) && !$force) {
161 // submitted form values
162 $this->_formValues
= &$formValues;
163 $this->_params
= &$params;
164 $this->_returnProperties
= &$returnProperties;
165 $this->_contextMenu
= &$contextMenu;
166 $this->_context
= $searchContext;
169 $this->_action
= $action;
171 $this->_searchContext
= $searchContext;
173 $this->_ufGroupID
= CRM_Utils_Array
::value('uf_group_id', $this->_formValues
);
175 if ($this->_ufGroupID
) {
176 $this->_fields
= CRM_Core_BAO_UFGroup
::getListingFields(CRM_Core_Action
::VIEW
,
177 CRM_Core_BAO_UFGroup
::PUBLIC_VISIBILITY |
178 CRM_Core_BAO_UFGroup
::LISTINGS_VISIBILITY
,
179 FALSE, $this->_ufGroupID
181 self
::$_columnHeaders = NULL;
183 $this->_customFields
= CRM_Core_BAO_CustomField
::getFieldsForImport('Individual');
185 $this->_returnProperties
= CRM_Contact_BAO_Contact
::makeHierReturnProperties($this->_fields
);
186 $this->_returnProperties
['contact_type'] = 1;
187 $this->_returnProperties
['contact_sub_type'] = 1;
188 $this->_returnProperties
['sort_name'] = 1;
191 $displayRelationshipType = CRM_Utils_Array
::value('display_relationship_type', $this->_formValues
);
192 $operator = CRM_Utils_Array
::value('operator', $this->_formValues
, 'AND');
194 // rectify params to what proximity search expects if there is a value for prox_distance
196 if (!empty($this->_params
)) {
197 CRM_Contact_BAO_ProximityQuery
::fixInputParams($this->_params
);
200 $this->_query
= new CRM_Contact_BAO_Query(
202 $this->_returnProperties
,
206 CRM_Contact_BAO_Query
::MODE_CONTACTS
,
208 $searchDescendentGroups,
210 $displayRelationshipType,
214 $this->_options
= &$this->_query
->_options
;
218 * This method returns the links that are given for each search row.
219 * currently the links added for each row are
227 public static function &links() {
228 list($context, $contextMenu, $key) = func_get_args();
229 $extraParams = ($key) ?
"&key={$key}" : NULL;
230 $searchContext = ($context) ?
"&context=$context" : NULL;
232 if (!(self
::$_links)) {
233 self
::$_links = array(
234 CRM_Core_Action
::VIEW
=> array(
235 'name' => ts('View'),
236 'url' => 'civicrm/contact/view',
237 'class' => 'no-popup',
238 'qs' => "reset=1&cid=%%id%%{$searchContext}{$extraParams}",
239 'title' => ts('View Contact Details'),
240 'ref' => 'view-contact',
242 CRM_Core_Action
::UPDATE
=> array(
243 'name' => ts('Edit'),
244 'url' => 'civicrm/contact/add',
245 'class' => 'no-popup',
246 'qs' => "reset=1&action=update&cid=%%id%%{$searchContext}{$extraParams}",
247 'title' => ts('Edit Contact Details'),
248 'ref' => 'edit-contact',
252 $config = CRM_Core_Config
::singleton();
253 if ($config->mapAPIKey
&& $config->mapProvider
) {
254 self
::$_links[CRM_Core_Action
::MAP
] = array(
256 'url' => 'civicrm/contact/map',
257 'qs' => "reset=1&cid=%%id%%{$searchContext}{$extraParams}",
258 'title' => ts('Map Contact'),
262 // Adding Context Menu Links in more action
265 foreach ($contextMenu as $key => $value) {
266 $contextVal = '&context=' . $value['key'];
267 if ($value['key'] == 'delete') {
268 $contextVal = $searchContext;
270 $url = "civicrm/contact/view/{$value['key']}";
271 $qs = "reset=1&action=add&cid=%%id%%{$contextVal}{$extraParams}";
272 if ($value['key'] == 'activity') {
273 $qs = "action=browse&selectedChild=activity&reset=1&cid=%%id%%{$extraParams}";
275 elseif ($value['key'] == 'email') {
276 $url = "civicrm/contact/view/activity";
277 $qs = "atype=3&action=add&reset=1&cid=%%id%%{$extraParams}";
280 self
::$_links[$counter++
] = array(
281 'name' => $value['title'],
284 'title' => $value['title'],
285 'ref' => $value['ref'],
286 'class' => CRM_Utils_Array
::value('class', $value),
291 return self
::$_links;
295 * Getter for array of the parameters required for creating pager.
298 * @param array $params
301 public function getPagerParams($action, &$params) {
302 $params['status'] = ts('Contact %%StatusMessage%%');
303 $params['csvString'] = NULL;
304 $params['rowCount'] = CRM_Utils_Pager
::ROWCOUNT
;
306 $params['buttonTop'] = 'PagerTopButton';
307 $params['buttonBottom'] = 'PagerBottomButton';
311 * @param null $action
312 * @param null $output
316 public function &getColHeads($action = NULL, $output = NULL) {
317 $colHeads = self
::_getColumnHeaders();
318 $colHeads[] = array('desc' => ts('Actions'), 'name' => ts('Action'));
323 * Returns the column headers as an array of tuples:
324 * (name, sortName (key to the sort array))
326 * @param string $action the action being performed
327 * @param enum $output what should the result set include (web/email/csv)
329 * @return array the column headers that need to be displayed
331 public function &getColumnHeaders($action = NULL, $output = NULL) {
334 // unset return property elements that we don't care
335 if (!empty($this->_returnProperties
)) {
336 $doNotCareElements = array(
341 foreach ( $doNotCareElements as $value) {
342 unset($this->_returnProperties
[$value]);
346 if ($output == CRM_Core_Selector_Controller
::EXPORT
) {
347 $csvHeaders = array(ts('Contact ID'), ts('Contact Type'));
348 foreach ($this->getColHeads($action, $output) as $column) {
349 if (array_key_exists('name', $column)) {
350 $csvHeaders[] = $column['name'];
353 $headers = $csvHeaders;
355 elseif ($output == CRM_Core_Selector_Controller
::SCREEN
) {
356 $csvHeaders = array(ts('Name'));
357 foreach ($this->getColHeads($action, $output) as $key => $column) {
358 if (array_key_exists('name', $column) &&
360 $column['name'] != ts('Name')
362 $csvHeaders[$key] = $column['name'];
365 $headers = $csvHeaders;
367 elseif ($this->_ufGroupID
) {
368 // we dont use the cached value of column headers
369 // since it potentially changed because of the profile selected
370 static $skipFields = array('group', 'tag');
371 $direction = CRM_Utils_Sort
::ASCENDING
;
373 if (!self
::$_columnHeaders) {
374 self
::$_columnHeaders = array(array('name' => ''),
376 'name' => ts('Name'),
377 'sort' => 'sort_name',
378 'direction' => CRM_Utils_Sort
::ASCENDING
,
382 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
384 foreach ($this->_fields
as $name => $field) {
385 if (!empty($field['in_selector']) &&
386 !in_array($name, $skipFields)
388 if (strpos($name, '-') !== FALSE) {
389 list($fieldName, $lType, $type) = CRM_Utils_System
::explode('-', $name, 3);
391 if ($lType == 'Primary') {
392 $locationTypeName = 1;
395 $locationTypeName = $locationTypes[$lType];
398 if (in_array($fieldName, array(
399 'phone', 'im', 'email'))) {
401 $name = "`$locationTypeName-$fieldName-$type`";
404 $name = "`$locationTypeName-$fieldName`";
408 $name = "`$locationTypeName-$fieldName`";
411 //to handle sort key for Internal contactId.CRM-2289
413 $name = 'contact_id';
416 self
::$_columnHeaders[] = array(
417 'name' => $field['title'],
419 'direction' => $direction,
421 $direction = CRM_Utils_Sort
::DONTCARE
;
426 // if we dont have any valid columns, dont add the implicit ones
427 // this allows the template to check on emptiness of column headers
429 self
::$_columnHeaders = array();
432 self
::$_columnHeaders[] = array('desc' => ts('Actions'), 'name' => ts('Action'));
435 $headers = self
::$_columnHeaders;
437 elseif (!empty($this->_returnProperties
)) {
438 self
::$_columnHeaders = array(array('name' => ''),
440 'name' => ts('Name'),
441 'sort' => 'sort_name',
442 'direction' => CRM_Utils_Sort
::ASCENDING
,
445 $properties = self
::makeProperties($this->_returnProperties
);
447 foreach ($properties as $prop) {
448 if (strpos($prop, '-')) {
449 list($loc, $fld, $phoneType) = CRM_Utils_System
::explode('-', $prop, 3);
450 $title = $this->_query
->_fields
[$fld]['title'];
451 if (trim($phoneType) && !is_numeric($phoneType) && strtolower($phoneType) != $fld) {
452 $title .= "-{$phoneType}";
456 elseif (isset($this->_query
->_fields
[$prop]) && isset($this->_query
->_fields
[$prop]['title'])) {
457 $title = $this->_query
->_fields
[$prop]['title'];
463 self
::$_columnHeaders[] = array('name' => $title, 'sort' => $prop);
465 self
::$_columnHeaders[] = array('name' => ts('Actions'));
466 $headers = self
::$_columnHeaders;
469 $headers = $this->getColHeads($action, $output);
476 * Returns total number of rows for the query.
480 * @return int Total number of rows
482 public function getTotalCount($action) {
483 // Use count from cache during paging/sorting
484 if (!empty($_GET['crmPID']) ||
!empty($_GET['crmSID'])) {
485 $count = CRM_Core_BAO_Cache
::getItem('Search Results Count', $this->_key
);
488 $count = $this->_query
->searchQuery(0, 0, NULL, TRUE);
489 CRM_Core_BAO_Cache
::setItem($count, 'Search Results Count', $this->_key
);
495 * Returns all the rows in the given offset and rowCount
497 * @param enum $action the action being performed
498 * @param int $offset the row number to start from
499 * @param int $rowCount the number of rows to return
500 * @param string $sort the sql string that describes the sort order
501 * @param enum $output what should the result set include (web/email/csv)
503 * @return int the total number of rows for this action
505 public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
506 $config = CRM_Core_Config
::singleton();
508 if (($output == CRM_Core_Selector_Controller
::EXPORT ||
509 $output == CRM_Core_Selector_Controller
::SCREEN
511 $this->_formValues
['radio_ts'] == 'ts_sel'
513 $includeContactIds = TRUE;
516 $includeContactIds = FALSE;
519 // note the formvalues were given by CRM_Contact_Form_Search to us
520 // and contain the search criteria (parameters)
521 // note that the default action is basic
523 $cacheKey = $this->buildPrevNextCache($sort);
524 $result = $this->_query
->getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds);
527 $result = $this->_query
->searchQuery($offset, $rowCount, $sort, FALSE, $includeContactIds);
530 // process the result of the query
532 $permissions = array(CRM_Core_Permission
::getPermission());
533 if (CRM_Core_Permission
::check('delete contacts')) {
534 $permissions[] = CRM_Core_Permission
::DELETE
;
536 $mask = CRM_Core_Action
::mask($permissions);
538 // mask value to hide map link if there are not lat/long
539 $mapMask = $mask & 4095;
541 if ($this->_searchContext
== 'smog') {
542 $gc = CRM_Core_SelectValues
::groupContactStatus();
545 if ($this->_ufGroupID
) {
546 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
549 static $skipFields = array('group', 'tag');
550 foreach ($this->_fields
as $key => $field) {
551 if (!empty($field['in_selector']) &&
552 !in_array($key, $skipFields)
554 if (strpos($key, '-') !== FALSE) {
555 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $key, 3);
557 if ($id == 'Primary') {
558 $locationTypeName = 1;
561 $locationTypeName = CRM_Utils_Array
::value($id, $locationTypes);
562 if (!$locationTypeName) {
567 $locationTypeName = str_replace(' ', '_', $locationTypeName);
568 if (in_array($fieldName, array(
569 'phone', 'im', 'email'))) {
571 $names[] = "{$locationTypeName}-{$fieldName}-{$type}";
574 $names[] = "{$locationTypeName}-{$fieldName}";
578 $names[] = "{$locationTypeName}-{$fieldName}";
582 $names[] = $field['name'];
589 elseif (!empty($this->_returnProperties
)) {
590 $names = self
::makeProperties($this->_returnProperties
);
593 $names = self
::$_properties;
596 $multipleSelectFields = array('preferred_communication_method' => 1);
598 $links = self
::links($this->_context
, $this->_contextMenu
, $this->_key
);
600 //check explicitly added contact to a Smart Group.
601 $groupID = CRM_Utils_Array
::key('1', $this->_formValues
['group']);
603 $pseudoconstants = array();
604 // for CRM-3157 purposes
605 if (in_array('world_region', $names)) {
606 $pseudoconstants['world_region'] = array(
607 'dbName' => 'world_region_id',
608 'values' => CRM_Core_PseudoConstant
::worldRegion()
613 while ($result->fetch()) {
615 $this->_query
->convertToPseudoNames($result);
617 // the columns we are interested in
618 foreach ($names as $property) {
619 if ($property == 'status') {
622 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($property)) {
623 $row[$property] = CRM_Core_BAO_CustomField
::getDisplayValue(
631 $multipleSelectFields &&
632 array_key_exists($property, $multipleSelectFields)
635 $paramsNew = array($key => $result->$property);
636 $name = array($key => array('newName' => $key, 'groupName' => $key));
638 CRM_Core_OptionGroup
::lookupValues($paramsNew, $name, FALSE);
639 $row[$key] = $paramsNew[$key];
641 elseif (strpos($property, '-im')) {
642 $row[$property] = $result->$property;
643 if (!empty($result->$property)) {
644 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
645 $providerId = $property . "-provider_id";
646 $providerName = $imProviders[$result->$providerId];
647 $row[$property] = $result->$property . " ({$providerName})";
650 elseif (in_array($property, array(
651 'addressee', 'email_greeting', 'postal_greeting'))) {
652 $greeting = $property . '_display';
653 $row[$property] = $result->$greeting;
655 elseif (isset($pseudoconstants[$property])) {
656 $row[$property] = CRM_Utils_Array
::value(
657 $result->{$pseudoconstants[$property]['dbName']},
658 $pseudoconstants[$property]['values']
661 elseif (strpos($property, '-url') !== FALSE) {
663 $websiteKey = 'website-1';
664 $propertyArray = explode('-', $property);
665 $websiteFld = $websiteKey . '-' . array_pop($propertyArray);
666 if (!empty($result->$websiteFld)) {
667 $websiteTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Website', 'website_type_id');
668 $websiteType = $websiteTypes[$result->{"$websiteKey-website_type_id"}];
669 $websiteValue = $result->$websiteFld;
670 $websiteUrl = "<a href=\"{$websiteValue}\">{$websiteValue} ({$websiteType})</a>";
672 $row[$property] = $websiteUrl;
675 $row[$property] = isset($result->$property) ?
$result->$property : NULL;
679 if (!empty($result->postal_code_suffix
)) {
680 $row['postal_code'] .= "-" . $result->postal_code_suffix
;
683 if ($output != CRM_Core_Selector_Controller
::EXPORT
&&
684 $this->_searchContext
== 'smog'
686 if (empty($result->status
) &&
689 $contactID = $result->contact_id
;
692 'contact_id' => $contactID,
693 'group_id' => $groupID,
696 $gcDefaults = array();
697 CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_GroupContact', $gcParams, $gcDefaults);
699 if (empty($gcDefaults)) {
700 $row['status'] = ts('Smart');
703 $row['status'] = $gc[$gcDefaults['status']];
707 $row['status'] = NULL;
711 $row['status'] = $gc[$result->status
];
715 if ($output != CRM_Core_Selector_Controller
::EXPORT
) {
716 $row['checkbox'] = CRM_Core_Form
::CB_PREFIX
. $result->contact_id
;
718 if (!empty($this->_formValues
['deleted_contacts']) && CRM_Core_Permission
::check('access deleted contacts')
722 'name' => ts('View'),
723 'url' => 'civicrm/contact/view',
724 'qs' => 'reset=1&cid=%%id%%',
725 'class' => 'no-popup',
726 'title' => ts('View Contact Details'),
729 'name' => ts('Restore'),
730 'url' => 'civicrm/contact/view/delete',
731 'qs' => 'reset=1&cid=%%id%%&restore=1',
732 'title' => ts('Restore Contact'),
735 if (CRM_Core_Permission
::check('delete contacts')) {
737 'name' => ts('Delete Permanently'),
738 'url' => 'civicrm/contact/view/delete',
739 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1',
740 'title' => ts('Permanently Delete Contact'),
743 $row['action'] = CRM_Core_Action
::formLink(
746 array('id' => $result->contact_id
),
749 'contact.selector.row',
754 elseif ((is_numeric(CRM_Utils_Array
::value('geo_code_1', $row))) ||
755 ($config->mapGeoCoding
&& !empty($row['city']) &&
756 CRM_Utils_Array
::value('state_province', $row)
759 $row['action'] = CRM_Core_Action
::formLink(
762 array('id' => $result->contact_id
),
765 'contact.selector.row',
771 $row['action'] = CRM_Core_Action
::formLink(
774 array('id' => $result->contact_id
),
777 'contact.selector.row',
783 // allow components to add more actions
784 CRM_Core_Component
::searchAction($row, $result->contact_id
);
786 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils
::getImage($result->contact_sub_type ?
787 $result->contact_sub_type
: $result->contact_type
,
792 $row['contact_type_orig'] = $result->contact_sub_type ?
$result->contact_sub_type
: $result->contact_type
;
793 $row['contact_sub_type'] = $result->contact_sub_type ?
794 CRM_Contact_BAO_ContactType
::contactTypePairs(FALSE, $result->contact_sub_type
, ', ') : $result->contact_sub_type
;
795 $row['contact_id'] = $result->contact_id
;
796 $row['sort_name'] = $result->sort_name
;
797 if (array_key_exists('id', $row)) {
798 $row['id'] = $result->contact_id
;
803 if (in_array($row['contact_id'], $seenIDs) === FALSE) {
804 $seenIDs[] = $row['contact_id'];
813 * @param CRM_Utils_Sort $sort
817 public function buildPrevNextCache($sort) {
818 $cacheKey = 'civicrm search ' . $this->_key
;
820 // We should clear the cache in following conditions:
821 // 1. when starting from scratch, i.e new search
822 // 2. if records are sorted
824 // get current page requested
825 $pageNum = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
827 // get the current sort order
828 $currentSortID = CRM_Utils_Request
::retrieve('crmSID', 'String', CRM_Core_DAO
::$_nullObject);
830 $session = CRM_Core_Session
::singleton();
832 // get previous sort id
833 $previousSortID = $session->get('previousSortID');
835 // check for current != previous to ensure cache is not reset if paging is done without changing
837 if (!$pageNum ||
(!empty($currentSortID) && $currentSortID != $previousSortID) ) {
838 CRM_Core_BAO_PrevNextCache
::deleteItem(NULL, $cacheKey, 'civicrm_contact');
839 // this means it's fresh search, so set pageNum=1
845 // set the current sort as previous sort
846 if (!empty($currentSortID)) {
847 $session->set('previousSortID', $currentSortID);
850 $pageSize = CRM_Utils_Request
::retrieve('crmRowCount', 'Integer', CRM_Core_DAO
::$_nullObject, FALSE, 50);
851 $firstRecord = ($pageNum - 1) * $pageSize;
853 //for alphabetic pagination selection save
854 $sortByCharacter = CRM_Utils_Request
::retrieve('sortByCharacter', 'String', CRM_Core_DAO
::$_nullObject);
856 //for text field pagination selection save
857 $countRow = CRM_Core_BAO_PrevNextCache
::getCount($cacheKey, NULL, "entity_table = 'civicrm_contact'");
859 // $sortByCharacter triggers a refresh in the prevNext cache
860 if ($sortByCharacter && $sortByCharacter != 'all') {
861 $cacheKey .= "_alphabet";
862 $this->fillupPrevNextCache($sort, $cacheKey);
864 elseif ($firstRecord >= $countRow) {
865 $this->fillupPrevNextCache($sort, $cacheKey, $countRow, 500);
873 public function addActions(&$rows) {
874 $config = CRM_Core_Config
::singleton();
876 $permissions = array(CRM_Core_Permission
::getPermission());
877 if (CRM_Core_Permission
::check('delete contacts')) {
878 $permissions[] = CRM_Core_Permission
::DELETE
;
880 $mask = CRM_Core_Action
::mask($permissions);
881 // mask value to hide map link if there are not lat/long
882 $mapMask = $mask & 4095;
884 // mask value to hide map link if there are not lat/long
885 $mapMask = $mask & 4095;
887 $links = self
::links($this->_context
, $this->_contextMenu
, $this->_key
);
890 foreach ($rows as $id => & $row) {
891 if (!empty($this->_formValues
['deleted_contacts']) && CRM_Core_Permission
::check('access deleted contacts')
895 'name' => ts('View'),
896 'url' => 'civicrm/contact/view',
897 'qs' => 'reset=1&cid=%%id%%',
898 'class' => 'no-popup',
899 'title' => ts('View Contact Details'),
902 'name' => ts('Restore'),
903 'url' => 'civicrm/contact/view/delete',
904 'qs' => 'reset=1&cid=%%id%%&restore=1',
905 'title' => ts('Restore Contact'),
908 if (CRM_Core_Permission
::check('delete contacts')) {
910 'name' => ts('Delete Permanently'),
911 'url' => 'civicrm/contact/view/delete',
912 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1',
913 'title' => ts('Permanently Delete Contact'),
916 $row['action'] = CRM_Core_Action
::formLink(
919 array('id' => $row['contact_id']),
922 'contact.selector.actions',
927 elseif ((is_numeric(CRM_Utils_Array
::value('geo_code_1', $row))) ||
928 ($config->mapGeoCoding
&& !empty($row['city']) &&
929 CRM_Utils_Array
::value('state_province', $row)
932 $row['action'] = CRM_Core_Action
::formLink(
935 array('id' => $row['contact_id']),
938 'contact.selector.actions',
944 $row['action'] = CRM_Core_Action
::formLink(
947 array('id' => $row['contact_id']),
950 'contact.selector.actions',
956 // allow components to add more actions
957 CRM_Core_Component
::searchAction($row, $row['contact_id']);
959 if (!empty($row['contact_type_orig'])) {
960 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils
::getImage($row['contact_type_orig'],
961 FALSE, $row['contact_id']);
969 public function removeActions(&$rows) {
970 foreach ($rows as $rid => & $rValue) {
971 unset($rValue['contact_type']);
972 unset($rValue['action']);
977 * @param CRM_Utils_Sort $sort
978 * @param string $cacheKey
982 public function fillupPrevNextCache($sort, $cacheKey, $start = 0, $end = 500) {
984 // For custom searches, use the contactIDs method
985 if (is_a($this, 'CRM_Contact_Selector_Custom')) {
986 $sql = $this->_search
->contactIDs($start, $end, $sort, TRUE);
987 $replaceSQL = "SELECT contact_a.id as contact_id";
990 // For core searches use the searchQuery method
992 $sql = $this->_query
->searchQuery($start, $end, $sort, FALSE, $this->_query
->_includeContactIds
,
994 $replaceSQL = "SELECT contact_a.id as id";
998 // due to limitations in our search query writer, the above query does not work
999 // in cases where the query is being sorted on a non-contact table
1000 // this results in a fatal error :(
1001 // see below for the gross hack of trapping the error and not filling
1002 // the prev next cache in this situation
1003 // the other alternative of running the FULL query will just be incredibly inefficient
1004 // and slow things down way too much on large data sets / complex queries
1007 INSERT INTO civicrm_prevnext_cache ( entity_table, entity_id1, entity_id2, cacheKey, data )
1008 SELECT DISTINCT 'civicrm_contact', contact_a.id, contact_a.id, '$cacheKey', contact_a.display_name
1011 $sql = str_replace($replaceSQL, $insertSQL, $sql);
1013 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1014 $result = CRM_Core_DAO
::executeQuery($sql);
1017 if (is_a($result, 'DB_Error')) {
1018 // check if we get error during core search
1020 // in the case of error, try rebuilding cache using full sql which is used for search selector display
1021 // this fixes the bugs reported in CRM-13996 & CRM-14438
1022 $this->rebuildPreNextCache($start, $end, $sort, $cacheKey);
1025 // return if above query fails
1030 // also record an entry in the cache key table, so we can delete it periodically
1031 CRM_Core_BAO_Cache
::setItem($cacheKey, 'CiviCRM Search PrevNextCache', $cacheKey);
1035 * This function is called to rebuild prev next cache using full sql in case of core search ( excluding custom search)
1037 * @param int $start start for limit clause
1038 * @param int $end end for limit clause
1039 * @param CRM_Utils_Sort $sort
1040 * @param string $cacheKey cache key
1044 public function rebuildPreNextCache($start, $end, $sort, $cacheKey) {
1045 // generate full SQL
1046 $sql = $this->_query
->searchQuery($start, $end, $sort, FALSE, $this->_query
->_includeContactIds
,
1047 FALSE, FALSE, TRUE);
1049 $dao = CRM_Core_DAO
::executeQuery($sql);
1051 // build insert query, note that currently we build cache for 500 contact records at a time, hence below approach
1052 $insertValues = array();
1053 while($dao->fetch()) {
1054 $insertValues[] = "('civicrm_contact', {$dao->contact_id}, {$dao->contact_id}, '{$cacheKey}', '" . CRM_Core_DAO
::escapeString($dao->sort_name
) . "')";
1057 //update pre/next cache using single insert query
1058 if (!empty($insertValues)) {
1059 $sql = 'INSERT INTO civicrm_prevnext_cache ( entity_table, entity_id1, entity_id2, cacheKey, data ) VALUES
1060 '.implode(',', $insertValues);
1062 $result = CRM_Core_DAO
::executeQuery($sql);
1067 * Given the current formValues, gets the query in local
1071 reference) $formValues submitted formValues
1073 * @return array $qill which contains an array of strings
1076 // the current internationalisation is bad, but should more or less work
1077 // for most of "European" languages
1078 public function getQILL() {
1079 return $this->_query
->qill();
1083 * Name of export file.
1085 * @param string $output type of output
1087 * @return string name of the file
1089 public function getExportFileName($output = 'csv') {
1090 return ts('CiviCRM Contact Search');
1094 * Get colunmn headers for search selector
1097 * @return array $_columnHeaders
1099 private static function &_getColumnHeaders() {
1100 if (!isset(self
::$_columnHeaders)) {
1101 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1102 'address_options', TRUE, NULL, TRUE
1105 self
::$_columnHeaders = array(
1106 'contact_type' => array('desc' => ts('Contact Type')),
1107 'sort_name' => array(
1108 'name' => ts('Name'),
1109 'sort' => 'sort_name',
1110 'direction' => CRM_Utils_Sort
::ASCENDING
,
1114 $defaultAddress = array(
1115 'street_address' => array('name' => ts('Address')),
1117 'name' => ts('City'),
1119 'direction' => CRM_Utils_Sort
::DONTCARE
,
1121 'state_province' => array(
1122 'name' => ts('State'),
1123 'sort' => 'state_province',
1124 'direction' => CRM_Utils_Sort
::DONTCARE
,
1126 'postal_code' => array(
1127 'name' => ts('Postal'),
1128 'sort' => 'postal_code',
1129 'direction' => CRM_Utils_Sort
::DONTCARE
,
1132 'name' => ts('Country'),
1133 'sort' => 'country',
1134 'direction' => CRM_Utils_Sort
::DONTCARE
,
1138 foreach ($defaultAddress as $columnName => $column) {
1139 if (!empty($addressOptions[$columnName])) {
1140 self
::$_columnHeaders[$columnName] = $column;
1144 self
::$_columnHeaders['email'] = array(
1145 'name' => ts('Email'),
1147 'direction' => CRM_Utils_Sort
::DONTCARE
,
1150 self
::$_columnHeaders['phone'] = array('name' => ts('Phone'));
1152 return self
::$_columnHeaders;
1156 * @return CRM_Contact_BAO_Query
1158 public function &getQuery() {
1159 return $this->_query
;
1163 * @return CRM_Contact_DAO_Contact
1165 public function alphabetQuery() {
1166 return $this->_query
->searchQuery(NULL, NULL, NULL, FALSE, FALSE, TRUE);
1170 * @param array $params
1172 * @param int $sortID
1173 * @param null $displayRelationshipType
1174 * @param string $queryOperator
1176 * @return CRM_Contact_DAO_Contact
1178 public function contactIDQuery($params, $action, $sortID, $displayRelationshipType = NULL, $queryOperator = 'AND') {
1179 $sortOrder = &$this->getSortOrder($this->_action
);
1180 $sort = new CRM_Utils_Sort($sortOrder, $sortID);
1182 // rectify params to what proximity search expects if there is a value for prox_distance
1183 // CRM-7021 CRM-7905
1184 if (!empty($params)) {
1185 CRM_Contact_BAO_ProximityQuery
::fixInputParams($params);
1188 if (!$displayRelationshipType) {
1189 $query = new CRM_Contact_BAO_Query($params,
1190 $this->_returnProperties
,
1191 NULL, FALSE, FALSE, 1,
1192 FALSE, TRUE, TRUE, NULL,
1197 $query = new CRM_Contact_BAO_Query($params, $this->_returnProperties
,
1198 NULL, FALSE, FALSE, 1,
1199 FALSE, TRUE, TRUE, $displayRelationshipType,
1203 $value = $query->searchQuery(0, 0, $sort,
1204 FALSE, FALSE, FALSE,
1211 * @param $returnProperties
1215 public function &makeProperties(&$returnProperties) {
1216 $properties = array();
1217 foreach ($returnProperties as $name => $value) {
1218 if ($name != 'location') {
1219 // special handling for group and tag
1220 if (in_array($name, array('group', 'tag'))) {
1224 // special handling for notes
1225 if (in_array($name, array('note', 'note_subject', 'note_body'))) {
1229 $properties[] = $name;
1232 // extract all the location stuff
1233 foreach ($value as $n => $v) {
1234 foreach ($v as $n1 => $v1) {
1235 if (!strpos('_id', $n1) && $n1 != 'location_type') {
1236 $properties[] = "{$n}-{$n1}";