-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode_recur.module
More file actions
667 lines (597 loc) · 20.4 KB
/
node_recur.module
File metadata and controls
667 lines (597 loc) · 20.4 KB
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
<?php
/**
* @file
* Allow content creators to copy nodes based on a recurring date.
*/
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\Entity\Node;
use Drupal\node\Entity\NodeType;
use Drupal\node\NodeTypeInterface;
use Drupal\node_recur\Form\NodeRecurForm;
/**
* Implements hook_form_alter().
*/
function node_recur_form_node_form_alter(&$form, &$form_state, $form_id) {
$node = $form_state->getFormObject()->getEntity();
// See if this is an 'add' operation
if ($node->isNew()) {
// Check permissions
if (node_recur_node_recur_form_access($node)) {
// See if we should display options for this node type
if (node_recur_node_form_enabled($node->getType())) {
// Make sure recurring is enabled for this node
if (node_recur_recurring_enabled($node->getType())) {
$node_recur_form_object = \Drupal::classResolver()->getInstanceFromDefinition(NodeRecurForm::class);
// Get the date field name
$date_field = node_recur_get_date_field_name($node->getType());
// Get the recur form
$recur_form = $node_recur_form_object->_buildForm($node->getType());
// Change the default option
$recur_form['option']['#default_value'] = 'none';
// Set the until date to not be required
$recur_form['until']['#required'] = FALSE;
// Add fieldset wrapper
$form['node_recur'] = array(
'#type' => 'fieldset',
'#title' => t('Repeat'),
'#weight' => $form[$date_field]['#weight'] + 0.1,
);
// Merge the form into the wrapper
$form['node_recur'] = array_merge($form['node_recur'], $recur_form);
// Add validation and submission
$form['#validate'][] = '_node_recur_form_validate_form';
$form['actions']['submit']['#submit'][] = '_node_recur_form_submit_form';
}
}
}
}
}
/**
* Access handler for the node recur form
*/
function node_recur_node_recur_form_access(Node $node) {
$access = FALSE;
$user = \Drupal::currentUser();
// See if recurring is enabled for this node
if (node_recur_recurring_enabled($node->getType())) {
// Check permissions
if ($user->hasPermission('recur all nodes') ||
($user->hasPermission('recur own nodes') && $node->getOwnerId() == $user->id())) {
// Make sure node is published, or admin
if ($node->isPublished() || $user->hasPermission('administer nodes')) {
// Make sure we have a valid date field
if (node_recur_get_date_field_name($node->getType())) {
// Granted
$access = TRUE;
}
}
}
// Allow modules to alter this
\Drupal::moduleHandler()->alter('node_recur_access', $access, $node);
}
return AccessResult::allowedIf($access);
}
/**
* Determine if recurring is enabled for a given node type
*
* @param $type
* The node type
*
* @return mixed|null
* TRUE if recurring is enabled, otherwise FALSE
*/
function node_recur_recurring_enabled($type) {
return NodeType::load($type)->getThirdPartySetting('node_recur', 'enabled');
}
/**
* Determine if recurring options should appear on a node type's node
* add form.
*
* @param $type
* The node type
* @return mixed|null
* TRUE if recurring should appear on the node add form, otherwise
* FALSE.
*/
function node_recur_node_form_enabled($type) {
return NodeType::load($type)->getThirdPartySetting('node_recur', 'node_form');
}
/**
* Determine if dates in the past are allowed for a node type
*
* @param $type
* The node type
*
* @return mixed|null
* TRUE if past dates are allowed, otherwise
* FALSE.
*/
function node_recur_allow_past_dates($type) {
return NodeType::load($type)->getThirdPartySetting('node_recur', 'allow_past_dates');
}
/**
* Determine what the max future dates can recur to for a given
* node type
*
* @param $type
* The node type
*
* @return mixed|null
* The max future time span.
*/
function node_recur_max_future_date_span($type) {
return NodeType::load($type)->getThirdPartySetting('node_recur', 'max_future_date_span');
}
/**
* Determine a node type's recurring date field name
*
* @param $type
* A node type
*
* @return mixed|null
* The node's date field name, otherwise NULL
*/
function node_recur_get_date_field_name($type) {
if ($field_name = NodeType::load($type)->getThirdPartySetting('node_recur', 'date_field')) {
// Check that the field still exists
if (\Drupal::config('field.storage.node.' . $field_name)->get()) {
return $field_name;
}
}
return NULL;
}
/**
* Determine the value of a node's recurring date field
*
* @param $node
* A node
* @param bool $start
* TRUE if the start date should be used. FALSE is the end date should
* be used.
*
* @return mixed|null
* The value of the node's date field
*/
function node_recur_get_node_date_field_value($node, bool $start = TRUE) {
if ($field_name = node_recur_get_date_field_name($node->getType())) {
$key = $start ? 'value' : 'end_value';
$field = $node->get($field_name)->getValue();
if (isset($field[0][$key])) {
return (string) new Drupal\Core\Datetime\DrupalDateTime($field[0][$key], 'UTC');
}
}
return NULL;
}
/**
* Title callback for the recur form menu item
*/
function node_recur_menu_title_callback($node) {
return t('Repeat this @type', array('@type' => strtolower($node->getType())));
}
/**
* Implements hook_form_node_type_form_alter().
*/
function node_recur_form_node_type_form_alter(&$form, &$form_state) {
$type = $form['type']['#default_value'];
// Determine the available date fields on this node type
$fields = array();
$instances = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', $type);
if (isset($instances)) {
foreach ($instances as $name => $field) {
if (in_array($field->getType(), ['datetime', 'daterange'])) {
$fields[$name] = $field->getLabel() . ' (' . $name . ')';
}
}
}
$form['node_recur'] = array(
'#type' => 'details',
'#title' => t('Node recurring'),
'#group' => 'additional_settings',
);
if (!empty($fields)) {
$form['node_recur']['node_recur_enabled_node_type'] = array(
'#type' => 'checkbox',
'#title' => t('Enable recurring for this node type'),
'#default_value' => node_recur_recurring_enabled($type),
'#description' => t('If checked, users with permission can create recurring copies of these nodes.'),
);
$form['node_recur']['node_recur_allow_past_dates_node_type'] = array(
'#type' => 'checkbox',
'#title' => t('Allow dates in the past'),
'#default_value' => node_recur_allow_past_dates($type),
'#description' => t('If checked, recurrences with dates in the past will be allowed.'),
);
$form['node_recur']['node_recur_max_span_node_type'] = array(
'#type' => 'select',
'#title' => t('Max recurring duration'),
'#options' => array(
0 => t('No max'),
'1 week' => t('1 week'),
'2 weeks' => t('2 weeks'),
'1 month' => t('1 month'),
'3 months' => t('3 months'),
'6 months' => t('6 months'),
'1 year' => t('1 year'),
),
'#default_value' => node_recur_max_future_date_span($type),
'#description' => t('Select a maximum time span that recurring will be allowed to continue to.'),
);
$form['node_recur']['node_recur_date_field_node_type'] = array(
'#type' => 'select',
'#title' => t('Date field'),
'#options' => $fields,
'#default_value' => node_recur_get_date_field_name($type),
'#description' => t('Select the date field that will be used to base the recurrences on.'),
);
$form['node_recur']['node_recur_node_form_node_type'] = array(
'#type' => 'checkbox',
'#title' => t('Display recur options on node add form'),
'#default_value' => node_recur_node_form_enabled($type),
'#description' => t('If checked, recurring options will appear on the node add form.'),
);
}
else {
$form['node_recur']['node_recur_null'] = array(
'#markup' => t('There are no date fields available for this node type.'),
);
}
$form['#entity_builders'][] = 'node_recur_form_node_type_form_builder';
}
/**
* Entity builder for the node type form with node recur options.
*
* @see node_recur_form_node_type_form_alter()
*/
function node_recur_form_node_type_form_builder($entity_type, NodeTypeInterface $type, &$form, FormStateInterface $form_state) {
$type->setThirdPartySetting('node_recur', 'enabled', $form_state->getValue('node_recur_enabled_node_type'));
$type->setThirdPartySetting('node_recur', 'allow_past_dates', $form_state->getValue('node_recur_allow_past_dates_node_type'));
$type->setThirdPartySetting('node_recur', 'max_future_date_span', $form_state->getValue('node_recur_max_span_node_type'));
$type->setThirdPartySetting('node_recur', 'date_field', $form_state->getValue('node_recur_date_field_node_type'));
$type->setThirdPartySetting('node_recur', 'node_form', $form_state->getValue('node_recur_node_form_node_type'));
}
/**
* Generate an array of recurring dates based on the provided rule criteria
*
* @param $node
* The node that's being recurred
* @param $date
* The initial starting date belonging to the node that will be recurring.
* Can be in string or numeric format.
* @param $frequency
* The frequency that the period occurs, ie, every 5 days, the frequency
* would be 5.
* @param $period
* The period of each frequency, ie, every 5 days, the period will be
* 'day'. It can also be 'week' or 'month'.
* @param $until
* The date to recur until. Can be in string or numeric format.
* @param bool $weekends
* TRUE if weekends should be included.
*
* @return array|false
* An array of timestamps
*/
function node_recur_generate_dates_rule($node, $date, $frequency, $period, $until, bool $weekends = TRUE) {
$dates = array();
$month = FALSE;
// Convert date and until date to timestamp, if needed
$date = is_string($date) ? strtotime($date) : $date;
$until = is_string($until) ? strtotime($until) : $until;
// Make sure we have valid timestamps
if (!is_numeric($date) || !is_numeric($until)) {
return FALSE;
}
// Make sure the until is ahead of the date
if ($date >= $until) {
return FALSE;
}
// Convert month period to weeks, in order to preserve the day
// of the week
if ($period == 'month') {
$frequency = $frequency * 4;
$period = 'week';
$month = TRUE;
}
// Track the current date
$current = $date;
// Iterate and generate dates until we reach the end
while (TRUE) {
// Generate the next date
$next = strtotime("+$frequency " . \Drupal::translation()->formatPlural($frequency, $period, "{$period}s"), $current);
// If this is a month recur, we need to make sure the the next date
// is on the next month. Some months have 5 repeats of the same day
if ($month && (date('n', $next) == date('n', $current))) {
// Jump forward one more week
$next = strtotime('+1 week', $next);
}
$current = $next;
// Make sure date is in the future, if the settings dictate that
if (!node_recur_allow_past_dates($node->getType()) && $next < \Drupal::time()->getRequestTime()) {
continue;
}
// If we're excluding weekends, skip this if it's a weekend
if (!$weekends) {
$day = date('D', $next);
if ($day == 'Sun' || $day == 'Sat') {
continue;
}
}
// See if this date puts us past the limit
if ($next > $until) {
break;
}
$dates[] = $current;
}
return $dates;
}
/**
* Generate an array of recurring dates based on days
*
* @param $node
* The node that's being recurred
* @param $date
* The initial starting date belonging to the node that will be recurring.
* Can be in string or numeric format.
* @param $days
* An array of days (monday, tuesday, etc)
* @param $until
* The date to recur until. Can be in string or numeric format.
* @param null $offset
* The amount of days the $days should be offset by, ie if $days = 'monday',
* and offset = 2, $days becomes 'wednesday'. This is used to calculate
* end dates that are N days apart from the start dates.
*
* @return array|false
* An array of timestamps
*/
function node_recur_generate_dates_days($node, $date, $days, $until, $offset = NULL) {
$dates = array();
// Convert date and until date to timestamp, if needed
$date = is_string($date) ? strtotime($date) : $date;
$until = is_string($until) ? strtotime($until) : $until;
// Determine the hour of the date
$hour = date('G', $date);
// Move the date back based on the offset
if ($offset) {
$date = $date - ($offset * 86400);
}
// Make sure we have valid timestamps
if (!is_numeric($date) || !is_numeric($until)) {
return FALSE;
}
// Make sure the until is ahead of the date
if ($date >= $until) {
return FALSE;
}
// Track the current date
$current = $date;
// We want to find occurrences of $days after $date until $until.
// The original logic tried to find the "next" occurrence of each day,
// but it had issues with year jumps and skipping the remainder of the first week.
// Create an array of day names to their numeric representation (0-6, sun-sat)
$day_map = [
'sunday' => 0,
'monday' => 1,
'tuesday' => 2,
'wednesday' => 3,
'thursday' => 4,
'friday' => 5,
'saturday' => 6,
];
$target_days = [];
foreach ($days as $day) {
if (isset($day_map[strtolower($day)])) {
$target_days[] = $day_map[strtolower($day)];
}
}
if (empty($target_days)) {
return FALSE;
}
// Iterate day by day from $current until $until
while (TRUE) {
// Move to next day
$current += 86400;
// Make sure the hours match, to avoid DST issue
$current_hour = date('G', $current);
if ($current_hour != $hour) {
$current += (($hour - $current_hour) * 3600);
}
if ($current > $until) {
break;
}
$current_day_of_week = (int) date('w', $current);
if (in_array($current_day_of_week, $target_days)) {
// Apply the offset, if one
$date_to_use = $current;
if ($offset) {
$date_to_use = $current + ($offset * 86400);
}
// Make sure date is in the future, if the settings dictate that
if (!node_recur_allow_past_dates($node->getType()) && $date_to_use < \Drupal::time()->getRequestTime()) {
continue;
}
$dates[] = $date_to_use;
}
}
return $dates;
}
/**
* Generate dates from a form state
*
* @param $node
* @param $form_state
*
* @return array
* An array of start and end dates, keyed by start and
* end
*/
function node_recur_generate_dates_from_form($node, $form_state) {
// Extract the option
$option = $form_state->getValue('option');
// Extract the days
$days = array();
foreach ($form_state->getValue('days') as $day => $value) {
if ($value) {
$days[] = $day;
}
}
// Extract the frequency
$frequency = $form_state->getValue('frequency');
// Extract the period
$period = $form_state->getValue('period');
// Extract the until date
$until = strtotime($form_state->getValue('until'));
// Move until date to 1 minute before midnight
$until += 86399;
// Extract weekend toggle
$weekends = !$form_state->getValue('exclude_weekends');
// Get the initial dates
$start_date = node_recur_get_node_date_field_value($node);
$end_date = node_recur_get_node_date_field_value($node, FALSE);
// Initalize
$start_dates = array();
$end_dates = array();
// Generate the start dates
if ($start_date) {
if ($option == 'days') {
$start_dates = node_recur_generate_dates_days($node, $start_date, $days, $until);
}
else if ($option == 'rules') {
$start_dates = node_recur_generate_dates_rule($node, $start_date, $frequency, $period, $until, $weekends);
}
}
// Generate the end dates
if ($end_date) {
// Determine if the start and end dates are different days
$days_apart = NULL;
if ($start_date) {
if (date('j', strtotime($start_date)) != date('j', strtotime($end_date))) {
// Determine the amount of days
$days_apart = floor((strtotime($end_date) - strtotime($start_date)) / 86400);
// Adjust the until date
$until += ($days_apart * 86400);
}
}
if ($option == 'days') {
$end_dates = node_recur_generate_dates_days($node, $end_date, $days, $until, $days_apart);
}
else if ($option == 'rules') {
$end_dates = node_recur_generate_dates_rule($node, $end_date, $frequency, $period, $until, $weekends);
}
}
// Allow other modules to alter the dates
$dates = array(
'start' => $start_dates,
'end' => $end_dates,
);
$variables = array(
'node' => $node,
'start_date' => $start_date,
'end_date' => $end_date,
'option' => $option,
'until' => $until,
);
if ($option == 'days') {
$variables['days'] = $days;
}
if ($option == 'rules') {
$variables += array(
'frequency' => $frequency,
'period' => $period,
'weekends' => $weekends,
);
}
\Drupal::moduleHandler()->alter('node_recur_dates', $dates, $variables);
return $dates;
}
/**
* Helper function to display a start and end time together
*
* @param $start
* A start datetime or timestamp
* @param null $end
* An end datetime or timestamp
* @param string $format
* The format type to use, sent to format_date()
*
* @return string
* A string of formatted dates
*/
function node_recur_format_date($start, $end = NULL, string $format = 'long') {
$string = '';
// Convert start to timestamp, if needed, then format
$start = is_string($start) ? strtotime($start) : $start;
$start = \Drupal::service('date.formatter')->format($start, $format);
$string .= $start;
// Convert end to timestamp, if needed, then format
if ($end) {
$end = is_string($end) ? strtotime($end) : $end;
$end = \Drupal::service('date.formatter')->format($end, $format);
if ($start != $end) {
$string .= ' - ' . $end;
}
else {
$string .= ' (' . t('All day') . ')';
}
}
return $string;
}
function _node_recur_form_validate_form(array &$form, FormStateInterface $form_state) {
// If this is the confirm form, then skip validation
if (!empty($form_state->getValue('confirm'))) {
return;
}
// If option is set to nothing, then skip validation
if ($form_state->getValue('option') == 'none') {
return;
}
$node = $form['#node'] ?? $form_state->getFormObject()->getEntity();
// If days option is selected, make sure we have at least one day
if ($form_state->getValue('option') == 'days') {
$days = 0;
foreach ($form_state->getValue('days') as $value) {
if ($value) {
$days++;
}
}
if ($days == 0) {
$form_state->setErrorByName('days', t('At least one day must be selected.'));
}
}
// Check until date format
$until = strtotime($form_state->getValue('until'));
if (!is_numeric($until)) {
$form_state->setErrorByName('until', t('You must supply a valid end date.'));
// Stop here
return;
}
// Make sure until date is in the future
if (!node_recur_allow_past_dates($node->getType()) && ($until < \Drupal::time()->getRequestTime())) {
$form_state->setErrorByName('until', t('The end date must be in the future.'));
}
// Check that until date isn't too far in the future, according
// to node settings (if any)
if ($max = node_recur_max_future_date_span($node->getType())) {
if ($until > strtotime($max, \Drupal::time()->getRequestTime())) {
$form_state->setErrorByName('until', t('The end date can only be up to %max in the future.', array('%max' => $max)));
}
}
// If there were no errors, allow other modules to validate the dates
if (!$form_state->getErrors()) {
$errors = \Drupal::moduleHandler()->invokeAll('node_recur_validate_dates', [$node, $form_state]);
foreach ($errors as $error) {
$form_state->setErrorByName($error['field'], $error['message']);
}
}
}
function _node_recur_form_submit_form(array &$form, FormStateInterface $form_state) {
$node = $form['#node'] ?? $form_state->getFormObject()->getEntity();
// Store the dates to which to copy this node.
$tempstore = \Drupal::service('tempstore.private')->get('node_recur');
$tempstore->set('dates', node_recur_generate_dates_from_form($node, $form_state));
// Redirect to the confirm form
if ($form_state->getValue('option') != 'none') {
$form_state->setRedirect('node_recur.recur.confirm', ['node' => $node->id()]);
}
}