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