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