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