Merge pull request #17389 from seamuslee001/dev_core_1776
[civicrm-core.git] / CRM / Profile / Page / MultipleRecordFieldsListing.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 class CRM_Profile_Page_MultipleRecordFieldsListing extends CRM_Core_Page_Basic {
19
20 /**
21 * The action links that we need to display for the browse screen.
22 *
23 * @var array
24 */
25 public static $_links = NULL;
26
27 protected $_fields = NULL;
28
29 protected $_profileId = NULL;
30
31 public $_contactId = NULL;
32
33 public $_customGroupTitle = NULL;
34
35 public $_pageViewType = NULL;
36
37 public $_contactType = NULL;
38
39 /**
40 * Get BAO Name.
41 *
42 * @return string
43 * Classname of BAO.
44 */
45 public function getBAOName() {
46 return '';
47 }
48
49 /**
50 * Get action Links.
51 *
52 * @return array
53 * (reference) of action links
54 */
55 public function &links() {
56 if (!isset(self::$_links[$this->_pageViewType])) {
57 // helper variable for nicer formatting
58 $links = [];
59
60 $view = array_search(CRM_Core_Action::VIEW, CRM_Core_Action::$_names);
61 $update = array_search(CRM_Core_Action::UPDATE, CRM_Core_Action::$_names);
62 $delete = array_search(CRM_Core_Action::DELETE, CRM_Core_Action::$_names);
63
64 // names and titles
65 $links[CRM_Core_Action::VIEW] = [
66 'name' => ts('View'),
67 'title' => ts('View %1', [1 => $this->_customGroupTitle . ' record']),
68 ];
69
70 $links[CRM_Core_Action::UPDATE] = [
71 'name' => ts('Edit'),
72 'title' => ts('Edit %1', [1 => $this->_customGroupTitle . ' record']),
73 ];
74
75 $links[CRM_Core_Action::DELETE] = [
76 'name' => ts('Delete'),
77 'title' => ts('Delete %1', [1 => $this->_customGroupTitle . ' record']),
78 ];
79
80 // urls and queryStrings
81 if ($this->_pageViewType == 'profileDataView') {
82 $links[CRM_Core_Action::VIEW]['url'] = 'civicrm/profile/view';
83 $links[CRM_Core_Action::VIEW]['qs'] = "reset=1&id=%%id%%&recordId=%%recordId%%&gid=%%gid%%&multiRecord={$view}";
84
85 $links[CRM_Core_Action::UPDATE]['url'] = 'civicrm/profile/edit';
86 $links[CRM_Core_Action::UPDATE]['qs'] = "reset=1&id=%%id%%&recordId=%%recordId%%&gid=%%gid%%&multiRecord={$update}";
87
88 $links[CRM_Core_Action::DELETE]['url'] = 'civicrm/profile/edit';
89 $links[CRM_Core_Action::DELETE]['qs'] = "reset=1&id=%%id%%&recordId=%%recordId%%&gid=%%gid%%&multiRecord={$delete}";
90
91 }
92 elseif ($this->_pageViewType == 'customDataView') {
93 // custom data specific view links
94 $links[CRM_Core_Action::VIEW]['url'] = 'civicrm/contact/view/cd';
95 $links[CRM_Core_Action::VIEW]['qs'] = 'reset=1&gid=%%gid%%&cid=%%cid%%&recId=%%recId%%&cgcount=%%cgcount%%&multiRecordDisplay=single&mode=view';
96
97 // custom data specific update links
98 $links[CRM_Core_Action::UPDATE]['url'] = 'civicrm/contact/view/cd/edit';
99 $links[CRM_Core_Action::UPDATE]['qs'] = 'reset=1&type=%%type%%&groupID=%%groupID%%&entityID=%%entityID%%&cgcount=%%cgcount%%&multiRecordDisplay=single&mode=edit';
100 // NOTE : links for DELETE action for customDataView is handled in browse
101
102 // copy action
103 $links[CRM_Core_Action::COPY] = [
104 'name' => ts('Copy'),
105 'title' => ts('Copy %1', [1 => $this->_customGroupTitle . ' record']),
106 'url' => 'civicrm/contact/view/cd/edit',
107 'qs' => 'reset=1&type=%%type%%&groupID=%%groupID%%&entityID=%%entityID%%&cgcount=%%newCgCount%%&multiRecordDisplay=single&copyValueId=%%cgcount%%&mode=copy',
108 ];
109 }
110
111 self::$_links[$this->_pageViewType] = $links;
112 }
113 return self::$_links[$this->_pageViewType];
114 }
115
116 /**
117 * Run the page.
118 *
119 * This method is called after the page is created. It checks for the type
120 * of action and executes that action. Finally it calls the parent's run
121 * method.
122 *
123 */
124 public function run() {
125 // get the requested action, default to 'browse'
126 $action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, FALSE);
127
128 // assign vars to templates
129 $this->assign('action', $action);
130 $profileId = CRM_Utils_Request::retrieve('profileId', 'Positive', $this, FALSE);
131 if (!is_array($profileId) && is_numeric($profileId)) {
132 $this->_profileId = $profileId;
133 }
134
135 $this->_contactId = CRM_Utils_Request::retrieve('contactId', 'Positive', $this, FALSE);
136 $this->_pageViewType = CRM_Utils_Request::retrieve('pageViewType', 'Positive', $this, FALSE, 'profileDataView');
137 $this->_customGroupId = CRM_Utils_Request::retrieve('customGroupId', 'Positive', $this, FALSE, 0);
138 $this->_contactType = CRM_Utils_Request::retrieve('contactType', 'String', $this, FALSE);
139 if ($action & CRM_Core_Action::BROWSE) {
140 //browse
141 $this->browse();
142 return;
143 }
144 // parent run
145 return parent::run();
146 }
147
148 /**
149 * Browse the listing.
150 *
151 */
152 public function browse() {
153 $dateFields = NULL;
154 $newCgCount = $cgcount = 0;
155 $attributes = $result = $headerAttr = [];
156 $dateFieldsVals = NULL;
157 if ($this->_pageViewType == 'profileDataView' && $this->_profileId) {
158 $fields = CRM_Core_BAO_UFGroup::getFields($this->_profileId, FALSE, NULL,
159 NULL, NULL,
160 FALSE, NULL,
161 FALSE,
162 NULL,
163 CRM_Core_Permission::EDIT
164 );
165 $multiRecordFields = [];
166 $fieldIDs = NULL;
167 $result = NULL;
168 $multiRecordFieldsWithSummaryListing = CRM_Core_BAO_UFGroup::shiftMultiRecordFields($fields, $multiRecordFields, TRUE);
169
170 $multiFieldId = CRM_Core_BAO_CustomField::getKeyID(key($multiRecordFields));
171 $customGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $multiFieldId, 'custom_group_id');
172 $reached = CRM_Core_BAO_CustomGroup::hasReachedMaxLimit($customGroupId, $this->_contactId);
173 if (!$reached) {
174 $this->assign('contactId', $this->_contactId);
175 $this->assign('gid', $this->_profileId);
176 }
177 $this->assign('reachedMax', $reached);
178
179 if ($multiRecordFieldsWithSummaryListing && !empty($multiRecordFieldsWithSummaryListing)) {
180 $fieldIDs = array_keys($multiRecordFieldsWithSummaryListing);
181 }
182 }
183 elseif ($this->_pageViewType == 'customDataView') {
184 // require custom group id for _pageViewType of customDataView
185 $customGroupId = $this->_customGroupId;
186 $this->assign('customGroupId', $customGroupId);
187 $reached = CRM_Core_BAO_CustomGroup::hasReachedMaxLimit($customGroupId, $this->_contactId);
188 if (!$reached) {
189 $this->assign('contactId', $this->_contactId);
190 $this->assign('ctype', $this->_contactType);
191 }
192 $this->assign('reachedMax', $reached);
193 // custom group info : this consists of the field title of group fields
194 $groupDetail = CRM_Core_BAO_CustomGroup::getGroupDetail($customGroupId, NULL, CRM_Core_DAO::$_nullObject, TRUE);
195 // field ids of fields in_selector for the custom group id provided
196 $fieldIDs = array_keys($groupDetail[$customGroupId]['fields']);
197 // field labels for headers
198 $fieldLabels = $groupDetail[$customGroupId]['fields'];
199
200 // from the above customGroupInfo we can get $this->_customGroupTitle
201 $this->_customGroupTitle = $groupDetail[$customGroupId]['title'];
202 }
203 if (!empty($fieldIDs) && $this->_contactId) {
204 $options = [];
205 $returnProperities = [
206 'html_type',
207 'data_type',
208 'date_format',
209 'time_format',
210 'default_value',
211 'is_required',
212 'is_view',
213 ];
214 foreach ($fieldIDs as $key => $fieldID) {
215 $fieldIDs[$key] = !is_numeric($fieldID) ? CRM_Core_BAO_CustomField::getKeyID($fieldID) : $fieldID;
216 $param = ['id' => $fieldIDs[$key]];
217 $returnValues = [];
218 CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $param, $returnValues, $returnProperities);
219 if ($returnValues['data_type'] == 'Date') {
220 $dateFields[$fieldIDs[$key]] = 1;
221 $actualPHPFormats = CRM_Utils_Date::datePluginToPHPFormats();
222 $dateFormat = (array) CRM_Utils_Array::value($returnValues['date_format'], $actualPHPFormats);
223 $timeFormat = $returnValues['time_format'] ?? NULL;
224 }
225
226 $optionValuePairs = CRM_Core_BAO_CustomOption::getCustomOption($fieldIDs[$key]);
227 if (!empty($optionValuePairs)) {
228 foreach ($optionValuePairs as $optionPairs) {
229 $options[$fieldIDs[$key]][$optionPairs['value']] = $optionPairs['label'];
230 }
231 }
232
233 $options[$fieldIDs[$key]]['attributes']['html_type'] = $returnValues['html_type'];
234 $options[$fieldIDs[$key]]['attributes']['data_type'] = $returnValues['data_type'];
235 $options[$fieldIDs[$key]]['attributes']['is_required'] = !empty($returnValues['is_required']);
236 $options[$fieldIDs[$key]]['attributes']['default_value'] = $returnValues['default_value'] ?? NULL;
237 $options[$fieldIDs[$key]]['attributes']['is_view'] = $returnValues['is_view'] ?? NULL;
238
239 $options[$fieldIDs[$key]]['attributes']['format']
240 = $options[$fieldIDs[$key]]['attributes']['date_format'] = $returnValues['date_format'] ?? NULL;
241 $options[$fieldIDs[$key]]['attributes']['time_format'] = $returnValues['time_format'] ?? NULL;
242 }
243 $linkAction = array_sum(array_keys($this->links()));
244 }
245
246 if (!empty($fieldIDs) && $this->_contactId) {
247 $DTparams = !empty($this->_DTparams) ? $this->_DTparams : NULL;
248 // commonly used for both views i.e profile listing view (profileDataView) and custom data listing view (customDataView)
249 $result = CRM_Core_BAO_CustomValueTable::getEntityValues($this->_contactId, NULL, $fieldIDs, TRUE, $DTparams);
250 $resultCount = !empty($result['count']) ? $result['count'] : count($result);
251 $sortedResult = !empty($result['sortedResult']) ? $result['sortedResult'] : [];
252 unset($result['count']);
253 unset($result['sortedResult']);
254
255 if ($this->_pageViewType == 'profileDataView') {
256 if (!empty($fieldIDs)) {
257 //get the group info of multi rec fields in listing view
258 $fieldInput = $fieldIDs;
259 $fieldIdInput = $fieldIDs[0];
260 }
261 else {
262 //if no listing fields exist, take the group title for display
263 $nonListingFieldIds = array_keys($multiRecordFields);
264 $singleField = CRM_Core_BAO_CustomField::getKeyID($nonListingFieldIds[0]);
265 $fieldIdInput = $singleField;
266 $singleField = [$singleField];
267 $fieldInput = $singleField;
268 }
269 $customGroupInfo = CRM_Core_BAO_CustomGroup::getGroupTitles($fieldInput);
270 $this->_customGroupTitle = $customGroupInfo[$fieldIdInput]['groupTitle'];
271 }
272 // $cgcount is defined before 'if' condition as entity may have no record
273 // and $cgcount is used to build new record url
274 $cgcount = 1;
275 $newCgCount = (!$reached) ? $resultCount + 1 : NULL;
276 if (!empty($result) && empty($this->_headersOnly)) {
277 $links = self::links();
278 if ($this->_pageViewType == 'profileDataView') {
279 $pageCheckSum = $this->get('pageCheckSum');
280 if ($pageCheckSum) {
281 foreach ($links as $key => $link) {
282 $links[$key] = $link['qs'] . "&cs=%%cs%%";
283 }
284 }
285 }
286
287 if ($reached) {
288 unset($links[CRM_Core_Action::COPY]);
289 }
290 if (!empty($DTparams)) {
291 $this->_total = $resultCount;
292 $cgcount = $DTparams['offset'] + 1;
293 }
294 foreach ($result as $recId => &$value) {
295 foreach ($value as $fieldId => &$val) {
296 if (is_numeric($fieldId)) {
297 $customValue = &$val;
298 if (!empty($dateFields) && array_key_exists($fieldId, $dateFields)) {
299 // formatted date capture value capture
300 $dateFieldsVals[$fieldId][$recId] = CRM_Core_BAO_CustomField::displayValue($customValue, $fieldId);
301
302 //set date and time format
303 switch ($timeFormat) {
304 case 1:
305 $dateFormat[1] = 'g:iA';
306 break;
307
308 case 2:
309 $dateFormat[1] = 'G:i';
310 break;
311
312 default:
313 // if time is not selected remove time from value
314 $result[$recId][$fieldId] = substr($result[$recId][$fieldId], 0, 10);
315 }
316 $result[$recId][$fieldId] = CRM_Utils_Date::processDate($result[$recId][$fieldId], NULL, FALSE, implode(" ", $dateFormat));
317 }
318 else {
319 // assign to $result
320 $customValue = CRM_Core_BAO_CustomField::displayValue($customValue, $fieldId);
321 }
322
323 // Set field attributes to support crmEditable
324 // Note that $fieldAttributes[data-type] actually refers to the html type not the sql data type
325 // TODO: Not all widget types and validation rules are supported by crmEditable so some fields will not be in-place editable
326 $fieldAttributes = ['class' => "crmf-custom_{$fieldId}_$recId"];
327 $editable = FALSE;
328 if (!$options[$fieldId]['attributes']['is_view'] && $this->_pageViewType == 'customDataView' && $linkAction & CRM_Core_Action::UPDATE) {
329 $spec = $options[$fieldId]['attributes'];
330 switch ($spec['html_type']) {
331 case 'Text':
332 // Other data types like money would require some extra validation
333 // FIXME: crmEditable currently does not support any validation rules :(
334 $supportedDataTypes = ['Float', 'String', 'Int'];
335 $editable = in_array($spec['data_type'], $supportedDataTypes);
336 break;
337
338 case 'TextArea':
339 $editable = TRUE;
340 $fieldAttributes['data-type'] = 'textarea';
341 break;
342
343 case 'Radio':
344 case 'Select':
345 case 'Select Country':
346 case 'Select State/Province':
347 $editable = TRUE;
348 $fieldAttributes['data-type'] = $spec['data_type'] == 'Boolean' ? 'boolean' : 'select';
349 if (!$spec['is_required']) {
350 $fieldAttributes['data-empty-option'] = ts('- none -');
351 }
352 break;
353 }
354 }
355 if ($editable) {
356 $fieldAttributes['class'] .= ' crm-editable';
357 }
358 $attributes[$fieldId][$recId] = $fieldAttributes;
359
360 $op = NULL;
361 if ($this->_pageViewType == 'profileDataView') {
362 $actionParams = [
363 'recordId' => $recId,
364 'gid' => $this->_profileId,
365 'id' => $this->_contactId,
366 ];
367 $op = 'profile.multiValue.row';
368 }
369 else {
370 // different set of url params
371 $actionParams['gid'] = $actionParams['groupID'] = $this->_customGroupId;
372 $actionParams['cid'] = $actionParams['entityID'] = $this->_contactId;
373 $actionParams['recId'] = $recId;
374 $actionParams['type'] = $this->_contactType;
375 $actionParams['cgcount'] = empty($DTparams['sort']) ? $cgcount : $sortedResult[$recId];
376 $actionParams['newCgCount'] = $newCgCount;
377
378 // DELETE action links
379 $deleteData = [
380 'valueID' => $recId,
381 'groupID' => $this->_customGroupId,
382 'contactId' => $this->_contactId,
383 'key' => CRM_Core_Key::get('civicrm/ajax/customvalue'),
384 ];
385 $links[CRM_Core_Action::DELETE]['url'] = '#';
386 $links[CRM_Core_Action::DELETE]['extra'] = ' data-delete_params="' . htmlspecialchars(json_encode($deleteData)) . '"';
387 $links[CRM_Core_Action::DELETE]['class'] = 'delete-custom-row';
388 }
389 if (!empty($pageCheckSum)) {
390 $actionParams['cs'] = $pageCheckSum;
391 }
392
393 $value['action'] = CRM_Core_Action::formLink(
394 $links,
395 $linkAction,
396 $actionParams,
397 ts('more'),
398 FALSE,
399 $op,
400 'customValue',
401 $fieldId
402 );
403 }
404 }
405 $cgcount++;
406 }
407 }
408 }
409
410 $headers = [];
411 if (!empty($fieldIDs)) {
412 $fields = ['Radio', 'Select', 'Select Country', 'Select State/Province'];
413 foreach ($fieldIDs as $fieldID) {
414 if ($this->_pageViewType == 'profileDataView') {
415 $headers[$fieldID] = $customGroupInfo[$fieldID]['fieldLabel'];
416 }
417 elseif (!empty($this->_headersOnly)) {
418 if (!$options[$fieldID]['attributes']['is_view'] && $linkAction & CRM_Core_Action::UPDATE) {
419 $spec = $options[$fieldID]['attributes'];
420
421 if (in_array($spec['html_type'], $fields)) {
422 $headerAttr[$fieldID]['dataType'] = $spec['data_type'] == 'Boolean' ? 'boolean' : 'select';
423 if (!$spec['is_required']) {
424 $headerAttr[$fieldID]['dataEmptyOption'] = ts('- none -');
425 }
426 }
427 elseif ($spec['html_type'] == 'TextArea') {
428 $headerAttr[$fieldID]['dataType'] = 'textarea';
429 }
430 }
431 $headers[$fieldID] = $fieldLabels[$fieldID]['label'];
432 $headerAttr[$fieldID]['columnName'] = $fieldLabels[$fieldID]['column_name'];
433 }
434 }
435 }
436 $this->assign('dateFields', $dateFields);
437 $this->assign('dateFieldsVals', $dateFieldsVals);
438 $this->assign('cgcount', $cgcount);
439 $this->assign('newCgCount', $newCgCount);
440 $this->assign('contactId', $this->_contactId);
441 $this->assign('contactType', $this->_contactType);
442 $this->assign('customGroupTitle', $this->_customGroupTitle);
443 $this->assign('headers', $headers);
444 $this->assign('headerAttr', $headerAttr);
445 $this->assign('records', $result);
446 $this->assign('attributes', $attributes);
447
448 return [$result, $attributes];
449 }
450
451 /**
452 * Get name of edit form.
453 *
454 * @return string
455 * classname of edit form
456 */
457 public function editForm() {
458 return '';
459 }
460
461 /**
462 * Get edit form name.
463 *
464 * @return string
465 * name of this page
466 */
467 public function editName() {
468 return '';
469 }
470
471 /**
472 * Get user context.
473 *
474 * @param null $mode
475 *
476 * @return string
477 * user context
478 */
479 public function userContext($mode = NULL) {
480 return '';
481 }
482
483 }