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