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