Merge pull request #18114 from eileenmcnaughton/phone
[civicrm-core.git] / CRM / Profile / Selector / Listings.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * This class is used to retrieve and display a range of
20 * contacts that match the given criteria (specifically for
21 * results of advanced search options.
22 *
23 */
24 class CRM_Profile_Selector_Listings extends CRM_Core_Selector_Base implements CRM_Core_Selector_API {
25
26 /**
27 * Array of supported links, currently view and edit
28 *
29 * @var array
30 */
31 public static $_links = NULL;
32
33 /**
34 * We use desc to remind us what that column is, name is used in the tpl
35 *
36 * @var array
37 */
38 public static $_columnHeaders;
39
40 /**
41 * The sql params we use to get the list of contacts.
42 *
43 * @var string
44 */
45 protected $_params;
46
47 /**
48 * The public visible fields to be shown to the user.
49 *
50 * @var array
51 */
52 protected $_fields;
53
54 /**
55 * The custom fields for this domain.
56 *
57 * @var array
58 */
59 protected $_customFields;
60
61 /**
62 * Cache the query object.
63 *
64 * @var object
65 */
66 protected $_query;
67
68 /**
69 * Cache the expanded options list if any.
70 *
71 * @var object
72 */
73 protected $_options;
74
75 /**
76 * The group id that we are editing.
77 *
78 * @var int
79 */
80 protected $_gid;
81
82 /**
83 * Do we enable mapping of users.
84 *
85 * @var bool
86 */
87 protected $_map;
88
89 /**
90 * Do we enable edit link.
91 *
92 * @var bool
93 */
94 protected $_editLink;
95
96 /**
97 * Should we link to the UF Profile.
98 *
99 * @var bool
100 */
101 protected $_linkToUF;
102
103 /**
104 * Store profile ids if multiple profile ids are passed using comma separated.
105 * Currently lets implement this functionality only for dialog mode
106 * @var array
107 */
108 protected $_profileIds = [];
109
110 protected $_multiRecordTableName = NULL;
111
112 /**
113 * Class constructor.
114 *
115 * @param array $params the params for the where clause
116 * @param array $customFields
117 * @param array $ufGroupIds
118 * @param bool $map
119 * @param bool $editLink
120 * @param bool $linkToUF
121 *
122 * @return \CRM_Profile_Selector_Listings
123 */
124 public function __construct(
125 &$params,
126 &$customFields,
127 $ufGroupIds = NULL,
128 $map = FALSE,
129 $editLink = FALSE,
130 $linkToUF = FALSE
131 ) {
132 $this->_params = $params;
133
134 if (is_array($ufGroupIds)) {
135 $this->_profileIds = $ufGroupIds;
136 $this->_gid = $ufGroupIds[0];
137 }
138 else {
139 $this->_profileIds = [$ufGroupIds];
140 $this->_gid = $ufGroupIds;
141 }
142
143 $this->_map = $map;
144 $this->_editLink = $editLink;
145 $this->_linkToUF = $linkToUF;
146
147 //get the details of the uf group
148 if ($this->_gid) {
149 $groupId = CRM_Core_DAO::getFieldValue('CRM_Core_BAO_UFGroup',
150 $this->_gid, 'limit_listings_group_id'
151 );
152 }
153
154 // add group id to params if a uf group belong to a any group
155 if ($groupId) {
156 if (!empty($this->_params['group'])) {
157 $this->_params['group'][$groupId] = 1;
158 }
159 else {
160 $this->_params['group'] = [$groupId => 1];
161 }
162 }
163
164 $this->_fields = CRM_Core_BAO_UFGroup::getListingFields(CRM_Core_Action::VIEW,
165 CRM_Core_BAO_UFGroup::PUBLIC_VISIBILITY |
166 CRM_Core_BAO_UFGroup::LISTINGS_VISIBILITY,
167 FALSE, $this->_profileIds
168 );
169
170 $this->_customFields = &$customFields;
171
172 $returnProperties = CRM_Contact_BAO_Contact::makeHierReturnProperties($this->_fields);
173 $returnProperties['contact_type'] = 1;
174 $returnProperties['contact_sub_type'] = 1;
175 $returnProperties['sort_name'] = 1;
176
177 $queryParams = CRM_Contact_BAO_Query::convertFormValues($this->_params, 1);
178 $this->_query = new CRM_Contact_BAO_Query($queryParams, $returnProperties, $this->_fields);
179
180 //the below is done for query building for multirecord custom field listing
181 //to show all the custom field multi valued records of a particular contact
182 $this->setMultiRecordTableName($this->_fields);
183
184 $this->_options = &$this->_query->_options;
185 }
186
187 /**
188 * This method returns the links that are given for each search row.
189 *
190 * @param bool $map
191 * @param bool $editLink
192 * @param bool $ufLink
193 * @param null $gids
194 *
195 * @return array
196 */
197 public static function &links($map = FALSE, $editLink = FALSE, $ufLink = FALSE, $gids = NULL) {
198 if (!self::$_links) {
199 self::$_links = [];
200
201 $viewPermission = TRUE;
202 if ($gids) {
203 // check view permission for each profile id, in case multiple profile ids are rendered
204 // then view action is disabled if any profile returns false
205 foreach ($gids as $profileId) {
206 $viewPermission = CRM_Core_Permission::ufGroupValid($profileId, CRM_Core_Permission::VIEW);
207 if (!$viewPermission) {
208 break;
209 }
210 }
211 }
212
213 if ($viewPermission) {
214 self::$_links[CRM_Core_Action::VIEW] = [
215 'name' => ts('View'),
216 'url' => 'civicrm/profile/view',
217 'qs' => 'reset=1&id=%%id%%&gid=%%gid%%',
218 'title' => ts('View Profile Details'),
219 ];
220 }
221
222 if ($editLink) {
223 self::$_links[CRM_Core_Action::UPDATE] = [
224 'name' => ts('Edit'),
225 'url' => 'civicrm/profile/edit',
226 'qs' => 'reset=1&id=%%id%%&gid=%%gid%%',
227 'title' => ts('Edit'),
228 ];
229 }
230
231 if ($ufLink) {
232 self::$_links[CRM_Core_Action::PROFILE] = [
233 'name' => ts('Website Profile'),
234 'url' => 'user/%%ufID%%',
235 'qs' => ' ',
236 'title' => ts('View Website Profile'),
237 ];
238 }
239
240 if ($map) {
241 self::$_links[CRM_Core_Action::MAP] = [
242 'name' => ts('Map'),
243 'url' => 'civicrm/profile/map',
244 'qs' => 'reset=1&cid=%%id%%&gid=%%gid%%',
245 'title' => ts('Map'),
246 ];
247 }
248 }
249 return self::$_links;
250 }
251
252 /**
253 * Getter for array of the parameters required for creating pager.
254 *
255 * @param $action
256 * @param array $params
257 */
258 public function getPagerParams($action, &$params) {
259 $status = CRM_Utils_System::isNull($this->_multiRecordTableName) ? ts('Contact %%StatusMessage%%') : ts('Contact Multi Records %%StatusMessage%%');
260 $params['status'] = $status;
261 $params['csvString'] = NULL;
262 $params['rowCount'] = CRM_Utils_Pager::ROWCOUNT;
263
264 $params['buttonTop'] = 'PagerTopButton';
265 $params['buttonBottom'] = 'PagerBottomButton';
266 }
267
268 /**
269 * Returns the column headers as an array of tuples:
270 * (name, sortName (key to the sort array))
271 *
272 * @param string $action
273 * The action being performed.
274 * @param string $output
275 * What should the result set include (web/email/csv).
276 *
277 * @return array
278 * the column headers that need to be displayed
279 */
280 public function &getColumnHeaders($action = NULL, $output = NULL) {
281 static $skipFields = ['group', 'tag'];
282 $multipleFields = ['url'];
283 $direction = CRM_Utils_Sort::ASCENDING;
284 $empty = TRUE;
285 if (!isset(self::$_columnHeaders)) {
286 self::$_columnHeaders = [
287 ['name' => ''],
288 [
289 'name' => ts('Name'),
290 'sort' => 'sort_name',
291 'direction' => CRM_Utils_Sort::ASCENDING,
292 'field_name' => 'sort_name',
293 ],
294 ];
295
296 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
297
298 foreach ($this->_fields as $name => $field) {
299 // skip pseudo fields
300 if (substr($name, 0, 9) == 'phone_ext') {
301 continue;
302 }
303
304 if (!empty($field['in_selector']) &&
305 !in_array($name, $skipFields)
306 ) {
307
308 if (strpos($name, '-') !== FALSE) {
309 $value = explode('-', $name);
310 $fieldName = $value[0] ?? NULL;
311 $lType = $value[1] ?? NULL;
312 $type = $value[2] ?? NULL;
313
314 if (!in_array($fieldName, $multipleFields)) {
315 if ($lType == 'Primary') {
316 $locationTypeName = 1;
317 }
318 else {
319 $locationTypeName = $locationTypes[$lType];
320 }
321
322 if (in_array($fieldName, [
323 'phone',
324 'im',
325 'email',
326 ])) {
327 if ($type) {
328 $name = "`$locationTypeName-$fieldName-$type`";
329 }
330 else {
331 $name = "`$locationTypeName-$fieldName`";
332 }
333 }
334 else {
335 $name = "`$locationTypeName-$fieldName`";
336 }
337 }
338 else {
339 $name = "website-{$lType}-{$fieldName}";
340 }
341 }
342
343 self::$_columnHeaders[] = [
344 'name' => $field['title'],
345 'sort' => $name,
346 'direction' => $direction,
347 'field_name' => CRM_Core_BAO_UFField::isValidFieldName($name) ? $name : $fieldName,
348 ];
349
350 $direction = CRM_Utils_Sort::DONTCARE;
351 $empty = FALSE;
352 }
353 }
354
355 // if we don't have any valid columns, don't add the implicit ones
356 // this allows the template to check on emptiness of column headers
357 if ($empty) {
358 self::$_columnHeaders = [];
359 }
360 else {
361 self::$_columnHeaders[] = ['desc' => ts('Actions')];
362 }
363 }
364 return self::$_columnHeaders;
365 }
366
367 /**
368 * Returns total number of rows for the query.
369 *
370 * @param int $action
371 *
372 * @return int
373 * Total number of rows
374 */
375 public function getTotalCount($action) {
376 $additionalWhereClause = 'contact_a.is_deleted = 0';
377 $additionalFromClause = NULL;
378 $returnQuery = NULL;
379
380 if ($this->_multiRecordTableName &&
381 !array_key_exists($this->_multiRecordTableName, $this->_query->_whereTables)
382 ) {
383 $additionalFromClause = $this->_query->_tables[$this->_multiRecordTableName] ?? NULL;
384 $returnQuery = TRUE;
385 }
386
387 $countVal = $this->_query->searchQuery(0, 0, NULL, TRUE, NULL, NULL, NULL,
388 $returnQuery, $additionalWhereClause, NULL, $additionalFromClause
389 );
390
391 if (!$returnQuery) {
392 return $countVal;
393 }
394
395 if ($returnQuery) {
396 $sql = preg_replace('/DISTINCT/', '', $countVal);
397 return CRM_Core_DAO::singleValueQuery($sql);
398 }
399 }
400
401 /**
402 * Return the qill for this selector.
403 *
404 * @return string
405 */
406 public function getQill() {
407 return $this->_query->qill();
408 }
409
410 /**
411 * Returns all the rows in the given offset and rowCount.
412 *
413 * @param string $action
414 * The action being performed.
415 * @param int $offset
416 * The row number to start from.
417 * @param int $rowCount
418 * The number of rows to return.
419 * @param string $sort
420 * The sql string that describes the sort order.
421 * @param string $output
422 * What should the result set include (web/email/csv).
423 *
424 * @param string $extraWhereClause
425 *
426 * @return int
427 * the total number of rows for this action
428 */
429 public function &getRows($action, $offset, $rowCount, $sort, $output = NULL, $extraWhereClause = NULL) {
430
431 $multipleFields = ['url'];
432 //$sort object processing for location fields
433 if ($sort) {
434 $vars = $sort->_vars;
435 $varArray = [];
436 foreach ($vars as $key => $field) {
437 $field = $vars[$key];
438 $fieldArray = explode('-', $field['name']);
439 $fieldType = $fieldArray['2'] ?? NULL;
440 if (is_numeric(CRM_Utils_Array::value('1', $fieldArray))) {
441 if (!in_array($fieldType, $multipleFields)) {
442 $locationType = new CRM_Core_DAO_LocationType();
443 $locationType->id = $fieldArray[1];
444 $locationType->find(TRUE);
445 if ($fieldArray[0] == 'email' || $fieldArray[0] == 'im' || $fieldArray[0] == 'phone') {
446 $field['name'] = "`" . $locationType->name . "-" . $fieldArray[0] . "-1`";
447 }
448 else {
449 $field['name'] = "`" . $locationType->name . "-" . $fieldArray[0] . "`";
450 }
451 }
452 else {
453 $field['name'] = "`website-" . $fieldArray[1] . "-{$fieldType}`";
454 }
455 }
456 $varArray[$key] = $field;
457 }
458 $sort->_vars = $varArray;
459 }
460
461 $additionalWhereClause = 'contact_a.is_deleted = 0';
462
463 if ($extraWhereClause) {
464 $additionalWhereClause .= " AND {$extraWhereClause}";
465 }
466
467 $returnQuery = NULL;
468 if ($this->_multiRecordTableName) {
469 $returnQuery = TRUE;
470 }
471 $this->_query->_useGroupBy = TRUE;
472 $result = $this->_query->searchQuery($offset, $rowCount, $sort, NULL, NULL,
473 NULL, NULL, $returnQuery, $additionalWhereClause
474 );
475
476 if ($returnQuery) {
477 $resQuery = preg_replace('/GROUP BY contact_a.id[\s]+ORDER BY/', ' ORDER BY', $result);
478 $result = CRM_Core_DAO::executeQuery($resQuery);
479 }
480
481 // process the result of the query
482 $rows = [];
483
484 // check if edit is configured in profile settings
485 if ($this->_gid) {
486 $editLink = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $this->_gid, 'is_edit_link');
487 }
488
489 //FIXME : make sure to handle delete separately. CRM-4418
490 $mask = CRM_Core_Action::mask([CRM_Core_Permission::getPermission()]);
491 if ($editLink && ($mask & CRM_Core_Permission::EDIT)) {
492 // do not allow edit for anon users in joomla frontend, CRM-4668
493 $config = CRM_Core_Config::singleton();
494 if (!$config->userFrameworkFrontend || CRM_Core_Session::getLoggedInContactID()) {
495 $this->_editLink = TRUE;
496 }
497 }
498 $links = self::links($this->_map, $this->_editLink, $this->_linkToUF, $this->_profileIds);
499
500 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
501
502 $names = [];
503 static $skipFields = ['group', 'tag'];
504
505 foreach ($this->_fields as $key => $field) {
506 // skip pseudo fields
507 if (substr($key, 0, 9) == 'phone_ext') {
508 continue;
509 }
510
511 if (!empty($field['in_selector']) &&
512 !in_array($key, $skipFields)
513 ) {
514 if (strpos($key, '-') !== FALSE) {
515 $value = explode('-', $key);
516 $fieldName = $value[0] ?? NULL;
517 $id = $value[1] ?? NULL;
518 $type = $value[2] ?? NULL;
519
520 if (!in_array($fieldName, $multipleFields)) {
521 $locationTypeName = NULL;
522 if (is_numeric($id)) {
523 $locationTypeName = $locationTypes[$id] ?? NULL;
524 }
525 else {
526 if ($id == 'Primary') {
527 $locationTypeName = 1;
528 }
529 }
530
531 if (!$locationTypeName) {
532 continue;
533 }
534 $locationTypeName = str_replace(' ', '_', $locationTypeName);
535 if (in_array($fieldName, [
536 'phone',
537 'im',
538 'email',
539 ])) {
540 if ($type) {
541 $names[] = "{$locationTypeName}-{$fieldName}-{$type}";
542 }
543 else {
544 $names[] = "{$locationTypeName}-{$fieldName}";
545 }
546 }
547 else {
548 $names[] = "{$locationTypeName}-{$fieldName}";
549 }
550 }
551 else {
552 $names[] = "website-{$id}-{$fieldName}";
553 }
554 }
555 elseif ($field['name'] == 'id') {
556 $names[] = 'contact_id';
557 }
558 else {
559 $names[] = $field['name'];
560 }
561 }
562 }
563
564 $multipleSelectFields = ['preferred_communication_method' => 1];
565 $multiRecordTableId = NULL;
566 if ($this->_multiRecordTableName) {
567 $multiRecordTableId = "{$this->_multiRecordTableName}_id";
568 }
569
570 // we need to determine of overlay profile should be shown
571 $showProfileOverlay = CRM_Core_BAO_UFGroup::showOverlayProfile();
572
573 while ($result->fetch()) {
574 $this->_query->convertToPseudoNames($result);
575
576 if (isset($result->country)) {
577 // the query returns the untranslated country name
578 $i18n = CRM_Core_I18n::singleton();
579 $result->country = $i18n->translate($result->country);
580 }
581 $row = [];
582 $empty = TRUE;
583 $row[] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type,
584 FALSE,
585 $result->contact_id,
586 $showProfileOverlay
587 );
588 if ($result->sort_name) {
589 $row[] = $result->sort_name;
590 $empty = FALSE;
591 }
592 else {
593 continue;
594 }
595
596 foreach ($names as $name) {
597 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name)) {
598 $row[] = CRM_Core_BAO_CustomField::displayValue($result->$name,
599 $cfID,
600 $result->contact_id
601 );
602 }
603 elseif (substr($name, -4) == '-url' &&
604 !empty($result->$name)
605 ) {
606 $url = CRM_Utils_System::fixURL($result->$name);
607 $typeId = substr($name, 0, -4) . "-website_type_id";
608 $typeName = CRM_Core_PseudoConstant::getLabel('CRM_Core_DAO_Website', 'website_type_id', $result->$typeId);
609 if ($typeName) {
610 $row[] = "<a href=\"$url\">{$result->$name} (${typeName})</a>";
611 }
612 else {
613 $row[] = "<a href=\"$url\">{$result->$name}</a>";
614 }
615 }
616 elseif ($name == 'preferred_language') {
617 $row[] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $result->$name);
618 }
619 elseif ($multipleSelectFields &&
620 array_key_exists($name, $multipleSelectFields)
621 ) {
622 $paramsNew = [$name => $result->$name];
623 $name = [$name => ['newName' => $name, 'groupName' => $name]];
624
625 CRM_Core_OptionGroup::lookupValues($paramsNew, $name, FALSE);
626 $row[] = $paramsNew[$key];
627 }
628 elseif (strpos($name, '-im')) {
629 if (!empty($result->$name)) {
630 $providerId = $name . "-provider_id";
631 $providerName = CRM_Core_PseudoConstant::getLabel('CRM_Core_DAO_IM', 'provider_id', $result->$providerId);
632 $row[] = $result->$name . " ({$providerName})";
633 }
634 else {
635 $row[] = '';
636 }
637 }
638 elseif (strpos($name, '-phone-')) {
639 $phoneExtField = str_replace('phone', 'phone_ext', $name);
640 if (isset($result->$phoneExtField)) {
641 $row[] = $result->$name . " (" . $result->$phoneExtField . ")";
642 }
643 else {
644 $row[] = $result->$name;
645 }
646 }
647 elseif (in_array($name, [
648 'addressee',
649 'email_greeting',
650 'postal_greeting',
651 ])) {
652 $dname = $name . '_display';
653 $row[] = $result->$dname;
654 }
655 elseif (in_array($name, [
656 'birth_date',
657 'deceased_date',
658 ])) {
659 $row[] = CRM_Utils_Date::customFormat($result->$name);
660 }
661 elseif (isset($result->$name)) {
662 $row[] = $result->$name;
663 }
664 else {
665 $row[] = '';
666 }
667
668 if (!empty($result->$name)) {
669 $empty = FALSE;
670 }
671 }
672
673 $newLinks = $links;
674 $params = [
675 'id' => $result->contact_id,
676 'gid' => implode(',', $this->_profileIds),
677 ];
678
679 // pass record id param to view url for multi record view
680 if ($multiRecordTableId && $newLinks) {
681 if ($result->$multiRecordTableId) {
682 if ($newLinks[CRM_Core_Action::VIEW]['url'] == 'civicrm/profile/view') {
683 $newLinks[CRM_Core_Action::VIEW]['qs'] .= "&multiRecord=view&recordId=%%recordId%%&allFields=1";
684 $params['recordId'] = $result->$multiRecordTableId;
685 }
686 }
687 }
688
689 if ($this->_linkToUF) {
690 $ufID = CRM_Core_BAO_UFMatch::getUFId($result->contact_id);
691 if (!$ufID) {
692 unset($newLinks[CRM_Core_Action::PROFILE]);
693 }
694 else {
695 $params['ufID'] = $ufID;
696 }
697 }
698
699 $row[] = CRM_Core_Action::formLink($newLinks,
700 $mask,
701 $params,
702 ts('more'),
703 FALSE,
704 'profile.selector.row',
705 'Contact',
706 $result->contact_id
707 );
708
709 if (!$empty) {
710 $rows[] = $row;
711 }
712 }
713 return $rows;
714 }
715
716 /**
717 * Name of export file.
718 *
719 * @param string $output
720 * Type of output.
721 *
722 * @return string
723 * name of the file
724 */
725 public function getExportFileName($output = 'csv') {
726 return ts('CiviCRM Profile Listings');
727 }
728
729 /**
730 * Set the _multiRecordTableName to display the result set.
731 *
732 * (according to multi record custom field values).
733 *
734 * @param array $fields
735 */
736 public function setMultiRecordTableName($fields) {
737 $customGroupId = $multiRecordTableName = NULL;
738 $selectorSet = FALSE;
739
740 foreach ($fields as $field => $properties) {
741 if (!CRM_Core_BAO_CustomField::getKeyID($field)) {
742 continue;
743 }
744 if ($cgId = CRM_Core_BAO_CustomField::isMultiRecordField($field)) {
745 $customGroupId = CRM_Utils_System::isNull($customGroupId) ? $cgId : $customGroupId;
746
747 //if the field is submitted set multiRecordTableName
748 if ($customGroupId) {
749 $isSubmitted = FALSE;
750 foreach ($this->_query->_params as $key => $value) {
751 //check the query params 'where' element
752 if ($value[0] == $field) {
753 $isSubmitted = TRUE;
754 break;
755 }
756 }
757
758 if ($isSubmitted) {
759 $this->_multiRecordTableName
760 = $multiRecordTableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
761 if ($multiRecordTableName) {
762 return;
763 }
764 }
765
766 if (!empty($properties['in_selector'])) {
767 $selectorSet = TRUE;
768 }
769 }
770 }
771 }
772
773 if (!isset($customGroupId) || !$customGroupId) {
774 return;
775 }
776
777 //if the field is in selector and not a searchable field
778 //get the proper custom value table name
779 if ($selectorSet) {
780 $this->_multiRecordTableName
781 = $multiRecordTableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
782 }
783 } //func close
784
785 }