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