INFRA-132 - CRM/Event - phpcbf
[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 ? $result->contact_sub_type : $result->contact_type,
796 FALSE,
797 $result->contact_id
798 );
799
800 $row['contact_type_orig'] = $result->contact_sub_type ? $result->contact_sub_type : $result->contact_type;
801 $row['contact_sub_type'] = $result->contact_sub_type ? CRM_Contact_BAO_ContactType::contactTypePairs(FALSE, $result->contact_sub_type, ', ') : $result->contact_sub_type;
802 $row['contact_id'] = $result->contact_id;
803 $row['sort_name'] = $result->sort_name;
804 if (array_key_exists('id', $row)) {
805 $row['id'] = $result->contact_id;
806 }
807 }
808
809 // Dedupe contacts
810 if (in_array($row['contact_id'], $seenIDs) === FALSE) {
811 $seenIDs[] = $row['contact_id'];
812 $rows[] = $row;
813 }
814 }
815
816 return $rows;
817 }
818
819 /**
820 * @param CRM_Utils_Sort $sort
821 *
822 * @return string
823 */
824 public function buildPrevNextCache($sort) {
825 $cacheKey = 'civicrm search ' . $this->_key;
826
827 // We should clear the cache in following conditions:
828 // 1. when starting from scratch, i.e new search
829 // 2. if records are sorted
830
831 // get current page requested
832 $pageNum = CRM_Utils_Request::retrieve('crmPID', 'Integer', CRM_Core_DAO::$_nullObject);
833
834 // get the current sort order
835 $currentSortID = CRM_Utils_Request::retrieve('crmSID', 'String', CRM_Core_DAO::$_nullObject);
836
837 $session = CRM_Core_Session::singleton();
838
839 // get previous sort id
840 $previousSortID = $session->get('previousSortID');
841
842 // check for current != previous to ensure cache is not reset if paging is done without changing
843 // sort criteria
844 if (!$pageNum || (!empty($currentSortID) && $currentSortID != $previousSortID) ) {
845 CRM_Core_BAO_PrevNextCache::deleteItem(NULL, $cacheKey, 'civicrm_contact');
846 // this means it's fresh search, so set pageNum=1
847 if (!$pageNum) {
848 $pageNum = 1;
849 }
850 }
851
852 // set the current sort as previous sort
853 if (!empty($currentSortID)) {
854 $session->set('previousSortID', $currentSortID);
855 }
856
857 $pageSize = CRM_Utils_Request::retrieve('crmRowCount', 'Integer', CRM_Core_DAO::$_nullObject, FALSE, 50);
858 $firstRecord = ($pageNum - 1) * $pageSize;
859
860 //for alphabetic pagination selection save
861 $sortByCharacter = CRM_Utils_Request::retrieve('sortByCharacter', 'String', CRM_Core_DAO::$_nullObject);
862
863 //for text field pagination selection save
864 $countRow = CRM_Core_BAO_PrevNextCache::getCount($cacheKey, NULL, "entity_table = 'civicrm_contact'");
865
866 // $sortByCharacter triggers a refresh in the prevNext cache
867 if ($sortByCharacter && $sortByCharacter != 'all') {
868 $cacheKey .= "_alphabet";
869 $this->fillupPrevNextCache($sort, $cacheKey);
870 }
871 elseif ($firstRecord >= $countRow) {
872 $this->fillupPrevNextCache($sort, $cacheKey, $countRow, 500);
873 }
874 return $cacheKey;
875 }
876
877 /**
878 * @param $rows
879 */
880 public function addActions(&$rows) {
881 $config = CRM_Core_Config::singleton();
882
883 $permissions = array(CRM_Core_Permission::getPermission());
884 if (CRM_Core_Permission::check('delete contacts')) {
885 $permissions[] = CRM_Core_Permission::DELETE;
886 }
887 $mask = CRM_Core_Action::mask($permissions);
888 // mask value to hide map link if there are not lat/long
889 $mapMask = $mask & 4095;
890
891 // mask value to hide map link if there are not lat/long
892 $mapMask = $mask & 4095;
893
894 $links = self::links($this->_context, $this->_contextMenu, $this->_key);
895
896 foreach ($rows as $id => & $row) {
897 if (!empty($this->_formValues['deleted_contacts']) && CRM_Core_Permission::check('access deleted contacts')
898 ) {
899 $links = array(
900 array(
901 'name' => ts('View'),
902 'url' => 'civicrm/contact/view',
903 'qs' => 'reset=1&cid=%%id%%',
904 'class' => 'no-popup',
905 'title' => ts('View Contact Details'),
906 ),
907 array(
908 'name' => ts('Restore'),
909 'url' => 'civicrm/contact/view/delete',
910 'qs' => 'reset=1&cid=%%id%%&restore=1',
911 'title' => ts('Restore Contact'),
912 ),
913 );
914 if (CRM_Core_Permission::check('delete contacts')) {
915 $links[] = array(
916 'name' => ts('Delete Permanently'),
917 'url' => 'civicrm/contact/view/delete',
918 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1',
919 'title' => ts('Permanently Delete Contact'),
920 );
921 }
922 $row['action'] = CRM_Core_Action::formLink(
923 $links,
924 NULL,
925 array('id' => $row['contact_id']),
926 ts('more'),
927 FALSE,
928 'contact.selector.actions',
929 'Contact',
930 $row['contact_id']
931 );
932 }
933 elseif ((is_numeric(CRM_Utils_Array::value('geo_code_1', $row))) ||
934 ($config->mapGeoCoding && !empty($row['city']) &&
935 CRM_Utils_Array::value('state_province', $row)
936 )
937 ) {
938 $row['action'] = CRM_Core_Action::formLink(
939 $links,
940 $mask,
941 array('id' => $row['contact_id']),
942 ts('more'),
943 FALSE,
944 'contact.selector.actions',
945 'Contact',
946 $row['contact_id']
947 );
948 }
949 else {
950 $row['action'] = CRM_Core_Action::formLink(
951 $links,
952 $mapMask,
953 array('id' => $row['contact_id']),
954 ts('more'),
955 FALSE,
956 'contact.selector.actions',
957 'Contact',
958 $row['contact_id']
959 );
960 }
961
962 // allow components to add more actions
963 CRM_Core_Component::searchAction($row, $row['contact_id']);
964
965 if (!empty($row['contact_type_orig'])) {
966 $row['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage($row['contact_type_orig'],
967 FALSE, $row['contact_id']);
968 }
969 }
970 }
971
972 /**
973 * @param $rows
974 */
975 public function removeActions(&$rows) {
976 foreach ($rows as $rid => & $rValue) {
977 unset($rValue['contact_type']);
978 unset($rValue['action']);
979 }
980 }
981
982 /**
983 * @param CRM_Utils_Sort $sort
984 * @param string $cacheKey
985 * @param int $start
986 * @param int $end
987 */
988 public function fillupPrevNextCache($sort, $cacheKey, $start = 0, $end = 500) {
989 $coreSearch = TRUE;
990 // For custom searches, use the contactIDs method
991 if (is_a($this, 'CRM_Contact_Selector_Custom')) {
992 $sql = $this->_search->contactIDs($start, $end, $sort, TRUE);
993 $replaceSQL = "SELECT contact_a.id as contact_id";
994 $coreSearch = FALSE;
995 }
996 // For core searches use the searchQuery method
997 else {
998 $sql = $this->_query->searchQuery($start, $end, $sort, FALSE, $this->_query->_includeContactIds,
999 FALSE, TRUE, TRUE);
1000 $replaceSQL = "SELECT contact_a.id as id";
1001 }
1002
1003 // CRM-9096
1004 // due to limitations in our search query writer, the above query does not work
1005 // in cases where the query is being sorted on a non-contact table
1006 // this results in a fatal error :(
1007 // see below for the gross hack of trapping the error and not filling
1008 // the prev next cache in this situation
1009 // the other alternative of running the FULL query will just be incredibly inefficient
1010 // and slow things down way too much on large data sets / complex queries
1011
1012 $insertSQL = "
1013 INSERT INTO civicrm_prevnext_cache ( entity_table, entity_id1, entity_id2, cacheKey, data )
1014 SELECT DISTINCT 'civicrm_contact', contact_a.id, contact_a.id, '$cacheKey', contact_a.display_name
1015 ";
1016
1017 $sql = str_replace($replaceSQL, $insertSQL, $sql);
1018
1019 $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
1020 $result = CRM_Core_DAO::executeQuery($sql);
1021 unset($errorScope);
1022
1023 if (is_a($result, 'DB_Error')) {
1024 // check if we get error during core search
1025 if ($coreSearch) {
1026 // in the case of error, try rebuilding cache using full sql which is used for search selector display
1027 // this fixes the bugs reported in CRM-13996 & CRM-14438
1028 $this->rebuildPreNextCache($start, $end, $sort, $cacheKey);
1029 }
1030 else {
1031 // return if above query fails
1032 return;
1033 }
1034 }
1035
1036 // also record an entry in the cache key table, so we can delete it periodically
1037 CRM_Core_BAO_Cache::setItem($cacheKey, 'CiviCRM Search PrevNextCache', $cacheKey);
1038 }
1039
1040 /**
1041 * This function is called to rebuild prev next cache using full sql in case of core search ( excluding custom search)
1042 *
1043 * @param int $start
1044 * Start for limit clause.
1045 * @param int $end
1046 * End for limit clause.
1047 * @param CRM_Utils_Sort $sort
1048 * @param string $cacheKey
1049 * Cache key.
1050 *
1051 * @return void
1052 */
1053 public function rebuildPreNextCache($start, $end, $sort, $cacheKey) {
1054 // generate full SQL
1055 $sql = $this->_query->searchQuery($start, $end, $sort, FALSE, $this->_query->_includeContactIds,
1056 FALSE, FALSE, TRUE);
1057
1058 $dao = CRM_Core_DAO::executeQuery($sql);
1059
1060 // build insert query, note that currently we build cache for 500 contact records at a time, hence below approach
1061 $insertValues = array();
1062 while($dao->fetch()) {
1063 $insertValues[] = "('civicrm_contact', {$dao->contact_id}, {$dao->contact_id}, '{$cacheKey}', '" . CRM_Core_DAO::escapeString($dao->sort_name) . "')";
1064 }
1065
1066 //update pre/next cache using single insert query
1067 if (!empty($insertValues)) {
1068 $sql = 'INSERT INTO civicrm_prevnext_cache ( entity_table, entity_id1, entity_id2, cacheKey, data ) VALUES
1069 '.implode(',', $insertValues);
1070
1071 $result = CRM_Core_DAO::executeQuery($sql);
1072 }
1073 }
1074
1075 /**
1076 * Given the current formValues, gets the query in local
1077 * language
1078 *
1079 * @param array(
1080 reference) $formValues submitted formValues
1081 *
1082 * @return array $qill which contains an array of strings
1083 */
1084
1085 // the current internationalisation is bad, but should more or less work
1086 // for most of "European" languages
1087 public function getQILL() {
1088 return $this->_query->qill();
1089 }
1090
1091 /**
1092 * Name of export file.
1093 *
1094 * @param string $output
1095 * Type of output.
1096 *
1097 * @return string name of the file
1098 */
1099 public function getExportFileName($output = 'csv') {
1100 return ts('CiviCRM Contact Search');
1101 }
1102
1103 /**
1104 * Get colunmn headers for search selector
1105 *
1106 *
1107 * @return array $_columnHeaders
1108 */
1109 private static function &_getColumnHeaders() {
1110 if (!isset(self::$_columnHeaders)) {
1111 $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
1112 'address_options', TRUE, NULL, TRUE
1113 );
1114
1115 self::$_columnHeaders = array(
1116 'contact_type' => array('desc' => ts('Contact Type')),
1117 'sort_name' => array(
1118 'name' => ts('Name'),
1119 'sort' => 'sort_name',
1120 'direction' => CRM_Utils_Sort::ASCENDING,
1121 ),
1122 );
1123
1124 $defaultAddress = array(
1125 'street_address' => array('name' => ts('Address')),
1126 'city' => array(
1127 'name' => ts('City'),
1128 'sort' => 'city',
1129 'direction' => CRM_Utils_Sort::DONTCARE,
1130 ),
1131 'state_province' => array(
1132 'name' => ts('State'),
1133 'sort' => 'state_province',
1134 'direction' => CRM_Utils_Sort::DONTCARE,
1135 ),
1136 'postal_code' => array(
1137 'name' => ts('Postal'),
1138 'sort' => 'postal_code',
1139 'direction' => CRM_Utils_Sort::DONTCARE,
1140 ),
1141 'country' => array(
1142 'name' => ts('Country'),
1143 'sort' => 'country',
1144 'direction' => CRM_Utils_Sort::DONTCARE,
1145 ),
1146 );
1147
1148 foreach ($defaultAddress as $columnName => $column) {
1149 if (!empty($addressOptions[$columnName])) {
1150 self::$_columnHeaders[$columnName] = $column;
1151 }
1152 }
1153
1154 self::$_columnHeaders['email'] = array(
1155 'name' => ts('Email'),
1156 'sort' => 'email',
1157 'direction' => CRM_Utils_Sort::DONTCARE,
1158 );
1159
1160 self::$_columnHeaders['phone'] = array('name' => ts('Phone'));
1161 }
1162 return self::$_columnHeaders;
1163 }
1164
1165 /**
1166 * @return CRM_Contact_BAO_Query
1167 */
1168 public function &getQuery() {
1169 return $this->_query;
1170 }
1171
1172 /**
1173 * @return CRM_Contact_DAO_Contact
1174 */
1175 public function alphabetQuery() {
1176 return $this->_query->searchQuery(NULL, NULL, NULL, FALSE, FALSE, TRUE);
1177 }
1178
1179 /**
1180 * @param array $params
1181 * @param $action
1182 * @param int $sortID
1183 * @param null $displayRelationshipType
1184 * @param string $queryOperator
1185 *
1186 * @return CRM_Contact_DAO_Contact
1187 */
1188 public function contactIDQuery($params, $action, $sortID, $displayRelationshipType = NULL, $queryOperator = 'AND') {
1189 $sortOrder = &$this->getSortOrder($this->_action);
1190 $sort = new CRM_Utils_Sort($sortOrder, $sortID);
1191
1192 // rectify params to what proximity search expects if there is a value for prox_distance
1193 // CRM-7021 CRM-7905
1194 if (!empty($params)) {
1195 CRM_Contact_BAO_ProximityQuery::fixInputParams($params);
1196 }
1197
1198 if (!$displayRelationshipType) {
1199 $query = new CRM_Contact_BAO_Query($params,
1200 $this->_returnProperties,
1201 NULL, FALSE, FALSE, 1,
1202 FALSE, TRUE, TRUE, NULL,
1203 $queryOperator
1204 );
1205 }
1206 else {
1207 $query = new CRM_Contact_BAO_Query($params, $this->_returnProperties,
1208 NULL, FALSE, FALSE, 1,
1209 FALSE, TRUE, TRUE, $displayRelationshipType,
1210 $queryOperator
1211 );
1212 }
1213 $value = $query->searchQuery(0, 0, $sort,
1214 FALSE, FALSE, FALSE,
1215 FALSE, FALSE
1216 );
1217 return $value;
1218 }
1219
1220 /**
1221 * @param $returnProperties
1222 *
1223 * @return array
1224 */
1225 public function &makeProperties(&$returnProperties) {
1226 $properties = array();
1227 foreach ($returnProperties as $name => $value) {
1228 if ($name != 'location') {
1229 // special handling for group and tag
1230 if (in_array($name, array('group', 'tag'))) {
1231 $name = "{$name}s";
1232 }
1233
1234 // special handling for notes
1235 if (in_array($name, array('note', 'note_subject', 'note_body'))) {
1236 $name = "notes";
1237 }
1238
1239 $properties[] = $name;
1240 }
1241 else {
1242 // extract all the location stuff
1243 foreach ($value as $n => $v) {
1244 foreach ($v as $n1 => $v1) {
1245 if (!strpos('_id', $n1) && $n1 != 'location_type') {
1246 $properties[] = "{$n}-{$n1}";
1247 }
1248 }
1249 }
1250 }
1251 }
1252 return $properties;
1253 }
1254 }