Merge pull request #13289 from mfb/pear-mail
[civicrm-core.git] / CRM / Contact / Selector.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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
31 * @copyright CiviCRM LLC (c) 2004-2019
32 */
33
34 /**
35 * Class is to retrieve and display a range of contacts that match the given criteria.
36 *
37 * It is specifically for results of advanced search options.
38 */
39 class CRM_Contact_Selector extends CRM_Core_Selector_Base implements CRM_Core_Selector_API {
40
41 const CACHE_SIZE = 500;
42
43 /**
44 * This defines two actions- View and Edit.
45 *
46 * @var array
47 */
48 static $_links = NULL;
49
50 /**
51 * We use desc to remind us what that column is, name is used in the tpl
52 *
53 * @var array
54 */
55 static $_columnHeaders;
56
57 /**
58 * Properties of contact we're interested in displaying
59 * @var array
60 */
61 static $_properties = array(
62 'contact_id',
63 'contact_type',
64 'contact_sub_type',
65 'sort_name',
66 'street_address',
67 'city',
68 'state_province',
69 'postal_code',
70 'country',
71 'geo_code_1',
72 'geo_code_2',
73 'is_deceased',
74 'email',
75 'on_hold',
76 'phone',
77 'status',
78 'do_not_email',
79 'do_not_phone',
80 'do_not_mail',
81 );
82
83 /**
84 * FormValues is the array returned by exportValues called on
85 * the HTML_QuickForm_Controller for that page.
86 *
87 * @var array
88 */
89 public $_formValues;
90
91 /**
92 * The contextMenu
93 *
94 * @var array
95 */
96 protected $_contextMenu;
97
98 /**
99 * Params is the array in a value used by the search query creator
100 *
101 * @var array
102 */
103 public $_params;
104
105 /**
106 * The return properties used for search
107 *
108 * @var array
109 */
110 protected $_returnProperties;
111
112 /**
113 * Represent the type of selector
114 *
115 * @var int
116 */
117 protected $_action;
118
119 protected $_searchContext;
120
121 /**
122 * Query object for this selector.
123 *
124 * @var CRM_Contact_BAO_Query
125 */
126 protected $_query;
127
128 /**
129 * Get the query object for this selector.
130 *
131 * @return CRM_Contact_BAO_Query
132 */
133 public function getQueryObject() {
134 return $this->_query;
135 }
136
137 /**
138 * Group id
139 *
140 * @var int
141 */
142 protected $_ufGroupID;
143
144 /**
145 * The public visible fields to be shown to the user
146 *
147 * @var array
148 */
149 protected $_fields;
150
151 /**
152 * Class constructor.
153 *
154 * @param $customSearchClass
155 * @param array $formValues
156 * Array of form values imported.
157 * @param array $params
158 * Array of parameters for query.
159 * @param null $returnProperties
160 * @param \const|int $action - action of search basic or advanced.
161 *
162 * @param bool $includeContactIds
163 * @param bool $searchDescendentGroups
164 * @param string $searchContext
165 * @param null $contextMenu
166 *
167 * @return CRM_Contact_Selector
168 */
169 public function __construct(
170 $customSearchClass,
171 $formValues = NULL,
172 $params = NULL,
173 $returnProperties = NULL,
174 $action = CRM_Core_Action::NONE,
175 $includeContactIds = FALSE,
176 $searchDescendentGroups = TRUE,
177 $searchContext = 'search',
178 $contextMenu = NULL
179 ) {
180 //don't build query constructor, if form is not submitted
181 $force = CRM_Utils_Request::retrieve('force', 'Boolean');
182 if (empty($formValues) && !$force) {
183 return;
184 }
185
186 // submitted form values
187 $this->_formValues = &$formValues;
188 $this->_params = &$params;
189 $this->_returnProperties = &$returnProperties;
190 $this->_contextMenu = &$contextMenu;
191 $this->_context = $searchContext;
192
193 // type of selector
194 $this->_action = $action;
195
196 $this->_searchContext = $searchContext;
197
198 $this->_ufGroupID = CRM_Utils_Array::value('uf_group_id', $this->_formValues);
199
200 if ($this->_ufGroupID) {
201 $this->_fields = CRM_Core_BAO_UFGroup::getListingFields(CRM_Core_Action::VIEW,
202 CRM_Core_BAO_UFGroup::PUBLIC_VISIBILITY |
203 CRM_Core_BAO_UFGroup::LISTINGS_VISIBILITY,
204 FALSE, $this->_ufGroupID
205 );
206 self::$_columnHeaders = NULL;
207
208 $this->_customFields = CRM_Core_BAO_CustomField::getFieldsForImport('Individual');
209
210 $this->_returnProperties = CRM_Contact_BAO_Contact::makeHierReturnProperties($this->_fields);
211 $this->_returnProperties['contact_type'] = 1;
212 $this->_returnProperties['contact_sub_type'] = 1;
213 $this->_returnProperties['sort_name'] = 1;
214 }
215
216 $displayRelationshipType = CRM_Utils_Array::value('display_relationship_type', $this->_formValues);
217 $operator = CRM_Utils_Array::value('operator', $this->_formValues, 'AND');
218
219 // rectify params to what proximity search expects if there is a value for prox_distance
220 // CRM-7021
221 if (!empty($this->_params)) {
222 CRM_Contact_BAO_ProximityQuery::fixInputParams($this->_params);
223 }
224
225 $this->_query = new CRM_Contact_BAO_Query(
226 $this->_params,
227 $this->_returnProperties,
228 NULL,
229 $includeContactIds,
230 FALSE,
231 CRM_Contact_BAO_Query::MODE_CONTACTS,
232 FALSE,
233 $searchDescendentGroups,
234 FALSE,
235 $displayRelationshipType,
236 $operator
237 );
238
239 $this->_options = &$this->_query->_options;
240 }
241
242 /**
243 * This method set cache key, later used in test environment
244 *
245 * @param string $key
246 */
247 public function setKey($key) {
248 $this->_key = $key;
249 }
250
251 /**
252 * This method returns the links that are given for each search row.
253 * currently the links added for each row are
254 *
255 * - View
256 * - Edit
257 *
258 * @return array
259 */
260 public static function &links() {
261 list($context, $contextMenu, $key) = func_get_args();
262 $extraParams = ($key) ? "&key={$key}" : NULL;
263 $searchContext = ($context) ? "&context=$context" : NULL;
264
265 if (!(self::$_links)) {
266 self::$_links = array(
267 CRM_Core_Action::VIEW => array(
268 'name' => ts('View'),
269 'url' => 'civicrm/contact/view',
270 'class' => 'no-popup',
271 'qs' => "reset=1&cid=%%id%%{$searchContext}{$extraParams}",
272 'title' => ts('View Contact Details'),
273 'ref' => 'view-contact',
274 ),
275 CRM_Core_Action::UPDATE => array(
276 'name' => ts('Edit'),
277 'url' => 'civicrm/contact/add',
278 'class' => 'no-popup',
279 'qs' => "reset=1&action=update&cid=%%id%%{$searchContext}{$extraParams}",
280 'title' => ts('Edit Contact Details'),
281 'ref' => 'edit-contact',
282 ),
283 );
284
285 $config = CRM_Core_Config::singleton();
286 //CRM-16552: mapAPIKey is not mandatory as google no longer requires an API Key
287 if ($config->mapProvider && ($config->mapAPIKey || $config->mapProvider == 'Google')) {
288 self::$_links[CRM_Core_Action::MAP] = array(
289 'name' => ts('Map'),
290 'url' => 'civicrm/contact/map',
291 'qs' => "reset=1&cid=%%id%%{$searchContext}{$extraParams}",
292 'title' => ts('Map Contact'),
293 );
294 }
295
296 // Adding Context Menu Links in more action
297 if ($contextMenu) {
298 $counter = 7000;
299 foreach ($contextMenu as $key => $value) {
300 $contextVal = '&context=' . $value['key'];
301 if ($value['key'] == 'delete') {
302 $contextVal = $searchContext;
303 }
304 $url = "civicrm/contact/view/{$value['key']}";
305 $qs = "reset=1&action=add&cid=%%id%%{$contextVal}{$extraParams}";
306 if ($value['key'] == 'activity') {
307 $qs = "action=browse&selectedChild=activity&reset=1&cid=%%id%%{$extraParams}";
308 }
309 elseif ($value['key'] == 'email') {
310 $url = "civicrm/contact/view/activity";
311 $qs = "atype=3&action=add&reset=1&cid=%%id%%{$extraParams}";
312 }
313
314 self::$_links[$counter++] = array(
315 'name' => $value['title'],
316 'url' => $url,
317 'qs' => $qs,
318 'title' => $value['title'],
319 'ref' => $value['ref'],
320 'class' => CRM_Utils_Array::value('class', $value),
321 );
322 }
323 }
324 }
325 return self::$_links;
326 }
327
328 /**
329 * Getter for array of the parameters required for creating pager.
330 *
331 * @param $action
332 * @param array $params
333 */
334 public function getPagerParams($action, &$params) {
335 $params['status'] = ts('Contact %%StatusMessage%%');
336 $params['csvString'] = NULL;
337 $params['rowCount'] = CRM_Utils_Pager::ROWCOUNT;
338
339 $params['buttonTop'] = 'PagerTopButton';
340 $params['buttonBottom'] = 'PagerBottomButton';
341 }
342
343 /**
344 * @param null $action
345 * @param null $output
346 *
347 * @return array
348 */
349 public function &getColHeads($action = NULL, $output = NULL) {
350 $colHeads = self::_getColumnHeaders();
351 $colHeads[] = array('desc' => ts('Actions'), 'name' => ts('Action'));
352 return $colHeads;
353 }
354
355 /**
356 * Returns the column headers as an array of tuples:
357 * (name, sortName (key to the sort array))
358 *
359 * @param string $action
360 * The action being performed.
361 * @param string $output
362 * What should the result set include (web/email/csv).
363 *
364 * @return array
365 * the column headers that need to be displayed
366 */
367 public function &getColumnHeaders($action = NULL, $output = NULL) {
368 $headers = NULL;
369
370 // unset return property elements that we don't care
371 if (!empty($this->_returnProperties)) {
372 $doNotCareElements = array(
373 'contact_type',
374 'contact_sub_type',
375 'sort_name',
376 );
377 foreach ($doNotCareElements as $value) {
378 unset($this->_returnProperties[$value]);
379 }
380 }
381
382 if ($output == CRM_Core_Selector_Controller::EXPORT) {
383 $csvHeaders = array(ts('Contact ID'), ts('Contact Type'));
384 foreach ($this->getColHeads($action, $output) as $column) {
385 if (array_key_exists('name', $column)) {
386 $csvHeaders[] = $column['name'];
387 }
388 }
389 $headers = $csvHeaders;
390 }
391 elseif ($output == CRM_Core_Selector_Controller::SCREEN) {
392 $csvHeaders = array(ts('Name'));
393 foreach ($this->getColHeads($action, $output) as $key => $column) {
394 if (array_key_exists('name', $column) &&
395 $column['name'] &&
396 $column['name'] != ts('Name')
397 ) {
398 $csvHeaders[$key] = $column['name'];
399 }
400 }
401 $headers = $csvHeaders;
402 }
403 elseif ($this->_ufGroupID) {
404 // we dont use the cached value of column headers
405 // since it potentially changed because of the profile selected
406 static $skipFields = array('group', 'tag');
407 $direction = CRM_Utils_Sort::ASCENDING;
408 $empty = TRUE;
409 if (!self::$_columnHeaders) {
410 self::$_columnHeaders = array(
411 array('name' => ''),
412 array(
413 'name' => ts('Name'),
414 'sort' => 'sort_name',
415 'direction' => CRM_Utils_Sort::ASCENDING,
416 ),
417 );
418
419 $locationTypes = CRM_Core_DAO_Address::buildOptions('location_type_id', 'validate');
420
421 foreach ($this->_fields as $name => $field) {
422 if (!empty($field['in_selector']) &&
423 !in_array($name, $skipFields)
424 ) {
425 if (strpos($name, '-') !== FALSE) {
426 list($fieldName, $lType, $type) = CRM_Utils_System::explode('-', $name, 3);
427
428 if ($lType == 'Primary') {
429 $locationTypeName = 1;
430 }
431 else {
432 $locationTypeName = $locationTypes[$lType];
433 }
434
435 if (in_array($fieldName, array(
436 'phone',
437 'im',
438 'email',
439 ))) {
440 if ($type) {
441 $name = "`$locationTypeName-$fieldName-$type`";
442 }
443 else {
444 $name = "`$locationTypeName-$fieldName`";
445 }
446 }
447 else {
448 $name = "`$locationTypeName-$fieldName`";
449 }
450 }
451 //to handle sort key for Internal contactId.CRM-2289
452 if ($name == 'id') {
453 $name = 'contact_id';
454 }
455
456 self::$_columnHeaders[] = array(
457 'name' => $field['title'],
458 'sort' => $name,
459 'direction' => $direction,
460 );
461 $direction = CRM_Utils_Sort::DONTCARE;
462 $empty = FALSE;
463 }
464 }
465
466 // if we dont have any valid columns, dont add the implicit ones
467 // this allows the template to check on emptiness of column headers
468 if ($empty) {
469 self::$_columnHeaders = array();
470 }
471 else {
472 self::$_columnHeaders[] = array('desc' => ts('Actions'), 'name' => ts('Action'));
473 }
474 }
475 $headers = self::$_columnHeaders;
476 }
477 elseif (!empty($this->_returnProperties)) {
478 self::$_columnHeaders = array(
479 array('name' => ''),
480 array(
481 'name' => ts('Name'),
482 'sort' => 'sort_name',
483 'direction' => CRM_Utils_Sort::ASCENDING,
484 ),
485 );
486 $properties = self::makeProperties($this->_returnProperties);
487
488 foreach ($properties as $prop) {
489 if (strpos($prop, '-')) {
490 list($loc, $fld, $phoneType) = CRM_Utils_System::explode('-', $prop, 3);
491 $title = $this->_query->_fields[$fld]['title'];
492 if (trim($phoneType) && !is_numeric($phoneType) && strtolower($phoneType) != $fld) {
493 $title .= "-{$phoneType}";
494 }
495 // fetch Location type label from name as $loc, which will be later used in column header
496 $title .= sprintf(" (%s)",
497 CRM_Core_PseudoConstant::getLabel(
498 'CRM_Core_DAO_Address',
499 'location_type_id',
500 CRM_Core_PseudoConstant::getKey('CRM_Core_DAO_Address', 'location_type_id', $loc)
501 )
502 );
503 // use field name instead of table alias
504 $prop = $fld;
505 }
506 elseif (isset($this->_query->_fields[$prop]) && isset($this->_query->_fields[$prop]['title'])) {
507 $title = $this->_query->_fields[$prop]['title'];
508 }
509 elseif (isset($this->_query->_pseudoConstantsSelect[$prop]) && isset($this->_query->_pseudoConstantsSelect[$prop]['pseudoconstant']['optionGroupName'])) {
510 $title = CRM_Core_BAO_OptionGroup::getTitleByName($this->_query->_pseudoConstantsSelect[$prop]['pseudoconstant']['optionGroupName']);
511 }
512 else {
513 $title = '';
514 }
515
516 self::$_columnHeaders[] = array('name' => $title, 'sort' => $prop);
517 }
518 self::$_columnHeaders[] = array('name' => ts('Actions'));
519 $headers = self::$_columnHeaders;
520 }
521 else {
522 $headers = $this->getColHeads($action, $output);
523 }
524
525 return $headers;
526 }
527
528 /**
529 * Returns total number of rows for the query.
530 *
531 * @param int $action
532 *
533 * @return int
534 * Total number of rows
535 */
536 public function getTotalCount($action) {
537 // Use count from cache during paging/sorting
538 if (!empty($_GET['crmPID']) || !empty($_GET['crmSID'])) {
539 $count = Civi::cache('long')->get("Search Results Count $this->_key");
540 }
541 if (empty($count)) {
542 $count = $this->_query->searchQuery(0, 0, NULL, TRUE);
543 Civi::cache('long')->set("Search Results Count $this->_key", $count);
544 }
545 return $count;
546 }
547
548 /**
549 * Returns all the rows in the given offset and rowCount.
550 *
551 * @param string $action
552 * The action being performed.
553 * @param int $offset
554 * The row number to start from.
555 * @param int $rowCount
556 * The number of rows to return.
557 * @param string $sort
558 * The sql string that describes the sort order.
559 * @param string $output
560 * What should the result set include (web/email/csv).
561 *
562 * @return int
563 * the total number of rows for this action
564 */
565 public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
566 if (($output == CRM_Core_Selector_Controller::EXPORT ||
567 $output == CRM_Core_Selector_Controller::SCREEN
568 ) &&
569 $this->_formValues['radio_ts'] == 'ts_sel'
570 ) {
571 $includeContactIds = TRUE;
572 }
573 else {
574 $includeContactIds = FALSE;
575 }
576
577 // note the formvalues were given by CRM_Contact_Form_Search to us
578 // and contain the search criteria (parameters)
579 // note that the default action is basic
580 if ($rowCount) {
581 /** @var CRM_Core_PrevNextCache_Interface $prevNext */
582 $prevNext = Civi::service('prevnext');
583 $cacheKey = $this->buildPrevNextCache($sort);
584 $cids = $prevNext->fetch($cacheKey, $offset, $rowCount);
585 $resultSet = empty($cids) ? [] : $this->_query->getCachedContacts($cids, $includeContactIds)->fetchGenerator();
586 }
587 else {
588 $resultSet = $this->_query->searchQuery($offset, $rowCount, $sort, FALSE, $includeContactIds)->fetchGenerator();
589 }
590
591 // process the result of the query
592 $rows = array();
593 $permissions = array(CRM_Core_Permission::getPermission());
594 if (CRM_Core_Permission::check('delete contacts')) {
595 $permissions[] = CRM_Core_Permission::DELETE;
596 }
597 $mask = CRM_Core_Action::mask($permissions);
598
599 // mask value to hide map link if there are not lat/long
600 $mapMask = $mask & 4095;
601
602 if ($this->_searchContext == 'smog') {
603 $gc = CRM_Core_SelectValues::groupContactStatus();
604 }
605
606 if ($this->_ufGroupID) {
607 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
608
609 $names = array();
610 static $skipFields = array('group', 'tag');
611 foreach ($this->_fields as $key => $field) {
612 if (!empty($field['in_selector']) &&
613 !in_array($key, $skipFields)
614 ) {
615 if (strpos($key, '-') !== FALSE) {
616 list($fieldName, $id, $type) = CRM_Utils_System::explode('-', $key, 3);
617
618 if ($id == 'Primary') {
619 $locationTypeName = 1;
620 }
621 elseif ($fieldName == 'url') {
622 $locationTypeName = "website-{$id}";
623 }
624 else {
625 $locationTypeName = CRM_Utils_Array::value($id, $locationTypes);
626 if (!$locationTypeName) {
627 continue;
628 }
629 }
630
631 $locationTypeName = str_replace(' ', '_', $locationTypeName);
632 if (in_array($fieldName, array(
633 'phone',
634 'im',
635 'email',
636 ))) {
637 if ($type) {
638 $names[] = "{$locationTypeName}-{$fieldName}-{$type}";
639 }
640 else {
641 $names[] = "{$locationTypeName}-{$fieldName}";
642 }
643 }
644 else {
645 $names[] = "{$locationTypeName}-{$fieldName}";
646 }
647 }
648 else {
649 $names[] = $field['name'];
650 }
651 }
652 }
653
654 $names[] = "status";
655 }
656 elseif (!empty($this->_returnProperties)) {
657 $names = self::makeProperties($this->_returnProperties);
658 }
659 else {
660 $names = self::$_properties;
661 }
662
663 $links = self::links($this->_context, $this->_contextMenu, $this->_key);
664
665 //check explicitly added contact to a Smart Group.
666 $groupID = CRM_Utils_Array::value('group', $this->_formValues);
667
668 $pseudoconstants = array();
669 // for CRM-3157 purposes
670 if (in_array('world_region', $names)) {
671 $pseudoconstants['world_region'] = array(
672 'dbName' => 'worldregion_id',
673 'values' => CRM_Core_PseudoConstant::worldRegion(),
674 );
675 }
676
677 foreach ($resultSet as $result) {
678 $row = array();
679 $this->_query->convertToPseudoNames($result);
680 // the columns we are interested in
681 foreach ($names as $property) {
682 if ($property == 'status') {
683 continue;
684 }
685 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($property)) {
686 $row[$property] = CRM_Core_BAO_CustomField::displayValue(
687 $result->$property,
688 $cfID,
689 $result->contact_id
690 );
691 }
692 elseif (strpos($property, '-im')) {
693 $row[$property] = $result->$property;
694 if (!empty($result->$property)) {
695 $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
696 $providerId = $property . "-provider_id";
697 $providerName = $imProviders[$result->$providerId];
698 $row[$property] = $result->$property . " ({$providerName})";
699 }
700 }
701 elseif (in_array($property, array(
702 'addressee',
703 'email_greeting',
704 'postal_greeting',
705 ))) {
706 $greeting = $property . '_display';
707 $row[$property] = $result->$greeting;
708 }
709 elseif (isset($pseudoconstants[$property])) {
710 $row[$property] = CRM_Utils_Array::value(
711 $result->{$pseudoconstants[$property]['dbName']},
712 $pseudoconstants[$property]['values']
713 );
714 }
715 elseif (strpos($property, '-url') !== FALSE) {
716 $websiteUrl = '';
717 $websiteKey = str_replace('-url', '', $property);
718 $propertyArray = explode('-', $property);
719 $websiteFld = $websiteKey . '-' . array_pop($propertyArray);
720 if (!empty($result->$websiteFld)) {
721 $websiteTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id');
722 $websiteType = $websiteTypes[$result->{"$websiteKey-website_type_id"}];
723 $websiteValue = $result->$websiteFld;
724 $websiteUrl = "<a href=\"{$websiteValue}\">{$websiteValue} ({$websiteType})</a>";
725 }
726 $row[$property] = $websiteUrl;
727 }
728 else {
729 $row[$property] = isset($result->$property) ? $result->$property : NULL;
730 }
731 }
732
733 if (!empty($result->postal_code_suffix)) {
734 $row['postal_code'] .= "-" . $result->postal_code_suffix;
735 }
736
737 if ($output != CRM_Core_Selector_Controller::EXPORT &&
738 $this->_searchContext == 'smog'
739 ) {
740 if (empty($result->status) &&
741 $groupID
742 ) {
743 $contactID = $result->contact_id;
744 if ($contactID) {
745 $gcParams = array(
746 'contact_id' => $contactID,
747 'group_id' => $groupID,
748 );
749
750 $gcDefaults = array();
751 CRM_Core_DAO::commonRetrieve('CRM_Contact_DAO_GroupContact', $gcParams, $gcDefaults);
752
753 if (empty($gcDefaults)) {
754 $row['status'] = ts('Smart');
755 }
756 else {
757 $row['status'] = $gc[$gcDefaults['status']];
758 }
759 }
760 else {
761 $row['status'] = NULL;
762 }
763 }
764 else {
765 $row['status'] = $gc[$result->status];
766 }
767 }
768
769 if ($output != CRM_Core_Selector_Controller::EXPORT) {
770 $row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->contact_id;
771
772 if (!empty($this->_formValues['deleted_contacts']) && CRM_Core_Permission::check('access deleted contacts')
773 ) {
774 $links = array(
775 array(
776 'name' => ts('View'),
777 'url' => 'civicrm/contact/view',
778 'qs' => 'reset=1&cid=%%id%%',
779 'class' => 'no-popup',
780 'title' => ts('View Contact Details'),
781 ),
782 array(
783 'name' => ts('Restore'),
784 'url' => 'civicrm/contact/view/delete',
785 'qs' => 'reset=1&cid=%%id%%&restore=1',
786 'title' => ts('Restore Contact'),
787 ),
788 );
789 if (CRM_Core_Permission::check('delete contacts')) {
790 $links[] = array(
791 'name' => ts('Delete Permanently'),
792 'url' => 'civicrm/contact/view/delete',
793 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1',
794 'title' => ts('Permanently Delete Contact'),
795 );
796 }
797 $row['action'] = CRM_Core_Action::formLink(
798 $links,
799 NULL,
800 array('id' => $result->contact_id),
801 ts('more'),
802 FALSE,
803 'contact.selector.row',
804 'Contact',
805 $result->contact_id
806 );
807 }
808 elseif ((is_numeric(CRM_Utils_Array::value('geo_code_1', $row))) ||
809 (!empty($row['city']) &&
810 CRM_Utils_Array::value('state_province', $row)
811 )
812 ) {
813 $row['action'] = CRM_Core_Action::formLink(
814 $links,
815 $mask,
816 array('id' => $result->contact_id),
817 ts('more'),
818 FALSE,
819 'contact.selector.row',
820 'Contact',
821 $result->contact_id
822 );
823 }
824 else {
825 $row['action'] = CRM_Core_Action::formLink(
826 $links,
827 $mapMask,
828 array('id' => $result->contact_id),
829 ts('more'),
830 FALSE,
831 'contact.selector.row',
832 'Contact',
833 $result->contact_id
834 );
835 }
836
837 // allow components to add more actions
838 CRM_Core_Component::searchAction($row, $result->contact_id);
839
840 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type,
841 FALSE,
842 $result->contact_id
843 );
844
845 $row['contact_type_orig'] = $result->contact_sub_type ? $result->contact_sub_type : $result->contact_type;
846 $row['contact_sub_type'] = $result->contact_sub_type ? CRM_Contact_BAO_ContactType::contactTypePairs(FALSE, $result->contact_sub_type, ', ') : $result->contact_sub_type;
847 $row['contact_id'] = $result->contact_id;
848 $row['sort_name'] = $result->sort_name;
849 // Surely this if should be if NOT - otherwise it's just wierd.
850 if (array_key_exists('id', $row)) {
851 $row['id'] = $result->contact_id;
852 }
853 }
854
855 $rows[$row['contact_id']] = $row;
856 }
857
858 return $rows;
859 }
860
861 /**
862 * @param CRM_Utils_Sort $sort
863 *
864 * @return string
865 */
866 public function buildPrevNextCache($sort) {
867 $cacheKey = 'civicrm search ' . $this->_key;
868
869 // We should clear the cache in following conditions:
870 // 1. when starting from scratch, i.e new search
871 // 2. if records are sorted
872
873 // get current page requested
874 $pageNum = CRM_Utils_Request::retrieve('crmPID', 'Integer');
875
876 // get the current sort order
877 $currentSortID = CRM_Utils_Request::retrieve('crmSID', 'String');
878
879 $session = CRM_Core_Session::singleton();
880
881 // get previous sort id
882 $previousSortID = $session->get('previousSortID');
883
884 // check for current != previous to ensure cache is not reset if paging is done without changing
885 // sort criteria
886 if (!$pageNum || (!empty($currentSortID) && $currentSortID != $previousSortID)) {
887 Civi::service('prevnext')->deleteItem(NULL, $cacheKey, 'civicrm_contact');
888 // this means it's fresh search, so set pageNum=1
889 if (!$pageNum) {
890 $pageNum = 1;
891 }
892 }
893
894 // set the current sort as previous sort
895 if (!empty($currentSortID)) {
896 $session->set('previousSortID', $currentSortID);
897 }
898
899 $pageSize = CRM_Utils_Request::retrieve('crmRowCount', 'Integer', CRM_Core_DAO::$_nullObject, FALSE, 50);
900 $firstRecord = ($pageNum - 1) * $pageSize;
901
902 //for alphabetic pagination selection save
903 $sortByCharacter = CRM_Utils_Request::retrieve('sortByCharacter', 'String');
904
905 //for text field pagination selection save
906 $countRow = Civi::service('prevnext')->getCount($cacheKey);
907 // $sortByCharacter triggers a refresh in the prevNext cache
908 if ($sortByCharacter && $sortByCharacter != 'all') {
909 $this->fillupPrevNextCache($sort, $cacheKey, 0, max(self::CACHE_SIZE, $pageSize));
910 }
911 elseif (($firstRecord + $pageSize) >= $countRow) {
912 $this->fillupPrevNextCache($sort, $cacheKey, $countRow, max(self::CACHE_SIZE, $pageSize) + $firstRecord - $countRow);
913 }
914 return $cacheKey;
915 }
916
917 /**
918 * @param $rows
919 */
920 public function addActions(&$rows) {
921
922 $basicPermissions = CRM_Core_Permission::check('delete contacts') ? array(CRM_Core_Permission::DELETE) : array();
923
924 // get permissions on an individual level (CRM-12645)
925 // @todo look at storing this to the session as this is called twice during search results render.
926 $can_edit_list = CRM_Contact_BAO_Contact_Permission::allowList(array_keys($rows), CRM_Core_Permission::EDIT);
927
928 $links_template = self::links($this->_context, $this->_contextMenu, $this->_key);
929
930 foreach ($rows as $id => & $row) {
931 $links = $links_template;
932 if (in_array($id, $can_edit_list)) {
933 $mask = CRM_Core_Action::mask(array_merge(array(CRM_Core_Permission::EDIT), $basicPermissions));
934 }
935 else {
936 $mask = CRM_Core_Action::mask(array_merge(array(CRM_Core_Permission::VIEW), $basicPermissions));
937 }
938
939 if ((!is_numeric(CRM_Utils_Array::value('geo_code_1', $row))) &&
940 (empty($row['city']) ||
941 !CRM_Utils_Array::value('state_province', $row)
942 )
943 ) {
944 $mask = $mask & 4095;
945 }
946
947 if (!empty($this->_formValues['deleted_contacts']) && CRM_Core_Permission::check('access deleted contacts')
948 ) {
949 $links = array(
950 array(
951 'name' => ts('View'),
952 'url' => 'civicrm/contact/view',
953 'qs' => 'reset=1&cid=%%id%%',
954 'class' => 'no-popup',
955 'title' => ts('View Contact Details'),
956 ),
957 array(
958 'name' => ts('Restore'),
959 'url' => 'civicrm/contact/view/delete',
960 'qs' => 'reset=1&cid=%%id%%&restore=1',
961 'title' => ts('Restore Contact'),
962 ),
963 );
964 if (CRM_Core_Permission::check('delete contacts')) {
965 $links[] = array(
966 'name' => ts('Delete Permanently'),
967 'url' => 'civicrm/contact/view/delete',
968 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1',
969 'title' => ts('Permanently Delete Contact'),
970 );
971 }
972 $row['action'] = CRM_Core_Action::formLink(
973 $links,
974 NULL,
975 array('id' => $row['contact_id']),
976 ts('more'),
977 FALSE,
978 'contact.selector.actions',
979 'Contact',
980 $row['contact_id']
981 );
982 }
983 else {
984 $row['action'] = CRM_Core_Action::formLink(
985 $links,
986 $mask,
987 array('id' => $row['contact_id']),
988 ts('more'),
989 FALSE,
990 'contact.selector.actions',
991 'Contact',
992 $row['contact_id']
993 );
994 }
995
996 // allow components to add more actions
997 CRM_Core_Component::searchAction($row, $row['contact_id']);
998
999 if (!empty($row['contact_type_orig'])) {
1000 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage($row['contact_type_orig'],
1001 FALSE, $row['contact_id']);
1002 }
1003 }
1004 }
1005
1006 /**
1007 * @param $rows
1008 */
1009 public function removeActions(&$rows) {
1010 foreach ($rows as $rid => & $rValue) {
1011 unset($rValue['contact_type']);
1012 unset($rValue['action']);
1013 }
1014 }
1015
1016 /**
1017 * @param CRM_Utils_Sort $sort
1018 * @param string $cacheKey
1019 * @param int $start
1020 * @param int $end
1021 */
1022 public function fillupPrevNextCache($sort, $cacheKey, $start = 0, $end = self::CACHE_SIZE) {
1023 $coreSearch = TRUE;
1024 // For custom searches, use the contactIDs method
1025 if (is_a($this, 'CRM_Contact_Selector_Custom')) {
1026 $sql = $this->_search->contactIDs($start, $end, $sort, TRUE);
1027 $coreSearch = FALSE;
1028 }
1029 // For core searches use the searchQuery method
1030 else {
1031 $sql = $this->_query->searchQuery($start, $end, $sort, FALSE, $this->_query->_includeContactIds,
1032 FALSE, TRUE, TRUE);
1033 }
1034
1035 // CRM-9096
1036 // due to limitations in our search query writer, the above query does not work
1037 // in cases where the query is being sorted on a non-contact table
1038 // this results in a fatal error :(
1039 // see below for the gross hack of trapping the error and not filling
1040 // the prev next cache in this situation
1041 // the other alternative of running the FULL query will just be incredibly inefficient
1042 // and slow things down way too much on large data sets / complex queries
1043
1044 $selectSQL = "SELECT DISTINCT %1, contact_a.id, contact_a.sort_name";
1045
1046 $sql = str_ireplace(array("SELECT contact_a.id as contact_id", "SELECT contact_a.id as id"), $selectSQL, $sql);
1047 try {
1048 Civi::service('prevnext')->fillWithSql($cacheKey, $sql, [1 => [$cacheKey, 'String']]);
1049 }
1050 catch (CRM_Core_Exception $e) {
1051 if ($coreSearch) {
1052 // in the case of error, try rebuilding cache using full sql which is used for search selector display
1053 // this fixes the bugs reported in CRM-13996 & CRM-14438
1054 $this->rebuildPreNextCache($start, $end, $sort, $cacheKey);
1055 }
1056 else {
1057 // This will always show for CiviRules :-( as a) it orders by 'rule_label'
1058 // which is not available in the query & b) it uses contact not contact_a
1059 // as an alias.
1060 // CRM_Core_Session::setStatus(ts('Query Failed'));
1061 return;
1062 }
1063 }
1064
1065 if (Civi::service('prevnext') instanceof CRM_Core_PrevNextCache_Sql) {
1066 // SQL-backed prevnext cache uses an extra record for pruning the cache.
1067 CRM_Core_BAO_Cache::setItem($cacheKey, 'CiviCRM Search PrevNextCache', $cacheKey);
1068 }
1069 }
1070
1071 /**
1072 * called to rebuild prev next cache using full sql in case of core search ( excluding custom search)
1073 *
1074 * @param int $start
1075 * Start for limit clause.
1076 * @param int $end
1077 * End for limit clause.
1078 * @param CRM_Utils_Sort $sort
1079 * @param string $cacheKey
1080 * Cache key.
1081 */
1082 public function rebuildPreNextCache($start, $end, $sort, $cacheKey) {
1083 // generate full SQL
1084 $sql = $this->_query->searchQuery($start, $end, $sort, FALSE, $this->_query->_includeContactIds,
1085 FALSE, FALSE, TRUE);
1086
1087 $dao = CRM_Core_DAO::executeQuery($sql);
1088
1089 // build insert query, note that currently we build cache for 500 (self::CACHE_SIZE) contact records at a time, hence below approach
1090 $rows = [];
1091 while ($dao->fetch()) {
1092 $rows[] = [
1093 'entity_table' => 'civicrm_contact',
1094 'entity_id1' => $dao->contact_id,
1095 'entity_id2' => $dao->contact_id,
1096 'data' => $dao->sort_name,
1097 ];
1098 }
1099
1100 Civi::service('prevnext')->fillWithArray($cacheKey, $rows);
1101 }
1102
1103 /**
1104 * @inheritDoc
1105 */
1106 public function getQILL() {
1107 return $this->_query->qill();
1108 }
1109
1110 /**
1111 * Name of export file.
1112 *
1113 * @param string $output
1114 * Type of output.
1115 *
1116 * @return string
1117 * name of the file
1118 */
1119 public function getExportFileName($output = 'csv') {
1120 return ts('CiviCRM Contact Search');
1121 }
1122
1123 /**
1124 * Get colunmn headers for search selector.
1125 *
1126 * @return array
1127 */
1128 private static function &_getColumnHeaders() {
1129 if (!isset(self::$_columnHeaders)) {
1130 $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
1131 'address_options', TRUE, NULL, TRUE
1132 );
1133
1134 self::$_columnHeaders = array(
1135 'contact_type' => array('desc' => ts('Contact Type')),
1136 'sort_name' => array(
1137 'name' => ts('Name'),
1138 'sort' => 'sort_name',
1139 'direction' => CRM_Utils_Sort::ASCENDING,
1140 ),
1141 );
1142
1143 $defaultAddress = array(
1144 'street_address' => array('name' => ts('Address')),
1145 'city' => array(
1146 'name' => ts('City'),
1147 'sort' => 'city',
1148 'direction' => CRM_Utils_Sort::DONTCARE,
1149 ),
1150 'state_province' => array(
1151 'name' => ts('State'),
1152 'sort' => 'state_province',
1153 'direction' => CRM_Utils_Sort::DONTCARE,
1154 ),
1155 'postal_code' => array(
1156 'name' => ts('Postal'),
1157 'sort' => 'postal_code',
1158 'direction' => CRM_Utils_Sort::DONTCARE,
1159 ),
1160 'country' => array(
1161 'name' => ts('Country'),
1162 'sort' => 'country',
1163 'direction' => CRM_Utils_Sort::DONTCARE,
1164 ),
1165 );
1166
1167 foreach ($defaultAddress as $columnName => $column) {
1168 if (!empty($addressOptions[$columnName])) {
1169 self::$_columnHeaders[$columnName] = $column;
1170 }
1171 }
1172
1173 self::$_columnHeaders['email'] = array(
1174 'name' => ts('Email'),
1175 'sort' => 'email',
1176 'direction' => CRM_Utils_Sort::DONTCARE,
1177 );
1178
1179 self::$_columnHeaders['phone'] = array('name' => ts('Phone'));
1180 }
1181 return self::$_columnHeaders;
1182 }
1183
1184 /**
1185 * @return CRM_Contact_BAO_Query
1186 */
1187 public function getQuery() {
1188 return $this->_query;
1189 }
1190
1191 /**
1192 * @return CRM_Contact_DAO_Contact
1193 */
1194 public function alphabetQuery() {
1195 return $this->_query->searchQuery(NULL, NULL, NULL, FALSE, FALSE, TRUE);
1196 }
1197
1198 /**
1199 * @param array $params
1200 * @param int $sortID
1201 * @param null $displayRelationshipType
1202 * @param string $queryOperator
1203 *
1204 * @return CRM_Contact_DAO_Contact
1205 */
1206 public function contactIDQuery($params, $sortID, $displayRelationshipType = NULL, $queryOperator = 'AND') {
1207 $sortOrder = &$this->getSortOrder($this->_action);
1208 $sort = new CRM_Utils_Sort($sortOrder, $sortID);
1209
1210 // rectify params to what proximity search expects if there is a value for prox_distance
1211 // CRM-7021 CRM-7905
1212 if (!empty($params)) {
1213 CRM_Contact_BAO_ProximityQuery::fixInputParams($params);
1214 }
1215
1216 if (!$displayRelationshipType) {
1217 $query = new CRM_Contact_BAO_Query($params,
1218 CRM_Contact_BAO_Query::NO_RETURN_PROPERTIES,
1219 NULL, FALSE, FALSE, 1,
1220 FALSE, TRUE, TRUE, NULL,
1221 $queryOperator
1222 );
1223 }
1224 else {
1225 $query = new CRM_Contact_BAO_Query($params,
1226 CRM_Contact_BAO_Query::NO_RETURN_PROPERTIES,
1227 NULL, FALSE, FALSE, 1,
1228 FALSE, TRUE, TRUE, $displayRelationshipType,
1229 $queryOperator
1230 );
1231 }
1232 $value = $query->searchQuery(0, 0, $sort,
1233 FALSE, FALSE, FALSE,
1234 FALSE, FALSE
1235 );
1236 return $value;
1237 }
1238
1239 /**
1240 * @param $returnProperties
1241 *
1242 * @return array
1243 */
1244 public function &makeProperties(&$returnProperties) {
1245 $properties = array();
1246 foreach ($returnProperties as $name => $value) {
1247 if ($name != 'location') {
1248 // special handling for group and tag
1249 if (in_array($name, array('group', 'tag'))) {
1250 $name = "{$name}s";
1251 }
1252
1253 // special handling for notes
1254 if (in_array($name, array('note', 'note_subject', 'note_body'))) {
1255 $name = "notes";
1256 }
1257
1258 $properties[] = $name;
1259 }
1260 else {
1261 // extract all the location stuff
1262 foreach ($value as $n => $v) {
1263 foreach ($v as $n1 => $v1) {
1264 if (!strpos('_id', $n1) && $n1 != 'location_type') {
1265 $n = str_replace(' ', '_', $n);
1266 $properties[] = "{$n}-{$n1}";
1267 }
1268 }
1269 }
1270 }
1271 }
1272 return $properties;
1273 }
1274
1275 }