Merge pull request #3208 from eileenmcnaughton/comments
[civicrm-core.git] / CRM / Contact / Selector.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
06b69b18 4 | CiviCRM version 4.5 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26*/
27
28/**
29 *
30 * @package CRM
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35
36/**
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.
40 *
41 */
42class CRM_Contact_Selector extends CRM_Core_Selector_Base implements CRM_Core_Selector_API {
43
44 /**
45 * This defines two actions- View and Edit.
46 *
47 * @var array
48 * @static
49 */
50 static $_links = NULL;
51
52 /**
53 * we use desc to remind us what that column is, name is used in the tpl
54 *
55 * @var array
56 * @static
57 */
58 static $_columnHeaders;
59
60 /**
61 * Properties of contact we're interested in displaying
62 * @var array
63 * @static
64 */
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',
72 );
73
74 /**
75 * formValues is the array returned by exportValues called on
76 * the HTML_QuickForm_Controller for that page.
77 *
78 * @var array
79 * @access protected
80 */
81 public $_formValues;
82
83 /**
84 * The contextMenu
85 *
86 * @var array
87 * @access protected
88 */
89 protected $_contextMenu;
90
91 /**
92 * params is the array in a value used by the search query creator
93 *
94 * @var array
95 * @access protected
96 */
97 public $_params;
98
99 /**
100 * The return properties used for search
101 *
102 * @var array
103 * @access protected
104 */
105 protected $_returnProperties;
106
107 /**
108 * represent the type of selector
109 *
110 * @var int
111 * @access protected
112 */
113 protected $_action;
114
115 protected $_searchContext;
116
117 protected $_query;
118
119 /**
120 * group id
121 *
122 * @var int
123 */
124 protected $_ufGroupID;
125
126 /**
127 * the public visible fields to be shown to the user
128 *
129 * @var array
130 * @access protected
131 */
132 protected $_fields;
133
134 /**
135 * Class constructor
136 *
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.
140 *
141 * @return CRM_Contact_Selector
142 * @access public
143 */
144 function __construct(
145 $customSearchClass,
146 $formValues = NULL,
147 $params = NULL,
148 $returnProperties = NULL,
149 $action = CRM_Core_Action::NONE,
150 $includeContactIds = FALSE,
151 $searchDescendentGroups = TRUE,
152 $searchContext = 'search',
153 $contextMenu = NULL
154 ) {
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) {
158 return;
159 }
160
161 // submitted form values
162 $this->_formValues = &$formValues;
163 $this->_params = &$params;
164 $this->_returnProperties = &$returnProperties;
165 $this->_contextMenu = &$contextMenu;
166 $this->_context = $searchContext;
167
168 // type of selector
169 $this->_action = $action;
170
171 $this->_searchContext = $searchContext;
172
173 $this->_ufGroupID = CRM_Utils_Array::value('uf_group_id', $this->_formValues);
174
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
180 );
181 self::$_columnHeaders = NULL;
182
183 $this->_customFields = CRM_Core_BAO_CustomField::getFieldsForImport('Individual');
184
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;
189 }
190
191 $displayRelationshipType = CRM_Utils_Array::value('display_relationship_type', $this->_formValues);
192 $operator = CRM_Utils_Array::value('operator', $this->_formValues, 'AND');
193
194 // rectify params to what proximity search expects if there is a value for prox_distance
195 // CRM-7021
196 if (!empty($this->_params)) {
197 CRM_Contact_BAO_ProximityQuery::fixInputParams($this->_params);
198 }
199
200 $this->_query = new CRM_Contact_BAO_Query(
201 $this->_params,
202 $this->_returnProperties,
203 NULL,
204 $includeContactIds,
205 FALSE,
206 CRM_Contact_BAO_Query::MODE_CONTACTS,
207 FALSE,
208 $searchDescendentGroups,
209 FALSE,
210 $displayRelationshipType,
211 $operator
212 );
213
214 $this->_options = &$this->_query->_options;
215 }
216 //end of constructor
217
218 /**
219 * This method returns the links that are given for each search row.
220 * currently the links added for each row are
221 *
222 * - View
223 * - Edit
224 *
225 * @return array
226 * @access public
227 *
228 */
229 static function &links() {
230 list($context, $contextMenu, $key) = func_get_args();
231 $extraParams = ($key) ? "&key={$key}" : NULL;
232 $searchContext = ($context) ? "&context=$context" : NULL;
233
234 if (!(self::$_links)) {
235 self::$_links = array(
236 CRM_Core_Action::VIEW => array(
237 'name' => ts('View'),
238 'url' => 'civicrm/contact/view',
8e4ec1f5 239 'class' => 'no-popup',
6a488035
TO
240 'qs' => "reset=1&cid=%%id%%{$searchContext}{$extraParams}",
241 'title' => ts('View Contact Details'),
242 'ref' => 'view-contact',
243 ),
244 CRM_Core_Action::UPDATE => array(
245 'name' => ts('Edit'),
246 'url' => 'civicrm/contact/add',
8e4ec1f5 247 'class' => 'no-popup',
6a488035
TO
248 'qs' => "reset=1&action=update&cid=%%id%%{$searchContext}{$extraParams}",
249 'title' => ts('Edit Contact Details'),
250 'ref' => 'edit-contact',
251 ),
252 );
253
254 $config = CRM_Core_Config::singleton();
255 if ($config->mapAPIKey && $config->mapProvider) {
256 self::$_links[CRM_Core_Action::MAP] = array(
257 'name' => ts('Map'),
258 'url' => 'civicrm/contact/map',
259 'qs' => "reset=1&cid=%%id%%{$searchContext}{$extraParams}",
260 'title' => ts('Map Contact'),
261 );
262 }
263
264 // Adding Context Menu Links in more action
265 if ($contextMenu) {
266 $counter = 7000;
267 foreach ($contextMenu as $key => $value) {
268 $contextVal = '&context=' . $value['key'];
269 if ($value['key'] == 'delete') {
270 $contextVal = $searchContext;
271 }
6a488035
TO
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}";
276 }
277 elseif ($value['key'] == 'email') {
278 $url = "civicrm/contact/view/activity";
279 $qs = "atype=3&action=add&reset=1&cid=%%id%%{$extraParams}";
280 }
281
282 self::$_links[$counter++] = array(
283 'name' => $value['title'],
284 'url' => $url,
285 'qs' => $qs,
286 'title' => $value['title'],
287 'ref' => $value['ref'],
8e4ec1f5 288 'class' => CRM_Utils_Array::value('class', $value),
6a488035
TO
289 );
290 }
291 }
292 }
293 return self::$_links;
294 }
295 //end of function
296
297 /**
298 * getter for array of the parameters required for creating pager.
299 *
300 * @param
301 * @access public
302 */
303 function getPagerParams($action, &$params) {
304 $params['status'] = ts('Contact %%StatusMessage%%');
305 $params['csvString'] = NULL;
306 $params['rowCount'] = CRM_Utils_Pager::ROWCOUNT;
307
308 $params['buttonTop'] = 'PagerTopButton';
309 $params['buttonBottom'] = 'PagerBottomButton';
310 }
311 //end of function
6a488035 312
5defa2fd 313 function &getColHeads($action = NULL, $output = NULL) {
6a488035 314 $colHeads = self::_getColumnHeaders();
6a488035
TO
315 $colHeads[] = array('desc' => ts('Actions'), 'name' => ts('Action'));
316 return $colHeads;
317 }
318
319 /**
320 * returns the column headers as an array of tuples:
321 * (name, sortName (key to the sort array))
322 *
323 * @param string $action the action being performed
324 * @param enum $output what should the result set include (web/email/csv)
325 *
326 * @return array the column headers that need to be displayed
327 * @access public
328 */
329 function &getColumnHeaders($action = NULL, $output = NULL) {
330 $headers = NULL;
b3eeb853 331
332 // unset return property elements that we don't care
333 if (!empty($this->_returnProperties)) {
334 $doNotCareElements = array(
335 'contact_type',
336 'contact_sub_type',
337 'sort_name',
338 );
339 foreach ( $doNotCareElements as $value) {
340 unset($this->_returnProperties[$value]);
341 }
342 }
343
6a488035
TO
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'];
349 }
350 }
351 $headers = $csvHeaders;
352 }
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) &&
357 $column['name'] &&
358 $column['name'] != ts('Name')
359 ) {
360 $csvHeaders[$key] = $column['name'];
361 }
362 }
363 $headers = $csvHeaders;
364 }
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;
370 $empty = TRUE;
371 if (!self::$_columnHeaders) {
372 self::$_columnHeaders = array(array('name' => ''),
373 array(
374 'name' => ts('Name'),
375 'sort' => 'sort_name',
376 'direction' => CRM_Utils_Sort::ASCENDING,
377 ),
378 );
379
b2b0530a 380 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
6a488035
TO
381
382 foreach ($this->_fields as $name => $field) {
a7488080 383 if (!empty($field['in_selector']) &&
6a488035
TO
384 !in_array($name, $skipFields)
385 ) {
386 if (strpos($name, '-') !== FALSE) {
387 list($fieldName, $lType, $type) = CRM_Utils_System::explode('-', $name, 3);
388
389 if ($lType == 'Primary') {
390 $locationTypeName = 1;
391 }
392 else {
393 $locationTypeName = $locationTypes[$lType];
394 }
395
396 if (in_array($fieldName, array(
397 'phone', 'im', 'email'))) {
398 if ($type) {
399 $name = "`$locationTypeName-$fieldName-$type`";
400 }
401 else {
402 $name = "`$locationTypeName-$fieldName`";
403 }
404 }
405 else {
406 $name = "`$locationTypeName-$fieldName`";
407 }
408 }
409 //to handle sort key for Internal contactId.CRM-2289
410 if ($name == 'id') {
411 $name = 'contact_id';
412 }
413
414 self::$_columnHeaders[] = array(
415 'name' => $field['title'],
416 'sort' => $name,
417 'direction' => $direction,
418 );
419 $direction = CRM_Utils_Sort::DONTCARE;
420 $empty = FALSE;
421 }
422 }
423
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
426 if ($empty) {
427 self::$_columnHeaders = array();
428 }
429 else {
430 self::$_columnHeaders[] = array('desc' => ts('Actions'), 'name' => ts('Action'));
431 }
432 }
433 $headers = self::$_columnHeaders;
434 }
435 elseif (!empty($this->_returnProperties)) {
6a488035
TO
436 self::$_columnHeaders = array(array('name' => ''),
437 array(
438 'name' => ts('Name'),
439 'sort' => 'sort_name',
440 'direction' => CRM_Utils_Sort::ASCENDING,
441 ),
442 );
443 $properties = self::makeProperties($this->_returnProperties);
444
445 foreach ($properties as $prop) {
6a488035
TO
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}";
451 }
452 $title .= " ($loc)";
453 }
454 elseif (isset($this->_query->_fields[$prop]) && isset($this->_query->_fields[$prop]['title'])) {
455 $title = $this->_query->_fields[$prop]['title'];
b3eeb853 456 }
457 else {
6a488035
TO
458 $title = '';
459 }
460
461 self::$_columnHeaders[] = array('name' => $title, 'sort' => $prop);
462 }
463 self::$_columnHeaders[] = array('name' => ts('Actions'));
464 $headers = self::$_columnHeaders;
465 }
466 else {
467 $headers = $this->getColHeads($action, $output);
468 }
469
470 return $headers;
471 }
472
473 /**
474 * Returns total number of rows for the query.
475 *
476 * @param
477 *
478 * @return int Total number of rows
479 * @access public
480 */
481 function getTotalCount($action) {
f0c8c107
CW
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);
485 }
486 if (empty($count)) {
487 $count = $this->_query->searchQuery(0, 0, NULL, TRUE);
488 CRM_Core_BAO_Cache::setItem($count, 'Search Results Count', $this->_key);
489 }
490 return $count;
6a488035
TO
491 }
492
493 /**
494 * returns all the rows in the given offset and rowCount
495 *
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)
501 *
502 * @return int the total number of rows for this action
503 */
504 function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
505 $config = CRM_Core_Config::singleton();
506
507 if (($output == CRM_Core_Selector_Controller::EXPORT ||
508 $output == CRM_Core_Selector_Controller::SCREEN
509 ) &&
510 $this->_formValues['radio_ts'] == 'ts_sel'
511 ) {
512 $includeContactIds = TRUE;
513 }
514 else {
515 $includeContactIds = FALSE;
516 }
517
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
4243847f
CW
521 if ($rowCount) {
522 $cacheKey = $this->buildPrevNextCache($sort);
523 $result = $this->_query->getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds);
524 }
525 else {
526 $result = $this->_query->searchQuery($offset, $rowCount, $sort, FALSE, $includeContactIds);
527 }
6a488035
TO
528
529 // process the result of the query
530 $rows = array();
531 $permissions = array(CRM_Core_Permission::getPermission());
532 if (CRM_Core_Permission::check('delete contacts')) {
533 $permissions[] = CRM_Core_Permission::DELETE;
534 }
535 $mask = CRM_Core_Action::mask($permissions);
536
537 // mask value to hide map link if there are not lat/long
538 $mapMask = $mask & 4095;
539
540 if ($this->_searchContext == 'smog') {
541 $gc = CRM_Core_SelectValues::groupContactStatus();
542 }
543
544 if ($this->_ufGroupID) {
b2b0530a 545 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
6a488035
TO
546
547 $names = array();
548 static $skipFields = array('group', 'tag');
549 foreach ($this->_fields as $key => $field) {
a7488080 550 if (!empty($field['in_selector']) &&
6a488035
TO
551 !in_array($key, $skipFields)
552 ) {
553 if (strpos($key, '-') !== FALSE) {
554 list($fieldName, $id, $type) = CRM_Utils_System::explode('-', $key, 3);
555
556 if ($id == 'Primary') {
557 $locationTypeName = 1;
558 }
559 else {
560 $locationTypeName = CRM_Utils_Array::value($id, $locationTypes);
561 if (!$locationTypeName) {
562 continue;
563 }
564 }
565
566 $locationTypeName = str_replace(' ', '_', $locationTypeName);
567 if (in_array($fieldName, array(
568 'phone', 'im', 'email'))) {
569 if ($type) {
570 $names[] = "{$locationTypeName}-{$fieldName}-{$type}";
571 }
572 else {
573 $names[] = "{$locationTypeName}-{$fieldName}";
574 }
575 }
576 else {
577 $names[] = "{$locationTypeName}-{$fieldName}";
578 }
579 }
580 else {
581 $names[] = $field['name'];
582 }
583 }
584 }
585
586 $names[] = "status";
587 }
588 elseif (!empty($this->_returnProperties)) {
589 $names = self::makeProperties($this->_returnProperties);
590 }
591 else {
592 $names = self::$_properties;
593 }
594
595 $multipleSelectFields = array('preferred_communication_method' => 1);
596
597 $links = self::links($this->_context, $this->_contextMenu, $this->_key);
598
599 //check explicitly added contact to a Smart Group.
600 $groupID = CRM_Utils_Array::key('1', $this->_formValues['group']);
601
0c145cc0 602 $pseudoconstants = array();
6a488035 603 // for CRM-3157 purposes
6a488035 604 if (in_array('world_region', $names)) {
0c145cc0
DL
605 $pseudoconstants['world_region'] = array(
606 'dbName' => 'world_region_id',
607 'values' => CRM_Core_PseudoConstant::worldRegion()
608 );
6a488035
TO
609 }
610
611 $seenIDs = array();
612 while ($result->fetch()) {
613 $row = array();
d9ab802d 614 $this->_query->convertToPseudoNames($result);
6a488035
TO
615
616 // the columns we are interested in
617 foreach ($names as $property) {
618 if ($property == 'status') {
619 continue;
620 }
621 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($property)) {
0c145cc0
DL
622 $row[$property] = CRM_Core_BAO_CustomField::getDisplayValue(
623 $result->$property,
6a488035
TO
624 $cfID,
625 $this->_options,
626 $result->contact_id
627 );
628 }
0c145cc0
DL
629 elseif (
630 $multipleSelectFields &&
6a488035
TO
631 array_key_exists($property, $multipleSelectFields)
632 ) {
6a488035
TO
633 $key = $property;
634 $paramsNew = array($key => $result->$property);
0c145cc0 635 $name = array($key => array('newName' => $key, 'groupName' => $key));
6a488035 636
6a488035
TO
637 CRM_Core_OptionGroup::lookupValues($paramsNew, $name, FALSE);
638 $row[$key] = $paramsNew[$key];
639 }
640 elseif (strpos($property, '-im')) {
641 $row[$property] = $result->$property;
642 if (!empty($result->$property)) {
e7e657f0 643 $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
6a488035
TO
644 $providerId = $property . "-provider_id";
645 $providerName = $imProviders[$result->$providerId];
646 $row[$property] = $result->$property . " ({$providerName})";
647 }
648 }
649 elseif (in_array($property, array(
650 'addressee', 'email_greeting', 'postal_greeting'))) {
651 $greeting = $property . '_display';
652 $row[$property] = $result->$greeting;
653 }
0c145cc0
DL
654 elseif (isset($pseudoconstants[$property])) {
655 $row[$property] = CRM_Utils_Array::value(
656 $result->{$pseudoconstants[$property]['dbName']},
657 $pseudoconstants[$property]['values']
658 );
6a488035
TO
659 }
660 elseif (strpos($property, '-url') !== FALSE) {
661 $websiteUrl = '';
662 $websiteKey = 'website-1';
663 $propertyArray = explode('-', $property);
664 $websiteFld = $websiteKey . '-' . array_pop($propertyArray);
665 if (!empty($result->$websiteFld)) {
cbf48754 666 $websiteTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id');
6a488035
TO
667 $websiteType = $websiteTypes[$result->{"$websiteKey-website_type_id"}];
668 $websiteValue = $result->$websiteFld;
669 $websiteUrl = "<a href=\"{$websiteValue}\">{$websiteValue} ({$websiteType})</a>";
670 }
671 $row[$property] = $websiteUrl;
672 }
673 else {
674 $row[$property] = isset($result->$property) ? $result->$property : NULL;
675 }
676 }
677
678 if (!empty($result->postal_code_suffix)) {
679 $row['postal_code'] .= "-" . $result->postal_code_suffix;
680 }
681
682 if ($output != CRM_Core_Selector_Controller::EXPORT &&
683 $this->_searchContext == 'smog'
684 ) {
685 if (empty($result->status) &&
686 $groupID
687 ) {
688 $contactID = $result->contact_id;
689 if ($contactID) {
690 $gcParams = array(
691 'contact_id' => $contactID,
692 'group_id' => $groupID,
693 );
694
695 $gcDefaults = array();
696 CRM_Core_DAO::commonRetrieve('CRM_Contact_DAO_GroupContact', $gcParams, $gcDefaults);
697
698 if (empty($gcDefaults)) {
699 $row['status'] = ts('Smart');
700 }
701 else {
702 $row['status'] = $gc[$gcDefaults['status']];
703 }
704 }
705 else {
706 $row['status'] = NULL;
707 }
708 }
709 else {
710 $row['status'] = $gc[$result->status];
711 }
712 }
713
714 if ($output != CRM_Core_Selector_Controller::EXPORT) {
715 $row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->contact_id;
716
a7488080 717 if (!empty($this->_formValues['deleted_contacts']) && CRM_Core_Permission::check('access deleted contacts')
6a488035
TO
718 ) {
719 $links = array(
720 array(
721 'name' => ts('View'),
722 'url' => 'civicrm/contact/view',
723 'qs' => 'reset=1&cid=%%id%%',
8e4ec1f5 724 'class' => 'no-popup',
6a488035
TO
725 'title' => ts('View Contact Details'),
726 ),
727 array(
728 'name' => ts('Restore'),
729 'url' => 'civicrm/contact/view/delete',
730 'qs' => 'reset=1&cid=%%id%%&restore=1',
731 'title' => ts('Restore Contact'),
732 ),
733 );
734 if (CRM_Core_Permission::check('delete contacts')) {
735 $links[] = array(
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'),
740 );
741 }
87dab4a4
AH
742 $row['action'] = CRM_Core_Action::formLink(
743 $links,
744 NULL,
745 array('id' => $result->contact_id),
746 ts('more'),
747 FALSE,
748 'contact.selector.row',
749 'Contact',
750 $result->contact_id
751 );
6a488035
TO
752 }
753 elseif ((is_numeric(CRM_Utils_Array::value('geo_code_1', $row))) ||
8cc574cf 754 ($config->mapGeoCoding && !empty($row['city']) &&
6a488035
TO
755 CRM_Utils_Array::value('state_province', $row)
756 )
757 ) {
87dab4a4
AH
758 $row['action'] = CRM_Core_Action::formLink(
759 $links,
760 $mask,
761 array('id' => $result->contact_id),
762 ts('more'),
763 FALSE,
764 'contact.selector.row',
765 'Contact',
766 $result->contact_id
767 );
6a488035
TO
768 }
769 else {
87dab4a4
AH
770 $row['action'] = CRM_Core_Action::formLink(
771 $links,
772 $mapMask,
773 array('id' => $result->contact_id),
774 ts('more'),
775 FALSE,
776 'contact.selector.row',
777 'Contact',
778 $result->contact_id
779 );
6a488035
TO
780 }
781
782 // allow components to add more actions
783 CRM_Core_Component::searchAction($row, $result->contact_id);
784
785 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ?
786 $result->contact_sub_type : $result->contact_type,
787 FALSE,
788 $result->contact_id
789 );
790
2bbddafc 791 $row['contact_type_orig'] = $result->contact_sub_type ? $result->contact_sub_type : $result->contact_type;
6a488035
TO
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;
798 }
799 }
800
801 // Dedupe contacts
802 if (in_array($row['contact_id'], $seenIDs) === FALSE) {
803 $seenIDs[] = $row['contact_id'];
804 $rows[] = $row;
805 }
806 }
807
6a488035
TO
808 return $rows;
809 }
810
811 function buildPrevNextCache($sort) {
4243847f
CW
812 $cacheKey = 'civicrm search ' . $this->_key;
813
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
817 if (!$pageNum) {
818 CRM_Core_BAO_PrevNextCache::deleteItem(NULL, $cacheKey, 'civicrm_contact');
819 $pageNum = 1;
820 }
6a488035 821
64951b63
CW
822 $pageSize = CRM_Utils_Request::retrieve('crmRowCount', 'Integer', CRM_Core_DAO::$_nullObject, FALSE, 50);
823 $firstRecord = ($pageNum - 1) * $pageSize;
6a488035
TO
824
825 //for alphabetic pagination selection save
826 $sortByCharacter = CRM_Utils_Request::retrieve('sortByCharacter', 'String', CRM_Core_DAO::$_nullObject);
827
828 //for text field pagination selection save
4243847f 829 $countRow = CRM_Core_BAO_PrevNextCache::getCount($cacheKey, NULL, "entity_table = 'civicrm_contact'");
6a488035 830
64951b63 831 // $sortByCharacter triggers a refresh in the prevNext cache
4243847f
CW
832 if ($sortByCharacter && $sortByCharacter != 'all') {
833 $cacheKey .= "_alphabet";
834 $this->fillupPrevNextCache($sort, $cacheKey);
6a488035 835 }
64951b63 836 elseif ($firstRecord >= $countRow) {
4243847f 837 $this->fillupPrevNextCache($sort, $cacheKey, $countRow, $firstRecord + 500);
64951b63 838 }
4243847f 839 return $cacheKey;
6a488035
TO
840 }
841
842 function addActions(&$rows) {
843 $config = CRM_Core_Config::singleton();
844
845 $permissions = array(CRM_Core_Permission::getPermission());
846 if (CRM_Core_Permission::check('delete contacts')) {
847 $permissions[] = CRM_Core_Permission::DELETE;
848 }
849 $mask = CRM_Core_Action::mask($permissions);
850 // mask value to hide map link if there are not lat/long
851 $mapMask = $mask & 4095;
852
853 // mask value to hide map link if there are not lat/long
854 $mapMask = $mask & 4095;
855
856 $links = self::links($this->_context, $this->_contextMenu, $this->_key);
857
858
859 foreach ($rows as $id => & $row) {
a7488080 860 if (!empty($this->_formValues['deleted_contacts']) && CRM_Core_Permission::check('access deleted contacts')
6a488035
TO
861 ) {
862 $links = array(
863 array(
864 'name' => ts('View'),
865 'url' => 'civicrm/contact/view',
866 'qs' => 'reset=1&cid=%%id%%',
867 'title' => ts('View Contact Details'),
868 ),
869 array(
870 'name' => ts('Restore'),
871 'url' => 'civicrm/contact/view/delete',
872 'qs' => 'reset=1&cid=%%id%%&restore=1',
873 'title' => ts('Restore Contact'),
874 ),
875 );
876 if (CRM_Core_Permission::check('delete contacts')) {
877 $links[] = array(
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'),
882 );
883 }
87dab4a4
AH
884 $row['action'] = CRM_Core_Action::formLink(
885 $links,
886 null,
887 array('id' => $row['contact_id']),
888 ts('more'),
889 FALSE,
890 'contact.selector.actions',
891 'Contact',
892 $row['contact_id']
893 );
6a488035
TO
894 }
895 elseif ((is_numeric(CRM_Utils_Array::value('geo_code_1', $row))) ||
8cc574cf 896 ($config->mapGeoCoding && !empty($row['city']) &&
6a488035
TO
897 CRM_Utils_Array::value('state_province', $row)
898 )
899 ) {
87dab4a4
AH
900 $row['action'] = CRM_Core_Action::formLink(
901 $links,
902 $mask,
903 array('id' => $row['contact_id']),
904 ts('more'),
905 FALSE,
906 'contact.selector.actions',
907 'Contact',
908 $row['contact_id']
909 );
6a488035
TO
910 }
911 else {
87dab4a4
AH
912 $row['action'] = CRM_Core_Action::formLink(
913 $links,
914 $mapMask,
915 array('id' => $row['contact_id']),
916 ts('more'),
917 FALSE,
918 'contact.selector.actions',
919 'Contact',
920 $row['contact_id']
921 );
6a488035
TO
922 }
923
924 // allow components to add more actions
925 CRM_Core_Component::searchAction($row, $row['contact_id']);
926
2bbddafc
CW
927 if (!empty($row['contact_type_orig'])) {
928 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage($row['contact_type_orig'],
6a488035
TO
929 FALSE, $row['contact_id']);
930 }
931 }
932 }
933
934 function removeActions(&$rows) {
935 foreach ($rows as $rid => & $rValue) {
936 unset($rValue['contact_type']);
937 unset($rValue['action']);
938 }
939 }
940
64951b63
CW
941 /**
942 * @param object $sort
943 * @param string $cacheKey
944 * @param int $start
945 * @param int $end
946 */
4243847f 947 function fillupPrevNextCache($sort, $cacheKey, $start = 0, $end = 500) {
778a10cb 948 $coreSearch = TRUE;
64951b63 949 // For custom searches, use the contactIDs method
6a488035 950 if (is_a($this, 'CRM_Contact_Selector_Custom')) {
64951b63 951 $sql = $this->_search->contactIDs($start, $end, $sort, TRUE);
6a488035 952 $replaceSQL = "SELECT contact_a.id as contact_id";
778a10cb 953 $coreSearch = FALSE;
6a488035 954 }
64951b63 955 // For core searches use the searchQuery method
6a488035 956 else {
778a10cb 957 $sql = $this->_query->searchQuery($start, $end, $sort, FALSE, $this->_query->_includeContactIds,
958 FALSE, TRUE, TRUE);
6a488035
TO
959 $replaceSQL = "SELECT contact_a.id as id";
960 }
961
962 // CRM-9096
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
970
971 $insertSQL = "
972INSERT INTO civicrm_prevnext_cache ( entity_table, entity_id1, entity_id2, cacheKey, data )
973SELECT 'civicrm_contact', contact_a.id, contact_a.id, '$cacheKey', contact_a.display_name
974";
975
976 $sql = str_replace($replaceSQL, $insertSQL, $sql);
977
6a4257d4 978 $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
6a488035 979 $result = CRM_Core_DAO::executeQuery($sql);
6a4257d4 980 unset($errorScope);
6a488035
TO
981
982 if (is_a($result, 'DB_Error')) {
778a10cb 983 // check if we get error during core search
984 if ($coreSearch) {
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);
988 }
989 else {
990 // return if above query fails
991 return;
992 }
6a488035
TO
993 }
994
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);
997 }
998
778a10cb 999 /**
1000 * This function is called to rebuild prev next cache using full sql in case of core search ( excluding custom search)
1001 *
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
1006 *
1007 * @return void
1008 */
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);
1013
1014 $dao = CRM_Core_DAO::executeQuery($sql);
1015
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}')";
1020 }
1021
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);
1026
1027 $result = CRM_Core_DAO::executeQuery($sql);
1028 }
1029 }
1030
6a488035
TO
1031 /**
1032 * Given the current formValues, gets the query in local
1033 * language
1034 *
1035 * @param array(
1036 reference) $formValues submitted formValues
1037 *
1038 * @return array $qill which contains an array of strings
1039 * @access public
1040 */
1041
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();
1046 }
1047
1048 /**
1049 * name of export file.
1050 *
1051 * @param string $output type of output
1052 *
1053 * @return string name of the file
1054 */
1055 function getExportFileName($output = 'csv') {
1056 return ts('CiviCRM Contact Search');
1057 }
1058
1059 /**
1060 * get colunmn headers for search selector
1061 *
1062 *
1063 * @return array $_columnHeaders
1064 * @access private
1065 */
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
1070 );
1071
5defa2fd
KJ
1072 self::$_columnHeaders = array(
1073 'contact_type' => array('desc' => ts('Contact Type')),
6a488035
TO
1074 'sort_name' => array(
1075 'name' => ts('Name'),
1076 'sort' => 'sort_name',
1077 'direction' => CRM_Utils_Sort::ASCENDING,
1078 ),
1079 );
1080
5defa2fd
KJ
1081 $defaultAddress = array(
1082 'street_address' => array('name' => ts('Address')),
1083 'city' => array(
1084 'name' => ts('City'),
6a488035
TO
1085 'sort' => 'city',
1086 'direction' => CRM_Utils_Sort::DONTCARE,
1087 ),
5defa2fd
KJ
1088 'state_province' => array(
1089 'name' => ts('State'),
6a488035
TO
1090 'sort' => 'state_province',
1091 'direction' => CRM_Utils_Sort::DONTCARE,
1092 ),
5defa2fd
KJ
1093 'postal_code' => array(
1094 'name' => ts('Postal'),
6a488035
TO
1095 'sort' => 'postal_code',
1096 'direction' => CRM_Utils_Sort::DONTCARE,
1097 ),
5defa2fd
KJ
1098 'country' => array(
1099 'name' => ts('Country'),
6a488035
TO
1100 'sort' => 'country',
1101 'direction' => CRM_Utils_Sort::DONTCARE,
1102 ),
1103 );
1104
1105 foreach ($defaultAddress as $columnName => $column) {
a7488080 1106 if (!empty($addressOptions[$columnName])) {
6a488035
TO
1107 self::$_columnHeaders[$columnName] = $column;
1108 }
1109 }
1110
5defa2fd
KJ
1111 self::$_columnHeaders['email'] = array(
1112 'name' => ts('Email'),
6a488035
TO
1113 'sort' => 'email',
1114 'direction' => CRM_Utils_Sort::DONTCARE,
1115 );
1116
1117 self::$_columnHeaders['phone'] = array('name' => ts('Phone'));
1118 }
1119 return self::$_columnHeaders;
1120 }
1121
1122 function &getQuery() {
1123 return $this->_query;
1124 }
1125
1126 function alphabetQuery() {
1127 return $this->_query->searchQuery(NULL, NULL, NULL, FALSE, FALSE, TRUE);
1128 }
1129
1130 function contactIDQuery($params, $action, $sortID, $displayRelationshipType = NULL, $queryOperator = 'AND') {
1131 $sortOrder = &$this->getSortOrder($this->_action);
1132 $sort = new CRM_Utils_Sort($sortOrder, $sortID);
1133
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);
1138 }
1139
1140 if (!$displayRelationshipType) {
1141 $query = new CRM_Contact_BAO_Query($params,
1142 $this->_returnProperties,
1143 NULL, FALSE, FALSE, 1,
1144 FALSE, TRUE, TRUE, NULL,
1145 $queryOperator
1146 );
1147 }
1148 else {
1149 $query = new CRM_Contact_BAO_Query($params, $this->_returnProperties,
1150 NULL, FALSE, FALSE, 1,
1151 FALSE, TRUE, TRUE, $displayRelationshipType,
1152 $queryOperator
1153 );
1154 }
1155 $value = $query->searchQuery(0, 0, $sort,
1156 FALSE, FALSE, FALSE,
1157 FALSE, FALSE
1158 );
1159 return $value;
1160 }
1161
1162 function &makeProperties(&$returnProperties) {
1163 $properties = array();
1164 foreach ($returnProperties as $name => $value) {
1165 if ($name != 'location') {
c6ff5b0d 1166 // special handling for group and tag
fd18baa6
KJ
1167 if (in_array($name, array('group', 'tag'))) {
1168 $name = "{$name}s";
1169 }
c6ff5b0d
KJ
1170
1171 // special handling for notes
1172 if (in_array($name, array('note', 'note_subject', 'note_body'))) {
1173 $name = "notes";
1174 }
1175
6a488035
TO
1176 $properties[] = $name;
1177 }
1178 else {
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}";
1184 }
1185 }
1186 }
1187 }
1188 }
1189 return $properties;
1190 }
1191}
1192//end of class
1193