-
Notifications
You must be signed in to change notification settings - Fork 1
/
InputfieldOpeningHours.module
446 lines (404 loc) · 21.3 KB
/
InputfieldOpeningHours.module
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
<?php
declare(strict_types=1);
namespace ProcessWire;
class InputfieldOpeningHours extends Inputfield
{
public function __construct()
{
include_once(__DIR__ . '/OpeningHours.php');
//set configuration field properties to make them callable inside this class
$this->set('numberOftimes', 2); // must have value (required)
$this->set('timeformat', '%R');// must have value (required)
$this->set('tableheader', '');// optional value (not required)
$this->set('hideholiday', 0);// optional value (not required)
parent::__construct();
}
/**
* @return array
*/
public static function getModuleInfo():array
{
return array(
'title' => 'Inputfield Opening Hours',
'summary' => 'Renders an input field for entering opening hours',
'version' => '1.2.0',
'href' => 'https://github.com/juergenweb/FieldtypeOpeningHours',
'icon' => 'clock-o',
'permanent' => false,
'requires' => [
'PHP>=8.0.0',
'ProcessWire>=3.0.181',
'FieldtypeOpeningHours'
],
'author' => 'Jürgen Kern'
);
}
/**
* Init is called when the system is ready for API usage
* @return void
*/
public function init():void
{
$version = $this->getModuleInfo()['version'] . '-' . time();
//Add CSS and JS files for this inputfield
$this->config->styles->add($this->config->urls->{$this->className} . 'openinghours.css?v=' . $version);
$this->config->scripts->add($this->config->urls->{$this->className} . 'openinghours.js?v=' . $version);
if ($this->languages) {
foreach ($this->languages as $language) {
/** @var Language $language */
// account for alternate formats in other languages
if ($language->isDefault()) {
continue;
}
$this->set("timeformat$language", '');
$this->set("tableheader$language", '');
}
}
}
/**
* Method to render the inputfields in the backend
* @return string
*/
public function ___render():string
{
$name = $this->attr('name');
$data = $this->attr('value');
$times = $data->data['times'];
$output = '<table id="' . $name . '-table" class="AdminDataTable AdminDataList AdminDataTableResponsive openinghours-table">';
$output .= '<thead>';
$output .= '<tr>';
$output .= '<th>' . $this->_('Day of the week') . '</th>';
$output .= '<th>' . $this->_('Status') . '</th>';
if (wire('languages')) {
foreach (wire('languages') as $language) {
if ($language->id == wire('user')->language->id) {
$tableheader = $this->get("tableheader$language");
if ($tableheader) {
$tableheaderNew = $tableheader;
} else {
if ($this->get("tableheader")) {
$tableheaderNew = $this->get("tableheader");
} else {
$tableheaderNew = $this->_('Opening hours');
}
}
$output .= '<th colspan="3">' . $tableheaderNew . '</th>';
}
}
}
$output .= '</tr>';
$output .= '</thead>';
$output .= '<tbody>';
foreach ($times as $dayAbbr => $daytimesArray) {
// show or hide Holiday input depending on the configuration settings
if(($this->hideholiday) && ($dayAbbr === 'ho')){
$styleAttr = ' style="display:none"';
} else {
$styleAttr = '';
}
//set checkbox status depending on first value in times array
if ($daytimesArray[0]['start']) {
$checkboxStatus = ' checked';
$statusClass = 'open';
} else {
$checkboxStatus = '';
$statusClass = 'closed';
}
$output .= '<tr id="' . $name . '-row-' . $dayAbbr . '" class="day-row day-' . $dayAbbr . ' ' . $statusClass . '"'.$styleAttr.'>';
// Output name of the weekday
$output .= '<td class="weekday"><span>' . OpeningHours::getWeekdays()[$dayAbbr][1] . '</span></td>';
// Output checkbox switcher
$output .= '<td>';
$output .= '<label class="switch">';
$output .= '<input id="' . $name . '-toggle-' . $dayAbbr . '" class="togglestatus" type="checkbox"' . $checkboxStatus . '>';
$output .= '<span class="slider round"></span>';
$output .= '</label>';
$output .= '</td>';
// output times per day
$output .= '<td id="' . $name . '-hours-' . $dayAbbr . '">';
$output .= '<table id="' . $name . '-hours-' . $dayAbbr . '" class="openinghours">';
$output .= '<tbody>';
foreach ($daytimesArray as $num => $daytimeArray) {
$output .= '<tr id="' . $name . '-' . $dayAbbr . '-' . $num . '">';
$output .= '<td><span class="number">' . (intval($num) + 1) . '</span></td>';
foreach ($daytimeArray as $time => $timeValue) {
if ($time === 'start') {
$label = $this->_('From');
$class = ' from';
} else {
$label = $this->_('To');
$class = ' to';
}
$output .= '<td><label class="openinghours-label' . $class . '">' . $label . ':</label><input type="time" id="' . $name . '-' . $dayAbbr . '-' . $num . '-' . $time . '" class="input" name="' . $name . '-' . $dayAbbr . '-' . $num . '-' . $time . '" value="' . $timeValue . '"/></td>';
}
if ($num === 0) {
$output .= '<td><button id="' . $name . '-add-' . $dayAbbr . '" class="add-btn ui-button" type="button" data-max="' . $this->numberOftimes . '">' . $this->_('Add') . '</button></td>';
} else {
$output .= '<td><button id="' . $name . '-remove-' . $dayAbbr . '-' . $num . '" class="remove-btn ui-button ui-priority-secondary" type="button">' . $this->_('Remove') . '</button></td>';
}
$output .= '</tr>';
}
$output .= '</tbody>';
$output .= '</table>';
$output .= '</td>';
$output .= '</tr>';
}
$output .= '</tbody>';
$output .= '<tfoot><tr><td colspan="3">' . sprintf($this->_n('Only 1 time per day is permitted.',
'A max number of %s times per day is permitted.', $this->numberOftimes),
$this->numberOftimes) . '</td></tr></tfoot>';
$output .= '</table>';
return $output;
}
/**
* Method for various sanitizations to clean user input after form submission
* removes completely empty times from the array (no start and no end time)
* removes incomplete times from the array (only start or end time)
* removes duplicate times from each day
* re-ordering multiple times on start time ascending
* re-index the array after all sanitization
* @param array $times
* @return array
*/
public function sanitizeValidateValues(array $times):array
{
$sanitizedValues = [];
foreach (OpeningHours::getWeekdays() as $key => $value) { //key = mo,tu,.. value = ['Mo' => 'Monday']
//$value = [$value[0] => $value[1]];
$value = [$key => $value[1]];
foreach ($value as $dayAbbr => $dayName) {
$timeValues = [];
foreach ($times as $key => $timesArray) { //key = mo,tu,.. value = multidimes. array of times on this day
//check for max times/day and remove all times which are above the limit
$timesArray = array_slice($timesArray, 0, $this->numberOftimes);
foreach ($timesArray as $pos => $timePair) {
$numberOfValues = count(array_filter($timePair));
// set all incomplete values (only start or end time was entered) to completely empty
if ($numberOfValues === 1) {
//set both values to empty and add it back to the array
$timePair = ['start' => '', 'finish' => ''];
$this->warning($this->_('Incomplete time with only a start or endtime was removed.'));
}
if ((count($timePair) === 0)) {
$timePair = false;
}
if ($dayAbbr == $key) {
if ((count(array_filter($timePair)) === 2) || ($pos === 0)) {
if (count(array_filter($timePair)) === 2) {
if ($timePair['start'] == $timePair['finish']) {
$this->error(sprintf($this->_('On %s start and end time is equal.Please set different times.'),
$dayName . ' (#' . ($pos + 1) . ')'));
}
if ($timePair['start'] > $timePair['finish']) {
$this->warning(sprintf($this->_('On %s start time is after end time. If end time is on the next day it would be ok.'),
$dayName . ' (#' . ($pos + 1) . ')'));
}
}
$timeValues[$dayAbbr][] = $timePair;
}
}
}
}
//remove the first empty array of multi times array (if present)
$numberOfTimes = count($timeValues[$dayAbbr]);
if ($numberOfTimes > 1) {
if (count(array_filter($timeValues[$dayAbbr][0])) === 0) { //first item is empty - lets remove it
unset($timeValues[$dayAbbr][0]);
}
$unique = array_unique($timeValues[$dayAbbr], SORT_REGULAR);
$keys = array_column($unique, 'start');
array_multisort($keys, SORT_ASC, $unique);
$sanitizedValues[$dayAbbr] = $unique;
} else {
$sanitizedValues[$dayAbbr] = $timeValues[$dayAbbr];
}
}
}
return $sanitizedValues;
}
/**
* Pull the value from the given $input argument ($input->post or $input->get) as WireInputData object, sanitize/validate it, and populate it back to the value attribute of this Inputfield.
*
* @param WireInputData $input
* @return $this
*
*/
public function ___processInput(WireInputData $input):self
{
$name = $this->attr('name');
//input object includes always input values from every field on the page, so lets filter out only the inputs from this field
//we need to do this, because the number of values is variable - so extract only values that starts with fieldname_.
$timeInputs = [];
foreach ($input as $key => $value) {
if (str_starts_with($key, $name)) {
$timeInputs[$key] = $value;
}
}
// 1) check if all days are present with at least 1 start and 1 end time - if not add it to the array with index 0
foreach (OpeningHours::getWeekdays() as $key => $days) {
foreach (['start', 'finish'] as $time) {
if (!array_key_exists($name . '-' . $key . '-0-' . $time, $timeInputs)) {
$timeInputs[$name . '-' . $key . '-0-' . $time] = '';
}
}
}
// 2) Set inputs as a string and check if it is in a valid time format(H:i) - otherwise get rid of them
$cleanedValues = [];
foreach ($timeInputs as $key => $value) {
$value = strval($value);
if ($value) {
//check if value has valid time format (fe 08:00)
if (OpeningHours::isTimeValid($value)) {
$cleanedValues[$key] = $value;
} else {
$cleanedValues[$key] = '';
$this->error($this->_('A value was not a valid time string so it was deleted.'));
}
} else {
//empty value
$cleanedValues[$key] = '';
}
}
// 3) create multidimensional array from onedimensional POST array -> needed for sanitization and validation on per days base afterwards
$times = OpeningHours::createMultidimArray($cleanedValues);
// 4) sanitize all values
$sanitizedValues = $this->sanitizeValidateValues($times);
// 5) set validate values back
$validationValues = [];
//validate if endtime is after starttime
foreach (OpeningHours::getWeekdays() as $dayAbbr => $days) {
//foreach($times as $key=>$value){
foreach ($sanitizedValues as $key => $value) { //key = mo,tu,..
if ($key === $dayAbbr) {
foreach ($value as $keyNumber => $timesArray) {
$validationValues[$dayAbbr][$keyNumber] = $timesArray;
}
}
}
}
// 6) transform the multidim. array back to a one-dim. array like we got from POST
$flattenArray = OpeningHours::flattenArray($validationValues, $name);
//add it to the object to make it reachable in fieldtype as property 'value'
$this->value['times'] = $flattenArray;
return $this;
}
/**
* Add additional configuration fields to the backend
* @return Inputfield
* @throws WireException
* @throws WirePermissionException
*/
public function ___getConfigInputfields():Inputfield
{
$inputfields = parent::___getConfigInputfields();
$languages = $this->wire('languages');
/** @var InputfieldInteger $f */
$f = $this->wire('modules')->get('InputfieldInteger');
$f->attr('name+id', 'numberOftimes');
$f->required(true);
$f->label = $this->_('Number of times per day');
$f->initValue = 2;
$f->attr('value', $this->numberOftimes ? $this->numberOftimes : 2);
$f->min = 1;
$f->max = 10;
$f->inputType = 'number';
$f->description = $this->_('Please enter the number of how many different times are allowed on each day.');
$f->notes = $this->_('For example 2 means, that you can enter 2 different times per day. A max. number of 5 different times per day is possible.');
$f->columnWidth = 100;
$inputfields->add($f);
/** @var InputfieldText $f */
$f = $this->wire('modules')->get('InputfieldText');
$f->attr('name+id', 'timeformat');
$f->required(true);
$f->label = $this->_('Timeformat on frontend');
$f->initValue = '%R';//default value
$f->inputType = 'text';
$f->attr('value', $this->timeformat ? $this->timeformat : '%R');
if ($languages) {
$f->useLanguages = true;
foreach ($languages as $language) {
if ($language->isDefault()) {
continue;
}
$f->set("value$language", (string)$this->get("timeformat$language"));
}
}
$f->description = $this->_('Please enter the time format in which the times should be displayed on the frontend. Use date() or sprintf() syntax.');
$f->notes = sprintf($this->_('For example a timeformat of %s shows the time as 08:00, a timeformat of %s will be rendered as 08:00 AM. You can find more examples at %s or %s.'),
'%R', '%r',
'[https://www.php.net/manual/de/function.strftime.php](https://www.php.net/manual/de/function.strftime.php)',
'[https://www.php.net/manual/de/function.date.php](https://www.php.net/manual/de/function.date.php)');
$f->columnWidth = 100;
$inputfields->add($f);
/** @var InputfieldText $f */
$f = $this->wire('modules')->get('InputfieldText');
$f->attr('name+id', 'tableheader');
$f->label = $this->_('Tableheader for times column in backend');
$f->inputType = 'text';
$f->initValue = '';//default value
$f->attr('value', $this->tableheader ? $this->tableheader : '');
if ($languages) {
$f->useLanguages = true;
foreach ($languages as $language) {
if ($language->isDefault()) {
continue;
}
$f->set("value$language", (string)$this->get("tableheader$language"));
}
}
$f->description = $this->_('Here you can overwrite (adapt) the tableheader text for the times column to fit your requirements (optional).');
$f->notes = $this->_('This could be fe opening times, times of courses and so on - depending on what times you want to enter.');
$f->columnWidth = 100;
$inputfields->add($f);
// checkbox field to enable/disable the hint text for the max numbers of decimals on the form
$f = $this->modules->get('InputfieldCheckbox');
$f->attr('name+id', 'hideholiday');
$f->attr('checked', $this->hideholiday == '1' ? 'checked' : '');
$f->checkboxLabel = $this->_('Disable the input for Holidays');
$f->label = $this->_('Input for Holidays');
$f->description = $this->_('If checked, the input field for Holidays will not be displayed.');
$inputfields->append($f);
/** $docFieldset */
$docFieldset = $this->wire('modules')->get('InputfieldFieldset');
$docFieldset->label = $this->_('How to');
$docFieldset->description = $this->_('This is a simple quick start guide on how to output the opening hours in your site.');
$docFieldset->collapsed = true;
$docFieldset->columnWidth = 100;
$text = '<h3>' . $this->_('Easiest integration') . '</h3>';
$text .= '<p>' . $this->_('Put this code inside your template, where the opening hours should be displayed.') . '</p>';
$text .= '<pre><code>echo $page->' . $this->name . '->render();</code></pre>';
$text .= '<p>' . $this->_('In this case the opening hours for each day will be displayed as an unordered list.') . '</p>';
$text .= '<pre><code><ul><li class="time day-mo">Mo: 08:00:00 AM - 12:00:00 PM, 02:00:00 PM - 06:00:00 PM</li><li class="time day-tu">Tu: 08:00:00 AM - 12:00:00 PM</li><li class="time day-we">We: 02:00:00 PM - 06:00:00 PM</li><li class="time day-th">Th: 08:00:00 AM - 12:00:00 PM, 02:00:00 PM - 06:00:00 PM</li><li class="time day-fr">Fr: 08:00:00 AM - 12:00:00 PM</li><li class="time day-sa">Sa: 08:00:00 AM - 10:00:00 AM</li><li class="time day-su">Su: closed</li><li class="time day-ho">Ho: closed</li></ul></code></pre>';
$text .= '<h3>' . $this->_('Render combined days with same opening times') . '</h3>';
$text .= '<pre><code>echo $page->' . $this->name . '->renderCombinedDays();</code></pre>';
$text .= '<pre><code><ul><li class="times">Mo, Th: 08:00:00 AM - 12:00:00 PM, 02:00:00 PM - 06:00:00 PM</li><li class="times">Tu, Fr: 08:00:00 AM - 12:00:00 PM</li><li class="times">We: 02:00:00 PM - 06:00:00 PM</li><li class="times">Sa: 08:00:00 AM - 10:00:00 AM</li><li class="times">Su, Ho: closed</li></ul></code></pre>';
$text .= '<h3>' . $this->_('Render only the opening times of one specific day') . '</h3>';
$text .= '<p>' . $this->_('If you want to display the opening times on a specific day (fe Monday), you can do it like this:') . '</p>';
$text .= '<pre><code>echo $page->' . $this->name . '->renderDay(\'mo\');</code></pre>';
$text .= '<p>' . $this->_('This will output the opening hours on that day as a string.') . '</p>';
$text .= '<pre><code>08:00:00 AM - 12:00:00 PM, 02:00:00 PM - 06:00:00 PM</code></pre>';
$link = '<a href="https://github.com/juergenweb/FieldtypeOpeningHours/tree/master#output-in-templates" target="_blank">GitHub</a>';
$text .= sprintf($this->_('You will find more advanced output methods inside the description of this module on %s.'),
$link);
$description = $this->wire()->modules->get('InputfieldMarkup');
$description->markupText = $text;
$docFieldset->add($description);
$inputfields->add($docFieldset);
return $inputfields;
}
/**
* Allow these fields to get overwritten by user on per template base
* @param Field $field
* @return array
*
*/
public function getConfigAllowContext(Field $field):array
{
return [
'numberOftimes',
'timeformat',
'tableheader',
'hideholiday'
];
}
}