Merge pull request #12162 from seamuslee001/group_query_count
[civicrm-core.git] / CRM / Contact / Selector.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
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_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
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 $title .= " ($loc)";
496 }
497 elseif (isset($this->_query->_fields[$prop]) && isset($this->_query->_fields[$prop]['title'])) {
498 $title = $this->_query->_fields[$prop]['title'];
499 }
500 elseif (isset($this->_query->_pseudoConstantsSelect[$prop]) && isset($this->_query->_pseudoConstantsSelect[$prop]['pseudoconstant']['optionGroupName'])) {
501 $title = CRM_Core_BAO_OptionGroup::getTitleByName($this->_query->_pseudoConstantsSelect[$prop]['pseudoconstant']['optionGroupName']);
502 }
503 else {
504 $title = '';
505 }
506
507 self::$_columnHeaders[] = array('name' => $title, 'sort' => $prop);
508 }
509 self::$_columnHeaders[] = array('name' => ts('Actions'));
510 $headers = self::$_columnHeaders;
511 }
512 else {
513 $headers = $this->getColHeads($action, $output);
514 }
515
516 return $headers;
517 }
518
519 /**
520 * Returns total number of rows for the query.
521 *
522 * @param int $action
523 *
524 * @return int
525 * Total number of rows
526 */
527 public function getTotalCount($action) {
528 // Use count from cache during paging/sorting
529 if (!empty($_GET['crmPID']) || !empty($_GET['crmSID'])) {
530 $count = CRM_Core_BAO_Cache::getItem('Search Results Count', $this->_key);
531 }
532 if (empty($count)) {
533 $count = $this->_query->searchQuery(0, 0, NULL, TRUE);
534 CRM_Core_BAO_Cache::setItem($count, 'Search Results Count', $this->_key);
535 }
536 return $count;
537 }
538
539 /**
540 * Returns all the rows in the given offset and rowCount.
541 *
542 * @param string $action
543 * The action being performed.
544 * @param int $offset
545 * The row number to start from.
546 * @param int $rowCount
547 * The number of rows to return.
548 * @param string $sort
549 * The sql string that describes the sort order.
550 * @param string $output
551 * What should the result set include (web/email/csv).
552 *
553 * @return int
554 * the total number of rows for this action
555 */
556 public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
557 if (($output == CRM_Core_Selector_Controller::EXPORT ||
558 $output == CRM_Core_Selector_Controller::SCREEN
559 ) &&
560 $this->_formValues['radio_ts'] == 'ts_sel'
561 ) {
562 $includeContactIds = TRUE;
563 }
564 else {
565 $includeContactIds = FALSE;
566 }
567
568 // note the formvalues were given by CRM_Contact_Form_Search to us
569 // and contain the search criteria (parameters)
570 // note that the default action is basic
571 if ($rowCount) {
572 $cacheKey = $this->buildPrevNextCache($sort);
573 $result = $this->_query->getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds);
574 }
575 else {
576 $result = $this->_query->searchQuery($offset, $rowCount, $sort, FALSE, $includeContactIds);
577 }
578
579 // process the result of the query
580 $rows = array();
581 $permissions = array(CRM_Core_Permission::getPermission());
582 if (CRM_Core_Permission::check('delete contacts')) {
583 $permissions[] = CRM_Core_Permission::DELETE;
584 }
585 $mask = CRM_Core_Action::mask($permissions);
586
587 // mask value to hide map link if there are not lat/long
588 $mapMask = $mask & 4095;
589
590 if ($this->_searchContext == 'smog') {
591 $gc = CRM_Core_SelectValues::groupContactStatus();
592 }
593
594 if ($this->_ufGroupID) {
595 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
596
597 $names = array();
598 static $skipFields = array('group', 'tag');
599 foreach ($this->_fields as $key => $field) {
600 if (!empty($field['in_selector']) &&
601 !in_array($key, $skipFields)
602 ) {
603 if (strpos($key, '-') !== FALSE) {
604 list($fieldName, $id, $type) = CRM_Utils_System::explode('-', $key, 3);
605
606 if ($id == 'Primary') {
607 $locationTypeName = 1;
608 }
609 elseif ($fieldName == 'url') {
610 $locationTypeName = "website-{$id}";
611 }
612 else {
613 $locationTypeName = CRM_Utils_Array::value($id, $locationTypes);
614 if (!$locationTypeName) {
615 continue;
616 }
617 }
618
619 $locationTypeName = str_replace(' ', '_', $locationTypeName);
620 if (in_array($fieldName, array(
621 'phone',
622 'im',
623 'email',
624 ))) {
625 if ($type) {
626 $names[] = "{$locationTypeName}-{$fieldName}-{$type}";
627 }
628 else {
629 $names[] = "{$locationTypeName}-{$fieldName}";
630 }
631 }
632 else {
633 $names[] = "{$locationTypeName}-{$fieldName}";
634 }
635 }
636 else {
637 $names[] = $field['name'];
638 }
639 }
640 }
641
642 $names[] = "status";
643 }
644 elseif (!empty($this->_returnProperties)) {
645 $names = self::makeProperties($this->_returnProperties);
646 }
647 else {
648 $names = self::$_properties;
649 }
650
651 $links = self::links($this->_context, $this->_contextMenu, $this->_key);
652
653 //check explicitly added contact to a Smart Group.
654 $groupID = CRM_Utils_Array::value('group', $this->_formValues);
655
656 $pseudoconstants = array();
657 // for CRM-3157 purposes
658 if (in_array('world_region', $names)) {
659 $pseudoconstants['world_region'] = array(
660 'dbName' => 'worldregion_id',
661 'values' => CRM_Core_PseudoConstant::worldRegion(),
662 );
663 }
664
665 while ($result->fetch()) {
666 $row = array();
667 $this->_query->convertToPseudoNames($result);
668 // the columns we are interested in
669 foreach ($names as $property) {
670 if ($property == 'status') {
671 continue;
672 }
673 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($property)) {
674 $row[$property] = CRM_Core_BAO_CustomField::displayValue(
675 $result->$property,
676 $cfID,
677 $result->contact_id
678 );
679 }
680 elseif (strpos($property, '-im')) {
681 $row[$property] = $result->$property;
682 if (!empty($result->$property)) {
683 $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
684 $providerId = $property . "-provider_id";
685 $providerName = $imProviders[$result->$providerId];
686 $row[$property] = $result->$property . " ({$providerName})";
687 }
688 }
689 elseif (in_array($property, array(
690 'addressee',
691 'email_greeting',
692 'postal_greeting',
693 ))) {
694 $greeting = $property . '_display';
695 $row[$property] = $result->$greeting;
696 }
697 elseif (isset($pseudoconstants[$property])) {
698 $row[$property] = CRM_Utils_Array::value(
699 $result->{$pseudoconstants[$property]['dbName']},
700 $pseudoconstants[$property]['values']
701 );
702 }
703 elseif (strpos($property, '-url') !== FALSE) {
704 $websiteUrl = '';
705 $websiteKey = str_replace('-url', '', $property);
706 $propertyArray = explode('-', $property);
707 $websiteFld = $websiteKey . '-' . array_pop($propertyArray);
708 if (!empty($result->$websiteFld)) {
709 $websiteTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id');
710 $websiteType = $websiteTypes[$result->{"$websiteKey-website_type_id"}];
711 $websiteValue = $result->$websiteFld;
712 $websiteUrl = "<a href=\"{$websiteValue}\">{$websiteValue} ({$websiteType})</a>";
713 }
714 $row[$property] = $websiteUrl;
715 }
716 else {
717 $row[$property] = isset($result->$property) ? $result->$property : NULL;
718 }
719 }
720
721 if (!empty($result->postal_code_suffix)) {
722 $row['postal_code'] .= "-" . $result->postal_code_suffix;
723 }
724
725 if ($output != CRM_Core_Selector_Controller::EXPORT &&
726 $this->_searchContext == 'smog'
727 ) {
728 if (empty($result->status) &&
729 $groupID
730 ) {
731 $contactID = $result->contact_id;
732 if ($contactID) {
733 $gcParams = array(
734 'contact_id' => $contactID,
735 'group_id' => $groupID,
736 );
737
738 $gcDefaults = array();
739 CRM_Core_DAO::commonRetrieve('CRM_Contact_DAO_GroupContact', $gcParams, $gcDefaults);
740
741 if (empty($gcDefaults)) {
742 $row['status'] = ts('Smart');
743 }
744 else {
745 $row['status'] = $gc[$gcDefaults['status']];
746 }
747 }
748 else {
749 $row['status'] = NULL;
750 }
751 }
752 else {
753 $row['status'] = $gc[$result->status];
754 }
755 }
756
757 if ($output != CRM_Core_Selector_Controller::EXPORT) {
758 $row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->contact_id;
759
760 if (!empty($this->_formValues['deleted_contacts']) && CRM_Core_Permission::check('access deleted contacts')
761 ) {
762 $links = array(
763 array(
764 'name' => ts('View'),
765 'url' => 'civicrm/contact/view',
766 'qs' => 'reset=1&cid=%%id%%',
767 'class' => 'no-popup',
768 'title' => ts('View Contact Details'),
769 ),
770 array(
771 'name' => ts('Restore'),
772 'url' => 'civicrm/contact/view/delete',
773 'qs' => 'reset=1&cid=%%id%%&restore=1',
774 'title' => ts('Restore Contact'),
775 ),
776 );
777 if (CRM_Core_Permission::check('delete contacts')) {
778 $links[] = array(
779 'name' => ts('Delete Permanently'),
780 'url' => 'civicrm/contact/view/delete',
781 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1',
782 'title' => ts('Permanently Delete Contact'),
783 );
784 }
785 $row['action'] = CRM_Core_Action::formLink(
786 $links,
787 NULL,
788 array('id' => $result->contact_id),
789 ts('more'),
790 FALSE,
791 'contact.selector.row',
792 'Contact',
793 $result->contact_id
794 );
795 }
796 elseif ((is_numeric(CRM_Utils_Array::value('geo_code_1', $row))) ||
797 (!empty($row['city']) &&
798 CRM_Utils_Array::value('state_province', $row)
799 )
800 ) {
801 $row['action'] = CRM_Core_Action::formLink(
802 $links,
803 $mask,
804 array('id' => $result->contact_id),
805 ts('more'),
806 FALSE,
807 'contact.selector.row',
808 'Contact',
809 $result->contact_id
810 );
811 }
812 else {
813 $row['action'] = CRM_Core_Action::formLink(
814 $links,
815 $mapMask,
816 array('id' => $result->contact_id),
817 ts('more'),
818 FALSE,
819 'contact.selector.row',
820 'Contact',
821 $result->contact_id
822 );
823 }
824
825 // allow components to add more actions
826 CRM_Core_Component::searchAction($row, $result->contact_id);
827
828 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type,
829 FALSE,
830 $result->contact_id
831 );
832
833 $row['contact_type_orig'] = $result->contact_sub_type ? $result->contact_sub_type : $result->contact_type;
834 $row['contact_sub_type'] = $result->contact_sub_type ? CRM_Contact_BAO_ContactType::contactTypePairs(FALSE, $result->contact_sub_type, ', ') : $result->contact_sub_type;
835 $row['contact_id'] = $result->contact_id;
836 $row['sort_name'] = $result->sort_name;
837 // Surely this if should be if NOT - otherwise it's just wierd.
838 if (array_key_exists('id', $row)) {
839 $row['id'] = $result->contact_id;
840 }
841 }
842
843 $rows[$row['contact_id']] = $row;
844 }
845
846 return $rows;
847 }
848
849 /**
850 * @param CRM_Utils_Sort $sort
851 *
852 * @return string
853 */
854 public function buildPrevNextCache($sort) {
855 $cacheKey = 'civicrm search ' . $this->_key;
856
857 // We should clear the cache in following conditions:
858 // 1. when starting from scratch, i.e new search
859 // 2. if records are sorted
860
861 // get current page requested
862 $pageNum = CRM_Utils_Request::retrieve('crmPID', 'Integer');
863
864 // get the current sort order
865 $currentSortID = CRM_Utils_Request::retrieve('crmSID', 'String');
866
867 $session = CRM_Core_Session::singleton();
868
869 // get previous sort id
870 $previousSortID = $session->get('previousSortID');
871
872 // check for current != previous to ensure cache is not reset if paging is done without changing
873 // sort criteria
874 if (!$pageNum || (!empty($currentSortID) && $currentSortID != $previousSortID)) {
875 CRM_Core_BAO_PrevNextCache::deleteItem(NULL, $cacheKey, 'civicrm_contact');
876 // this means it's fresh search, so set pageNum=1
877 if (!$pageNum) {
878 $pageNum = 1;
879 }
880 }
881
882 // set the current sort as previous sort
883 if (!empty($currentSortID)) {
884 $session->set('previousSortID', $currentSortID);
885 }
886
887 $pageSize = CRM_Utils_Request::retrieve('crmRowCount', 'Integer', CRM_Core_DAO::$_nullObject, FALSE, 50);
888 $firstRecord = ($pageNum - 1) * $pageSize;
889
890 //for alphabetic pagination selection save
891 $sortByCharacter = CRM_Utils_Request::retrieve('sortByCharacter', 'String');
892
893 //for text field pagination selection save
894 $countRow = CRM_Core_BAO_PrevNextCache::getCount($cacheKey, NULL, "entity_table = 'civicrm_contact'");
895 // $sortByCharacter triggers a refresh in the prevNext cache
896 if ($sortByCharacter && $sortByCharacter != 'all') {
897 $cacheKey .= "_alphabet";
898 $this->fillupPrevNextCache($sort, $cacheKey, 0, max(self::CACHE_SIZE, $pageSize));
899 }
900 elseif (($firstRecord + $pageSize) >= $countRow) {
901 $this->fillupPrevNextCache($sort, $cacheKey, $countRow, max(self::CACHE_SIZE, $pageSize) + $firstRecord - $countRow);
902 }
903 return $cacheKey;
904 }
905
906 /**
907 * @param $rows
908 */
909 public function addActions(&$rows) {
910
911 $basicPermissions = CRM_Core_Permission::check('delete contacts') ? array(CRM_Core_Permission::DELETE) : array();
912
913 // get permissions on an individual level (CRM-12645)
914 // @todo look at storing this to the session as this is called twice during search results render.
915 $can_edit_list = CRM_Contact_BAO_Contact_Permission::allowList(array_keys($rows), CRM_Core_Permission::EDIT);
916
917 $links_template = self::links($this->_context, $this->_contextMenu, $this->_key);
918
919 foreach ($rows as $id => & $row) {
920 $links = $links_template;
921 if (in_array($id, $can_edit_list)) {
922 $mask = CRM_Core_Action::mask(array_merge(array(CRM_Core_Permission::EDIT), $basicPermissions));
923 }
924 else {
925 $mask = CRM_Core_Action::mask(array_merge(array(CRM_Core_Permission::VIEW), $basicPermissions));
926 }
927
928 if ((!is_numeric(CRM_Utils_Array::value('geo_code_1', $row))) &&
929 (empty($row['city']) ||
930 !CRM_Utils_Array::value('state_province', $row)
931 )
932 ) {
933 $mask = $mask & 4095;
934 }
935
936 if (!empty($this->_formValues['deleted_contacts']) && CRM_Core_Permission::check('access deleted contacts')
937 ) {
938 $links = array(
939 array(
940 'name' => ts('View'),
941 'url' => 'civicrm/contact/view',
942 'qs' => 'reset=1&cid=%%id%%',
943 'class' => 'no-popup',
944 'title' => ts('View Contact Details'),
945 ),
946 array(
947 'name' => ts('Restore'),
948 'url' => 'civicrm/contact/view/delete',
949 'qs' => 'reset=1&cid=%%id%%&restore=1',
950 'title' => ts('Restore Contact'),
951 ),
952 );
953 if (CRM_Core_Permission::check('delete contacts')) {
954 $links[] = array(
955 'name' => ts('Delete Permanently'),
956 'url' => 'civicrm/contact/view/delete',
957 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1',
958 'title' => ts('Permanently Delete Contact'),
959 );
960 }
961 $row['action'] = CRM_Core_Action::formLink(
962 $links,
963 NULL,
964 array('id' => $row['contact_id']),
965 ts('more'),
966 FALSE,
967 'contact.selector.actions',
968 'Contact',
969 $row['contact_id']
970 );
971 }
972 else {
973 $row['action'] = CRM_Core_Action::formLink(
974 $links,
975 $mask,
976 array('id' => $row['contact_id']),
977 ts('more'),
978 FALSE,
979 'contact.selector.actions',
980 'Contact',
981 $row['contact_id']
982 );
983 }
984
985 // allow components to add more actions
986 CRM_Core_Component::searchAction($row, $row['contact_id']);
987
988 if (!empty($row['contact_type_orig'])) {
989 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage($row['contact_type_orig'],
990 FALSE, $row['contact_id']);
991 }
992 }
993 }
994
995 /**
996 * @param $rows
997 */
998 public function removeActions(&$rows) {
999 foreach ($rows as $rid => & $rValue) {
1000 unset($rValue['contact_type']);
1001 unset($rValue['action']);
1002 }
1003 }
1004
1005 /**
1006 * @param CRM_Utils_Sort $sort
1007 * @param string $cacheKey
1008 * @param int $start
1009 * @param int $end
1010 */
1011 public function fillupPrevNextCache($sort, $cacheKey, $start = 0, $end = self::CACHE_SIZE) {
1012 $coreSearch = TRUE;
1013 // For custom searches, use the contactIDs method
1014 if (is_a($this, 'CRM_Contact_Selector_Custom')) {
1015 $sql = $this->_search->contactIDs($start, $end, $sort, TRUE);
1016 $coreSearch = FALSE;
1017 }
1018 // For core searches use the searchQuery method
1019 else {
1020 $sql = $this->_query->searchQuery($start, $end, $sort, FALSE, $this->_query->_includeContactIds,
1021 FALSE, TRUE, TRUE);
1022 }
1023
1024 // CRM-9096
1025 // due to limitations in our search query writer, the above query does not work
1026 // in cases where the query is being sorted on a non-contact table
1027 // this results in a fatal error :(
1028 // see below for the gross hack of trapping the error and not filling
1029 // the prev next cache in this situation
1030 // the other alternative of running the FULL query will just be incredibly inefficient
1031 // and slow things down way too much on large data sets / complex queries
1032
1033 $insertSQL = "
1034 INSERT INTO civicrm_prevnext_cache ( entity_table, entity_id1, entity_id2, cacheKey, data )
1035 SELECT DISTINCT 'civicrm_contact', contact_a.id, contact_a.id, '$cacheKey', contact_a.sort_name
1036 ";
1037
1038 $sql = str_replace(array("SELECT contact_a.id as contact_id", "SELECT contact_a.id as id"), $insertSQL, $sql);
1039 try {
1040 $result = CRM_Core_DAO::executeQuery($sql, [], FALSE, NULL, FALSE, TRUE, TRUE);
1041 if (is_a($result, 'DB_Error')) {
1042 throw new CRM_Core_Exception($result->message);
1043 }
1044 }
1045 catch (CRM_Core_Exception $e) {
1046 if ($coreSearch) {
1047 // in the case of error, try rebuilding cache using full sql which is used for search selector display
1048 // this fixes the bugs reported in CRM-13996 & CRM-14438
1049 $this->rebuildPreNextCache($start, $end, $sort, $cacheKey);
1050 }
1051 else {
1052 // This will always show for CiviRules :-( as a) it orders by 'rule_label'
1053 // which is not available in the query & b) it uses contact not contact_a
1054 // as an alias.
1055 // CRM_Core_Session::setStatus(ts('Query Failed'));
1056 return;
1057 }
1058 }
1059
1060 // also record an entry in the cache key table, so we can delete it periodically
1061 CRM_Core_BAO_Cache::setItem($cacheKey, 'CiviCRM Search PrevNextCache', $cacheKey);
1062 }
1063
1064 /**
1065 * called to rebuild prev next cache using full sql in case of core search ( excluding custom search)
1066 *
1067 * @param int $start
1068 * Start for limit clause.
1069 * @param int $end
1070 * End for limit clause.
1071 * @param CRM_Utils_Sort $sort
1072 * @param string $cacheKey
1073 * Cache key.
1074 */
1075 public function rebuildPreNextCache($start, $end, $sort, $cacheKey) {
1076 // generate full SQL
1077 $sql = $this->_query->searchQuery($start, $end, $sort, FALSE, $this->_query->_includeContactIds,
1078 FALSE, FALSE, TRUE);
1079
1080 $dao = CRM_Core_DAO::executeQuery($sql);
1081
1082 // build insert query, note that currently we build cache for 500 (self::CACHE_SIZE) contact records at a time, hence below approach
1083 $insertValues = array();
1084 while ($dao->fetch()) {
1085 $insertValues[] = "('civicrm_contact', {$dao->contact_id}, {$dao->contact_id}, '{$cacheKey}', '" . CRM_Core_DAO::escapeString($dao->sort_name) . "')";
1086 }
1087
1088 //update pre/next cache using single insert query
1089 if (!empty($insertValues)) {
1090 $sql = 'INSERT INTO civicrm_prevnext_cache ( entity_table, entity_id1, entity_id2, cacheKey, data ) VALUES
1091 ' . implode(',', $insertValues);
1092
1093 $result = CRM_Core_DAO::executeQuery($sql);
1094 }
1095 }
1096
1097 /**
1098 * @inheritDoc
1099 */
1100 public function getQILL() {
1101 return $this->_query->qill();
1102 }
1103
1104 /**
1105 * Name of export file.
1106 *
1107 * @param string $output
1108 * Type of output.
1109 *
1110 * @return string
1111 * name of the file
1112 */
1113 public function getExportFileName($output = 'csv') {
1114 return ts('CiviCRM Contact Search');
1115 }
1116
1117 /**
1118 * Get colunmn headers for search selector.
1119 *
1120 * @return array
1121 */
1122 private static function &_getColumnHeaders() {
1123 if (!isset(self::$_columnHeaders)) {
1124 $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
1125 'address_options', TRUE, NULL, TRUE
1126 );
1127
1128 self::$_columnHeaders = array(
1129 'contact_type' => array('desc' => ts('Contact Type')),
1130 'sort_name' => array(
1131 'name' => ts('Name'),
1132 'sort' => 'sort_name',
1133 'direction' => CRM_Utils_Sort::ASCENDING,
1134 ),
1135 );
1136
1137 $defaultAddress = array(
1138 'street_address' => array('name' => ts('Address')),
1139 'city' => array(
1140 'name' => ts('City'),
1141 'sort' => 'city',
1142 'direction' => CRM_Utils_Sort::DONTCARE,
1143 ),
1144 'state_province' => array(
1145 'name' => ts('State'),
1146 'sort' => 'state_province',
1147 'direction' => CRM_Utils_Sort::DONTCARE,
1148 ),
1149 'postal_code' => array(
1150 'name' => ts('Postal'),
1151 'sort' => 'postal_code',
1152 'direction' => CRM_Utils_Sort::DONTCARE,
1153 ),
1154 'country' => array(
1155 'name' => ts('Country'),
1156 'sort' => 'country',
1157 'direction' => CRM_Utils_Sort::DONTCARE,
1158 ),
1159 );
1160
1161 foreach ($defaultAddress as $columnName => $column) {
1162 if (!empty($addressOptions[$columnName])) {
1163 self::$_columnHeaders[$columnName] = $column;
1164 }
1165 }
1166
1167 self::$_columnHeaders['email'] = array(
1168 'name' => ts('Email'),
1169 'sort' => 'email',
1170 'direction' => CRM_Utils_Sort::DONTCARE,
1171 );
1172
1173 self::$_columnHeaders['phone'] = array('name' => ts('Phone'));
1174 }
1175 return self::$_columnHeaders;
1176 }
1177
1178 /**
1179 * @return CRM_Contact_BAO_Query
1180 */
1181 public function getQuery() {
1182 return $this->_query;
1183 }
1184
1185 /**
1186 * @return CRM_Contact_DAO_Contact
1187 */
1188 public function alphabetQuery() {
1189 return $this->_query->searchQuery(NULL, NULL, NULL, FALSE, FALSE, TRUE);
1190 }
1191
1192 /**
1193 * @param array $params
1194 * @param int $sortID
1195 * @param null $displayRelationshipType
1196 * @param string $queryOperator
1197 *
1198 * @return CRM_Contact_DAO_Contact
1199 */
1200 public function contactIDQuery($params, $sortID, $displayRelationshipType = NULL, $queryOperator = 'AND') {
1201 $sortOrder = &$this->getSortOrder($this->_action);
1202 $sort = new CRM_Utils_Sort($sortOrder, $sortID);
1203
1204 // rectify params to what proximity search expects if there is a value for prox_distance
1205 // CRM-7021 CRM-7905
1206 if (!empty($params)) {
1207 CRM_Contact_BAO_ProximityQuery::fixInputParams($params);
1208 }
1209
1210 if (!$displayRelationshipType) {
1211 $query = new CRM_Contact_BAO_Query($params,
1212 CRM_Contact_BAO_Query::NO_RETURN_PROPERTIES,
1213 NULL, FALSE, FALSE, 1,
1214 FALSE, TRUE, TRUE, NULL,
1215 $queryOperator
1216 );
1217 }
1218 else {
1219 $query = new CRM_Contact_BAO_Query($params,
1220 CRM_Contact_BAO_Query::NO_RETURN_PROPERTIES,
1221 NULL, FALSE, FALSE, 1,
1222 FALSE, TRUE, TRUE, $displayRelationshipType,
1223 $queryOperator
1224 );
1225 }
1226 $value = $query->searchQuery(0, 0, $sort,
1227 FALSE, FALSE, FALSE,
1228 FALSE, FALSE
1229 );
1230 return $value;
1231 }
1232
1233 /**
1234 * @param $returnProperties
1235 *
1236 * @return array
1237 */
1238 public function &makeProperties(&$returnProperties) {
1239 $properties = array();
1240 foreach ($returnProperties as $name => $value) {
1241 if ($name != 'location') {
1242 // special handling for group and tag
1243 if (in_array($name, array('group', 'tag'))) {
1244 $name = "{$name}s";
1245 }
1246
1247 // special handling for notes
1248 if (in_array($name, array('note', 'note_subject', 'note_body'))) {
1249 $name = "notes";
1250 }
1251
1252 $properties[] = $name;
1253 }
1254 else {
1255 // extract all the location stuff
1256 foreach ($value as $n => $v) {
1257 foreach ($v as $n1 => $v1) {
1258 if (!strpos('_id', $n1) && $n1 != 'location_type') {
1259 $n = str_replace(' ', '_', $n);
1260 $properties[] = "{$n}-{$n1}";
1261 }
1262 }
1263 }
1264 }
1265 }
1266 return $properties;
1267 }
1268
1269 }