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