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