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