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 array $formValues array of form values imported
138 * @param array $params array of parameters for query
139 * @param int $action - action of search basic or advanced.
141 * @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
;
219 * This method returns the links that are given for each search row.
220 * currently the links added for each row are
229 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;
298 * getter for array of the parameters required for creating pager.
303 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 function &getColHeads($action = NULL, $output = NULL) {
314 $colHeads = self
::_getColumnHeaders();
315 $colHeads[] = array('desc' => ts('Actions'), 'name' => ts('Action'));
320 * returns the column headers as an array of tuples:
321 * (name, sortName (key to the sort array))
323 * @param string $action the action being performed
324 * @param enum $output what should the result set include (web/email/csv)
326 * @return array the column headers that need to be displayed
329 function &getColumnHeaders($action = NULL, $output = NULL) {
332 // unset return property elements that we don't care
333 if (!empty($this->_returnProperties
)) {
334 $doNotCareElements = array(
339 foreach ( $doNotCareElements as $value) {
340 unset($this->_returnProperties
[$value]);
344 if ($output == CRM_Core_Selector_Controller
::EXPORT
) {
345 $csvHeaders = array(ts('Contact Id'), ts('Contact Type'));
346 foreach ($this->getColHeads($action, $output) as $column) {
347 if (array_key_exists('name', $column)) {
348 $csvHeaders[] = $column['name'];
351 $headers = $csvHeaders;
353 elseif ($output == CRM_Core_Selector_Controller
::SCREEN
) {
354 $csvHeaders = array(ts('Name'));
355 foreach ($this->getColHeads($action, $output) as $key => $column) {
356 if (array_key_exists('name', $column) &&
358 $column['name'] != ts('Name')
360 $csvHeaders[$key] = $column['name'];
363 $headers = $csvHeaders;
365 elseif ($this->_ufGroupID
) {
366 // we dont use the cached value of column headers
367 // since it potentially changed because of the profile selected
368 static $skipFields = array('group', 'tag');
369 $direction = CRM_Utils_Sort
::ASCENDING
;
371 if (!self
::$_columnHeaders) {
372 self
::$_columnHeaders = array(array('name' => ''),
374 'name' => ts('Name'),
375 'sort' => 'sort_name',
376 'direction' => CRM_Utils_Sort
::ASCENDING
,
380 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
382 foreach ($this->_fields
as $name => $field) {
383 if (!empty($field['in_selector']) &&
384 !in_array($name, $skipFields)
386 if (strpos($name, '-') !== FALSE) {
387 list($fieldName, $lType, $type) = CRM_Utils_System
::explode('-', $name, 3);
389 if ($lType == 'Primary') {
390 $locationTypeName = 1;
393 $locationTypeName = $locationTypes[$lType];
396 if (in_array($fieldName, array(
397 'phone', 'im', 'email'))) {
399 $name = "`$locationTypeName-$fieldName-$type`";
402 $name = "`$locationTypeName-$fieldName`";
406 $name = "`$locationTypeName-$fieldName`";
409 //to handle sort key for Internal contactId.CRM-2289
411 $name = 'contact_id';
414 self
::$_columnHeaders[] = array(
415 'name' => $field['title'],
417 'direction' => $direction,
419 $direction = CRM_Utils_Sort
::DONTCARE
;
424 // if we dont have any valid columns, dont add the implicit ones
425 // this allows the template to check on emptiness of column headers
427 self
::$_columnHeaders = array();
430 self
::$_columnHeaders[] = array('desc' => ts('Actions'), 'name' => ts('Action'));
433 $headers = self
::$_columnHeaders;
435 elseif (!empty($this->_returnProperties
)) {
436 self
::$_columnHeaders = array(array('name' => ''),
438 'name' => ts('Name'),
439 'sort' => 'sort_name',
440 'direction' => CRM_Utils_Sort
::ASCENDING
,
443 $properties = self
::makeProperties($this->_returnProperties
);
445 foreach ($properties as $prop) {
446 if (strpos($prop, '-')) {
447 list($loc, $fld, $phoneType) = CRM_Utils_System
::explode('-', $prop, 3);
448 $title = $this->_query
->_fields
[$fld]['title'];
449 if (trim($phoneType) && !is_numeric($phoneType) && strtolower($phoneType) != $fld) {
450 $title .= "-{$phoneType}";
454 elseif (isset($this->_query
->_fields
[$prop]) && isset($this->_query
->_fields
[$prop]['title'])) {
455 $title = $this->_query
->_fields
[$prop]['title'];
461 self
::$_columnHeaders[] = array('name' => $title, 'sort' => $prop);
463 self
::$_columnHeaders[] = array('name' => ts('Actions'));
464 $headers = self
::$_columnHeaders;
467 $headers = $this->getColHeads($action, $output);
474 * Returns total number of rows for the query.
478 * @return int Total number of rows
481 function getTotalCount($action) {
482 // Use count from cache during paging/sorting
483 if (!empty($_GET['crmPID']) ||
!empty($_GET['crmSID'])) {
484 $count = CRM_Core_BAO_Cache
::getItem('Search Results Count', $this->_key
);
487 $count = $this->_query
->searchQuery(0, 0, NULL, TRUE);
488 CRM_Core_BAO_Cache
::setItem($count, 'Search Results Count', $this->_key
);
494 * returns all the rows in the given offset and rowCount
496 * @param enum $action the action being performed
497 * @param int $offset the row number to start from
498 * @param int $rowCount the number of rows to return
499 * @param string $sort the sql string that describes the sort order
500 * @param enum $output what should the result set include (web/email/csv)
502 * @return int the total number of rows for this action
504 function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
505 $config = CRM_Core_Config
::singleton();
507 if (($output == CRM_Core_Selector_Controller
::EXPORT ||
508 $output == CRM_Core_Selector_Controller
::SCREEN
510 $this->_formValues
['radio_ts'] == 'ts_sel'
512 $includeContactIds = TRUE;
515 $includeContactIds = FALSE;
518 // note the formvalues were given by CRM_Contact_Form_Search to us
519 // and contain the search criteria (parameters)
520 // note that the default action is basic
522 $cacheKey = $this->buildPrevNextCache($sort);
523 $result = $this->_query
->getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds);
526 $result = $this->_query
->searchQuery($offset, $rowCount, $sort, FALSE, $includeContactIds);
529 // process the result of the query
531 $permissions = array(CRM_Core_Permission
::getPermission());
532 if (CRM_Core_Permission
::check('delete contacts')) {
533 $permissions[] = CRM_Core_Permission
::DELETE
;
535 $mask = CRM_Core_Action
::mask($permissions);
537 // mask value to hide map link if there are not lat/long
538 $mapMask = $mask & 4095;
540 if ($this->_searchContext
== 'smog') {
541 $gc = CRM_Core_SelectValues
::groupContactStatus();
544 if ($this->_ufGroupID
) {
545 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
548 static $skipFields = array('group', 'tag');
549 foreach ($this->_fields
as $key => $field) {
550 if (!empty($field['in_selector']) &&
551 !in_array($key, $skipFields)
553 if (strpos($key, '-') !== FALSE) {
554 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $key, 3);
556 if ($id == 'Primary') {
557 $locationTypeName = 1;
560 $locationTypeName = CRM_Utils_Array
::value($id, $locationTypes);
561 if (!$locationTypeName) {
566 $locationTypeName = str_replace(' ', '_', $locationTypeName);
567 if (in_array($fieldName, array(
568 'phone', 'im', 'email'))) {
570 $names[] = "{$locationTypeName}-{$fieldName}-{$type}";
573 $names[] = "{$locationTypeName}-{$fieldName}";
577 $names[] = "{$locationTypeName}-{$fieldName}";
581 $names[] = $field['name'];
588 elseif (!empty($this->_returnProperties
)) {
589 $names = self
::makeProperties($this->_returnProperties
);
592 $names = self
::$_properties;
595 $multipleSelectFields = array('preferred_communication_method' => 1);
597 $links = self
::links($this->_context
, $this->_contextMenu
, $this->_key
);
599 //check explicitly added contact to a Smart Group.
600 $groupID = CRM_Utils_Array
::key('1', $this->_formValues
['group']);
602 $pseudoconstants = array();
603 // for CRM-3157 purposes
604 if (in_array('world_region', $names)) {
605 $pseudoconstants['world_region'] = array(
606 'dbName' => 'world_region_id',
607 'values' => CRM_Core_PseudoConstant
::worldRegion()
612 while ($result->fetch()) {
614 $this->_query
->convertToPseudoNames($result);
616 // the columns we are interested in
617 foreach ($names as $property) {
618 if ($property == 'status') {
621 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($property)) {
622 $row[$property] = CRM_Core_BAO_CustomField
::getDisplayValue(
630 $multipleSelectFields &&
631 array_key_exists($property, $multipleSelectFields)
634 $paramsNew = array($key => $result->$property);
635 $name = array($key => array('newName' => $key, 'groupName' => $key));
637 CRM_Core_OptionGroup
::lookupValues($paramsNew, $name, FALSE);
638 $row[$key] = $paramsNew[$key];
640 elseif (strpos($property, '-im')) {
641 $row[$property] = $result->$property;
642 if (!empty($result->$property)) {
643 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
644 $providerId = $property . "-provider_id";
645 $providerName = $imProviders[$result->$providerId];
646 $row[$property] = $result->$property . " ({$providerName})";
649 elseif (in_array($property, array(
650 'addressee', 'email_greeting', 'postal_greeting'))) {
651 $greeting = $property . '_display';
652 $row[$property] = $result->$greeting;
654 elseif (isset($pseudoconstants[$property])) {
655 $row[$property] = CRM_Utils_Array
::value(
656 $result->{$pseudoconstants[$property]['dbName']},
657 $pseudoconstants[$property]['values']
660 elseif (strpos($property, '-url') !== FALSE) {
662 $websiteKey = 'website-1';
663 $propertyArray = explode('-', $property);
664 $websiteFld = $websiteKey . '-' . array_pop($propertyArray);
665 if (!empty($result->$websiteFld)) {
666 $websiteTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Website', 'website_type_id');
667 $websiteType = $websiteTypes[$result->{"$websiteKey-website_type_id"}];
668 $websiteValue = $result->$websiteFld;
669 $websiteUrl = "<a href=\"{$websiteValue}\">{$websiteValue} ({$websiteType})</a>";
671 $row[$property] = $websiteUrl;
674 $row[$property] = isset($result->$property) ?
$result->$property : NULL;
678 if (!empty($result->postal_code_suffix
)) {
679 $row['postal_code'] .= "-" . $result->postal_code_suffix
;
682 if ($output != CRM_Core_Selector_Controller
::EXPORT
&&
683 $this->_searchContext
== 'smog'
685 if (empty($result->status
) &&
688 $contactID = $result->contact_id
;
691 'contact_id' => $contactID,
692 'group_id' => $groupID,
695 $gcDefaults = array();
696 CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_GroupContact', $gcParams, $gcDefaults);
698 if (empty($gcDefaults)) {
699 $row['status'] = ts('Smart');
702 $row['status'] = $gc[$gcDefaults['status']];
706 $row['status'] = NULL;
710 $row['status'] = $gc[$result->status
];
714 if ($output != CRM_Core_Selector_Controller
::EXPORT
) {
715 $row['checkbox'] = CRM_Core_Form
::CB_PREFIX
. $result->contact_id
;
717 if (!empty($this->_formValues
['deleted_contacts']) && CRM_Core_Permission
::check('access deleted contacts')
721 'name' => ts('View'),
722 'url' => 'civicrm/contact/view',
723 'qs' => 'reset=1&cid=%%id%%',
724 'class' => 'no-popup',
725 'title' => ts('View Contact Details'),
728 'name' => ts('Restore'),
729 'url' => 'civicrm/contact/view/delete',
730 'qs' => 'reset=1&cid=%%id%%&restore=1',
731 'title' => ts('Restore Contact'),
734 if (CRM_Core_Permission
::check('delete contacts')) {
736 'name' => ts('Delete Permanently'),
737 'url' => 'civicrm/contact/view/delete',
738 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1',
739 'title' => ts('Permanently Delete Contact'),
742 $row['action'] = CRM_Core_Action
::formLink(
745 array('id' => $result->contact_id
),
748 'contact.selector.row',
753 elseif ((is_numeric(CRM_Utils_Array
::value('geo_code_1', $row))) ||
754 ($config->mapGeoCoding
&& !empty($row['city']) &&
755 CRM_Utils_Array
::value('state_province', $row)
758 $row['action'] = CRM_Core_Action
::formLink(
761 array('id' => $result->contact_id
),
764 'contact.selector.row',
770 $row['action'] = CRM_Core_Action
::formLink(
773 array('id' => $result->contact_id
),
776 'contact.selector.row',
782 // allow components to add more actions
783 CRM_Core_Component
::searchAction($row, $result->contact_id
);
785 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils
::getImage($result->contact_sub_type ?
786 $result->contact_sub_type
: $result->contact_type
,
791 $row['contact_type_orig'] = $result->contact_sub_type ?
$result->contact_sub_type
: $result->contact_type
;
792 $row['contact_sub_type'] = $result->contact_sub_type ?
793 CRM_Contact_BAO_ContactType
::contactTypePairs(FALSE, $result->contact_sub_type
, ', ') : $result->contact_sub_type
;
794 $row['contact_id'] = $result->contact_id
;
795 $row['sort_name'] = $result->sort_name
;
796 if (array_key_exists('id', $row)) {
797 $row['id'] = $result->contact_id
;
802 if (in_array($row['contact_id'], $seenIDs) === FALSE) {
803 $seenIDs[] = $row['contact_id'];
811 function buildPrevNextCache($sort) {
812 $cacheKey = 'civicrm search ' . $this->_key
;
814 // Get current page requested
815 $pageNum = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
816 // When starting from scratch, clear any old cache
818 CRM_Core_BAO_PrevNextCache
::deleteItem(NULL, $cacheKey, 'civicrm_contact');
822 $pageSize = CRM_Utils_Request
::retrieve('crmRowCount', 'Integer', CRM_Core_DAO
::$_nullObject, FALSE, 50);
823 $firstRecord = ($pageNum - 1) * $pageSize;
825 //for alphabetic pagination selection save
826 $sortByCharacter = CRM_Utils_Request
::retrieve('sortByCharacter', 'String', CRM_Core_DAO
::$_nullObject);
828 //for text field pagination selection save
829 $countRow = CRM_Core_BAO_PrevNextCache
::getCount($cacheKey, NULL, "entity_table = 'civicrm_contact'");
831 // $sortByCharacter triggers a refresh in the prevNext cache
832 if ($sortByCharacter && $sortByCharacter != 'all') {
833 $cacheKey .= "_alphabet";
834 $this->fillupPrevNextCache($sort, $cacheKey);
836 elseif ($firstRecord >= $countRow) {
837 $this->fillupPrevNextCache($sort, $cacheKey, $countRow, $firstRecord +
500);
842 function addActions(&$rows) {
843 $config = CRM_Core_Config
::singleton();
845 $permissions = array(CRM_Core_Permission
::getPermission());
846 if (CRM_Core_Permission
::check('delete contacts')) {
847 $permissions[] = CRM_Core_Permission
::DELETE
;
849 $mask = CRM_Core_Action
::mask($permissions);
850 // mask value to hide map link if there are not lat/long
851 $mapMask = $mask & 4095;
853 // mask value to hide map link if there are not lat/long
854 $mapMask = $mask & 4095;
856 $links = self
::links($this->_context
, $this->_contextMenu
, $this->_key
);
859 foreach ($rows as $id => & $row) {
860 if (!empty($this->_formValues
['deleted_contacts']) && CRM_Core_Permission
::check('access deleted contacts')
864 'name' => ts('View'),
865 'url' => 'civicrm/contact/view',
866 'qs' => 'reset=1&cid=%%id%%',
867 'title' => ts('View Contact Details'),
870 'name' => ts('Restore'),
871 'url' => 'civicrm/contact/view/delete',
872 'qs' => 'reset=1&cid=%%id%%&restore=1',
873 'title' => ts('Restore Contact'),
876 if (CRM_Core_Permission
::check('delete contacts')) {
878 'name' => ts('Delete Permanently'),
879 'url' => 'civicrm/contact/view/delete',
880 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1',
881 'title' => ts('Permanently Delete Contact'),
884 $row['action'] = CRM_Core_Action
::formLink(
887 array('id' => $row['contact_id']),
890 'contact.selector.actions',
895 elseif ((is_numeric(CRM_Utils_Array
::value('geo_code_1', $row))) ||
896 ($config->mapGeoCoding
&& !empty($row['city']) &&
897 CRM_Utils_Array
::value('state_province', $row)
900 $row['action'] = CRM_Core_Action
::formLink(
903 array('id' => $row['contact_id']),
906 'contact.selector.actions',
912 $row['action'] = CRM_Core_Action
::formLink(
915 array('id' => $row['contact_id']),
918 'contact.selector.actions',
924 // allow components to add more actions
925 CRM_Core_Component
::searchAction($row, $row['contact_id']);
927 if (!empty($row['contact_type_orig'])) {
928 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils
::getImage($row['contact_type_orig'],
929 FALSE, $row['contact_id']);
934 function removeActions(&$rows) {
935 foreach ($rows as $rid => & $rValue) {
936 unset($rValue['contact_type']);
937 unset($rValue['action']);
942 * @param object $sort
943 * @param string $cacheKey
947 function fillupPrevNextCache($sort, $cacheKey, $start = 0, $end = 500) {
949 // For custom searches, use the contactIDs method
950 if (is_a($this, 'CRM_Contact_Selector_Custom')) {
951 $sql = $this->_search
->contactIDs($start, $end, $sort, TRUE);
952 $replaceSQL = "SELECT contact_a.id as contact_id";
955 // For core searches use the searchQuery method
957 $sql = $this->_query
->searchQuery($start, $end, $sort, FALSE, $this->_query
->_includeContactIds
,
959 $replaceSQL = "SELECT contact_a.id as id";
963 // due to limitations in our search query writer, the above query does not work
964 // in cases where the query is being sorted on a non-contact table
965 // this results in a fatal error :(
966 // see below for the gross hack of trapping the error and not filling
967 // the prev next cache in this situation
968 // the other alternative of running the FULL query will just be incredibly inefficient
969 // and slow things down way too much on large data sets / complex queries
972 INSERT INTO civicrm_prevnext_cache ( entity_table, entity_id1, entity_id2, cacheKey, data )
973 SELECT 'civicrm_contact', contact_a.id, contact_a.id, '$cacheKey', contact_a.display_name
976 $sql = str_replace($replaceSQL, $insertSQL, $sql);
978 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
979 $result = CRM_Core_DAO
::executeQuery($sql);
982 if (is_a($result, 'DB_Error')) {
983 // check if we get error during core search
985 // in the case of error, try rebuilding cache using full sql which is used for search selector display
986 // this fixes the bugs reported in CRM-13996 & CRM-14438
987 $this->rebuildPreNextCache($start, $end, $sort, $cacheKey);
990 // return if above query fails
995 // also record an entry in the cache key table, so we can delete it periodically
996 CRM_Core_BAO_Cache
::setItem($cacheKey, 'CiviCRM Search PrevNextCache', $cacheKey);
1000 * This function is called to rebuild prev next cache using full sql in case of core search ( excluding custom search)
1002 * @param int $start start for limit clause
1003 * @param int $end end for limit clause
1004 * @param $object $sort sort object
1005 * @param string $cacheKey cache key
1009 function rebuildPreNextCache($start, $end, $sort, $cacheKey) {
1010 // generate full SQL
1011 $sql = $this->_query
->searchQuery($start, $end, $sort, FALSE, $this->_query
->_includeContactIds
,
1012 FALSE, FALSE, TRUE);
1014 $dao = CRM_Core_DAO
::executeQuery($sql);
1016 // build insert query, note that currently we build cache for 500 contact records at a time, hence below approach
1017 $insertValues = array();
1018 while($dao->fetch()) {
1019 $insertValues[] = "('civicrm_contact', {$dao->contact_id}, {$dao->contact_id}, '{$cacheKey}', '{$dao->sort_name}')";
1022 //update pre/next cache using single insert query
1023 if (!empty($insertValues)) {
1024 $sql = 'INSERT INTO civicrm_prevnext_cache ( entity_table, entity_id1, entity_id2, cacheKey, data ) VALUES
1025 '.implode(',', $insertValues);
1027 $result = CRM_Core_DAO
::executeQuery($sql);
1032 * Given the current formValues, gets the query in local
1036 reference) $formValues submitted formValues
1038 * @return array $qill which contains an array of strings
1042 // the current internationalisation is bad, but should more or less work
1043 // for most of "European" languages
1044 public function getQILL() {
1045 return $this->_query
->qill();
1049 * name of export file.
1051 * @param string $output type of output
1053 * @return string name of the file
1055 function getExportFileName($output = 'csv') {
1056 return ts('CiviCRM Contact Search');
1060 * get colunmn headers for search selector
1063 * @return array $_columnHeaders
1066 private static function &_getColumnHeaders() {
1067 if (!isset(self
::$_columnHeaders)) {
1068 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1069 'address_options', TRUE, NULL, TRUE
1072 self
::$_columnHeaders = array(
1073 'contact_type' => array('desc' => ts('Contact Type')),
1074 'sort_name' => array(
1075 'name' => ts('Name'),
1076 'sort' => 'sort_name',
1077 'direction' => CRM_Utils_Sort
::ASCENDING
,
1081 $defaultAddress = array(
1082 'street_address' => array('name' => ts('Address')),
1084 'name' => ts('City'),
1086 'direction' => CRM_Utils_Sort
::DONTCARE
,
1088 'state_province' => array(
1089 'name' => ts('State'),
1090 'sort' => 'state_province',
1091 'direction' => CRM_Utils_Sort
::DONTCARE
,
1093 'postal_code' => array(
1094 'name' => ts('Postal'),
1095 'sort' => 'postal_code',
1096 'direction' => CRM_Utils_Sort
::DONTCARE
,
1099 'name' => ts('Country'),
1100 'sort' => 'country',
1101 'direction' => CRM_Utils_Sort
::DONTCARE
,
1105 foreach ($defaultAddress as $columnName => $column) {
1106 if (!empty($addressOptions[$columnName])) {
1107 self
::$_columnHeaders[$columnName] = $column;
1111 self
::$_columnHeaders['email'] = array(
1112 'name' => ts('Email'),
1114 'direction' => CRM_Utils_Sort
::DONTCARE
,
1117 self
::$_columnHeaders['phone'] = array('name' => ts('Phone'));
1119 return self
::$_columnHeaders;
1122 function &getQuery() {
1123 return $this->_query
;
1126 function alphabetQuery() {
1127 return $this->_query
->searchQuery(NULL, NULL, NULL, FALSE, FALSE, TRUE);
1130 function contactIDQuery($params, $action, $sortID, $displayRelationshipType = NULL, $queryOperator = 'AND') {
1131 $sortOrder = &$this->getSortOrder($this->_action
);
1132 $sort = new CRM_Utils_Sort($sortOrder, $sortID);
1134 // rectify params to what proximity search expects if there is a value for prox_distance
1135 // CRM-7021 CRM-7905
1136 if (!empty($params)) {
1137 CRM_Contact_BAO_ProximityQuery
::fixInputParams($params);
1140 if (!$displayRelationshipType) {
1141 $query = new CRM_Contact_BAO_Query($params,
1142 $this->_returnProperties
,
1143 NULL, FALSE, FALSE, 1,
1144 FALSE, TRUE, TRUE, NULL,
1149 $query = new CRM_Contact_BAO_Query($params, $this->_returnProperties
,
1150 NULL, FALSE, FALSE, 1,
1151 FALSE, TRUE, TRUE, $displayRelationshipType,
1155 $value = $query->searchQuery(0, 0, $sort,
1156 FALSE, FALSE, FALSE,
1162 function &makeProperties(&$returnProperties) {
1163 $properties = array();
1164 foreach ($returnProperties as $name => $value) {
1165 if ($name != 'location') {
1166 // special handling for group and tag
1167 if (in_array($name, array('group', 'tag'))) {
1171 // special handling for notes
1172 if (in_array($name, array('note', 'note_subject', 'note_body'))) {
1176 $properties[] = $name;
1179 // extract all the location stuff
1180 foreach ($value as $n => $v) {
1181 foreach ($v as $n1 => $v1) {
1182 if (!strpos('_id', $n1) && $n1 != 'location_type') {
1183 $properties[] = "{$n}-{$n1}";