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