-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathTimeframe.php
699 lines (625 loc) · 19.6 KB
/
Timeframe.php
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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
<?php
namespace CommonsBooking\Repository;
use CommonsBooking\Helper\Helper;
use CommonsBooking\Helper\Wordpress;
use CommonsBooking\Model\Day;
use CommonsBooking\Plugin;
use Exception;
class Timeframe extends PostRepository {
/**
* Returns only bookable timeframes.
*
* @param array $locations
* @param array $items
* @param string|null $date
* @param bool $returnAsModel
* @param $minTimestamp
* @param array $postStatus
*
* @return array
* @throws Exception
*/
public static function getBookable(
array $locations = [],
array $items = [],
?string $date = null,
bool $returnAsModel = false,
$minTimestamp = null,
array $postStatus = [ 'confirmed', 'unconfirmed', 'publish', 'inherit' ]
): array {
return self::get(
$locations,
$items,
[ \CommonsBooking\Wordpress\CustomPostType\Timeframe::BOOKABLE_ID ],
$date,
$returnAsModel,
$minTimestamp,
$postStatus
);
}
/**
* Returns only bookable timeframes for current user.
*
* @param array $locations
* @param array $items
* @param string|null $date
* @param bool $returnAsModel
* @param $minTimestamp
* @param array $postStatus
*
* @return array
* @throws Exception
*/
public static function getBookableForCurrentUser(
array $locations = [],
array $items = [],
?string $date = null,
bool $returnAsModel = false,
$minTimestamp = null,
array $postStatus = [ 'confirmed', 'unconfirmed', 'publish', 'inherit' ]
): array {
$bookableTimeframes = self::getBookable(
$locations,
$items,
$date,
$returnAsModel,
$minTimestamp,
$postStatus
);
$bookableTimeframes = self::filterTimeframesForCurrentUser($bookableTimeframes);
return $bookableTimeframes;
}
/**
* Function to get timeframes with all possible options/params.
* Why? We have different types of timeframes and in some cases we need multiple of them.
* In this case we need this function.
* Other functions use this one as base function for more specialized searches.
*
* TODO: Investigate
* This function is not based on the WP_Query class, probably because of performance reasons.
*
* @param array $locations
* @param array $items
* @param array $types
* @param string|null $date Date-String in format YYYY-mm-dd
*
* @param bool $returnAsModel
*
* @param int|null $minTimestamp
*
* @param string[] $postStatus
*
* @return array
* @throws Exception
* @throws \Psr\Cache\InvalidArgumentException|\Psr\Cache\CacheException
*/
public static function get(
array $locations = [],
array $items = [],
array $types = [],
?string $date = null,
bool $returnAsModel = false,
?int $minTimestamp = null,
array $postStatus = [ 'confirmed', 'unconfirmed', 'publish', 'inherit' ]
): array {
if ( ! count( $types ) ) {
$types = [
\CommonsBooking\Wordpress\CustomPostType\Timeframe::HOLIDAYS_ID,
\CommonsBooking\Wordpress\CustomPostType\Timeframe::BOOKABLE_ID,
\CommonsBooking\Wordpress\CustomPostType\Timeframe::BOOKING_ID,
\CommonsBooking\Wordpress\CustomPostType\Timeframe::REPAIR_ID,
\CommonsBooking\Wordpress\CustomPostType\Timeframe::OFF_HOLIDAYS_ID,
];
}
$customId = md5( serialize( $types ) );
$cacheItem = Plugin::getCacheItem( $customId );
if ( $cacheItem ) {
return $cacheItem;
} else {
$posts = [];
// Get Post-IDs considering types, items and locations
$postIds = self::getPostIdsByType( $types, $items, $locations );
if ( $postIds && count( $postIds ) ) {
$posts = self::getPostsByBaseParams(
$date,
$minTimestamp,
null,
$postIds,
$postStatus
);
}
if ( $posts && count( $posts ) ) {
$posts = self::filterTimeframes( $posts, $date );
}
// if returnAsModel == TRUE the result is a timeframe model instead of a wordpress object
if ( $returnAsModel ) {
self::castPostsToModels( $posts );
}
Plugin::setCacheItem(
$posts,
Wordpress::getTags($posts, $items, $locations),
$customId
);
return $posts;
}
}
/**
* Returns Post-IDs by type(s), item(s), location(s)
* Why? It's because of performance. We use the ids as base set for following filter queries.
*
* @param array $types
* @param array $items
* @param array $locations
*
* @return mixed
* @throws \Psr\Cache\InvalidArgumentException
*/
public static function getPostIdsByType( array $types = [], array $items = [], array $locations = [] ) {
if ( ! count( $types ) ) {
$types = [
\CommonsBooking\Wordpress\CustomPostType\Timeframe::HOLIDAYS_ID,
\CommonsBooking\Wordpress\CustomPostType\Timeframe::BOOKABLE_ID,
\CommonsBooking\Wordpress\CustomPostType\Timeframe::BOOKING_ID,
\CommonsBooking\Wordpress\CustomPostType\Timeframe::REPAIR_ID,
\CommonsBooking\Wordpress\CustomPostType\Timeframe::OFF_HOLIDAYS_ID,
];
}
$customId = md5( serialize( $types ) );
$cacheItem = Plugin::getCacheItem( $customId );
if ( $cacheItem ) {
return $cacheItem;
} else {
global $wpdb;
$table_postmeta = $wpdb->prefix . 'postmeta';
$itemQuery = "";
$items = array_filter( $items );
$locations = array_filter( $locations );
// additional sanitizing. Allow only integer
$items = commonsbooking_sanitizeArrayorString( $items, 'intval' );
$locations = commonsbooking_sanitizeArrayorString( $locations, 'intval' );
$types = commonsbooking_sanitizeArrayorString( $types, 'intval' );
// Query for item(s)
if ( count( $items ) > 0 ) {
$itemQuery = "
INNER JOIN $table_postmeta pm2 ON
pm2.post_id = pm1.post_id AND
pm2.meta_key = 'item-id' AND
pm2.meta_value IN (" . implode( ',', $items ) . ")
";
}
// Query for location(s)
$locationQuery = "";
if ( count( $locations ) > 0 ) {
$locationQuery = "
INNER JOIN $table_postmeta pm3 ON
pm3.post_id = pm1.post_id AND
pm3.meta_key = 'location-id' AND
pm3.meta_value IN (" . implode( ',', $locations ) . ")
";
}
// Complete query, including types
$query = "
SELECT DISTINCT pm1.post_id from $table_postmeta pm1
" .
$itemQuery .
$locationQuery .
"
WHERE
pm1.meta_key = 'type' AND
pm1.meta_value IN (" . implode( ',', $types ) . ")
";
// Run query
$postIds = $wpdb->get_results( $query, ARRAY_N );
// Get Post-IDs
foreach ( $postIds as &$post ) {
$post = $post[0];
}
// Get Posts
$posts = array_map(function($post) {
return get_post($post);
}, $postIds);
Plugin::setCacheItem(
$postIds,
Wordpress::getTags($posts, $items, $locations),
$customId
);
return $postIds;
}
}
/**
* Queries for posts within $postIds and filters them by $date and/or $minTimestamp and $postStatus.
* Why? This kind of filtering is needed nearly everywhere in commonsbooking.
*
* @param string|null $date
* @param int|null $minTimestamp
* @param int|null $maxTimestamp
* @param array $postIds
* @param array $postStatus
*
* @return array
*/
private static function getPostsByBaseParams( ?string $date, ?int $minTimestamp, ?int $maxTimestamp, array $postIds, array $postStatus ): array {
$cacheItem = Plugin::getCacheItem();
if ( $cacheItem ) {
return $cacheItem;
} else {
global $wpdb;
$table_postmeta = $wpdb->prefix . 'postmeta';
$table_posts = $wpdb->prefix . 'posts';
$dateQuery = "";
// Filter by date
if ( $date && ! $minTimestamp ) {
$dateQuery = self::getFilterByDateQuery( $table_postmeta, $date );
}
// Filter only from a specific start date.
// Rep-End must be > Min Date (0:00)
if ( $minTimestamp && ! $maxTimestamp ) {
$dateQuery = self::getFilterFromDateQuery( $table_postmeta, $minTimestamp );
}
// Filter for specific timerange
if ( $minTimestamp && $maxTimestamp ) {
$dateQuery = self::getTimerangeQuery( $table_postmeta, $minTimestamp, $maxTimestamp );
}
// Complete query
$query = "SELECT DISTINCT pm1.* from $table_posts pm1
" . $dateQuery . "
WHERE
pm1.id in (" . implode( ",", $postIds ) . ") AND
pm1.post_type IN ('" . implode( "','", \CommonsBooking\Wordpress\CustomPostType\Timeframe::getSimilarPostTypes() ) . "') AND
pm1.post_status IN ('" . implode( "','", $postStatus ) . "')
";
$posts = $wpdb->get_results( $query );
$posts = Wordpress::flattenWpdbResult( $posts );
Plugin::setCacheItem(
$posts,
Wordpress::getTags($posts, $postIds)
);
return $posts;
}
}
/**
* Returns query to get posts which overlap with day of $date.
* Conditions:
* - Starts before or on this day
* - Ends after or on this day OR has no end
*
* @param string $table_postmeta
* @param string $date
*
* @return string
*/
private static function getFilterByDateQuery( string $table_postmeta, string $date ): string {
global $wpdb;
return $wpdb->prepare(
"INNER JOIN $table_postmeta pm4 ON
pm4.post_id = pm1.id AND
pm4.meta_key = %s AND
pm4.meta_value BETWEEN 0 AND %d
INNER JOIN $table_postmeta pm5 ON
pm5.post_id = pm1.id AND (
(
pm5.meta_key = '" . \CommonsBooking\Model\Timeframe::REPETITION_END . "' AND
pm5.meta_value BETWEEN %d AND 3000000000
) OR
(
pm1.id not in (
SELECT post_id FROM $table_postmeta
WHERE
meta_key = '" . \CommonsBooking\Model\Timeframe::REPETITION_END . "'
)
)
)
",
\CommonsBooking\Model\Timeframe::REPETITION_START,
strtotime( $date . 'T23:59' ),
strtotime( $date )
);
}
/**
* Returns query to get posts which end after $minTimestamp.
*
* @param string $table_postmeta
* @param int $minTimestamp
*
* @return string
*/
private static function getFilterFromDateQuery( string $table_postmeta, int $minTimestamp ): string {
global $wpdb;
$minTimestamp = Helper::getLastFullDayTimestamp($minTimestamp);
return $wpdb->prepare(
"INNER JOIN $table_postmeta pm4 ON
pm4.post_id = pm1.id AND (
(
pm4.meta_key = '" . \CommonsBooking\Model\Timeframe::REPETITION_END . "' AND
pm4.meta_value >= %d
) OR
(
pm1.id not in (
SELECT post_id FROM $table_postmeta
WHERE
meta_key = '" . \CommonsBooking\Model\Timeframe::REPETITION_END . "'
)
)
)
",
$minTimestamp
);
}
/**
* @param string $table_postmeta
* @param int $minTimestamp
* @param int $maxTimestamp
*
* @return string
*/
private static function getTimerangeQuery( string $table_postmeta, int $minTimestamp, int $maxTimestamp ): string {
global $wpdb;
return $wpdb->prepare(
"INNER JOIN $table_postmeta pm4 ON
pm4.post_id = pm1.id AND (
pm4.meta_key = %s AND
pm4.meta_value <= %d
)
INNER JOIN $table_postmeta pm5 ON
pm5.post_id = pm1.id AND (
(
pm5.meta_key = %s AND
pm5.meta_value >= %d
) OR (
NOT EXISTS (
SELECT * FROM $table_postmeta
WHERE
meta_key = %s AND
post_id = pm5.post_id
)
)
)
",
\CommonsBooking\Model\Timeframe::REPETITION_START,
$maxTimestamp,
\CommonsBooking\Model\Timeframe::REPETITION_END,
$minTimestamp,
\CommonsBooking\Model\Timeframe::REPETITION_END
);
}
/**
* Wrapper function for all filters.
*
* @param array $posts
* @param string|null $date
*
* @return array
*/
private static function filterTimeframes( array $posts, ?string $date ): array {
// Filter by configured days
$posts = self::filterTimeframesByConfiguredDays( $posts, $date );
// Filter by configured max booking days
return self::filterTimeframesByMaxBookingDays( $posts );
}
/**
* Filters posts for days, that are active in timeframe.
* Why? Because you can define days for your timeframe. Here's the point where we make sure, that only these days
* are taken into account.
*
* @param array $posts
* @param string|null $date string format: YYYY-mm-dd
*
* @return array
* @throws \Psr\Cache\InvalidArgumentException
*/
private static function filterTimeframesByConfiguredDays( array $posts, ?string $date ): array {
$cacheItem = Plugin::getCacheItem();
if ( $cacheItem ) {
return $cacheItem;
} else {
if ( $date ) {
$posts = array_filter( $posts, function ( $post ) use ( $date ) {
try {
$timeframe = new \CommonsBooking\Model\Timeframe( $post );
$day = new Day( $date );
return $day->isInTimeframe( $timeframe );
} catch ( Exception $e ) {
//this was also default behaviour before #802 (before #802 the function would just check the weekly repetition and if it was active on the given day return true)
//When none were set, it would return true for all days.
return true;
}
}
);
}
Plugin::setCacheItem( $posts, Wordpress::getTags( $posts ) );
return $posts;
}
}
/**
* Filters timeframes from array, which aren't bookable because of the max booking days in
* advance setting.
*
* @param $posts
*
* @return array
*/
private static function filterTimeframesByMaxBookingDays( $posts ): array {
return array_filter( $posts, function ( $post ) {
if ( $post->post_type == \CommonsBooking\Wordpress\CustomPostType\Timeframe::getPostType() ) {
try {
$timeframe = new \CommonsBooking\Model\Timeframe( $post );
return $timeframe->isBookable();
} catch ( Exception $e ) {
error_log( $e->getMessage() );
return false;
}
}
return true;
} );
}
/**
* Filters timeframes from array,
* removes timeframes which are not bookable by current user
*
* @param $posts
*
* @return array
*/
private static function filterTimeframesForCurrentUser( $posts ): array {
return array_filter( $posts, function ( $post ) {
try {
return commonsbooking_isCurrentUserAllowedToBook( $post->ID );
} catch ( Exception $e ) {
error_log( $e->getMessage() );
return false;
}
} );
}
/**
* Instantiate models for posts.
* Why? In some cases we need more than WP_Post methods and for this case we have Models, that enrich WP_Post
* objects with useful additional functions.
*
* @param $posts
*
* @throws Exception
*/
private static function castPostsToModels( &$posts ) {
foreach ( $posts as &$post ) {
// If we have a standard timeframe
if ( $post->post_type == \CommonsBooking\Wordpress\CustomPostType\Timeframe::getPostType() ) {
$post = new \CommonsBooking\Model\Timeframe( $post );
}
// If it is a booking
if ( $post->post_type == \CommonsBooking\Wordpress\CustomPostType\Booking::getPostType() ) {
$post = new \CommonsBooking\Model\Booking( $post );
}
}
}
/**
* Returns timeframe that matches for timestamp based on date AND its time.
* Why? Needed for booking creation based on multiple timeframes with different multi slot grids.
*
* @param int $locationId
* @param int $itemId
* @param int $timestamp
*
* @return \CommonsBooking\Model\Timeframe
* @throws Exception
*/
public static function getByLocationItemTimestamp( int $locationId, int $itemId, int $timestamp ): ?\CommonsBooking\Model\Timeframe {
$cacheItem = Plugin::getCacheItem();
if ( $cacheItem ) {
return $cacheItem;
} else {
$time_format = esc_html(get_option( 'time_format' ));
$startTimestampTime = date( $time_format, $timestamp );
$endTimestampTime = date( $time_format, $timestamp + 1 );
$relevantTimeframes = self::get(
[ $locationId ],
[ $itemId ],
[ \CommonsBooking\Wordpress\CustomPostType\Timeframe::BOOKABLE_ID ],
date('Y-m-d', $timestamp),
true
);
/** @var \CommonsBooking\Model\Timeframe $timeframe */
foreach ( $relevantTimeframes as $timeframe ) {
if (
date( $time_format, strtotime( $timeframe->getStartTime() ) ) == $startTimestampTime ||
date( $time_format, strtotime( $timeframe->getEndTime() ) ) == $endTimestampTime
) {
Plugin::setCacheItem( $timeframe, [$timeframe->ID, $itemId, $locationId] );
return $timeframe;
}
}
}
return null;
}
/**
* Returns timeframes in explicit timerange. Does not consider weekday configurations!!
* Why? We often need timeframes for a specific timerange. For example in the calendar the default range is
* three months. Another example is the table view.
*
* @param $minTimestamp
* @param $maxTimestamp
* @param array $locations
* @param array $items
* @param array $types
* @param false $returnAsModel
* @param string[] $postStatus
*
* @return array
* @throws Exception
*/
public static function getInRange(
$minTimestamp,
$maxTimestamp,
array $locations = [],
array $items = [],
array $types = [],
bool $returnAsModel = false,
array $postStatus = [ 'confirmed', 'unconfirmed', 'publish', 'inherit' ]
): array {
if ( ! count( $types ) ) {
$types = [
\CommonsBooking\Wordpress\CustomPostType\Timeframe::HOLIDAYS_ID,
\CommonsBooking\Wordpress\CustomPostType\Timeframe::BOOKABLE_ID,
\CommonsBooking\Wordpress\CustomPostType\Timeframe::BOOKING_ID,
\CommonsBooking\Wordpress\CustomPostType\Timeframe::REPAIR_ID,
\CommonsBooking\Wordpress\CustomPostType\Timeframe::OFF_HOLIDAYS_ID,
];
}
$customId = md5( serialize( $types ) );
$cacheItem = Plugin::getCacheItem( $customId );
if ( $cacheItem ) {
return $cacheItem;
} else {
$posts = [];
// Get Post-IDs considering types, items and locations
$postIds = self::getPostIdsByType( $types, $items, $locations );
if ( $postIds && count( $postIds ) ) {
$posts = self::getPostsByBaseParams(
null,
$minTimestamp,
$maxTimestamp,
$postIds,
$postStatus
);
}
// if returnAsModel == TRUE the result is a timeframe model instead of a WordPress object
if ( $returnAsModel ) {
foreach ( $posts as &$post ) {
$post = new \CommonsBooking\Model\Timeframe( $post );
}
}
Plugin::setCacheItem(
$posts,
Wordpress::getTags($posts, $locations, $items),
$customId
);
return $posts;
}
}
/**
* Returns timeframes in explicit timerange that are bookable by the current user.
*
* @param $minTimestamp
* @param $maxTimestamp
* @param array $locations
* @param array $items
* @param array $types
* @param false $returnAsModel
* @param string[] $postStatus
*
* @return array
* @throws Exception
*/
public static function getInRangeForCurrentUser(
$minTimestamp,
$maxTimestamp,
array $locations = [],
array $items = [],
array $types = [],
bool $returnAsModel = false,
array $postStatus = [ 'confirmed', 'unconfirmed', 'publish', 'inherit' ]
): array {
$bookableTimeframes = self::getInRange($minTimestamp,$maxTimestamp,$locations,$items,$types,$returnAsModel,$postStatus);
$bookableTimeframes = self::filterTimeframesForCurrentUser($bookableTimeframes);
return $bookableTimeframes;
}
}