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