3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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.
89 protected $_contextMenu;
92 * Params is the array in a value used by the search query creator
100 * The return properties used for search
105 protected $_returnProperties;
108 * Represent the type of selector
115 protected $_searchContext;
124 protected $_ufGroupID;
127 * The public visible fields to be shown to the user
137 * @param $customSearchClass
138 * @param array $formValues array of form values imported
139 * @param array $params array of parameters for query
140 * @param null $returnProperties
141 * @param \const|int $action - action of search basic or advanced.
143 * @param bool $includeContactIds
144 * @param bool $searchDescendentGroups
145 * @param string $searchContext
146 * @param null $contextMenu
148 * @return CRM_Contact_Selector
151 function __construct(
155 $returnProperties = NULL,
156 $action = CRM_Core_Action
::NONE
,
157 $includeContactIds = FALSE,
158 $searchDescendentGroups = TRUE,
159 $searchContext = 'search',
162 //don't build query constructor, if form is not submitted
163 $force = CRM_Utils_Request
::retrieve('force', 'Boolean', CRM_Core_DAO
::$_nullObject);
164 if (empty($formValues) && !$force) {
168 // submitted form values
169 $this->_formValues
= &$formValues;
170 $this->_params
= &$params;
171 $this->_returnProperties
= &$returnProperties;
172 $this->_contextMenu
= &$contextMenu;
173 $this->_context
= $searchContext;
176 $this->_action
= $action;
178 $this->_searchContext
= $searchContext;
180 $this->_ufGroupID
= CRM_Utils_Array
::value('uf_group_id', $this->_formValues
);
182 if ($this->_ufGroupID
) {
183 $this->_fields
= CRM_Core_BAO_UFGroup
::getListingFields(CRM_Core_Action
::VIEW
,
184 CRM_Core_BAO_UFGroup
::PUBLIC_VISIBILITY |
185 CRM_Core_BAO_UFGroup
::LISTINGS_VISIBILITY
,
186 FALSE, $this->_ufGroupID
188 self
::$_columnHeaders = NULL;
190 $this->_customFields
= CRM_Core_BAO_CustomField
::getFieldsForImport('Individual');
192 $this->_returnProperties
= CRM_Contact_BAO_Contact
::makeHierReturnProperties($this->_fields
);
193 $this->_returnProperties
['contact_type'] = 1;
194 $this->_returnProperties
['contact_sub_type'] = 1;
195 $this->_returnProperties
['sort_name'] = 1;
198 $displayRelationshipType = CRM_Utils_Array
::value('display_relationship_type', $this->_formValues
);
199 $operator = CRM_Utils_Array
::value('operator', $this->_formValues
, 'AND');
201 // rectify params to what proximity search expects if there is a value for prox_distance
203 if (!empty($this->_params
)) {
204 CRM_Contact_BAO_ProximityQuery
::fixInputParams($this->_params
);
207 $this->_query
= new CRM_Contact_BAO_Query(
209 $this->_returnProperties
,
213 CRM_Contact_BAO_Query
::MODE_CONTACTS
,
215 $searchDescendentGroups,
217 $displayRelationshipType,
221 $this->_options
= &$this->_query
->_options
;
225 * This method returns the links that are given for each search row.
226 * currently the links added for each row are
235 static function &links() {
236 list($context, $contextMenu, $key) = func_get_args();
237 $extraParams = ($key) ?
"&key={$key}" : NULL;
238 $searchContext = ($context) ?
"&context=$context" : NULL;
240 if (!(self
::$_links)) {
241 self
::$_links = array(
242 CRM_Core_Action
::VIEW
=> array(
243 'name' => ts('View'),
244 'url' => 'civicrm/contact/view',
245 'class' => 'no-popup',
246 'qs' => "reset=1&cid=%%id%%{$searchContext}{$extraParams}",
247 'title' => ts('View Contact Details'),
248 'ref' => 'view-contact',
250 CRM_Core_Action
::UPDATE
=> array(
251 'name' => ts('Edit'),
252 'url' => 'civicrm/contact/add',
253 'class' => 'no-popup',
254 'qs' => "reset=1&action=update&cid=%%id%%{$searchContext}{$extraParams}",
255 'title' => ts('Edit Contact Details'),
256 'ref' => 'edit-contact',
260 $config = CRM_Core_Config
::singleton();
261 if ($config->mapAPIKey
&& $config->mapProvider
) {
262 self
::$_links[CRM_Core_Action
::MAP
] = array(
264 'url' => 'civicrm/contact/map',
265 'qs' => "reset=1&cid=%%id%%{$searchContext}{$extraParams}",
266 'title' => ts('Map Contact'),
270 // Adding Context Menu Links in more action
273 foreach ($contextMenu as $key => $value) {
274 $contextVal = '&context=' . $value['key'];
275 if ($value['key'] == 'delete') {
276 $contextVal = $searchContext;
278 $url = "civicrm/contact/view/{$value['key']}";
279 $qs = "reset=1&action=add&cid=%%id%%{$contextVal}{$extraParams}";
280 if ($value['key'] == 'activity') {
281 $qs = "action=browse&selectedChild=activity&reset=1&cid=%%id%%{$extraParams}";
283 elseif ($value['key'] == 'email') {
284 $url = "civicrm/contact/view/activity";
285 $qs = "atype=3&action=add&reset=1&cid=%%id%%{$extraParams}";
288 self
::$_links[$counter++
] = array(
289 'name' => $value['title'],
292 'title' => $value['title'],
293 'ref' => $value['ref'],
294 'class' => CRM_Utils_Array
::value('class', $value),
299 return self
::$_links;
303 * Getter for array of the parameters required for creating pager.
306 * @param array $params
310 function getPagerParams($action, &$params) {
311 $params['status'] = ts('Contact %%StatusMessage%%');
312 $params['csvString'] = NULL;
313 $params['rowCount'] = CRM_Utils_Pager
::ROWCOUNT
;
315 $params['buttonTop'] = 'PagerTopButton';
316 $params['buttonBottom'] = 'PagerBottomButton';
320 * @param null $action
321 * @param null $output
325 function &getColHeads($action = NULL, $output = NULL) {
326 $colHeads = self
::_getColumnHeaders();
327 $colHeads[] = array('desc' => ts('Actions'), 'name' => ts('Action'));
332 * Returns the column headers as an array of tuples:
333 * (name, sortName (key to the sort array))
335 * @param string $action the action being performed
336 * @param enum $output what should the result set include (web/email/csv)
338 * @return array the column headers that need to be displayed
341 function &getColumnHeaders($action = NULL, $output = NULL) {
344 // unset return property elements that we don't care
345 if (!empty($this->_returnProperties
)) {
346 $doNotCareElements = array(
351 foreach ( $doNotCareElements as $value) {
352 unset($this->_returnProperties
[$value]);
356 if ($output == CRM_Core_Selector_Controller
::EXPORT
) {
357 $csvHeaders = array(ts('Contact ID'), ts('Contact Type'));
358 foreach ($this->getColHeads($action, $output) as $column) {
359 if (array_key_exists('name', $column)) {
360 $csvHeaders[] = $column['name'];
363 $headers = $csvHeaders;
365 elseif ($output == CRM_Core_Selector_Controller
::SCREEN
) {
366 $csvHeaders = array(ts('Name'));
367 foreach ($this->getColHeads($action, $output) as $key => $column) {
368 if (array_key_exists('name', $column) &&
370 $column['name'] != ts('Name')
372 $csvHeaders[$key] = $column['name'];
375 $headers = $csvHeaders;
377 elseif ($this->_ufGroupID
) {
378 // we dont use the cached value of column headers
379 // since it potentially changed because of the profile selected
380 static $skipFields = array('group', 'tag');
381 $direction = CRM_Utils_Sort
::ASCENDING
;
383 if (!self
::$_columnHeaders) {
384 self
::$_columnHeaders = array(array('name' => ''),
386 'name' => ts('Name'),
387 'sort' => 'sort_name',
388 'direction' => CRM_Utils_Sort
::ASCENDING
,
392 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
394 foreach ($this->_fields
as $name => $field) {
395 if (!empty($field['in_selector']) &&
396 !in_array($name, $skipFields)
398 if (strpos($name, '-') !== FALSE) {
399 list($fieldName, $lType, $type) = CRM_Utils_System
::explode('-', $name, 3);
401 if ($lType == 'Primary') {
402 $locationTypeName = 1;
405 $locationTypeName = $locationTypes[$lType];
408 if (in_array($fieldName, array(
409 'phone', 'im', 'email'))) {
411 $name = "`$locationTypeName-$fieldName-$type`";
414 $name = "`$locationTypeName-$fieldName`";
418 $name = "`$locationTypeName-$fieldName`";
421 //to handle sort key for Internal contactId.CRM-2289
423 $name = 'contact_id';
426 self
::$_columnHeaders[] = array(
427 'name' => $field['title'],
429 'direction' => $direction,
431 $direction = CRM_Utils_Sort
::DONTCARE
;
436 // if we dont have any valid columns, dont add the implicit ones
437 // this allows the template to check on emptiness of column headers
439 self
::$_columnHeaders = array();
442 self
::$_columnHeaders[] = array('desc' => ts('Actions'), 'name' => ts('Action'));
445 $headers = self
::$_columnHeaders;
447 elseif (!empty($this->_returnProperties
)) {
448 self
::$_columnHeaders = array(array('name' => ''),
450 'name' => ts('Name'),
451 'sort' => 'sort_name',
452 'direction' => CRM_Utils_Sort
::ASCENDING
,
455 $properties = self
::makeProperties($this->_returnProperties
);
457 foreach ($properties as $prop) {
458 if (strpos($prop, '-')) {
459 list($loc, $fld, $phoneType) = CRM_Utils_System
::explode('-', $prop, 3);
460 $title = $this->_query
->_fields
[$fld]['title'];
461 if (trim($phoneType) && !is_numeric($phoneType) && strtolower($phoneType) != $fld) {
462 $title .= "-{$phoneType}";
466 elseif (isset($this->_query
->_fields
[$prop]) && isset($this->_query
->_fields
[$prop]['title'])) {
467 $title = $this->_query
->_fields
[$prop]['title'];
473 self
::$_columnHeaders[] = array('name' => $title, 'sort' => $prop);
475 self
::$_columnHeaders[] = array('name' => ts('Actions'));
476 $headers = self
::$_columnHeaders;
479 $headers = $this->getColHeads($action, $output);
486 * Returns total number of rows for the query.
490 * @return int Total number of rows
493 function getTotalCount($action) {
494 // Use count from cache during paging/sorting
495 if (!empty($_GET['crmPID']) ||
!empty($_GET['crmSID'])) {
496 $count = CRM_Core_BAO_Cache
::getItem('Search Results Count', $this->_key
);
499 $count = $this->_query
->searchQuery(0, 0, NULL, TRUE);
500 CRM_Core_BAO_Cache
::setItem($count, 'Search Results Count', $this->_key
);
506 * Returns all the rows in the given offset and rowCount
508 * @param enum $action the action being performed
509 * @param int $offset the row number to start from
510 * @param int $rowCount the number of rows to return
511 * @param string $sort the sql string that describes the sort order
512 * @param enum $output what should the result set include (web/email/csv)
514 * @return int the total number of rows for this action
516 function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
517 $config = CRM_Core_Config
::singleton();
519 if (($output == CRM_Core_Selector_Controller
::EXPORT ||
520 $output == CRM_Core_Selector_Controller
::SCREEN
522 $this->_formValues
['radio_ts'] == 'ts_sel'
524 $includeContactIds = TRUE;
527 $includeContactIds = FALSE;
530 // note the formvalues were given by CRM_Contact_Form_Search to us
531 // and contain the search criteria (parameters)
532 // note that the default action is basic
534 $cacheKey = $this->buildPrevNextCache($sort);
535 $result = $this->_query
->getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds);
538 $result = $this->_query
->searchQuery($offset, $rowCount, $sort, FALSE, $includeContactIds);
541 // process the result of the query
543 $permissions = array(CRM_Core_Permission
::getPermission());
544 if (CRM_Core_Permission
::check('delete contacts')) {
545 $permissions[] = CRM_Core_Permission
::DELETE
;
547 $mask = CRM_Core_Action
::mask($permissions);
549 // mask value to hide map link if there are not lat/long
550 $mapMask = $mask & 4095;
552 if ($this->_searchContext
== 'smog') {
553 $gc = CRM_Core_SelectValues
::groupContactStatus();
556 if ($this->_ufGroupID
) {
557 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
560 static $skipFields = array('group', 'tag');
561 foreach ($this->_fields
as $key => $field) {
562 if (!empty($field['in_selector']) &&
563 !in_array($key, $skipFields)
565 if (strpos($key, '-') !== FALSE) {
566 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $key, 3);
568 if ($id == 'Primary') {
569 $locationTypeName = 1;
572 $locationTypeName = CRM_Utils_Array
::value($id, $locationTypes);
573 if (!$locationTypeName) {
578 $locationTypeName = str_replace(' ', '_', $locationTypeName);
579 if (in_array($fieldName, array(
580 'phone', 'im', 'email'))) {
582 $names[] = "{$locationTypeName}-{$fieldName}-{$type}";
585 $names[] = "{$locationTypeName}-{$fieldName}";
589 $names[] = "{$locationTypeName}-{$fieldName}";
593 $names[] = $field['name'];
600 elseif (!empty($this->_returnProperties
)) {
601 $names = self
::makeProperties($this->_returnProperties
);
604 $names = self
::$_properties;
607 $multipleSelectFields = array('preferred_communication_method' => 1);
609 $links = self
::links($this->_context
, $this->_contextMenu
, $this->_key
);
611 //check explicitly added contact to a Smart Group.
612 $groupID = CRM_Utils_Array
::key('1', $this->_formValues
['group']);
614 $pseudoconstants = array();
615 // for CRM-3157 purposes
616 if (in_array('world_region', $names)) {
617 $pseudoconstants['world_region'] = array(
618 'dbName' => 'world_region_id',
619 'values' => CRM_Core_PseudoConstant
::worldRegion()
624 while ($result->fetch()) {
626 $this->_query
->convertToPseudoNames($result);
628 // the columns we are interested in
629 foreach ($names as $property) {
630 if ($property == 'status') {
633 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($property)) {
634 $row[$property] = CRM_Core_BAO_CustomField
::getDisplayValue(
642 $multipleSelectFields &&
643 array_key_exists($property, $multipleSelectFields)
646 $paramsNew = array($key => $result->$property);
647 $name = array($key => array('newName' => $key, 'groupName' => $key));
649 CRM_Core_OptionGroup
::lookupValues($paramsNew, $name, FALSE);
650 $row[$key] = $paramsNew[$key];
652 elseif (strpos($property, '-im')) {
653 $row[$property] = $result->$property;
654 if (!empty($result->$property)) {
655 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
656 $providerId = $property . "-provider_id";
657 $providerName = $imProviders[$result->$providerId];
658 $row[$property] = $result->$property . " ({$providerName})";
661 elseif (in_array($property, array(
662 'addressee', 'email_greeting', 'postal_greeting'))) {
663 $greeting = $property . '_display';
664 $row[$property] = $result->$greeting;
666 elseif (isset($pseudoconstants[$property])) {
667 $row[$property] = CRM_Utils_Array
::value(
668 $result->{$pseudoconstants[$property]['dbName']},
669 $pseudoconstants[$property]['values']
672 elseif (strpos($property, '-url') !== FALSE) {
674 $websiteKey = 'website-1';
675 $propertyArray = explode('-', $property);
676 $websiteFld = $websiteKey . '-' . array_pop($propertyArray);
677 if (!empty($result->$websiteFld)) {
678 $websiteTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Website', 'website_type_id');
679 $websiteType = $websiteTypes[$result->{"$websiteKey-website_type_id"}];
680 $websiteValue = $result->$websiteFld;
681 $websiteUrl = "<a href=\"{$websiteValue}\">{$websiteValue} ({$websiteType})</a>";
683 $row[$property] = $websiteUrl;
686 $row[$property] = isset($result->$property) ?
$result->$property : NULL;
690 if (!empty($result->postal_code_suffix
)) {
691 $row['postal_code'] .= "-" . $result->postal_code_suffix
;
694 if ($output != CRM_Core_Selector_Controller
::EXPORT
&&
695 $this->_searchContext
== 'smog'
697 if (empty($result->status
) &&
700 $contactID = $result->contact_id
;
703 'contact_id' => $contactID,
704 'group_id' => $groupID,
707 $gcDefaults = array();
708 CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_GroupContact', $gcParams, $gcDefaults);
710 if (empty($gcDefaults)) {
711 $row['status'] = ts('Smart');
714 $row['status'] = $gc[$gcDefaults['status']];
718 $row['status'] = NULL;
722 $row['status'] = $gc[$result->status
];
726 if ($output != CRM_Core_Selector_Controller
::EXPORT
) {
727 $row['checkbox'] = CRM_Core_Form
::CB_PREFIX
. $result->contact_id
;
729 if (!empty($this->_formValues
['deleted_contacts']) && CRM_Core_Permission
::check('access deleted contacts')
733 'name' => ts('View'),
734 'url' => 'civicrm/contact/view',
735 'qs' => 'reset=1&cid=%%id%%',
736 'class' => 'no-popup',
737 'title' => ts('View Contact Details'),
740 'name' => ts('Restore'),
741 'url' => 'civicrm/contact/view/delete',
742 'qs' => 'reset=1&cid=%%id%%&restore=1',
743 'title' => ts('Restore Contact'),
746 if (CRM_Core_Permission
::check('delete contacts')) {
748 'name' => ts('Delete Permanently'),
749 'url' => 'civicrm/contact/view/delete',
750 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1',
751 'title' => ts('Permanently Delete Contact'),
754 $row['action'] = CRM_Core_Action
::formLink(
757 array('id' => $result->contact_id
),
760 'contact.selector.row',
765 elseif ((is_numeric(CRM_Utils_Array
::value('geo_code_1', $row))) ||
766 ($config->mapGeoCoding
&& !empty($row['city']) &&
767 CRM_Utils_Array
::value('state_province', $row)
770 $row['action'] = CRM_Core_Action
::formLink(
773 array('id' => $result->contact_id
),
776 'contact.selector.row',
782 $row['action'] = CRM_Core_Action
::formLink(
785 array('id' => $result->contact_id
),
788 'contact.selector.row',
794 // allow components to add more actions
795 CRM_Core_Component
::searchAction($row, $result->contact_id
);
797 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils
::getImage($result->contact_sub_type ?
798 $result->contact_sub_type
: $result->contact_type
,
803 $row['contact_type_orig'] = $result->contact_sub_type ?
$result->contact_sub_type
: $result->contact_type
;
804 $row['contact_sub_type'] = $result->contact_sub_type ?
805 CRM_Contact_BAO_ContactType
::contactTypePairs(FALSE, $result->contact_sub_type
, ', ') : $result->contact_sub_type
;
806 $row['contact_id'] = $result->contact_id
;
807 $row['sort_name'] = $result->sort_name
;
808 if (array_key_exists('id', $row)) {
809 $row['id'] = $result->contact_id
;
814 if (in_array($row['contact_id'], $seenIDs) === FALSE) {
815 $seenIDs[] = $row['contact_id'];
824 * @param CRM_Utils_Sort $sort
828 function buildPrevNextCache($sort) {
829 $cacheKey = 'civicrm search ' . $this->_key
;
831 // We should clear the cache in following conditions:
832 // 1. when starting from scratch, i.e new search
833 // 2. if records are sorted
835 // get current page requested
836 $pageNum = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
838 // get the current sort order
839 $currentSortID = CRM_Utils_Request
::retrieve('crmSID', 'String', CRM_Core_DAO
::$_nullObject);
841 $session = CRM_Core_Session
::singleton();
843 // get previous sort id
844 $previousSortID = $session->get('previousSortID');
846 // check for current != previous to ensure cache is not reset if paging is done without changing
848 if (!$pageNum ||
(!empty($currentSortID) && $currentSortID != $previousSortID) ) {
849 CRM_Core_BAO_PrevNextCache
::deleteItem(NULL, $cacheKey, 'civicrm_contact');
850 // this means it's fresh search, so set pageNum=1
856 // set the current sort as previous sort
857 if (!empty($currentSortID)) {
858 $session->set('previousSortID', $currentSortID);
861 $pageSize = CRM_Utils_Request
::retrieve('crmRowCount', 'Integer', CRM_Core_DAO
::$_nullObject, FALSE, 50);
862 $firstRecord = ($pageNum - 1) * $pageSize;
864 //for alphabetic pagination selection save
865 $sortByCharacter = CRM_Utils_Request
::retrieve('sortByCharacter', 'String', CRM_Core_DAO
::$_nullObject);
867 //for text field pagination selection save
868 $countRow = CRM_Core_BAO_PrevNextCache
::getCount($cacheKey, NULL, "entity_table = 'civicrm_contact'");
870 // $sortByCharacter triggers a refresh in the prevNext cache
871 if ($sortByCharacter && $sortByCharacter != 'all') {
872 $cacheKey .= "_alphabet";
873 $this->fillupPrevNextCache($sort, $cacheKey);
875 elseif ($firstRecord >= $countRow) {
876 $this->fillupPrevNextCache($sort, $cacheKey, $countRow, 500);
884 function addActions(&$rows) {
885 $config = CRM_Core_Config
::singleton();
887 $permissions = array(CRM_Core_Permission
::getPermission());
888 if (CRM_Core_Permission
::check('delete contacts')) {
889 $permissions[] = CRM_Core_Permission
::DELETE
;
891 $mask = CRM_Core_Action
::mask($permissions);
892 // mask value to hide map link if there are not lat/long
893 $mapMask = $mask & 4095;
895 // mask value to hide map link if there are not lat/long
896 $mapMask = $mask & 4095;
898 $links = self
::links($this->_context
, $this->_contextMenu
, $this->_key
);
901 foreach ($rows as $id => & $row) {
902 if (!empty($this->_formValues
['deleted_contacts']) && CRM_Core_Permission
::check('access deleted contacts')
906 'name' => ts('View'),
907 'url' => 'civicrm/contact/view',
908 'qs' => 'reset=1&cid=%%id%%',
909 'class' => 'no-popup',
910 'title' => ts('View Contact Details'),
913 'name' => ts('Restore'),
914 'url' => 'civicrm/contact/view/delete',
915 'qs' => 'reset=1&cid=%%id%%&restore=1',
916 'title' => ts('Restore Contact'),
919 if (CRM_Core_Permission
::check('delete contacts')) {
921 'name' => ts('Delete Permanently'),
922 'url' => 'civicrm/contact/view/delete',
923 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1',
924 'title' => ts('Permanently Delete Contact'),
927 $row['action'] = CRM_Core_Action
::formLink(
930 array('id' => $row['contact_id']),
933 'contact.selector.actions',
938 elseif ((is_numeric(CRM_Utils_Array
::value('geo_code_1', $row))) ||
939 ($config->mapGeoCoding
&& !empty($row['city']) &&
940 CRM_Utils_Array
::value('state_province', $row)
943 $row['action'] = CRM_Core_Action
::formLink(
946 array('id' => $row['contact_id']),
949 'contact.selector.actions',
955 $row['action'] = CRM_Core_Action
::formLink(
958 array('id' => $row['contact_id']),
961 'contact.selector.actions',
967 // allow components to add more actions
968 CRM_Core_Component
::searchAction($row, $row['contact_id']);
970 if (!empty($row['contact_type_orig'])) {
971 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils
::getImage($row['contact_type_orig'],
972 FALSE, $row['contact_id']);
980 function removeActions(&$rows) {
981 foreach ($rows as $rid => & $rValue) {
982 unset($rValue['contact_type']);
983 unset($rValue['action']);
988 * @param CRM_Utils_Sort $sort
989 * @param string $cacheKey
993 function fillupPrevNextCache($sort, $cacheKey, $start = 0, $end = 500) {
995 // For custom searches, use the contactIDs method
996 if (is_a($this, 'CRM_Contact_Selector_Custom')) {
997 $sql = $this->_search
->contactIDs($start, $end, $sort, TRUE);
998 $replaceSQL = "SELECT contact_a.id as contact_id";
1001 // For core searches use the searchQuery method
1003 $sql = $this->_query
->searchQuery($start, $end, $sort, FALSE, $this->_query
->_includeContactIds
,
1005 $replaceSQL = "SELECT contact_a.id as id";
1009 // due to limitations in our search query writer, the above query does not work
1010 // in cases where the query is being sorted on a non-contact table
1011 // this results in a fatal error :(
1012 // see below for the gross hack of trapping the error and not filling
1013 // the prev next cache in this situation
1014 // the other alternative of running the FULL query will just be incredibly inefficient
1015 // and slow things down way too much on large data sets / complex queries
1018 INSERT INTO civicrm_prevnext_cache ( entity_table, entity_id1, entity_id2, cacheKey, data )
1019 SELECT DISTINCT 'civicrm_contact', contact_a.id, contact_a.id, '$cacheKey', contact_a.display_name
1022 $sql = str_replace($replaceSQL, $insertSQL, $sql);
1024 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1025 $result = CRM_Core_DAO
::executeQuery($sql);
1028 if (is_a($result, 'DB_Error')) {
1029 // check if we get error during core search
1031 // in the case of error, try rebuilding cache using full sql which is used for search selector display
1032 // this fixes the bugs reported in CRM-13996 & CRM-14438
1033 $this->rebuildPreNextCache($start, $end, $sort, $cacheKey);
1036 // return if above query fails
1041 // also record an entry in the cache key table, so we can delete it periodically
1042 CRM_Core_BAO_Cache
::setItem($cacheKey, 'CiviCRM Search PrevNextCache', $cacheKey);
1046 * This function is called to rebuild prev next cache using full sql in case of core search ( excluding custom search)
1048 * @param int $start start for limit clause
1049 * @param int $end end for limit clause
1050 * @param CRM_Utils_Sort $sort
1051 * @param string $cacheKey cache key
1055 function rebuildPreNextCache($start, $end, $sort, $cacheKey) {
1056 // generate full SQL
1057 $sql = $this->_query
->searchQuery($start, $end, $sort, FALSE, $this->_query
->_includeContactIds
,
1058 FALSE, FALSE, TRUE);
1060 $dao = CRM_Core_DAO
::executeQuery($sql);
1062 // build insert query, note that currently we build cache for 500 contact records at a time, hence below approach
1063 $insertValues = array();
1064 while($dao->fetch()) {
1065 $insertValues[] = "('civicrm_contact', {$dao->contact_id}, {$dao->contact_id}, '{$cacheKey}', '" . CRM_Core_DAO
::escapeString($dao->sort_name
) . "')";
1068 //update pre/next cache using single insert query
1069 if (!empty($insertValues)) {
1070 $sql = 'INSERT INTO civicrm_prevnext_cache ( entity_table, entity_id1, entity_id2, cacheKey, data ) VALUES
1071 '.implode(',', $insertValues);
1073 $result = CRM_Core_DAO
::executeQuery($sql);
1078 * Given the current formValues, gets the query in local
1082 reference) $formValues submitted formValues
1084 * @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 type of output
1099 * @return string name of the file
1101 function getExportFileName($output = 'csv') {
1102 return ts('CiviCRM Contact Search');
1106 * Get colunmn headers for search selector
1109 * @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 function &getQuery() {
1172 return $this->_query
;
1176 * @return CRM_Contact_DAO_Contact
1178 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 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 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}";