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
;
226 * This method returns the links that are given for each search row.
227 * currently the links added for each row are
236 static function &links() {
237 list($context, $contextMenu, $key) = func_get_args();
238 $extraParams = ($key) ?
"&key={$key}" : NULL;
239 $searchContext = ($context) ?
"&context=$context" : NULL;
241 if (!(self
::$_links)) {
242 self
::$_links = array(
243 CRM_Core_Action
::VIEW
=> array(
244 'name' => ts('View'),
245 'url' => 'civicrm/contact/view',
246 'class' => 'no-popup',
247 'qs' => "reset=1&cid=%%id%%{$searchContext}{$extraParams}",
248 'title' => ts('View Contact Details'),
249 'ref' => 'view-contact',
251 CRM_Core_Action
::UPDATE
=> array(
252 'name' => ts('Edit'),
253 'url' => 'civicrm/contact/add',
254 'class' => 'no-popup',
255 'qs' => "reset=1&action=update&cid=%%id%%{$searchContext}{$extraParams}",
256 'title' => ts('Edit Contact Details'),
257 'ref' => 'edit-contact',
261 $config = CRM_Core_Config
::singleton();
262 if ($config->mapAPIKey
&& $config->mapProvider
) {
263 self
::$_links[CRM_Core_Action
::MAP
] = array(
265 'url' => 'civicrm/contact/map',
266 'qs' => "reset=1&cid=%%id%%{$searchContext}{$extraParams}",
267 'title' => ts('Map Contact'),
271 // Adding Context Menu Links in more action
274 foreach ($contextMenu as $key => $value) {
275 $contextVal = '&context=' . $value['key'];
276 if ($value['key'] == 'delete') {
277 $contextVal = $searchContext;
279 $url = "civicrm/contact/view/{$value['key']}";
280 $qs = "reset=1&action=add&cid=%%id%%{$contextVal}{$extraParams}";
281 if ($value['key'] == 'activity') {
282 $qs = "action=browse&selectedChild=activity&reset=1&cid=%%id%%{$extraParams}";
284 elseif ($value['key'] == 'email') {
285 $url = "civicrm/contact/view/activity";
286 $qs = "atype=3&action=add&reset=1&cid=%%id%%{$extraParams}";
289 self
::$_links[$counter++
] = array(
290 'name' => $value['title'],
293 'title' => $value['title'],
294 'ref' => $value['ref'],
295 'class' => CRM_Utils_Array
::value('class', $value),
300 return self
::$_links;
305 * getter for array of the parameters required for creating pager.
313 function getPagerParams($action, &$params) {
314 $params['status'] = ts('Contact %%StatusMessage%%');
315 $params['csvString'] = NULL;
316 $params['rowCount'] = CRM_Utils_Pager
::ROWCOUNT
;
318 $params['buttonTop'] = 'PagerTopButton';
319 $params['buttonBottom'] = 'PagerBottomButton';
323 function &getColHeads($action = NULL, $output = NULL) {
324 $colHeads = self
::_getColumnHeaders();
325 $colHeads[] = array('desc' => ts('Actions'), 'name' => ts('Action'));
330 * returns the column headers as an array of tuples:
331 * (name, sortName (key to the sort array))
333 * @param string $action the action being performed
334 * @param enum $output what should the result set include (web/email/csv)
336 * @return array the column headers that need to be displayed
339 function &getColumnHeaders($action = NULL, $output = NULL) {
342 // unset return property elements that we don't care
343 if (!empty($this->_returnProperties
)) {
344 $doNotCareElements = array(
349 foreach ( $doNotCareElements as $value) {
350 unset($this->_returnProperties
[$value]);
354 if ($output == CRM_Core_Selector_Controller
::EXPORT
) {
355 $csvHeaders = array(ts('Contact Id'), ts('Contact Type'));
356 foreach ($this->getColHeads($action, $output) as $column) {
357 if (array_key_exists('name', $column)) {
358 $csvHeaders[] = $column['name'];
361 $headers = $csvHeaders;
363 elseif ($output == CRM_Core_Selector_Controller
::SCREEN
) {
364 $csvHeaders = array(ts('Name'));
365 foreach ($this->getColHeads($action, $output) as $key => $column) {
366 if (array_key_exists('name', $column) &&
368 $column['name'] != ts('Name')
370 $csvHeaders[$key] = $column['name'];
373 $headers = $csvHeaders;
375 elseif ($this->_ufGroupID
) {
376 // we dont use the cached value of column headers
377 // since it potentially changed because of the profile selected
378 static $skipFields = array('group', 'tag');
379 $direction = CRM_Utils_Sort
::ASCENDING
;
381 if (!self
::$_columnHeaders) {
382 self
::$_columnHeaders = array(array('name' => ''),
384 'name' => ts('Name'),
385 'sort' => 'sort_name',
386 'direction' => CRM_Utils_Sort
::ASCENDING
,
390 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
392 foreach ($this->_fields
as $name => $field) {
393 if (!empty($field['in_selector']) &&
394 !in_array($name, $skipFields)
396 if (strpos($name, '-') !== FALSE) {
397 list($fieldName, $lType, $type) = CRM_Utils_System
::explode('-', $name, 3);
399 if ($lType == 'Primary') {
400 $locationTypeName = 1;
403 $locationTypeName = $locationTypes[$lType];
406 if (in_array($fieldName, array(
407 'phone', 'im', 'email'))) {
409 $name = "`$locationTypeName-$fieldName-$type`";
412 $name = "`$locationTypeName-$fieldName`";
416 $name = "`$locationTypeName-$fieldName`";
419 //to handle sort key for Internal contactId.CRM-2289
421 $name = 'contact_id';
424 self
::$_columnHeaders[] = array(
425 'name' => $field['title'],
427 'direction' => $direction,
429 $direction = CRM_Utils_Sort
::DONTCARE
;
434 // if we dont have any valid columns, dont add the implicit ones
435 // this allows the template to check on emptiness of column headers
437 self
::$_columnHeaders = array();
440 self
::$_columnHeaders[] = array('desc' => ts('Actions'), 'name' => ts('Action'));
443 $headers = self
::$_columnHeaders;
445 elseif (!empty($this->_returnProperties
)) {
446 self
::$_columnHeaders = array(array('name' => ''),
448 'name' => ts('Name'),
449 'sort' => 'sort_name',
450 'direction' => CRM_Utils_Sort
::ASCENDING
,
453 $properties = self
::makeProperties($this->_returnProperties
);
455 foreach ($properties as $prop) {
456 if (strpos($prop, '-')) {
457 list($loc, $fld, $phoneType) = CRM_Utils_System
::explode('-', $prop, 3);
458 $title = $this->_query
->_fields
[$fld]['title'];
459 if (trim($phoneType) && !is_numeric($phoneType) && strtolower($phoneType) != $fld) {
460 $title .= "-{$phoneType}";
464 elseif (isset($this->_query
->_fields
[$prop]) && isset($this->_query
->_fields
[$prop]['title'])) {
465 $title = $this->_query
->_fields
[$prop]['title'];
471 self
::$_columnHeaders[] = array('name' => $title, 'sort' => $prop);
473 self
::$_columnHeaders[] = array('name' => ts('Actions'));
474 $headers = self
::$_columnHeaders;
477 $headers = $this->getColHeads($action, $output);
484 * Returns total number of rows for the query.
488 * @return int Total number of rows
491 function getTotalCount($action) {
492 // Use count from cache during paging/sorting
493 if (!empty($_GET['crmPID']) ||
!empty($_GET['crmSID'])) {
494 $count = CRM_Core_BAO_Cache
::getItem('Search Results Count', $this->_key
);
497 $count = $this->_query
->searchQuery(0, 0, NULL, TRUE);
498 CRM_Core_BAO_Cache
::setItem($count, 'Search Results Count', $this->_key
);
504 * returns all the rows in the given offset and rowCount
506 * @param enum $action the action being performed
507 * @param int $offset the row number to start from
508 * @param int $rowCount the number of rows to return
509 * @param string $sort the sql string that describes the sort order
510 * @param enum $output what should the result set include (web/email/csv)
512 * @return int the total number of rows for this action
514 function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
515 $config = CRM_Core_Config
::singleton();
517 if (($output == CRM_Core_Selector_Controller
::EXPORT ||
518 $output == CRM_Core_Selector_Controller
::SCREEN
520 $this->_formValues
['radio_ts'] == 'ts_sel'
522 $includeContactIds = TRUE;
525 $includeContactIds = FALSE;
528 // note the formvalues were given by CRM_Contact_Form_Search to us
529 // and contain the search criteria (parameters)
530 // note that the default action is basic
532 $cacheKey = $this->buildPrevNextCache($sort);
533 $result = $this->_query
->getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds);
536 $result = $this->_query
->searchQuery($offset, $rowCount, $sort, FALSE, $includeContactIds);
539 // process the result of the query
541 $permissions = array(CRM_Core_Permission
::getPermission());
542 if (CRM_Core_Permission
::check('delete contacts')) {
543 $permissions[] = CRM_Core_Permission
::DELETE
;
545 $mask = CRM_Core_Action
::mask($permissions);
547 // mask value to hide map link if there are not lat/long
548 $mapMask = $mask & 4095;
550 if ($this->_searchContext
== 'smog') {
551 $gc = CRM_Core_SelectValues
::groupContactStatus();
554 if ($this->_ufGroupID
) {
555 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
558 static $skipFields = array('group', 'tag');
559 foreach ($this->_fields
as $key => $field) {
560 if (!empty($field['in_selector']) &&
561 !in_array($key, $skipFields)
563 if (strpos($key, '-') !== FALSE) {
564 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $key, 3);
566 if ($id == 'Primary') {
567 $locationTypeName = 1;
570 $locationTypeName = CRM_Utils_Array
::value($id, $locationTypes);
571 if (!$locationTypeName) {
576 $locationTypeName = str_replace(' ', '_', $locationTypeName);
577 if (in_array($fieldName, array(
578 'phone', 'im', 'email'))) {
580 $names[] = "{$locationTypeName}-{$fieldName}-{$type}";
583 $names[] = "{$locationTypeName}-{$fieldName}";
587 $names[] = "{$locationTypeName}-{$fieldName}";
591 $names[] = $field['name'];
598 elseif (!empty($this->_returnProperties
)) {
599 $names = self
::makeProperties($this->_returnProperties
);
602 $names = self
::$_properties;
605 $multipleSelectFields = array('preferred_communication_method' => 1);
607 $links = self
::links($this->_context
, $this->_contextMenu
, $this->_key
);
609 //check explicitly added contact to a Smart Group.
610 $groupID = CRM_Utils_Array
::key('1', $this->_formValues
['group']);
612 $pseudoconstants = array();
613 // for CRM-3157 purposes
614 if (in_array('world_region', $names)) {
615 $pseudoconstants['world_region'] = array(
616 'dbName' => 'world_region_id',
617 'values' => CRM_Core_PseudoConstant
::worldRegion()
622 while ($result->fetch()) {
624 $this->_query
->convertToPseudoNames($result);
626 // the columns we are interested in
627 foreach ($names as $property) {
628 if ($property == 'status') {
631 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($property)) {
632 $row[$property] = CRM_Core_BAO_CustomField
::getDisplayValue(
640 $multipleSelectFields &&
641 array_key_exists($property, $multipleSelectFields)
644 $paramsNew = array($key => $result->$property);
645 $name = array($key => array('newName' => $key, 'groupName' => $key));
647 CRM_Core_OptionGroup
::lookupValues($paramsNew, $name, FALSE);
648 $row[$key] = $paramsNew[$key];
650 elseif (strpos($property, '-im')) {
651 $row[$property] = $result->$property;
652 if (!empty($result->$property)) {
653 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
654 $providerId = $property . "-provider_id";
655 $providerName = $imProviders[$result->$providerId];
656 $row[$property] = $result->$property . " ({$providerName})";
659 elseif (in_array($property, array(
660 'addressee', 'email_greeting', 'postal_greeting'))) {
661 $greeting = $property . '_display';
662 $row[$property] = $result->$greeting;
664 elseif (isset($pseudoconstants[$property])) {
665 $row[$property] = CRM_Utils_Array
::value(
666 $result->{$pseudoconstants[$property]['dbName']},
667 $pseudoconstants[$property]['values']
670 elseif (strpos($property, '-url') !== FALSE) {
672 $websiteKey = 'website-1';
673 $propertyArray = explode('-', $property);
674 $websiteFld = $websiteKey . '-' . array_pop($propertyArray);
675 if (!empty($result->$websiteFld)) {
676 $websiteTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Website', 'website_type_id');
677 $websiteType = $websiteTypes[$result->{"$websiteKey-website_type_id"}];
678 $websiteValue = $result->$websiteFld;
679 $websiteUrl = "<a href=\"{$websiteValue}\">{$websiteValue} ({$websiteType})</a>";
681 $row[$property] = $websiteUrl;
684 $row[$property] = isset($result->$property) ?
$result->$property : NULL;
688 if (!empty($result->postal_code_suffix
)) {
689 $row['postal_code'] .= "-" . $result->postal_code_suffix
;
692 if ($output != CRM_Core_Selector_Controller
::EXPORT
&&
693 $this->_searchContext
== 'smog'
695 if (empty($result->status
) &&
698 $contactID = $result->contact_id
;
701 'contact_id' => $contactID,
702 'group_id' => $groupID,
705 $gcDefaults = array();
706 CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_GroupContact', $gcParams, $gcDefaults);
708 if (empty($gcDefaults)) {
709 $row['status'] = ts('Smart');
712 $row['status'] = $gc[$gcDefaults['status']];
716 $row['status'] = NULL;
720 $row['status'] = $gc[$result->status
];
724 if ($output != CRM_Core_Selector_Controller
::EXPORT
) {
725 $row['checkbox'] = CRM_Core_Form
::CB_PREFIX
. $result->contact_id
;
727 if (!empty($this->_formValues
['deleted_contacts']) && CRM_Core_Permission
::check('access deleted contacts')
731 'name' => ts('View'),
732 'url' => 'civicrm/contact/view',
733 'qs' => 'reset=1&cid=%%id%%',
734 'class' => 'no-popup',
735 'title' => ts('View Contact Details'),
738 'name' => ts('Restore'),
739 'url' => 'civicrm/contact/view/delete',
740 'qs' => 'reset=1&cid=%%id%%&restore=1',
741 'title' => ts('Restore Contact'),
744 if (CRM_Core_Permission
::check('delete contacts')) {
746 'name' => ts('Delete Permanently'),
747 'url' => 'civicrm/contact/view/delete',
748 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1',
749 'title' => ts('Permanently Delete Contact'),
752 $row['action'] = CRM_Core_Action
::formLink(
755 array('id' => $result->contact_id
),
758 'contact.selector.row',
763 elseif ((is_numeric(CRM_Utils_Array
::value('geo_code_1', $row))) ||
764 ($config->mapGeoCoding
&& !empty($row['city']) &&
765 CRM_Utils_Array
::value('state_province', $row)
768 $row['action'] = CRM_Core_Action
::formLink(
771 array('id' => $result->contact_id
),
774 'contact.selector.row',
780 $row['action'] = CRM_Core_Action
::formLink(
783 array('id' => $result->contact_id
),
786 'contact.selector.row',
792 // allow components to add more actions
793 CRM_Core_Component
::searchAction($row, $result->contact_id
);
795 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils
::getImage($result->contact_sub_type ?
796 $result->contact_sub_type
: $result->contact_type
,
801 $row['contact_type_orig'] = $result->contact_sub_type ?
$result->contact_sub_type
: $result->contact_type
;
802 $row['contact_sub_type'] = $result->contact_sub_type ?
803 CRM_Contact_BAO_ContactType
::contactTypePairs(FALSE, $result->contact_sub_type
, ', ') : $result->contact_sub_type
;
804 $row['contact_id'] = $result->contact_id
;
805 $row['sort_name'] = $result->sort_name
;
806 if (array_key_exists('id', $row)) {
807 $row['id'] = $result->contact_id
;
812 if (in_array($row['contact_id'], $seenIDs) === FALSE) {
813 $seenIDs[] = $row['contact_id'];
821 function buildPrevNextCache($sort) {
822 $cacheKey = 'civicrm search ' . $this->_key
;
824 // Get current page requested
825 $pageNum = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
826 // When starting from scratch, clear any old cache
828 CRM_Core_BAO_PrevNextCache
::deleteItem(NULL, $cacheKey, 'civicrm_contact');
832 $pageSize = CRM_Utils_Request
::retrieve('crmRowCount', 'Integer', CRM_Core_DAO
::$_nullObject, FALSE, 50);
833 $firstRecord = ($pageNum - 1) * $pageSize;
835 //for alphabetic pagination selection save
836 $sortByCharacter = CRM_Utils_Request
::retrieve('sortByCharacter', 'String', CRM_Core_DAO
::$_nullObject);
838 //for text field pagination selection save
839 $countRow = CRM_Core_BAO_PrevNextCache
::getCount($cacheKey, NULL, "entity_table = 'civicrm_contact'");
841 // $sortByCharacter triggers a refresh in the prevNext cache
842 if ($sortByCharacter && $sortByCharacter != 'all') {
843 $cacheKey .= "_alphabet";
844 $this->fillupPrevNextCache($sort, $cacheKey);
846 elseif ($firstRecord >= $countRow) {
847 $this->fillupPrevNextCache($sort, $cacheKey, $countRow, $firstRecord +
500);
852 function addActions(&$rows) {
853 $config = CRM_Core_Config
::singleton();
855 $permissions = array(CRM_Core_Permission
::getPermission());
856 if (CRM_Core_Permission
::check('delete contacts')) {
857 $permissions[] = CRM_Core_Permission
::DELETE
;
859 $mask = CRM_Core_Action
::mask($permissions);
860 // mask value to hide map link if there are not lat/long
861 $mapMask = $mask & 4095;
863 // mask value to hide map link if there are not lat/long
864 $mapMask = $mask & 4095;
866 $links = self
::links($this->_context
, $this->_contextMenu
, $this->_key
);
869 foreach ($rows as $id => & $row) {
870 if (!empty($this->_formValues
['deleted_contacts']) && CRM_Core_Permission
::check('access deleted contacts')
874 'name' => ts('View'),
875 'url' => 'civicrm/contact/view',
876 'qs' => 'reset=1&cid=%%id%%',
877 'title' => ts('View Contact Details'),
880 'name' => ts('Restore'),
881 'url' => 'civicrm/contact/view/delete',
882 'qs' => 'reset=1&cid=%%id%%&restore=1',
883 'title' => ts('Restore Contact'),
886 if (CRM_Core_Permission
::check('delete contacts')) {
888 'name' => ts('Delete Permanently'),
889 'url' => 'civicrm/contact/view/delete',
890 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1',
891 'title' => ts('Permanently Delete Contact'),
894 $row['action'] = CRM_Core_Action
::formLink(
897 array('id' => $row['contact_id']),
900 'contact.selector.actions',
905 elseif ((is_numeric(CRM_Utils_Array
::value('geo_code_1', $row))) ||
906 ($config->mapGeoCoding
&& !empty($row['city']) &&
907 CRM_Utils_Array
::value('state_province', $row)
910 $row['action'] = CRM_Core_Action
::formLink(
913 array('id' => $row['contact_id']),
916 'contact.selector.actions',
922 $row['action'] = CRM_Core_Action
::formLink(
925 array('id' => $row['contact_id']),
928 'contact.selector.actions',
934 // allow components to add more actions
935 CRM_Core_Component
::searchAction($row, $row['contact_id']);
937 if (!empty($row['contact_type_orig'])) {
938 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils
::getImage($row['contact_type_orig'],
939 FALSE, $row['contact_id']);
944 function removeActions(&$rows) {
945 foreach ($rows as $rid => & $rValue) {
946 unset($rValue['contact_type']);
947 unset($rValue['action']);
952 * @param object $sort
953 * @param string $cacheKey
957 function fillupPrevNextCache($sort, $cacheKey, $start = 0, $end = 500) {
959 // For custom searches, use the contactIDs method
960 if (is_a($this, 'CRM_Contact_Selector_Custom')) {
961 $sql = $this->_search
->contactIDs($start, $end, $sort, TRUE);
962 $replaceSQL = "SELECT contact_a.id as contact_id";
965 // For core searches use the searchQuery method
967 $sql = $this->_query
->searchQuery($start, $end, $sort, FALSE, $this->_query
->_includeContactIds
,
969 $replaceSQL = "SELECT contact_a.id as id";
973 // due to limitations in our search query writer, the above query does not work
974 // in cases where the query is being sorted on a non-contact table
975 // this results in a fatal error :(
976 // see below for the gross hack of trapping the error and not filling
977 // the prev next cache in this situation
978 // the other alternative of running the FULL query will just be incredibly inefficient
979 // and slow things down way too much on large data sets / complex queries
982 INSERT INTO civicrm_prevnext_cache ( entity_table, entity_id1, entity_id2, cacheKey, data )
983 SELECT 'civicrm_contact', contact_a.id, contact_a.id, '$cacheKey', contact_a.display_name
986 $sql = str_replace($replaceSQL, $insertSQL, $sql);
988 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
989 $result = CRM_Core_DAO
::executeQuery($sql);
992 if (is_a($result, 'DB_Error')) {
993 // check if we get error during core search
995 // in the case of error, try rebuilding cache using full sql which is used for search selector display
996 // this fixes the bugs reported in CRM-13996 & CRM-14438
997 $this->rebuildPreNextCache($start, $end, $sort, $cacheKey);
1000 // return if above query fails
1005 // also record an entry in the cache key table, so we can delete it periodically
1006 CRM_Core_BAO_Cache
::setItem($cacheKey, 'CiviCRM Search PrevNextCache', $cacheKey);
1010 * This function is called to rebuild prev next cache using full sql in case of core search ( excluding custom search)
1012 * @param int $start start for limit clause
1013 * @param int $end end for limit clause
1015 * @param string $cacheKey cache key
1017 * @internal param $object $sort sort object
1020 function rebuildPreNextCache($start, $end, $sort, $cacheKey) {
1021 // generate full SQL
1022 $sql = $this->_query
->searchQuery($start, $end, $sort, FALSE, $this->_query
->_includeContactIds
,
1023 FALSE, FALSE, TRUE);
1025 $dao = CRM_Core_DAO
::executeQuery($sql);
1027 // build insert query, note that currently we build cache for 500 contact records at a time, hence below approach
1028 $insertValues = array();
1029 while($dao->fetch()) {
1030 $insertValues[] = "('civicrm_contact', {$dao->contact_id}, {$dao->contact_id}, '{$cacheKey}', '{$dao->sort_name}')";
1033 //update pre/next cache using single insert query
1034 if (!empty($insertValues)) {
1035 $sql = 'INSERT INTO civicrm_prevnext_cache ( entity_table, entity_id1, entity_id2, cacheKey, data ) VALUES
1036 '.implode(',', $insertValues);
1038 $result = CRM_Core_DAO
::executeQuery($sql);
1043 * Given the current formValues, gets the query in local
1047 reference) $formValues submitted formValues
1049 * @return array $qill which contains an array of strings
1053 // the current internationalisation is bad, but should more or less work
1054 // for most of "European" languages
1055 public function getQILL() {
1056 return $this->_query
->qill();
1060 * name of export file.
1062 * @param string $output type of output
1064 * @return string name of the file
1066 function getExportFileName($output = 'csv') {
1067 return ts('CiviCRM Contact Search');
1071 * get colunmn headers for search selector
1074 * @return array $_columnHeaders
1077 private static function &_getColumnHeaders() {
1078 if (!isset(self
::$_columnHeaders)) {
1079 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1080 'address_options', TRUE, NULL, TRUE
1083 self
::$_columnHeaders = array(
1084 'contact_type' => array('desc' => ts('Contact Type')),
1085 'sort_name' => array(
1086 'name' => ts('Name'),
1087 'sort' => 'sort_name',
1088 'direction' => CRM_Utils_Sort
::ASCENDING
,
1092 $defaultAddress = array(
1093 'street_address' => array('name' => ts('Address')),
1095 'name' => ts('City'),
1097 'direction' => CRM_Utils_Sort
::DONTCARE
,
1099 'state_province' => array(
1100 'name' => ts('State'),
1101 'sort' => 'state_province',
1102 'direction' => CRM_Utils_Sort
::DONTCARE
,
1104 'postal_code' => array(
1105 'name' => ts('Postal'),
1106 'sort' => 'postal_code',
1107 'direction' => CRM_Utils_Sort
::DONTCARE
,
1110 'name' => ts('Country'),
1111 'sort' => 'country',
1112 'direction' => CRM_Utils_Sort
::DONTCARE
,
1116 foreach ($defaultAddress as $columnName => $column) {
1117 if (!empty($addressOptions[$columnName])) {
1118 self
::$_columnHeaders[$columnName] = $column;
1122 self
::$_columnHeaders['email'] = array(
1123 'name' => ts('Email'),
1125 'direction' => CRM_Utils_Sort
::DONTCARE
,
1128 self
::$_columnHeaders['phone'] = array('name' => ts('Phone'));
1130 return self
::$_columnHeaders;
1133 function &getQuery() {
1134 return $this->_query
;
1137 function alphabetQuery() {
1138 return $this->_query
->searchQuery(NULL, NULL, NULL, FALSE, FALSE, TRUE);
1141 function contactIDQuery($params, $action, $sortID, $displayRelationshipType = NULL, $queryOperator = 'AND') {
1142 $sortOrder = &$this->getSortOrder($this->_action
);
1143 $sort = new CRM_Utils_Sort($sortOrder, $sortID);
1145 // rectify params to what proximity search expects if there is a value for prox_distance
1146 // CRM-7021 CRM-7905
1147 if (!empty($params)) {
1148 CRM_Contact_BAO_ProximityQuery
::fixInputParams($params);
1151 if (!$displayRelationshipType) {
1152 $query = new CRM_Contact_BAO_Query($params,
1153 $this->_returnProperties
,
1154 NULL, FALSE, FALSE, 1,
1155 FALSE, TRUE, TRUE, NULL,
1160 $query = new CRM_Contact_BAO_Query($params, $this->_returnProperties
,
1161 NULL, FALSE, FALSE, 1,
1162 FALSE, TRUE, TRUE, $displayRelationshipType,
1166 $value = $query->searchQuery(0, 0, $sort,
1167 FALSE, FALSE, FALSE,
1173 function &makeProperties(&$returnProperties) {
1174 $properties = array();
1175 foreach ($returnProperties as $name => $value) {
1176 if ($name != 'location') {
1177 // special handling for group and tag
1178 if (in_array($name, array('group', 'tag'))) {
1182 // special handling for notes
1183 if (in_array($name, array('note', 'note_subject', 'note_body'))) {
1187 $properties[] = $name;
1190 // extract all the location stuff
1191 foreach ($value as $n => $v) {
1192 foreach ($v as $n1 => $v1) {
1193 if (!strpos('_id', $n1) && $n1 != 'location_type') {
1194 $properties[] = "{$n}-{$n1}";