- The future of this plugin depends on your support. You can support us by make a donation on our website: wielebenwir'
- , 'commonsbooking' ) ), commonsbooking_sanitizeHTML( COMMONSBOOKING_VERSION ) ),
- 'fields' => array()
- )
- )
+ The future of this plugin depends on your support. You can support us by make a donation on our website: wielebenwir',
+ 'commonsbooking'
+ )
+ ),
+ commonsbooking_sanitizeHTML( COMMONSBOOKING_VERSION )
+ ),
+ 'fields' => array(),
+ ),
+ ),
),
/* Tab: main end*/
@@ -76,18 +82,27 @@
'id' => 'posttypes',
// tranlsators: %s = admin url options page
'desc' =>
- commonsbooking_sanitizeHTML( __(
- 'Customize names & slugs. You can set an individual slug for items and locations to create individual permalinks. Notice: If the new settings do not work directly (you will get a 404 page error on frontend pages), you must click on the Settings -> Permalinks page after saving these settings to refresh the Wordpress permalink settings.'
- , 'commonsbooking' ) ),
+ commonsbooking_sanitizeHTML(
+ __(
+ 'Customize names & slugs. You can set an individual slug for items and locations to create individual permalinks. Notice: If the new settings do not work directly (you will get a 404 page error on frontend pages), you must click on the Settings -> Permalinks page after saving these settings to refresh the Wordpress permalink settings.',
+ 'commonsbooking'
+ )
+ ),
'fields' => array(
array(
'name' => commonsbooking_sanitizeHTML( __( 'Items slug', 'commonsbooking' ) ),
'id' => 'posttypes_items-slug',
// translators: %s = example url (like website.com/cb-items/)
'description' =>
- sprintf( commonsbooking_sanitizeHTML( __(
- 'The slug for article detail page. Type in the slug without slashes. Example: cb_item or article. The url for the items detail will be like %s',
- 'commonsbooking' ) ), network_site_url( '/cb_item/' ) ),
+ sprintf(
+ commonsbooking_sanitizeHTML(
+ __(
+ 'The slug for article detail page. Type in the slug without slashes. Example: cb_item or article. The url for the items detail will be like %s',
+ 'commonsbooking'
+ )
+ ),
+ network_site_url( '/cb_item/' )
+ ),
'type' => 'text',
'default' => Item::$postType,
),
@@ -96,9 +111,15 @@
'id' => 'posttypes_locations-slug',
// translators: %s = example url (like website.com/cb-locations/)
'description' =>
- sprintf( commonsbooking_sanitizeHTML( __(
- 'The slug for location detail page. Type in the slug without slashes. Example: cb_location or location. The url for the items detail will be like %s',
- 'commonsbooking' ) ), network_site_url( '/cb_location/' ) ),
+ sprintf(
+ commonsbooking_sanitizeHTML(
+ __(
+ 'The slug for location detail page. Type in the slug without slashes. Example: cb_location or location. The url for the items detail will be like %s',
+ 'commonsbooking'
+ )
+ ),
+ network_site_url( '/cb_location/' )
+ ),
'type' => 'text',
'default' => Location::$postType,
),
@@ -107,16 +128,22 @@
'id' => 'bookings_page',
// translators: %s = example url (like website.com/cb-locations/)
'description' =>
- sprintf( commonsbooking_sanitizeHTML( __(
- 'The page where you included the [cb_bookings] shortcode. This is used in the Users Widget',
- 'commonsbooking' ) ), network_site_url( '/bookings/' ) ),
+ sprintf(
+ commonsbooking_sanitizeHTML(
+ __(
+ 'The page where you included the [cb_bookings] shortcode. This is used in the Users Widget',
+ 'commonsbooking'
+ )
+ ),
+ network_site_url( '/bookings/' )
+ ),
'type' => 'select',
'options' => Wordpress::getPageListTitle(),
),
),
),
'bookingCommentSettings' => array(
- 'title' => __( "Booking comment", 'commonsbooking' ),
+ 'title' => __( 'Booking comment', 'commonsbooking' ),
'id' => 'bookingCommentSettings',
'fields' => array(
array(
@@ -139,15 +166,15 @@
'type' => 'textarea_small',
'default' => __( 'Here you can leave a comment about your booking. This will be sent to the station.', 'commonsbooking' ),
),
- )
+ ),
),
'globalLocationSettings' => array(
- 'title' => __( "Global location settings", 'commonsbooking' ),
+ 'title' => __( 'Global location settings', 'commonsbooking' ),
'desc' => commonsbooking_sanitizeHTML( __( 'These settings are used for all locations. You can overwrite these settings for each location in the location settings.', 'commonsbooking' ) ),
'id' => 'globalLocationSettings',
- 'fields' => Location::getOverbookingSettingsMetaboxes()
- )
- )
+ 'fields' => Location::getOverbookingSettingsMetaboxes(),
+ ),
+ ),
),
/* Tab: general end*/
@@ -160,8 +187,13 @@
'title' => commonsbooking_sanitizeHTML( __( 'Booking codes', 'commonsbooking' ) ),
'id' => 'bookingcodes',
'desc' =>
- commonsbooking_sanitizeHTML( __( 'Enter the booking codes to be generated in advance for booking types with all-day booking time frames. Enter booking codes as a comma separated list, e.g.: Code1,Code2,Code3,Code4
- More information in the documentation: Booking codes', 'commonsbooking' ) ),
+ commonsbooking_sanitizeHTML(
+ __(
+ 'Enter the booking codes to be generated in advance for booking types with all-day booking time frames. Enter booking codes as a comma separated list, e.g.: Code1,Code2,Code3,Code4
+ More information in the documentation: Booking codes',
+ 'commonsbooking'
+ )
+ ),
'fields' => array(
array(
'name' => commonsbooking_sanitizeHTML( __( 'Booking codes', 'commonsbooking' ) ),
@@ -179,7 +211,7 @@
),
'default' => '30',
),
- )
+ ),
),
'mail_booking_codes' => array(
'title' => commonsbooking_sanitizeHTML( __( 'Booking codes by email', 'commonsbooking' ) ),
@@ -197,7 +229,9 @@
'name' => commonsbooking_sanitizeHTML( __( 'Body for booking codes email', 'commonsbooking' ) ),
'id' => 'mail-booking-codes-body',
'type' => 'textarea',
- 'default' => commonsbooking_sanitizeHTML( __( '
+ 'default' => commonsbooking_sanitizeHTML(
+ __(
+ '
Booking codes for {{item:post_title}} : {{codes:formatDateRange}}
Unfortunately, the article {{item:post_title}} you booked is no longer usable from {{restriction:formattedStartDateTime}} to probably {{restriction:formattedEndDateTime}}. The reason is:{{restriction:hint}}
@@ -615,7 +681,10 @@
Please book the item again for a different period or check our website to see if an alternative item is available. We apologize for any inconvenience.
The article {{item:post_title}} you booked can only be used to a limited extent from {{restriction:formattedStartDateTime}} to probably {{restriction:formattedEndDateTime}}.
@@ -647,7 +718,10 @@
We strive to fix the restriction as soon as possible.
You will receive an email when the restriction is resolved.
- {{booking:getEmailSignature}}', 'commonsbooking' ) ),
+ {{booking:getEmailSignature}}',
+ 'commonsbooking'
+ )
+ ),
),
// E-Mail restriction cancellation
@@ -661,16 +735,21 @@
'name' => commonsbooking_sanitizeHTML( __( 'Restriction cancelled email body', 'commonsbooking' ) ),
'id' => 'restrictions-restriction-cancelled-body',
'type' => 'textarea',
- 'default' => commonsbooking_sanitizeHTML( __( '
Your booking period for the item {{item:post_title}} will start soon.
Your booking period: {{booking:formattedBookingDate}}
@@ -819,16 +904,22 @@
For booking details and cancellation, click on this booking link: {{booking:bookingLink}}
-{{booking:getEmailSignature}}', 'commonsbooking' ) ),
+{{booking:getEmailSignature}}',
+ 'commonsbooking'
+ )
+ ),
),
- // settings pre booking reminder -- min days
+ // settings pre booking reminder -- min days
array(
'name' => commonsbooking_sanitizeHTML( __( 'Sent reminder x days before booking start', 'commonsbooking' ) ),
'id' => 'pre-booking-days-before',
- 'desc' => '
' . commonsbooking_sanitizeHTML( __(
- 'This reminder email will be sent to users x days before the start of the booking. If the booking is made less days before the specified days, no reminder email will be sent'
- , 'commonsbooking' ) ) . '
',
+ 'desc' => '
' . commonsbooking_sanitizeHTML(
+ __(
+ 'This reminder email will be sent to users x days before the start of the booking. If the booking is made less days before the specified days, no reminder email will be sent',
+ 'commonsbooking'
+ )
+ ) . '
',
'type' => 'text_small',
'attributes' => array(
'type' => 'number',
@@ -842,9 +933,12 @@
array(
'name' => esc_html__( 'Time', 'commonsbooking' ),
'id' => 'pre-booking-time',
- 'desc' => ' ' . commonsbooking_sanitizeHTML( __(
- 'Define when the reminder should be sent. The actual sending may differ from the defined value by a few hours, depending on how your WordPress is configured.'
- , 'commonsbooking' ) ),
+ 'desc' => ' ' . commonsbooking_sanitizeHTML(
+ __(
+ 'Define when the reminder should be sent. The actual sending may differ from the defined value by a few hours, depending on how your WordPress is configured.',
+ 'commonsbooking'
+ )
+ ),
'type' => 'select',
'show_option_none' => false,
'default' => '1',
@@ -885,10 +979,13 @@
'post-booking-notice' => array(
'title' => commonsbooking_sanitizeHTML( __( 'email after booking has ended', 'commonsbooking' ) ),
'id' => 'post-booking-notice',
- 'desc' => commonsbooking_sanitizeHTML( __(
- 'Here you can set whether users should receive an additional e-mail after completing a booking. This can be used, for example, to inquire about the users satisfaction or possible problems during the booking.
- The email will be sent around midnight after the booking day has ended.'
- , 'commonsbooking' ) ),
+ 'desc' => commonsbooking_sanitizeHTML(
+ __(
+ 'Here you can set whether users should receive an additional e-mail after completing a booking. This can be used, for example, to inquire about the users satisfaction or possible problems during the booking.
+ The email will be sent around midnight after the booking day has ended.',
+ 'commonsbooking'
+ )
+ ),
'fields' => array(
// settings post booking reminder -- activate reminder
array(
@@ -896,7 +993,7 @@
'id' => 'post-booking-notice-activate',
'type' => 'checkbox',
),
- // E-Mail post booking reminder
+ // E-Mail post booking reminder
array(
'name' => commonsbooking_sanitizeHTML( __( 'E-mail subject', 'commonsbooking' ) ),
'id' => 'post-booking-notice-subject',
@@ -907,12 +1004,17 @@
'name' => commonsbooking_sanitizeHTML( __( 'email body', 'commonsbooking' ) ),
'id' => 'post-booking-notice-body',
'type' => 'textarea',
- 'default' => commonsbooking_sanitizeHTML( __( '
Your booking of {{item:post_title}} at {{location:post_title}} has ended.
We hope that everything worked as expected.
Please let us know if any problems occurred.
-{{booking:getEmailSignature}}', 'commonsbooking' ) ),
+{{booking:getEmailSignature}}',
+ 'commonsbooking'
+ )
+ ),
),
),
),
@@ -922,9 +1024,12 @@
'booking-start-location-reminder' => array(
'title' => commonsbooking_sanitizeHTML( __( 'Reminder for locations before booking starts', 'commonsbooking' ) ),
'id' => 'booking-start-location-reminder',
- 'desc' => commonsbooking_sanitizeHTML( __(
- 'You can set here whether locations should receive a reminder email before the start of a booking. More Information in the documentation'
- , 'commonsbooking' ) ),
+ 'desc' => commonsbooking_sanitizeHTML(
+ __(
+ 'You can set here whether locations should receive a reminder email before the start of a booking. More Information in the documentation',
+ 'commonsbooking'
+ )
+ ),
'fields' => array(
// settings booking start reminder -- activate reminder
array(
@@ -935,46 +1040,57 @@
),
// E-Mail booking start reminder for locations
array(
- 'name' => commonsbooking_sanitizeHTML( __( 'E-mail subject', 'commonsbooking' ) ),
- 'id' => 'booking-start-location-reminder-subject',
- 'type' => 'text',
- 'default' => commonsbooking_sanitizeHTML( __( 'Upcoming booking of {{item:post_title}} {{booking:formattedBookingDate}}', 'commonsbooking' ) ),
- ),
- array(
- 'name' => commonsbooking_sanitizeHTML( __( 'email body', 'commonsbooking' ) ),
- 'id' => 'booking-start-location-reminder-body',
- 'type' => 'textarea',
- 'default' => commonsbooking_sanitizeHTML( __( '
';
}
return '';
@@ -183,6 +188,7 @@ public function getDate() {
/**
* Returns user data.
+ *
* @return false|\WP_User
*/
public function getUserData() {
@@ -192,11 +198,12 @@ public function getUserData() {
/**
* Checks if the given user is the author of the current post.
+ *
* @param \WP_User $user
*
* @return bool - true if user is author, false if not.
*/
- public function isAuthor (\WP_User $user): bool {
+ public function isAuthor( \WP_User $user ): bool {
return $user->ID === intval( $this->post_author );
}
@@ -210,5 +217,4 @@ public function setDate( string $date = null ) {
return $this;
}
-
}
diff --git a/src/Model/Day.php b/src/Model/Day.php
index aedef3566..d7f008490 100644
--- a/src/Model/Day.php
+++ b/src/Model/Day.php
@@ -46,23 +46,29 @@ class Day {
* Day constructor.
*
* @param string $date
- * @param array $locations
- * @param array $items
- * @param array $types
- * @param array $possibleTimeframes
+ * @param array $locations
+ * @param array $items
+ * @param array $types
+ * @param array $possibleTimeframes
*/
public function __construct( string $date, array $locations = [], array $items = [], array $types = [], array $possibleTimeframes = [] ) {
$this->date = $date;
- $this->locations = array_map( function ( $location ) {
- return $location instanceof WP_Post ? $location->ID : $location;
- }, $locations );
- $this->items = array_map( function ( $item ) {
- return $item instanceof WP_Post ? $item->ID : $item;
- }, $items );
+ $this->locations = array_map(
+ function ( $location ) {
+ return $location instanceof WP_Post ? $location->ID : $location;
+ },
+ $locations
+ );
+ $this->items = array_map(
+ function ( $item ) {
+ return $item instanceof WP_Post ? $item->ID : $item;
+ },
+ $items
+ );
$this->types = $types;
- if ( ! empty ( $possibleTimeframes ) ) {
+ if ( ! empty( $possibleTimeframes ) ) {
$this->timeframes = \CommonsBooking\Repository\Timeframe::filterTimeframesForTimerange( $possibleTimeframes, $this->getStartTimestamp(), $this->getEndTimestamp() );
$this->timeframes = array_filter( $this->timeframes, fn( $timeframe ) => $this->filterTimeframe( $timeframe ) );
}
@@ -103,6 +109,7 @@ public function getFormattedDate( string $format ) {
/**
* Returns name of the day.
+ *
* @return false|string
*/
public function getName() {
@@ -113,6 +120,7 @@ public function getName() {
* Returns array with timeframes relevant for the Day.
* This function will only be able to run once.
* When on the first try, no Timeframes are found, it will set it to an empty array
+ *
* @return \CommonsBooking\Model\Timeframe[]
* @throws Exception
*/
@@ -140,6 +148,7 @@ public function getTimeframes(): array {
/**
* Returns array with restrictions.
+ *
* @return array
* @throws Exception
*/
@@ -169,7 +178,7 @@ public function getGrid(): array {
* Returns the slot number for specific timeframe and time.
*
* @param DateTime $date
- * @param int $grid
+ * @param int $grid
*
* @return float|int
*/
@@ -183,7 +192,7 @@ protected function getSlotByTime( DateTime $date, int $grid ) {
/**
* Returns start-slot id.
*
- * @param int $grid
+ * @param int $grid
* @param \CommonsBooking\Model\Timeframe $timeframe
*
* @return float|int
@@ -197,7 +206,6 @@ protected function getStartSlot( int $grid, \CommonsBooking\Model\Timeframe $tim
// If we have an overbooked day, we need to mark all slots as booked
if ( $timeframe->getType() === Timeframe::BOOKING_ID ) {
-
$booking = new Booking( $timeframe->getPost() );
$startDateBooking = $booking->getStartDate();
$startDateDay = strtotime( $this->getDate() );
@@ -219,7 +227,7 @@ protected function getStartSlot( int $grid, \CommonsBooking\Model\Timeframe $tim
/**
* Returns start slot for restriction.
*
- * @param int $grid
+ * @param int $grid
* @param Restriction $restriction
* @return float|int
@@ -243,8 +251,8 @@ protected function getRestrictionStartSlot( int $grid, Restriction $restriction
/**
* Returns end-slot id.
*
- * @param array $slots
- * @param int $grid
+ * @param array $slots
+ * @param int $grid
* @param \CommonsBooking\Model\Timeframe $timeframe
*
* @return float|int
@@ -265,7 +273,7 @@ protected function getEndSlot( array $slots, int $grid, \CommonsBooking\Model\Ti
}
// If we have a overbooked day, we need to mark all slots as booked
- if ( ! $timeframe->isOverBookable() && !empty( $endDate ) ) {
+ if ( ! $timeframe->isOverBookable() && ! empty( $endDate ) ) {
// Check if timeframe ends after the current day
if ( strtotime( $this->getFormattedDate( 'd.m.Y 23:59' ) ) < $endDate->getTimestamp() ) {
$endSlot = count( $slots );
@@ -278,8 +286,8 @@ protected function getEndSlot( array $slots, int $grid, \CommonsBooking\Model\Ti
/**
* Returns end slot for restriction.
*
- * @param array $slots
- * @param int $grid
+ * @param array $slots
+ * @param int $grid
* @param Restriction $restriction
*
* @return float|int
@@ -313,7 +321,7 @@ public function isInTimeframe( \CommonsBooking\Model\Timeframe $timeframe ): boo
if ( $timeframe->getRepetition() ) {
switch ( $timeframe->getRepetition() ) {
// Weekly Rep
- case "w":
+ case 'w':
$dayOfWeek = intval( $this->getDateObject()->format( 'w' ) );
$timeframeWeekdays = get_post_meta( $timeframe->ID, 'weekdays', true );
@@ -328,10 +336,10 @@ public function isInTimeframe( \CommonsBooking\Model\Timeframe $timeframe ): boo
return false;
}
- // Monthly Rep
- case "m":
+ // Monthly Rep
+ case 'm':
$dayOfMonth = intval( $this->getDateObject()->format( 'j' ) );
- $timeframeStartDayOfMonth = date('j',$timeframe->getStartDate());
+ $timeframeStartDayOfMonth = date( 'j', $timeframe->getStartDate() );
if ( $dayOfMonth == $timeframeStartDayOfMonth ) {
return true;
@@ -339,32 +347,32 @@ public function isInTimeframe( \CommonsBooking\Model\Timeframe $timeframe ): boo
return false;
}
- // Yearly Rep
- case "y":
+ // Yearly Rep
+ case 'y':
$date = intval( $this->getDateObject()->format( 'dm' ) );
- $timeframeDate = date('dm',$timeframe->getStartDate());
+ $timeframeDate = date( 'dm', $timeframe->getStartDate() );
if ( $date == $timeframeDate ) {
return true;
} else {
return false;
}
- // Manual Rep
- case "manual":
+ // Manual Rep
+ case 'manual':
return in_array( $this->getDate(), $timeframe->getManualSelectionDates() );
// No Repetition
- case "norep":
- $timeframeStartTimestamp = intval( $timeframe->getMeta( \CommonsBooking\Model\Timeframe::REPETITION_START ));
- $timeframeEndTimestamp = intval( $timeframe->getMeta( \CommonsBooking\Model\Timeframe::REPETITION_END ));
+ case 'norep':
+ $timeframeStartTimestamp = intval( $timeframe->getMeta( \CommonsBooking\Model\Timeframe::REPETITION_START ) );
+ $timeframeEndTimestamp = intval( $timeframe->getMeta( \CommonsBooking\Model\Timeframe::REPETITION_END ) );
- $currentDayStartTimestamp = strtotime('midnight', $this->getDateObject()->getTimestamp());
- $currentDayEndTimestamp = strtotime('+1 day midnight', $this->getDateObject()->getTimestamp()) - 1;
+ $currentDayStartTimestamp = strtotime( 'midnight', $this->getDateObject()->getTimestamp() );
+ $currentDayEndTimestamp = strtotime( '+1 day midnight', $this->getDateObject()->getTimestamp() ) - 1;
$timeframeStartsBeforeEndOfToday = $timeframeStartTimestamp <= $currentDayEndTimestamp;
- $timeframeEndsAfterStartOfToday = $timeframeEndTimestamp >= $currentDayStartTimestamp;
+ $timeframeEndsAfterStartOfToday = $timeframeEndTimestamp >= $currentDayStartTimestamp;
- if(!$timeframeEndTimestamp) {
+ if ( ! $timeframeEndTimestamp ) {
return $timeframeStartsBeforeEndOfToday;
} else {
return $timeframeStartsBeforeEndOfToday && $timeframeEndsAfterStartOfToday;
@@ -424,7 +432,7 @@ protected function mapTimeFrames( array &$slots ) {
$slots[ $startSlot ]['timeframe'] = Timeframe::getHigherPrioFrame( $timeframePost, $slots[ $startSlot ]['timeframe'] );
}
- $startSlot ++;
+ ++$startSlot;
}
}
}
@@ -455,7 +463,7 @@ protected function mapRestrictions( array &$slots ) {
$restrictionPost = $restriction->getPost();
$restrictionPost->locked = true;
$slots[ $startSlot ]['timeframe'] = $restrictionPost;
- $startSlot ++;
+ ++$startSlot;
}
}
}
@@ -539,7 +547,7 @@ protected function removeEmptySlots( &$slots ) {
protected function getTimeframeSlots(): array {
$customCacheKey = $this->getDate() . serialize( $this->items ) . serialize( $this->locations );
$customCacheKey = md5( $customCacheKey );
- $cacheItem = Plugin::getCacheItem( $customCacheKey );
+ $cacheItem = Plugin::getCacheItem( $customCacheKey );
if ( $cacheItem ) {
return $cacheItem;
} else {
@@ -547,12 +555,12 @@ protected function getTimeframeSlots(): array {
$slotsPerDay = 24;
// Init Slots
- for ( $i = 0; $i < $slotsPerDay; $i ++ ) {
+ for ( $i = 0; $i < $slotsPerDay; $i++ ) {
$slots[ $i ] = [
- 'timestart' => date( esc_html(get_option( 'time_format' )), $i * ( ( 24 / $slotsPerDay ) * 3600 ) ),
- 'timeend' => date( esc_html(get_option( 'time_format' )), ( $i + 1 ) * ( ( 24 / $slotsPerDay ) * 3600 ) ),
+ 'timestart' => date( esc_html( get_option( 'time_format' ) ), $i * ( ( 24 / $slotsPerDay ) * 3600 ) ),
+ 'timeend' => date( esc_html( get_option( 'time_format' ) ), ( $i + 1 ) * ( ( 24 / $slotsPerDay ) * 3600 ) ),
'timestampstart' => $this->getSlotTimestampStart( $slotsPerDay, $i ),
- 'timestampend' => $this->getSlotTimestampEnd( $slotsPerDay, $i )
+ 'timestampend' => $this->getSlotTimestampEnd( $slotsPerDay, $i ),
];
}
@@ -562,7 +570,7 @@ protected function getTimeframeSlots(): array {
Plugin::setCacheItem(
$slots,
- Wordpress::getTags($this->getTimeframes(), $this->items, $this->locations),
+ Wordpress::getTags( $this->getTimeframes(), $this->items, $this->locations ),
$customCacheKey
);
@@ -593,5 +601,4 @@ protected function getSlotTimestampStart( $slotsPerDay, $slotNr ) {
protected function getSlotTimestampEnd( $slotsPerDay, $slotNr ) {
return strtotime( $this->getDate() ) + ( ( $slotNr + 1 ) * ( ( 24 / $slotsPerDay ) * 3600 ) ) - 1;
}
-
}
diff --git a/src/Model/Item.php b/src/Model/Item.php
index 4d6fc73b5..1fdc3452e 100644
--- a/src/Model/Item.php
+++ b/src/Model/Item.php
@@ -3,7 +3,6 @@
namespace CommonsBooking\Model;
-
use CommonsBooking\Helper\Helper;
use CommonsBooking\Repository\Timeframe;
use Exception;
@@ -21,7 +20,7 @@ class Item extends BookablePost {
*
* @param $locationId
*
- * @param bool $asModel
+ * @param bool $asModel
*
* @return array
* @throws Exception
@@ -60,7 +59,7 @@ public function getAdmins() {
return array_values(
array_unique(
- array_map('intval', $itemAdminIds )
+ array_map( 'intval', $itemAdminIds )
)
);
}
@@ -69,16 +68,16 @@ public function getAdmins() {
* Returns all applicable restrictions for this item.
*
* This function is not used anywhere yet.
+ *
* @return array
* @throws Exception
*/
public function getRestrictions(): array {
return \CommonsBooking\Repository\Restriction::get(
[],
- [$this->ID],
+ [ $this->ID ],
null,
true
);
}
-
}
diff --git a/src/Model/Location.php b/src/Model/Location.php
index 4ace5c0d7..8a3581c61 100644
--- a/src/Model/Location.php
+++ b/src/Model/Location.php
@@ -23,7 +23,7 @@ class Location extends BookablePost {
* returns bookable timeframes for a given itemID
*
* @param mixed $itemId
- * @param bool $asModel
+ * @param bool $asModel
*
* @return array
* @throws \Exception
@@ -47,25 +47,30 @@ public function getBookableTimeframesByItem( $itemId, bool $asModel = false ): a
* E.g. a textarea "location format" in the backend that gets run through CB::get():
* {{location_street}} {{location_postcode}} {{location_city}}
*
- *
* @return string
* @throws \Exception
*/
public function formattedAddress() {
- $html_after = ' ';
- $html_output[] = CB::get( \CommonsBooking\Wordpress\CustomPostType\Location::$postType, 'post_title', $this->post ) . $html_after;
- $location_street = CB::get( \CommonsBooking\Wordpress\CustomPostType\Location::$postType, COMMONSBOOKING_METABOX_PREFIX . 'location_street',
- $this->post );
- if (!empty($location_street)){
+ $html_after = ' ';
+ $html_output[] = CB::get( \CommonsBooking\Wordpress\CustomPostType\Location::$postType, 'post_title', $this->post ) . $html_after;
+ $location_street = CB::get(
+ \CommonsBooking\Wordpress\CustomPostType\Location::$postType,
+ COMMONSBOOKING_METABOX_PREFIX . 'location_street',
+ $this->post
+ );
+ if ( ! empty( $location_street ) ) {
$html_output[] = $location_street . $html_after;
}
$location_postcode = CB::get( \CommonsBooking\Wordpress\CustomPostType\Location::$postType, COMMONSBOOKING_METABOX_PREFIX . 'location_postcode', $this->post );
- if (!empty($location_postcode)){
+ if ( ! empty( $location_postcode ) ) {
$html_output[] = $location_postcode;
}
- $location_city = CB::get( \CommonsBooking\Wordpress\CustomPostType\Location::$postType, COMMONSBOOKING_METABOX_PREFIX . 'location_city',
- $this->post );
- if (!empty($location_city)){
+ $location_city = CB::get(
+ \CommonsBooking\Wordpress\CustomPostType\Location::$postType,
+ COMMONSBOOKING_METABOX_PREFIX . 'location_city',
+ $this->post
+ );
+ if ( ! empty( $location_city ) ) {
$html_output[] = $location_city . $html_after;
}
@@ -77,6 +82,7 @@ public function formattedAddress() {
* This function is usually called using template tags in the e-mail templates.
*
* TODO: Fix the uncaught exception.
+ *
* @return string html
* @throws \Exception
*/
@@ -87,11 +93,11 @@ public function formattedAddressOneLine(): string {
$location_city = CB::get( \CommonsBooking\Wordpress\CustomPostType\Location::$postType, COMMONSBOOKING_METABOX_PREFIX . 'location_city', $this->post );
- if (empty($location_street) && empty($location_postcode) && empty($location_city)){
- return "";
- }
- elseif (empty($location_street) || empty($location_postcode)){
- return sprintf('%s %s %s',
+ if ( empty( $location_street ) && empty( $location_postcode ) && empty( $location_city ) ) {
+ return '';
+ } elseif ( empty( $location_street ) || empty( $location_postcode ) ) {
+ return sprintf(
+ '%s %s %s',
$location_street,
$location_postcode,
$location_city
@@ -120,14 +126,15 @@ public function formattedAddressOneLine(): string {
public function formattedContactInfo() {
$contact = array();
if ( ! empty( CB::get( \CommonsBooking\Wordpress\CustomPostType\Location::$postType, COMMONSBOOKING_METABOX_PREFIX . 'location_contact', $this->post ) ) ) {
- $contact[] = " "; // needed for email template
- $contact[] = esc_html__( 'Please contact the contact persons at the location directly if you have any questions regarding collection or return:',
- 'commonsbooking' );
+ $contact[] = ' '; // needed for email template
+ $contact[] = esc_html__(
+ 'Please contact the contact persons at the location directly if you have any questions regarding collection or return:',
+ 'commonsbooking'
+ );
$contact[] = nl2br( CB::get( \CommonsBooking\Wordpress\CustomPostType\Location::$postType, COMMONSBOOKING_METABOX_PREFIX . 'location_contact', $this->post ) );
}
return implode( ' ', $contact );
-
}
/**
@@ -143,7 +150,7 @@ public function formattedContactInfo() {
* @throws \Exception
*/
public function formattedContactInfoOneLine() {
- return commonsbooking_sanitizeHTML(CB::get( \CommonsBooking\Wordpress\CustomPostType\Location::$postType, COMMONSBOOKING_METABOX_PREFIX . 'location_contact', $this->post)) . ' ';
+ return commonsbooking_sanitizeHTML( CB::get( \CommonsBooking\Wordpress\CustomPostType\Location::$postType, COMMONSBOOKING_METABOX_PREFIX . 'location_contact', $this->post ) ) . ' ';
}
/**
@@ -154,10 +161,13 @@ public function formattedContactInfoOneLine() {
* @throws \Exception
*/
public function formattedPickupInstructions(): string {
- $html_br = ' ';
+ $html_br = ' ';
- return $html_br . $html_br . CB::get( \CommonsBooking\Wordpress\CustomPostType\Location::$postType,
- COMMONSBOOKING_METABOX_PREFIX . 'location_pickupinstructions', $this->post ) . $html_br;
+ return $html_br . $html_br . CB::get(
+ \CommonsBooking\Wordpress\CustomPostType\Location::$postType,
+ COMMONSBOOKING_METABOX_PREFIX . 'location_pickupinstructions',
+ $this->post
+ ) . $html_br;
}
/**
@@ -176,7 +186,6 @@ public function formattedPickupInstructionsOneLine() {
/**
* Calls the geocoder to update the geo coordinates of the location.
* Caution: Do not call this function without a one-second delay between calls. Do not overload the geocoder.
- *
*/
public function updateGeoLocation() {
$street = $this->getMeta( COMMONSBOOKING_METABOX_PREFIX . 'location_street' );
@@ -191,7 +200,7 @@ public function updateGeoLocation() {
return;
}
- $addressString = $street . ", " . $postCode . " " . $city . ", " . $country;
+ $addressString = $street . ', ' . $postCode . ' ' . $city . ', ' . $country;
try {
$addressData = GeoHelper::getAddressData( $addressString );
} catch ( Exception $e ) {
@@ -238,8 +247,9 @@ public function getAdmins() {
$locationAdminIds[] = get_post_field( 'post_author', $locationId );
return array_unique(
- array_map('intval',
- array_values($locationAdminIds)
+ array_map(
+ 'intval',
+ array_values( $locationAdminIds )
)
);
}
@@ -252,7 +262,7 @@ public function getAdmins() {
*/
public function getRestrictions(): array {
return \CommonsBooking\Repository\Restriction::get(
- [$this->ID],
+ [ $this->ID ],
[],
null,
true
@@ -267,6 +277,6 @@ public function getRestrictions(): array {
* @return mixed
*/
public function hasMap() {
- return $this->getMeta( 'loc_showmap') === "on";
+ return $this->getMeta( 'loc_showmap' ) === 'on';
}
}
diff --git a/src/Model/Map.php b/src/Model/Map.php
index 224620c42..5d86580fb 100644
--- a/src/Model/Map.php
+++ b/src/Model/Map.php
@@ -10,7 +10,6 @@
/**
* This class does the heavy lifting for the map shortcode
* Code style differs because it has been taken from the fLotte Map shortcode plugin
- *
*/
class Map extends CustomPost {
@@ -33,7 +32,6 @@ public function get_locations( array $mapItemTerms ): array {
$preset_categories = $this->getMeta( 'cb_items_preset_categories' );
$preset_location_categories = $this->getMeta( 'cb_locations_preset_categories' );
-
$args = [
'post_type' => Location::$postType,
'posts_per_page' => - 1,
@@ -55,8 +53,8 @@ public function get_locations( array $mapItemTerms ): array {
foreach ( $locationObjects as $post ) {
$location_meta = get_post_meta( $post->ID, null, true );
- //set serialized empty array if not set
- //THIS FUNCTIONALITY IS DEPRECATED, closing days were a feature of 0.9.X
+ // set serialized empty array if not set
+ // THIS FUNCTIONALITY IS DEPRECATED, closing days were a feature of 0.9.X
$closed_days = isset( $location_meta['commons-booking_location_closeddays'] ) ? $location_meta['commons-booking_location_closeddays'][0] : 'a:0:{}';
$items = [];
@@ -67,12 +65,11 @@ public function get_locations( array $mapItemTerms ): array {
if ( $preset_location_categories ) {
if ( ! has_term( $preset_location_categories, 'cb_locations_category', $post->ID ) ) {
- continue; //skip to next location in loop
+ continue; // skip to next location in loop
}
}
foreach ( Item::getByLocation( $post->ID, true ) as $item ) {
-
$item_terms = wp_get_post_terms(
$item->ID,
\CommonsBooking\Wordpress\CustomPostType\Item::$postType . 's_category'
@@ -98,13 +95,12 @@ function ( $item ) {
*/
if ( $preset_categories ) {
- //check if preset category is in items
+ // check if preset category is in items
if ( ! has_term( $preset_categories, 'cb_items_category', $item->ID ) ) {
- continue; //skip to next item in loop
+ continue; // skip to next item in loop
}
}
-
$timeframesData = [];
$timeframes = Timeframe::getBookableForCurrentUser(
[ $post->ID ],
@@ -119,12 +115,12 @@ function ( $item ) {
$endDate = $timeframe->getEndDate() ?: date( 'Y-m-d', strtotime( '2999-01-01' ) );
$timeframesData[] = [
'date_start' => $startDate,
- 'date_end' => $endDate
+ 'date_end' => $endDate,
];
}
$thumbnailID = get_post_thumbnail_id( $item->ID );
- //this thumbnail is kept for backwards compatibility
+ // this thumbnail is kept for backwards compatibility
$thumbnail = wp_get_attachment_image_url( $thumbnailID, 'thumbnail' );
$images = [
'thumbnail' => wp_get_attachment_image_src( $thumbnailID, 'thumbnail' ),
@@ -135,13 +131,13 @@ function ( $item ) {
$items[] = [
'id' => $item->ID,
'name' => $item->post_title,
- 'short_desc' => has_excerpt( $item->ID ) ? wp_strip_all_tags( get_the_excerpt( $item->ID ) ) : "",
+ 'short_desc' => has_excerpt( $item->ID ) ? wp_strip_all_tags( get_the_excerpt( $item->ID ) ) : '',
'status' => $item->post_status,
'terms' => $item_terms,
'link' => add_query_arg( 'cb-location', $post->ID, get_permalink( $item->ID ) ),
'thumbnail' => $thumbnail ?: null,
'images' => $images,
- 'timeframes' => $timeframesData
+ 'timeframes' => $timeframesData,
];
}
@@ -180,13 +176,13 @@ function ( $item ) {
public static function cleanup_location_data_entry( $value, $linebreak_replacement ) {
if ( is_string( $value ) ) {
- $value = wp_strip_all_tags( $value ); //strip all tags
- $value = preg_replace( '/(\r\n)|\n|\r/', $linebreak_replacement, $value ); //replace linebreaks
+ $value = wp_strip_all_tags( $value ); // strip all tags
+ $value = preg_replace( '/(\r\n)|\n|\r/', $linebreak_replacement, $value ); // replace linebreaks
}
if ( is_array( $value ) ) {
foreach ( $value as &$child_value ) {
- //recursive call
+ // recursive call
$child_value = self::cleanup_location_data_entry( $child_value, $linebreak_replacement );
}
}
@@ -209,5 +205,4 @@ public static function cleanup_location_data( $locations, $linebreak_replacement
return $locations;
}
-
-}
\ No newline at end of file
+}
diff --git a/src/Model/MessageRecipient.php b/src/Model/MessageRecipient.php
index a7f07c9f5..f4c3a3329 100644
--- a/src/Model/MessageRecipient.php
+++ b/src/Model/MessageRecipient.php
@@ -14,11 +14,13 @@ class MessageRecipient {
/**
* The email address of the recipient
+ *
* @var string
*/
private string $email;
/**
* The human-readable name in the "To" field of the email
+ *
* @var string
*/
private string $niceName;
@@ -52,4 +54,4 @@ public function getEmail(): string {
public function getNiceName(): string {
return $this->niceName;
}
-}
\ No newline at end of file
+}
diff --git a/src/Model/Restriction.php b/src/Model/Restriction.php
index ad1fa630e..3d4032fba 100644
--- a/src/Model/Restriction.php
+++ b/src/Model/Restriction.php
@@ -11,7 +11,7 @@
/**
* Timeframe for restricting access to an item.
* This is the logical wrapper for the restriction custom post type.
- *
+ *
* Retrieve restrictions from the database using the @see \CommonsBooking\Repository\Restriction class.
* Additionally, all the public functions in this class can be called using Template Tags.
*
@@ -29,7 +29,6 @@ class Restriction extends CustomPost {
/**
* This means, that the item is still bookable, but that users will be notified about the restriction.
* This is used for example when the item is only available in a limited manner.
- *
*/
const TYPE_HINT = 'hint';
@@ -85,7 +84,7 @@ class Restriction extends CustomPost {
/**
* Returns post id, for array_unique.
- *
+ *
* @return string
*/
public function __toString(): string {
@@ -125,7 +124,7 @@ public function getStartDate(): int {
* Returns true if the restriction has an enddate.
*
* As far as I know, this is never used.
- *
+ *
* @return bool
*/
public function hasEnddate() {
@@ -134,7 +133,7 @@ public function hasEnddate() {
/**
* Returns end timestamp. Of no end-date is set it returns a date far in the future.
- *
+ *
* @return int Timestamp
*/
public function getEndDate(): int {
@@ -146,7 +145,7 @@ public function getEndDate(): int {
/**
* Returns true if restriction isn't active.
- *
+ *
* @return bool
*/
public function isOverBookable(): bool {
@@ -180,7 +179,7 @@ public function isLocked(): bool {
/**
* Returns restriction hint.
* The restriction hint is the little message explaining why the item is restricted.
- *
+ *
* @return mixed
*/
public function getHint() {
@@ -189,7 +188,7 @@ public function getHint() {
/**
* Returns nicely formatted start datetime.
- *
+ *
* @return string, if META_START is not null.
*/
public function getFormattedStartDateTime() {
@@ -212,7 +211,7 @@ public function getStartTimeDateTime(): DateTime {
/**
* Returns nicely formatted end datetime.
- *
+ *
* @return string, if META_END is not null.
*/
public function getFormattedEndDateTime() {
@@ -235,7 +234,7 @@ public function getEndDateDateTime(): DateTime {
/**
* Returns item name for the item that is restricted.
- *
+ *
* @return string
*/
public function getItemName(): string {
@@ -250,7 +249,7 @@ public function getItemName(): string {
/**
* Returns itemId for the item that is restricted.
- *
+ *
* @return mixed
*/
public function getItemId() {
@@ -259,7 +258,7 @@ public function getItemId() {
/**
* Returns location name for the location that the restricted item is in.
- *
+ *
* @return string
*/
public function getLocationName(): string {
@@ -274,7 +273,7 @@ public function getLocationName(): string {
/**
* Returns location id for the location that the restricted item is in.
- *
+ *
* @return mixed
*/
public function getLocationId() {
@@ -290,15 +289,14 @@ public function apply() {
if ( $this->isActive() ) {
$bookings = \CommonsBooking\Repository\Booking::getByRestriction( $this );
if ( $bookings ) {
- // send restriction mails to all affected bookings
- $this->sendRestrictionMails( $bookings );
+ // send restriction mails to all affected bookings
+ $this->sendRestrictionMails( $bookings );
$userDisabledBookingCancellationOnTotalBreakdown = \CommonsBooking\Settings\Settings::getOption( 'commonsbooking_options_restrictions', 'restrictions-no-cancel-on-total-breakdown' ) == 'on';
- // cancel all affected booking
+ // cancel all affected booking
if ( ! $userDisabledBookingCancellationOnTotalBreakdown && $this->isActive() && $this->getType() == self::TYPE_REPAIR ) {
$this->cancelBookings( $bookings );
}
-
}
}
@@ -346,19 +344,19 @@ protected function sendRestrictionMails( $bookings ) {
// get User ID from booking
$userId = $booking->getUserData()->ID;
- //checks if this is the first booking that is processed
+ // checks if this is the first booking that is processed
$firstMessage = ( $key === array_key_first( $bookings ) );
- // send restriction message for each booking
- $hintMail = new RestrictionMessage( $this, get_userdata( $userId ), $booking, $this->getType(),$firstMessage);
- $hintMail->triggerMail();
- }
- }
+ // send restriction message for each booking
+ $hintMail = new RestrictionMessage( $this, get_userdata( $userId ), $booking, $this->getType(), $firstMessage );
+ $hintMail->triggerMail();
+ }
+ }
/**
- * Returns true if a restriction status in cancelled.
+ * Returns true if a restriction status in cancelled.
* Maybe it would make more sense to create an isActive() method and use that instead.
- *
+ *
* @return bool
*/
public function isCancelled(): bool {
@@ -368,5 +366,4 @@ public function isCancelled(): bool {
return $this->canceled;
}
-
}
diff --git a/src/Model/Timeframe.php b/src/Model/Timeframe.php
index 1184ef552..f4c9dec4e 100644
--- a/src/Model/Timeframe.php
+++ b/src/Model/Timeframe.php
@@ -76,11 +76,13 @@ class Timeframe extends CustomPost {
/**
* null means the data is not fetched yet
+ *
* @var int|null
*/
private ?int $repetitionStart = null;
/**
* null means the data is not fetched yet, 0 means there is no end date
+ *
* @var int|null
*/
private ?int $repetitionEnd = null;
@@ -93,7 +95,7 @@ class Timeframe extends CustomPost {
* @return string
*/
public function formattedBookableDate(): string {
- return self::formatBookableDate( $this->getStartDate() , $this->getEndDate() );
+ return self::formatBookableDate( $this->getStartDate(), $this->getEndDate() );
}
/**
@@ -148,8 +150,7 @@ public function getTimeframeEndDate() {
if ( ! $endDate ) {
$this->repetitionEnd = 0;
- }
- else {
+ } else {
$this->repetitionEnd = $endDate;
}
@@ -187,7 +188,7 @@ public function getEndDate() {
*
* @return bool
*/
- public function isUserPrivileged(\WP_User $user = null): bool {
+ public function isUserPrivileged( \WP_User $user = null ): bool {
if ( ! $user ) {
$user = wp_get_current_user();
}
@@ -195,16 +196,16 @@ public function isUserPrivileged(\WP_User $user = null): bool {
return false;
}
- //these roles are always allowed to book
+ // these roles are always allowed to book
$privilegedRoles = [ 'administrator' ];
apply_filters( 'commonsbooking_privileged_roles', $privilegedRoles );
- if (! empty( array_intersect($privilegedRoles, $user->roles) ) ) {
+ if ( ! empty( array_intersect( $privilegedRoles, $user->roles ) ) ) {
return true;
}
- $itemAdmin = commonsbooking_isUserAllowedToEdit($this->getItem(),$user);
- $locationAdmin = commonsbooking_isUserAllowedToEdit($this->getLocation(),$user);
- return ($itemAdmin || $locationAdmin);
+ $itemAdmin = commonsbooking_isUserAllowedToEdit( $this->getItem(), $user );
+ $locationAdmin = commonsbooking_isUserAllowedToEdit( $this->getLocation(), $user );
+ return ( $itemAdmin || $locationAdmin );
}
/**
@@ -221,15 +222,14 @@ public function getLatestPossibleBookingDateTimestamp() {
$calculationBase = time();
// if meta-value not set we define a default value far in the future so that we count all possibly relevant timeframes
- $advanceBookingDays = $this->getMeta( Timeframe::META_TIMEFRAME_ADVANCE_BOOKING_DAYS ) ?: 365;
+ $advanceBookingDays = $this->getMeta( self::META_TIMEFRAME_ADVANCE_BOOKING_DAYS ) ?: 365;
// we subtract one day to reflect the current day in calculation
- $advanceBookingDays --;
+ --$advanceBookingDays;
$advanceBookingTime = strtotime( '+ ' . $advanceBookingDays . ' days', $calculationBase );
return $advanceBookingTime;
-
}
/**
@@ -237,8 +237,8 @@ public function getLatestPossibleBookingDateTimestamp() {
* This is used to display the end date of the timeframe in the frontend.
* This is mainly in use by the [cb_items] shortcode.
*
- * @param int $startDate
- * @param int $endDate
+ * @param int $startDate
+ * @param int $endDate
*
* @return string
*/
@@ -259,9 +259,9 @@ public static function formatBookableDate( int $startDate, int $endDate ): strin
if ( $startDate > $today ) { // start is in the future
$availableString = sprintf(
/* translators: %s = date in WordPress defined format */
- commonsbooking_sanitizeHTML( __( 'from %s', 'commonsbooking' ) ),
- $startDateFormatted
- );
+ commonsbooking_sanitizeHTML( __( 'from %s', 'commonsbooking' ) ),
+ $startDateFormatted
+ );
} else { // start has passed, no end date, probably a fixed location
$availableString = commonsbooking_sanitizeHTML( __( 'permanently', 'commonsbooking' ) );
}
@@ -269,16 +269,16 @@ public static function formatBookableDate( int $startDate, int $endDate ): strin
if ( $startDate > $today ) { // start is in the future, with an end date
$availableString = sprintf(
/* translators: %1$s = startdate, second %2$s = enddate in WordPress defined format */
- commonsbooking_sanitizeHTML( __( 'from %1$s until %2$s', 'commonsbooking' ) ),
+ commonsbooking_sanitizeHTML( __( 'from %1$s until %2$s', 'commonsbooking' ) ),
$startDateFormatted,
- $endDateFormatted
- );
+ $endDateFormatted
+ );
} else { // start has passed, with an end date
$availableString = sprintf(
/* translators: %s = enddate in WordPress defined format */
- commonsbooking_sanitizeHTML( __( 'until %s', 'commonsbooking' ) ),
- $endDateFormatted
- );
+ commonsbooking_sanitizeHTML( __( 'until %s', 'commonsbooking' ) ),
+ $endDateFormatted
+ );
}
}
@@ -297,8 +297,9 @@ public static function getDateFormat(): string {
/**
* Returns end (repetition) date and does not respect advance booking days setting.
* Use the getEndDate() function if you want to get the end date that respects the advance booking days setting.
- *
- * TODO this or getTimeFrameEndDate can be deprecated
+ *
+ * TODO this or getTimeFrameEndDate can be deprecated
+ *
* @return false|int
*/
public function getRawEndDate() {
@@ -307,10 +308,10 @@ public function getRawEndDate() {
/**
* Returns true, if the start date is earlier and the end date later than the latest possible booking date.
- *
+ *
* @return bool
*/
- public function isBookable() :bool {
+ public function isBookable(): bool {
$startDateTimestamp = $this->getStartDate();
$latestPossibleBookingDateTimestamp = $this->getLatestPossibleBookingDateTimestamp();
@@ -328,15 +329,16 @@ public function getTimeFormat(): string {
/**
* Validates if there can be booking codes created for this timeframe.
- *
+ *
* TODO: #507
+ *
* @return bool
*/
public function bookingCodesApplicable(): bool {
try {
return $this->getLocation() && $this->getItem() &&
- $this->getStartDate() && $this->usesBookingCodes() &&
- $this->getType() === \CommonsBooking\Wordpress\CustomPostType\Timeframe::BOOKABLE_ID;
+ $this->getStartDate() && $this->usesBookingCodes() &&
+ $this->getType() === \CommonsBooking\Wordpress\CustomPostType\Timeframe::BOOKABLE_ID;
} catch ( Exception $e ) {
return false;
}
@@ -368,6 +370,7 @@ public function getLocation(): ?Location {
* Returns the corresponding single location id for a timeframe.
* This will solely rely on the location id stored in the timeframe.
* If the location is deleted, this function will still return the old location id.
+ *
* @deprecated 2.9.0 This should not be used for Timeframes of type HOLIDAYS_ID.
*
* @return int|null
@@ -375,7 +378,7 @@ public function getLocation(): ?Location {
public function getLocationID(): ?int {
$locationId = $this->getMeta( self::META_LOCATION_ID );
if ( $locationId ) {
- return intval($locationId);
+ return intval( $locationId );
}
return null;
@@ -399,8 +402,7 @@ public function getLocations(): ?array {
}
return $locations;
- }
- else {
+ } else {
return [];
}
}
@@ -415,14 +417,12 @@ public function getLocations(): ?array {
public function getLocationIDs(): array {
$locationIds = $this->getMeta( self::META_LOCATION_ID_LIST );
if ( $locationIds ) {
- return array_map('intval', $locationIds);
- }
- else {
+ return array_map( 'intval', $locationIds );
+ } else {
$locationId = $this->getLocationID();
if ( $locationId ) {
return [ $locationId ];
- }
- else {
+ } else {
return [];
}
}
@@ -460,7 +460,7 @@ public function getItem(): ?Item {
public function getItemID(): ?int {
$itemId = $this->getMeta( self::META_ITEM_ID );
if ( $itemId ) {
- return intval($itemId);
+ return intval( $itemId );
}
return null;
@@ -484,8 +484,7 @@ public function getItems(): ?array {
}
return $items;
- }
- else {
+ } else {
return [];
}
}
@@ -500,14 +499,12 @@ public function getItems(): ?array {
public function getItemIDs(): array {
$itemIds = $this->getMeta( self::META_ITEM_ID_LIST );
if ( $itemIds ) {
- return array_map('intval', $itemIds);
- }
- else {
+ return array_map( 'intval', $itemIds );
+ } else {
$itemId = $this->getItemID();
if ( $itemId ) {
return [ $itemId ];
- }
- else {
+ } else {
return [];
}
}
@@ -523,10 +520,10 @@ public function getItemIDs(): array {
* Timeframe::REPAIR_ID
* Timeframe::BOOKING_ID
* Timeframe::BOOKING_CANCELLED_ID
- *
+ *
* @return mixed
*/
- public function getType() : int {
+ public function getType(): int {
return intval( $this->getMeta( 'type' ) );
}
@@ -538,60 +535,66 @@ public function getType() : int {
* Will check if the start- and end-date are set.
* Will check if there is no timeframe with the same item and location that overlaps with this timeframe.
*
- *Will throw a TimeframeInvalidException with error message
- *
- * @return true if valid
- * @throws \CommonsBooking\Exception\TimeframeInvalidException
- */
+ * Will throw a TimeframeInvalidException with error message
+ *
+ * @return true if valid
+ * @throws \CommonsBooking\Exception\TimeframeInvalidException
+ */
public function isValid(): bool {
if (
$this->getType() === \CommonsBooking\Wordpress\CustomPostType\Timeframe::BOOKABLE_ID
) {
try {
- $item = $this->getItem();
+ $item = $this->getItem();
$location = $this->getLocation();
- }
- catch ( \Exception $e ) {
- throw new TimeframeInvalidException(__(
+ } catch ( \Exception $e ) {
+ throw new TimeframeInvalidException(
+ __(
'Could not get item or location. Please set a valid item and location.',
- 'commonsbooking')
+ 'commonsbooking'
+ )
);
}
if ( ! $item || ! $location ) {
// if location or item is missing
- throw new TimeframeInvalidException(__(
+ throw new TimeframeInvalidException(
+ __(
'Item or location is missing. Please set item and location.',
- 'commonsbooking' )
+ 'commonsbooking'
+ )
);
}
- //a timeframe with a manual repetition does not need a start date.
- //start- and enddate are automatically set upon saving the post
- if ($this->getRepetition() == 'manual') {
+ // a timeframe with a manual repetition does not need a start date.
+ // start- and enddate are automatically set upon saving the post
+ if ( $this->getRepetition() == 'manual' ) {
$manual_selection_dates = $this->getManualSelectionDates();
- if ( empty( $manual_selection_dates ) ){
- throw new TimeframeInvalidException(__(
+ if ( empty( $manual_selection_dates ) ) {
+ throw new TimeframeInvalidException(
+ __(
'No dates selected. Please select at least one date.',
- 'commonsbooking' )
+ 'commonsbooking'
+ )
);
}
- //make sure that there are no duplicate dates
- $unique_dates = array_unique($manual_selection_dates);
- if ( count($unique_dates) != count($manual_selection_dates) ){
- throw new TimeframeInvalidException(__(
+ // make sure that there are no duplicate dates
+ $unique_dates = array_unique( $manual_selection_dates );
+ if ( count( $unique_dates ) != count( $manual_selection_dates ) ) {
+ throw new TimeframeInvalidException(
+ __(
'The same date was selected multiple times. Please select each date only once.',
- 'commonsbooking' )
+ 'commonsbooking'
+ )
);
}
- }
- else {
- if ( ! $this->getStartDate() ) {
+ } elseif ( ! $this->getStartDate() ) {
// If there is at least one mandatory parameter missing, we cannot save/publish timeframe.
- throw new TimeframeInvalidException( __(
+ throw new TimeframeInvalidException(
+ __(
'Startdate is missing. Please enter a start date to publish this timeframe.',
- 'commonsbooking' )
+ 'commonsbooking'
+ )
);
- }
}
if (
@@ -600,25 +603,31 @@ public function isValid(): bool {
$postId = $this->ID;
if ( $this->getStartTime() && ! $this->getEndTime() && ! $this->isFullDay() ) {
- throw new TimeframeInvalidException( __(
+ throw new TimeframeInvalidException(
+ __(
'A pickup time but no return time has been set. Please set the return time.',
- 'commonsbooking' )
+ 'commonsbooking'
+ )
);
}
- //check if end date is before start date
- if (($this->getStartDate() && $this->getEndDate()) && ($this->getStartDate() > $this->getTimeframeEndDate())){
- throw new TimeframeInvalidException( __(
+ // check if end date is before start date
+ if ( ( $this->getStartDate() && $this->getEndDate() ) && ( $this->getStartDate() > $this->getTimeframeEndDate() ) ) {
+ throw new TimeframeInvalidException(
+ __(
'End date is before start date. Please set a valid end date.',
- 'commonsbooking' )
+ 'commonsbooking'
+ )
);
}
- //check if start-time and end-time are the same
- if (($this->getStartTime() && $this->getEndTime()) && ($this->getStartTime() == $this->getEndTime())){
- throw new TimeframeInvalidException( __(
+ // check if start-time and end-time are the same
+ if ( ( $this->getStartTime() && $this->getEndTime() ) && ( $this->getStartTime() == $this->getEndTime() ) ) {
+ throw new TimeframeInvalidException(
+ __(
'The start- and end-time of the timeframe can not be the same. Please check the full-day checkbox if you want users to be able to book the full day.',
- 'commonsbooking' )
+ 'commonsbooking'
+ )
);
}
@@ -634,9 +643,8 @@ public function isValid(): bool {
// check if timeframes of other locations overlap in date and return error message if true
foreach ( $sameItemTimeframes as $sameItemTimeframe ) {
-
if ( $location != $sameItemTimeframe->getLocation()
- && $this->hasTimeframeDateOverlap( $sameItemTimeframe )
+ && $this->hasTimeframeDateOverlap( $sameItemTimeframe )
) {
throw new TimeframeInvalidException(
/* translators: %1$s = timeframe-ID, %2$s is timeframe post_title */
@@ -675,12 +683,12 @@ function ( $timeframe ) use ( $postId ) {
} catch ( OverlappingException $e ) {
throw new TimeframeInvalidException(
$e->getMessage() .
- sprintf(
- /* translators: first %s = timeframe-ID, second %s is timeframe post_title */
- __('See overlapping timeframe ID: %1$s %2$s', 'commonsbooking'),
- '' . $otherTimeframe->ID . '',
- '' . $otherTimeframe->post_title . ''
- )
+ sprintf(
+ /* translators: first %s = timeframe-ID, second %s is timeframe post_title */
+ __( 'See overlapping timeframe ID: %1$s %2$s', 'commonsbooking' ),
+ '' . $otherTimeframe->ID . '',
+ '' . $otherTimeframe->post_title . ''
+ )
);
}
}
@@ -691,7 +699,7 @@ function ( $timeframe ) use ( $postId ) {
/**
* Returns start time for day-slots.
- *
+ *
* @return mixed
*/
public function getStartTime() {
@@ -700,6 +708,7 @@ public function getStartTime() {
/**
* Returns end time for day-slots.
+ *
* @return mixed
*/
public function getEndTime() {
@@ -709,9 +718,10 @@ public function getEndTime() {
/**
* Returns true if timeframe is spanning over the whole day.
* This means that this is not an hourly timeframe or a slot timeframe.
+ *
* @return bool
*/
- public function isFullDay() : bool {
+ public function isFullDay(): bool {
return $this->getMeta( 'full-day' ) === 'on';
}
@@ -724,32 +734,32 @@ public function isFullDay() : bool {
*/
public function hasTimeframeDateOverlap( Timeframe $otherTimeframe ): bool {
- // Check if both timeframes have no end date or if both are ongoing
- if ( ! $this->getTimeframeEndDate() && ! $otherTimeframe->getTimeframeEndDate() ) {
- return true;
- }
-
- // Check if only one timeframe has an end date
- if ( $this->getTimeframeEndDate() && ! $otherTimeframe->getTimeframeEndDate() ) {
- return ( $otherTimeframe->getStartDate() <= $this->getTimeframeEndDate() && $otherTimeframe->getStartDate() >= $this->getStartDate() );
- }
-
- if ( ! $this->getTimeframeEndDate() && $otherTimeframe->getTimeframeEndDate() ) {
- return ( $otherTimeframe->getTimeframeEndDate() > $this->getStartDate() );
- }
-
- // Check if both timeframes have an end date
- if ( $this->getTimeframeEndDate() && $otherTimeframe->getTimeframeEndDate() ) {
- return (
- // Check if the end date of the first timeframe is within the second timeframe
- ( $this->getTimeframeEndDate() >= $otherTimeframe->getStartDate() && $this->getTimeframeEndDate() <= $otherTimeframe->getTimeframeEndDate() ) ||
- // Check if the end date of the second timeframe is within the first timeframe
- ( $otherTimeframe->getTimeframeEndDate() >= $this->getStartDate() && $otherTimeframe->getTimeframeEndDate() <= $this->getTimeframeEndDate() )
- );
- }
+ // Check if both timeframes have no end date or if both are ongoing
+ if ( ! $this->getTimeframeEndDate() && ! $otherTimeframe->getTimeframeEndDate() ) {
+ return true;
+ }
+
+ // Check if only one timeframe has an end date
+ if ( $this->getTimeframeEndDate() && ! $otherTimeframe->getTimeframeEndDate() ) {
+ return ( $otherTimeframe->getStartDate() <= $this->getTimeframeEndDate() && $otherTimeframe->getStartDate() >= $this->getStartDate() );
+ }
+
+ if ( ! $this->getTimeframeEndDate() && $otherTimeframe->getTimeframeEndDate() ) {
+ return ( $otherTimeframe->getTimeframeEndDate() > $this->getStartDate() );
+ }
+
+ // Check if both timeframes have an end date
+ if ( $this->getTimeframeEndDate() && $otherTimeframe->getTimeframeEndDate() ) {
+ return (
+ // Check if the end date of the first timeframe is within the second timeframe
+ ( $this->getTimeframeEndDate() >= $otherTimeframe->getStartDate() && $this->getTimeframeEndDate() <= $otherTimeframe->getTimeframeEndDate() ) ||
+ // Check if the end date of the second timeframe is within the first timeframe
+ ( $otherTimeframe->getTimeframeEndDate() >= $this->getStartDate() && $otherTimeframe->getTimeframeEndDate() <= $this->getTimeframeEndDate() )
+ );
+ }
// If none of the above conditions are true, there is no overlap
- //TODO: When does this condition ever apply?
+ // TODO: When does this condition ever apply?
return false;
}
@@ -759,15 +769,15 @@ public function hasTimeframeDateOverlap( Timeframe $otherTimeframe ): bool {
*
* TODO: Refactor to return true if timeframes overlap and false if not. Throw exception in calling function.
*
- * @uses Timeframe::hasTimeframeDateOverlap()
+ * @uses Timeframe::hasTimeframeDateOverlap()
* @uses Timeframe::hasTimeframeTimeOverlap()
- *
+ *
* @param Timeframe $otherTimeframe
*
* @return false
* @throws OverlappingException
*/
- public function overlaps (Timeframe $otherTimeframe) : bool {
+ public function overlaps( Timeframe $otherTimeframe ): bool {
if (
$this->hasTimeframeDateOverlap( $otherTimeframe )
) {
@@ -778,23 +788,23 @@ public function overlaps (Timeframe $otherTimeframe) : bool {
);
}
- //timeframes that don't overlap in time range are not overlapping
- if (! $this->hasTimeframeTimeOverlap( $otherTimeframe) ) {
+ // timeframes that don't overlap in time range are not overlapping
+ if ( ! $this->hasTimeframeTimeOverlap( $otherTimeframe ) ) {
return false;
}
$otherTimeframeRepetition = $otherTimeframe->getRepetition();
$repetition = $this->getRepetition();
- //One of the timeframes takes up the full day and therefore none of the dates can overlap
- //at this stage there is already overlap in the date range and time range, therefore we must check if the repetitions create an overlap
+ // One of the timeframes takes up the full day and therefore none of the dates can overlap
+ // at this stage there is already overlap in the date range and time range, therefore we must check if the repetitions create an overlap
if ( $repetition === 'd' || $otherTimeframeRepetition === 'd' ) {
throw new OverlappingException(
__( 'Daily repeated time periods are not allowed to overlap.', 'commonsbooking' )
);
}
- //we concatenate the repetitions to make the switch statement more readable
+ // we concatenate the repetitions to make the switch statement more readable
switch ( $repetition . '|' . $otherTimeframeRepetition ) {
case 'w|w':
if ( $this->getWeekDays() && $otherTimeframe->getWeekDays() ) {
@@ -841,6 +851,7 @@ public function overlaps (Timeframe $otherTimeframe) : bool {
/**
* Checks if timeframes are overlapping in weekly slot and slot with manual repetition.
+ *
* @param $weeklyTimeframe
* @param $manualTimeframe
*
@@ -853,12 +864,12 @@ private static function hasWeeklyManualOverlap( $weeklyTimeframe, $manualTimefra
$manualTimeframe->getManualSelectionDates()
)
);
- //we have to make the sunday a 7 instead of 0 in order to detect overlaps with our other array correctly
+ // we have to make the sunday a 7 instead of 0 in order to detect overlaps with our other array correctly
$manualSelectionWeekdays = array_map(
fn ( $weekday ) => $weekday == 0 ? 7 : $weekday,
$manualSelectionWeekdays
);
- $weekDaysOverlap = array_intersect( $weeklyTimeframe->getWeekDays(), $manualSelectionWeekdays ) ;
+ $weekDaysOverlap = array_intersect( $weeklyTimeframe->getWeekDays(), $manualSelectionWeekdays );
if ( ! empty( $weekDaysOverlap ) ) {
return true;
}
@@ -871,12 +882,12 @@ private static function hasWeeklyManualOverlap( $weeklyTimeframe, $manualTimefra
*
* @return void
*/
- public function updatePostMetaStartAndEndDate() : void {
- if ($this->getRepetition() == 'manual') {
- $timestamps = array_map('strtotime', $this->getManualSelectionDates());
- asort($timestamps);
- update_post_meta( $this->ID, \CommonsBooking\Model\Timeframe::REPETITION_START, reset($timestamps) );
- update_post_meta( $this->ID, \CommonsBooking\Model\Timeframe::REPETITION_END, end($timestamps) );
+ public function updatePostMetaStartAndEndDate(): void {
+ if ( $this->getRepetition() == 'manual' ) {
+ $timestamps = array_map( 'strtotime', $this->getManualSelectionDates() );
+ asort( $timestamps );
+ update_post_meta( $this->ID, self::REPETITION_START, reset( $timestamps ) );
+ update_post_meta( $this->ID, self::REPETITION_END, end( $timestamps ) );
}
}
@@ -886,67 +897,66 @@ public function updatePostMetaStartAndEndDate() : void {
* The timeframe grid describes if either the full slot is bookable or if the timeframe is bookable hourly.
* 0 = slot
* 1 = hourly
- *
+ *
* @return mixed
*/
public function getGrid(): int {
- return intval($this->getMeta( 'grid' ));
+ return intval( $this->getMeta( 'grid' ) );
}
/**
* Checks if timeframes are overlapping in time ranges or daily slots.
- *
+ *
* Use {@see Timeframe::overlaps()} if you want to compute full-overlap between two timeframes.
- *
+ *
* @param Timeframe $otherTimeframe
*
* @return bool If start-time and end-time overlaps, regardless of overlapping start-date and end-date.
*/
+ public function hasTimeframeTimeOverlap( Timeframe $otherTimeframe ) {
+ // Check if both timeframes have an end time, if not, there is no overlap
+ if ( ! strtotime( $this->getEndTime() ) && ! strtotime( $otherTimeframe->getEndTime() ) ) {
+ return true;
+ }
+
+ // Check if only timeframe1 has an end time and if it overlaps with the other timeframe
+ if ( strtotime( $this->getEndTime() ) && ! strtotime( $otherTimeframe->getEndTime() )
+ && strtotime( $otherTimeframe->getStartTime() ) <= strtotime( $this->getEndTime() )
+ && strtotime( $otherTimeframe->getStartTime() ) >= strtotime( $this->getStartTime() ) ) {
+ return true;
+ }
- public function hasTimeframeTimeOverlap( Timeframe $otherTimeframe ) {
- // Check if both timeframes have an end time, if not, there is no overlap
- if ( ! strtotime( $this->getEndTime() ) && ! strtotime( $otherTimeframe->getEndTime() ) ) {
- return true;
- }
-
- // Check if only timeframe1 has an end time and if it overlaps with the other timeframe
- if ( strtotime( $this->getEndTime() ) && ! strtotime( $otherTimeframe->getEndTime() )
- && strtotime( $otherTimeframe->getStartTime() ) <= strtotime( $this->getEndTime() )
- && strtotime( $otherTimeframe->getStartTime() ) >= strtotime( $this->getStartTime() ) ) {
- return true;
- }
-
- // Check if only timeframe2 has an end time and if it overlaps with the other timeframe
- if ( ! strtotime( $this->getEndTime() ) && strtotime( $otherTimeframe->getEndTime() )
- && strtotime( $otherTimeframe->getEndTime() ) > strtotime( $this->getStartTime() ) ) {
- return true;
- }
-
- // Check if both timeframes have an end time and if they overlap
- if ( strtotime( $this->getEndTime() ) && strtotime( $otherTimeframe->getEndTime() )
- && ( ( strtotime( $this->getEndTime() ) > strtotime( $otherTimeframe->getStartTime() )
- && strtotime( $this->getEndTime() ) < strtotime( $otherTimeframe->getEndTime() ) )
- || ( strtotime( $otherTimeframe->getEndTime() ) > strtotime( $this->getStartTime() )
- && strtotime( $otherTimeframe->getEndTime() ) < strtotime( $this->getEndTime() ) ) ) ) {
- return true;
- }
-
- //Check if both timeframes have the same start and end time
- if ( strtotime( $this->getEndTime() ) && strtotime( $otherTimeframe->getEndTime() )
+ // Check if only timeframe2 has an end time and if it overlaps with the other timeframe
+ if ( ! strtotime( $this->getEndTime() ) && strtotime( $otherTimeframe->getEndTime() )
+ && strtotime( $otherTimeframe->getEndTime() ) > strtotime( $this->getStartTime() ) ) {
+ return true;
+ }
+
+ // Check if both timeframes have an end time and if they overlap
+ if ( strtotime( $this->getEndTime() ) && strtotime( $otherTimeframe->getEndTime() )
+ && ( ( strtotime( $this->getEndTime() ) > strtotime( $otherTimeframe->getStartTime() )
+ && strtotime( $this->getEndTime() ) < strtotime( $otherTimeframe->getEndTime() ) )
+ || ( strtotime( $otherTimeframe->getEndTime() ) > strtotime( $this->getStartTime() )
+ && strtotime( $otherTimeframe->getEndTime() ) < strtotime( $this->getEndTime() ) ) ) ) {
+ return true;
+ }
+
+ // Check if both timeframes have the same start and end time
+ if ( strtotime( $this->getEndTime() ) && strtotime( $otherTimeframe->getEndTime() )
&& strtotime( $this->getEndTime() ) === strtotime( $otherTimeframe->getEndTime() )
&& strtotime( $this->getStartTime() ) === strtotime( $otherTimeframe->getStartTime() ) ) {
return true;
}
- // If none of the above conditions are true, there is no overlap
- return false;
- }
+ // If none of the above conditions are true, there is no overlap
+ return false;
+ }
/**
* Returns weekdays array.
* This means what weekdays are selected for this timeframe.
* This only makes sense when the grid is repeating weekly.
- *
+ *
* @return mixed
*/
public function getWeekDays() {
@@ -957,20 +967,20 @@ public function getWeekDays() {
* Returns grid size in hours.
* This means the length of the individual bookable slots.
* For example if the grid is 2, the bookable slots are 2 hours long.
- *
+ *
* @return int|null
*/
public function getGridSize(): ?int {
if ( $this->isFullDay() ) {
return 24;
} elseif ( $this->getGrid() === 0 ) {
- //this is for slot timeframes
+ // this is for slot timeframes
$startTime = strtotime( $this->getMeta( 'start-time' ) );
$endTime = strtotime( $this->getMeta( 'end-time' ) );
return intval( round( abs( $endTime - $startTime ) / 3600, 2 ) );
} else {
- //this is for hourly timeframes, the grid will be 1, because each hour is bookable
+ // this is for hourly timeframes, the grid will be 1, because each hour is bookable
return intval( $this->getGrid() );
}
}
@@ -978,6 +988,7 @@ public function getGridSize(): ?int {
/**
* Gets an array of dates that were manually selected by the user.
* The dates are in the format YYYY-MM-DD
+ *
* @return String[]
*/
public function getManualSelectionDates(): array {
@@ -993,11 +1004,10 @@ public function getManualSelectionDates(): array {
/**
* Returns true if booking codes shall be shown in frontend.
- *
+ *
* @return bool
*/
- public function showBookingCodes() : bool
- {
+ public function showBookingCodes(): bool {
return $this->getMeta( self::META_SHOW_BOOKING_CODES ) === 'on';
}
@@ -1067,7 +1077,7 @@ public function getStartTimeDateTime(): ?DateTime {
if ( ! $startDateString ) {
return null;
}
- $startDate = Wordpress::getUTCDateTimeByTimestamp( $startDateString );
+ $startDate = Wordpress::getUTCDateTimeByTimestamp( $startDateString );
if ( $startTimeString ) {
$startTime = Wordpress::getUTCDateTimeByTimestamp( strtotime( $startTimeString ) );
$startDate->setTime( $startTime->format( 'H' ), $startTime->format( 'i' ) );
@@ -1087,7 +1097,7 @@ public function getStartTimeDateTime(): ?DateTime {
*/
public function getEndDateDateTime(): ?DateTime {
$endDateString = intval( $this->getMeta( self::REPETITION_END ) );
- if (! $endDateString ){
+ if ( ! $endDateString ) {
return null;
}
return Wordpress::getUTCDateTimeByTimestamp( $endDateString );
@@ -1099,12 +1109,13 @@ public function getEndDateDateTime(): ?DateTime {
* We need to do this weird conversion because the end date is stored as a local timestamp.
*
* TODO: Can throw uncaught exception.
+ *
* @return DateTime
* @throws Exception
*/
public function getUTCEndDateDateTime(): ?DateTime {
$endDateString = intval( $this->getMeta( self::REPETITION_END ) );
- if (! $endDateString ){
+ if ( ! $endDateString ) {
return null;
}
if ( $this->isFullDay() ) {
@@ -1169,25 +1180,25 @@ public function isLocked(): bool {
*/
public function getAdmins(): array {
$location = $this->getLocation();
- if (! empty($location)) {
+ if ( ! empty( $location ) ) {
$locationAdminIds = $location->getAdmins();
}
$item = $this->getItem();
- if (! empty($item)) {
+ if ( ! empty( $item ) ) {
$itemAdminIds = $item->getAdmins();
}
- if ( empty($locationAdminIds) && empty($itemAdminIds) ) {
+ if ( empty( $locationAdminIds ) && empty( $itemAdminIds ) ) {
return [];
}
- if ( empty($locationAdminIds) ) {
+ if ( empty( $locationAdminIds ) ) {
return $itemAdminIds;
}
- if ( empty($itemAdminIds) ) {
+ if ( empty( $itemAdminIds ) ) {
return $locationAdminIds;
}
- return array_unique( array_merge ($locationAdminIds,$itemAdminIds) );
+ return array_unique( array_merge( $locationAdminIds, $itemAdminIds ) );
}
/**
@@ -1199,26 +1210,25 @@ public function getAdmins(): array {
* y = yearly
* manual = manual selection of dates
* norep = no repetition
- *
+ *
* @return mixed
*/
public function getRepetition() {
return $this->getMeta( self::META_REPETITION );
}
- /**
- * Returns first bookable day based on the defined booking startday offset in timeframe
- *
- * @return string date format Y-m-d
- */
- public function getFirstBookableDay() {
- $offset = $this->getFieldValue( Timeframe::META_BOOKING_START_DAY_OFFSET ) ?: 0;
- $today = current_datetime()->format('Y-m-d');
- return date( 'Y-m-d', strtotime( $today . ' + ' . $offset . ' days' ) );
-
- }
+ /**
+ * Returns first bookable day based on the defined booking startday offset in timeframe
+ *
+ * @return string date format Y-m-d
+ */
+ public function getFirstBookableDay() {
+ $offset = $this->getFieldValue( self::META_BOOKING_START_DAY_OFFSET ) ?: 0;
+ $today = current_datetime()->format( 'Y-m-d' );
+ return date( 'Y-m-d', strtotime( $today . ' + ' . $offset . ' days' ) );
+ }
- public function getMaxDays():int{
- return $this->getMeta(self::META_MAX_DAYS);
+ public function getMaxDays(): int {
+ return $this->getMeta( self::META_MAX_DAYS );
}
}
diff --git a/src/Model/Week.php b/src/Model/Week.php
index 8e714ca77..8c38bb445 100644
--- a/src/Model/Week.php
+++ b/src/Model/Week.php
@@ -21,6 +21,7 @@ class Week {
/**
* Day in the year to start the week from (0-365)
+ *
* @var int
*/
protected $dayOfYear;
@@ -50,9 +51,9 @@ class Week {
*
* @param $year
* @param $dayOfYear
- * @param array $locations
- * @param array $items
- * @param array $types
+ * @param array $locations
+ * @param array $items
+ * @param array $types
* @param Timeframe[] $possibleTimeframes Timeframes that might be relevant for this week, need to be filtered.
*/
public function __construct( $year, $dayOfYear, array $locations = [], array $items = [], array $types = [], array $possibleTimeframes = [] ) {
@@ -93,7 +94,7 @@ public function getDays() {
$dto = Wordpress::getUTCDateTimeByTimestamp( $timestamp );
$days = array();
- for ( $i = 0; $i < 7; $i ++ ) {
+ for ( $i = 0; $i < 7; $i++ ) {
$dayDate = $dto->format( 'Y-m-d' );
$days[] = new Day( $dayDate, $this->locations, $this->items, $this->types, $this->timeframes ?: [] );
$dayOfWeek = $dto->format( 'w' );
@@ -113,6 +114,7 @@ public function getDays() {
/**
* Will return the timestamp of the first second of the given week.
+ *
* @return int
*/
public function getStartTimestamp(): int {
@@ -124,6 +126,7 @@ public function getStartTimestamp(): int {
/**
* Will return the timestamp of the last second of the given week.
+ *
* @return int
*/
public function getEndTimestamp(): int {
@@ -140,5 +143,4 @@ public function getEndTimestamp(): int {
private function getYearTimestamp() {
return mktime( 0, 0, 0, 1, 1, $this->year );
}
-
}
diff --git a/src/Plugin.php b/src/Plugin.php
index 6e0ec7203..b9839abfc 100644
--- a/src/Plugin.php
+++ b/src/Plugin.php
@@ -39,7 +39,7 @@ class Plugin {
/**
* CB-Manager id.
- *
+ *
* @var string
*/
public static $CB_MANAGER_ID = 'cb_manager';
@@ -82,17 +82,18 @@ public static function deactivation() {
* This is why we now assign the CB-Manager the capabilities of the admin, the supposedly correct behaviour is commented out below.
*
* Therefore, this function does not work differently, it just has the same behaviour when plugin is activated through wp-cli or through the admin interface.
+ *
* @return void
*/
public static function addCPTRoleCaps() {
- //admins are allowed to see all custom post types
- $adminAllowedCPT = self::getCustomPostTypes();
+ // admins are allowed to see all custom post types
+ $adminAllowedCPT = self::getCustomPostTypes();
$CBManagerAllowedCPT = self::getCBManagerCustomPostTypes();
// Add capabilities for user roles
foreach ( $adminAllowedCPT as $customPostType ) {
self::addRoleCaps( $customPostType::$postType, 'administrator' );
- //assign all capabilities of admin to CB-Manager (see comment above)
- //We deliberately don't use the getManagerRoles from the UserRepository here, because the custom roles should be able to define their own permissions
+ // assign all capabilities of admin to CB-Manager (see comment above)
+ // We deliberately don't use the getManagerRoles from the UserRepository here, because the custom roles should be able to define their own permissions
self::addRoleCaps( $customPostType::$postType, self::$CB_MANAGER_ID );
}
/*
@@ -104,13 +105,13 @@ public static function addCPTRoleCaps() {
/**
* Returns needed roles and caps for specific roles
- *
+ *
* @return \bool[][]
*/
- public static function getRoleCapMapping( $roleName = null) {
+ public static function getRoleCapMapping( $roleName = null ) {
if ( $roleName === null ) {
return [
- //We deliberately don't use the getManagerRoles from the UserRepository here, because the custom roles should be able to define their own permissions
+ // We deliberately don't use the getManagerRoles from the UserRepository here, because the custom roles should be able to define their own permissions
self::$CB_MANAGER_ID => [
'read' => true,
'manage_' . COMMONSBOOKING_PLUGIN_SLUG => true,
@@ -121,11 +122,10 @@ public static function getRoleCapMapping( $roleName = null) {
'manage_' . COMMONSBOOKING_PLUGIN_SLUG => true,
],
];
- }
- else {
+ } else {
$roleCapMapping = self::getRoleCapMapping();
return [
- $roleName => $roleCapMapping[$roleName]
+ $roleName => $roleCapMapping[ $roleName ],
];
}
}
@@ -139,7 +139,7 @@ public static function addCustomUserRoles() {
if ( ! $role ) {
$role = add_role(
$roleName,
- // TODO we should set a translatable role display name - for now its not defined at any place
+ // TODO we should set a translatable role display name - for now its not defined at any place
$roleName
);
}
@@ -156,6 +156,7 @@ public static function addCustomUserRoles() {
* All CustomPostType classes extend the CustomPostType class and must be registered in this method.
* When defining a CustomPostType, you must also define a model for it, which extends the CustomPost class.
* The existence of a model is checked in the @see PluginTest::testGetCustomPostTypes() test.
+ *
* @return CustomPostType[]
*/
public static function getCustomPostTypes(): array {
@@ -171,13 +172,14 @@ public static function getCustomPostTypes(): array {
/**
* Tests if a given post belongs to our CPTs
+ *
* @param $post int|\WP_Post - post id or post object
*
* @return bool
*/
- public static function isPostCustomPostType($post): bool {
- if (is_int($post)) {
- $post = get_post($post);
+ public static function isPostCustomPostType( $post ): bool {
+ if ( is_int( $post ) ) {
+ $post = get_post( $post );
}
if ( empty( $post ) ) {
@@ -185,12 +187,12 @@ public static function isPostCustomPostType($post): bool {
}
$validPostTypes = self::getCustomPostTypesLabels();
- return in_array($post->post_type,$validPostTypes);
+ return in_array( $post->post_type, $validPostTypes );
}
/**
* Returns only custom post types, which are allowed for cb manager
- *
+ *
* @return array
*/
public static function getCBManagerCustomPostTypes(): array {
@@ -257,7 +259,7 @@ public static function admin_init() {
flush_rewrite_rules();
- //checks if all the booking rules are in the correct format, complain if not
+ // checks if all the booking rules are in the correct format, complain if not
BookingRuleApplied::validateRules();
set_transient( 'commonsbooking_options_saved', 0 );
}
@@ -323,7 +325,7 @@ public static function addMenuPages() {
''
);
- //Add menu item for mass operations
+ // Add menu item for mass operations
add_submenu_page(
'cb-dashboard',
esc_html__( 'Mass Operations', 'commonsbooking' ),
@@ -338,20 +340,20 @@ public static function addMenuPages() {
/**
* Handles the validation of booking forms. We customize the transient so that only the user that is supposed to see the transient will
* actually see it.
+ *
* @return void
*/
public static function handleBookingForms(): void {
try {
\CommonsBooking\Wordpress\CustomPostType\Booking::handleFormRequest();
- }
- catch ( BookingDeniedException $e ) {
+ } catch ( BookingDeniedException $e ) {
set_transient(
\CommonsBooking\Wordpress\CustomPostType\Booking::ERROR_TYPE . '-' . get_current_user_id(),
$e->getMessage(),
- 30 //Expires very quickly, so that outdated messsages will not be shown to the user
+ 30 // Expires very quickly, so that outdated messsages will not be shown to the user
);
$targetUrl = $e->getRedirectUrl();
- if ( $targetUrl) {
+ if ( $targetUrl ) {
header( 'Location: ' . $targetUrl );
exit();
}
@@ -398,7 +400,7 @@ public static function filterAdminBodyClass( $classes ) {
public static function registerCustomPostTypes() {
foreach ( self::getCustomPostTypes() as $customPostType ) {
$cptArgs = $customPostType->getArgs();
- //make export possible when using WP_DEBUG, this allows us to use the export feature for creating new E2E tests
+ // make export possible when using WP_DEBUG, this allows us to use the export feature for creating new E2E tests
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
$cptArgs['can_export'] = true;
}
@@ -417,18 +419,18 @@ public static function registerPostStates() {
}
}
- /**
+ /**
* Registers category taxonomy for Custom Post Type Item
- *
- * TODO: This can probably be re-factored to the more generic CustomPostType
- *
+ *
+ * TODO: This can probably be re-factored to the more generic CustomPostType
+ *
* @return void
*/
public static function registerItemTaxonomy() {
$customPostType = Item::getPostType();
- $taxonomy = $customPostType . 's_category';
+ $taxonomy = $customPostType . 's_category';
- $result = register_taxonomy(
+ $result = register_taxonomy(
$taxonomy,
$customPostType,
array(
@@ -437,7 +439,7 @@ public static function registerItemTaxonomy() {
'hierarchical' => true,
'show_in_rest' => true,
'public' => true,
- 'show_admin_column' => true
+ 'show_admin_column' => true,
)
);
@@ -446,16 +448,17 @@ public static function registerItemTaxonomy() {
wp_die( $result->get_error_message() );
}
- //hook the term updates to the item post type function. This only runs when a term is updated but that is enough. When a term is added, the post is saved and therefore the other hook is triggered which also runs the same function.
+ // hook the term updates to the item post type function. This only runs when a term is updated but that is enough. When a term is added, the post is saved and therefore the other hook is triggered which also runs the same function.
add_action( 'saved_' . $taxonomy, array( 'CommonsBooking\Wordpress\CustomPostType\Item', 'termChange' ), 10, 3 );
add_action( 'delete_' . $taxonomy, array( 'CommonsBooking\Wordpress\CustomPostType\Item', 'termChange' ), 10, 3 );
- //hook this for later, if we run it now, it would fail
+ // hook this for later, if we run it now, it would fail
add_action( 'cmb2_admin_init', array( self::class, 'registerItemTaxonomyMetaboxes' ) );
}
/**
* Add custom label for item categories that will be displayed in the map filter groups.
+ *
* @return void
*/
public static function registerItemTaxonomyMetaboxes() {
@@ -483,14 +486,14 @@ public static function registerItemTaxonomyMetaboxes() {
/**
* Registers category taxonomy for Custom Post Type Location
- *
+ *
* @return void
*/
public static function registerLocationTaxonomy() {
$customPostType = Location::getPostType();
- $taxonomy = $customPostType . 's_category';
+ $taxonomy = $customPostType . 's_category';
- $result = register_taxonomy(
+ $result = register_taxonomy(
$taxonomy,
$customPostType,
array(
@@ -498,7 +501,7 @@ public static function registerLocationTaxonomy() {
'rewrite' => array( 'slug' => $customPostType . '-cat' ),
'hierarchical' => true,
'show_in_rest' => true,
- 'show_admin_column' => true
+ 'show_admin_column' => true,
)
);
@@ -507,7 +510,7 @@ public static function registerLocationTaxonomy() {
wp_die( $result->get_error_message() );
}
- //hook the term updates to the location post type function. This only runs when a term is updated but that is enough. When a term is added, the post is saved and therefore the other hook is triggered which also runs the same function.
+ // hook the term updates to the location post type function. This only runs when a term is updated but that is enough. When a term is added, the post is saved and therefore the other hook is triggered which also runs the same function.
add_action( 'saved_' . $taxonomy, array( 'CommonsBooking\Wordpress\CustomPostType\Location', 'termChange' ), 10, 3 );
add_action( 'delete_' . $taxonomy, array( 'CommonsBooking\Wordpress\CustomPostType\Location', 'termChange' ), 10, 3 );
}
@@ -522,7 +525,7 @@ public static function renderError() {
Model\Timeframe::ORPHANED_TYPE,
BookingCode::ERROR_TYPE,
OptionsTab::ERROR_TYPE,
- Model\Booking::ERROR_TYPE,
+ Model\Booking::ERROR_TYPE,
];
foreach ( $errorTypes as $errorType ) {
@@ -578,25 +581,25 @@ public static function registerAdminOptions() {
public static function registerScriptsAndStyles() {
$base = COMMONSBOOKING_PLUGIN_ASSETS_URL . 'packaged/';
- $version_file_path = COMMONSBOOKING_PLUGIN_DIR . 'assets/packaged/dist.json';
- $version_file_content = file_get_contents($version_file_path);
- $versions = json_decode($version_file_content, true);
- if (JSON_ERROR_NONE !== json_last_error()) {
- trigger_error("Unable to parse commonsbooking asset version file in $version_file_path.");
+ $version_file_path = COMMONSBOOKING_PLUGIN_DIR . 'assets/packaged/dist.json';
+ $version_file_content = file_get_contents( $version_file_path );
+ $versions = json_decode( $version_file_content, true );
+ if ( JSON_ERROR_NONE !== json_last_error() ) {
+ trigger_error( "Unable to parse commonsbooking asset version file in $version_file_path." );
}
// spin.js
- wp_register_script('cb-spin', $base . 'spin-js/spin.min.js', [], $versions['spin.js']);
+ wp_register_script( 'cb-spin', $base . 'spin-js/spin.min.js', [], $versions['spin.js'] );
// leaflet
- wp_register_script('cb-leaflet', $base . 'leaflet/leaflet.js',[], $versions['leaflet']);
- wp_register_style('cb-leaflet', $base . 'leaflet/leaflet.css', [], $versions['leaflet']);
+ wp_register_script( 'cb-leaflet', $base . 'leaflet/leaflet.js', [], $versions['leaflet'] );
+ wp_register_style( 'cb-leaflet', $base . 'leaflet/leaflet.css', [], $versions['leaflet'] );
// leaflet markercluster
wp_register_script(
'cb-leaflet-markercluster',
$base . 'leaflet-markercluster/leaflet.markercluster.js',
- ['cb-leaflet'],
+ [ 'cb-leaflet' ],
$versions['leaflet.markercluster']
);
wp_register_style(
@@ -608,7 +611,7 @@ public static function registerScriptsAndStyles() {
wp_register_style(
'cb-leaflet-markercluster',
$base . 'leaflet-markercluster/MarkerCluster.Default.css',
- ['cb-leaflet-markercluster-base'],
+ [ 'cb-leaflet-markercluster-base' ],
$versions['leaflet.markercluster']
);
@@ -616,13 +619,13 @@ public static function registerScriptsAndStyles() {
wp_register_script(
'cb-leaflet-easybutton',
$base . 'leaflet-easybutton/easy-button.js',
- ['cb-leaflet'],
+ [ 'cb-leaflet' ],
$versions['leaflet-easybutton']
);
wp_register_style(
'cb-leaflet-easybutton',
$base . 'leaflet-easybutton/easy-button.css',
- ['cb-leaflet'],
+ [ 'cb-leaflet' ],
$versions['leaflet-easybutton']
);
@@ -630,7 +633,7 @@ public static function registerScriptsAndStyles() {
wp_register_script(
'cb-leaflet-spin',
$base . 'leaflet-spin/leaflet.spin.min.js',
- ['cb-leaflet', 'cb-spin'],
+ [ 'cb-leaflet', 'cb-spin' ],
$versions['leaflet-spin']
);
@@ -638,13 +641,13 @@ public static function registerScriptsAndStyles() {
wp_register_script(
'cb-leaflet-messagebox',
COMMONSBOOKING_MAP_ASSETS_URL . 'leaflet-messagebox/leaflet-messagebox.js',
- ['cb-leaflet'],
+ [ 'cb-leaflet' ],
'1.1',
);
wp_register_style(
'cb-leaflet-messagebox',
COMMONSBOOKING_MAP_ASSETS_URL . 'leaflet-messagebox/leaflet-messagebox.css',
- ['cb-leaflet'],
+ [ 'cb-leaflet' ],
'1.1'
);
@@ -652,43 +655,44 @@ public static function registerScriptsAndStyles() {
wp_register_script(
'cb-jquery-overscroll',
COMMONSBOOKING_MAP_ASSETS_URL . 'overscroll/jquery.overscroll.min.js',
- ['jquery'],
+ [ 'jquery' ],
'1.7.7'
);
- //cb_map shortcode
- wp_register_script( 'cb-map-filters',
+ // cb_map shortcode
+ wp_register_script(
+ 'cb-map-filters',
COMMONSBOOKING_MAP_ASSETS_URL . 'js/cb-map-filters.js',
- ['jquery'],
+ [ 'jquery' ],
COMMONSBOOKING_MAP_PLUGIN_DATA['Version']
);
wp_register_script(
'cb-map-shortcode',
COMMONSBOOKING_MAP_ASSETS_URL . 'js/cb-map-shortcode.js',
- ['jquery', 'cb-jquery-overscroll', 'cb-leaflet', 'cb-leaflet-easybutton', 'cb-leaflet-markercluster', 'cb-leaflet-messagebox', 'cb-leaflet-spin', 'cb-map-filters'],
+ [ 'jquery', 'cb-jquery-overscroll', 'cb-leaflet', 'cb-leaflet-easybutton', 'cb-leaflet-markercluster', 'cb-leaflet-messagebox', 'cb-leaflet-spin', 'cb-map-filters' ],
COMMONSBOOKING_MAP_PLUGIN_DATA['Version']
);
wp_register_style(
'cb-map-shortcode',
COMMONSBOOKING_MAP_ASSETS_URL . 'css/cb-map-shortcode.css',
- ['dashicons', 'cb-leaflet', 'cb-leaflet-easybutton', 'cb-leaflet-markercluster', 'cb-leaflet-messagebox'],
+ [ 'dashicons', 'cb-leaflet', 'cb-leaflet-easybutton', 'cb-leaflet-markercluster', 'cb-leaflet-messagebox' ],
COMMONSBOOKING_MAP_PLUGIN_DATA['Version']
);
// vue
- wp_register_script('cb-vue', $base . 'vue/vue.runtime.global.prod.js', [], $versions['vue']);
+ wp_register_script( 'cb-vue', $base . 'vue/vue.runtime.global.prod.js', [], $versions['vue'] );
// commons-search
wp_register_script(
'cb-commons-search',
$base . 'commons-search/commons-search.umd.js',
- ['cb-leaflet', 'cb-leaflet-markercluster', 'cb-vue'],
+ [ 'cb-leaflet', 'cb-leaflet-markercluster', 'cb-vue' ],
$versions['@commonsbooking/frontend']
);
wp_register_style(
'cb-commons-search',
$base . 'commons-search/style.css',
- ['cb-leaflet', 'cb-leaflet-markercluster'],
+ [ 'cb-leaflet', 'cb-leaflet-markercluster' ],
$versions['@commonsbooking/frontend']
);
}
@@ -698,14 +702,14 @@ public function registerShortcodes() {
}
/**
- * Registers all user data exporters ({@link https://developer.wordpress.org/plugins/privacy/adding-the-personal-data-exporter-to-your-plugin/}).
- *
- * @param array $exporters
- *
- * @return mixed
- */
+ * Registers all user data exporters ({@link https://developer.wordpress.org/plugins/privacy/adding-the-personal-data-exporter-to-your-plugin/}).
+ *
+ * @param array $exporters
+ *
+ * @return mixed
+ */
public static function registerUserDataExporters( $exporters ) {
- $exporters[COMMONSBOOKING_PLUGIN_SLUG] = array(
+ $exporters[ COMMONSBOOKING_PLUGIN_SLUG ] = array(
'exporter_friendly_name' => __( 'CommonsBooking Bookings', 'commonsbooking' ),
'callback' => array( \CommonsBooking\Wordpress\CustomPostType\Booking::class, 'exportUserBookingsByEmail' ),
);
@@ -720,9 +724,9 @@ public static function registerUserDataExporters( $exporters ) {
* @return mixed
*/
public static function registerUserDataErasers( $erasers ) {
- $erasers[COMMONSBOOKING_PLUGIN_SLUG] = array(
+ $erasers[ COMMONSBOOKING_PLUGIN_SLUG ] = array(
'eraser_friendly_name' => __( 'CommonsBooking Bookings', 'commonsbooking' ),
- 'callback' => array( \CommonsBooking\Wordpress\CustomPostType\Booking::class, 'removeUserBookingsByEmail'),
+ 'callback' => array( \CommonsBooking\Wordpress\CustomPostType\Booking::class, 'removeUserBookingsByEmail' ),
);
return $erasers;
}
@@ -747,13 +751,13 @@ public function init() {
add_action( 'init', array( self::class, 'registerLocationTaxonomy' ), 30 );
// register admin options page
- add_action('init', array(self::class, 'registerAdminOptions'), 40);
+ add_action( 'init', array( self::class, 'registerAdminOptions' ), 40 );
- //loads the Scheduler
- add_action( 'init', array( Scheduler::class, 'initHooks' ) , 40);
+ // loads the Scheduler
+ add_action( 'init', array( Scheduler::class, 'initHooks' ), 40 );
- //handle the booking forms, needs to happen after taxonomy registration so that we can access the taxonomy
- add_action('init', array(self::class, 'handleBookingForms'), 50);
+ // handle the booking forms, needs to happen after taxonomy registration so that we can access the taxonomy
+ add_action( 'init', array( self::class, 'handleBookingForms' ), 50 );
// admin init tasks
add_action( 'admin_init', array( self::class, 'admin_init' ), 30 );
@@ -768,20 +772,20 @@ public function init() {
add_filter( 'parent_file', array( $this, 'setParentFile' ) );
// register scripts
- add_action('init', array($this, 'registerScriptsAndStyles'));
+ add_action( 'init', array( $this, 'registerScriptsAndStyles' ) );
// register shortcodes
- add_action('init', array($this, 'registerShortcodes'));
+ add_action( 'init', array( $this, 'registerShortcodes' ) );
// Remove cache items on save.
add_action( 'wp_insert_post', array( $this, 'savePostActions' ), 10, 3 );
- add_action( 'wp_enqueue_scripts', array( Plugin::class, 'addWarmupAjaxToOutput' ) );
- add_action( 'admin_enqueue_scripts', array( Plugin::class, 'addWarmupAjaxToOutput' ) );
+ add_action( 'wp_enqueue_scripts', array( self::class, 'addWarmupAjaxToOutput' ) );
+ add_action( 'admin_enqueue_scripts', array( self::class, 'addWarmupAjaxToOutput' ) );
- //Add custom hook to clear cache from cronjob
+ // Add custom hook to clear cache from cronjob
add_action( self::$clearCacheHook, array( $this, 'clearCache' ) );
- add_action('plugins_loaded', array($this, 'commonsbooking_load_textdomain'), 20);
+ add_action( 'plugins_loaded', array( $this, 'commonsbooking_load_textdomain' ), 20 );
$map_admin = new LocationMapAdmin();
add_action( 'plugins_loaded', array( $map_admin, 'load_location_map_admin' ) );
@@ -797,31 +801,33 @@ public function init() {
// renders custom update notice on plugin listing
add_action(
- 'in_plugin_update_message-' . COMMONSBOOKING_PLUGIN_BASE,
- function ( $plugin_data ) {
- $upgrade = new Upgrade(COMMONSBOOKING_VERSION, $plugin_data['new_version']);
- $upgrade->updateNotice();
- }
- );
-
- // add ajax search for cmb2 fields (e.g. user search etc.)
- add_filter('cmb2_field_ajax_search_url', function(){
- return (COMMONSBOOKING_PLUGIN_URL . '/vendor/ed-itsolutions/cmb2-field-ajax-search/');
- });
-
- //hook into WordPress personal data exporter
+ 'in_plugin_update_message-' . COMMONSBOOKING_PLUGIN_BASE,
+ function ( $plugin_data ) {
+ $upgrade = new Upgrade( COMMONSBOOKING_VERSION, $plugin_data['new_version'] );
+ $upgrade->updateNotice();
+ }
+ );
+
+ // add ajax search for cmb2 fields (e.g. user search etc.)
+ add_filter(
+ 'cmb2_field_ajax_search_url',
+ function () {
+ return ( COMMONSBOOKING_PLUGIN_URL . '/vendor/ed-itsolutions/cmb2-field-ajax-search/' );
+ }
+ );
+
+ // hook into WordPress personal data exporter
add_filter( 'wp_privacy_personal_data_exporters', array( $this, 'registerUserDataExporters' ) );
- //hook into WordPress personal data eraser
+ // hook into WordPress personal data eraser
add_filter( 'wp_privacy_personal_data_erasers', array( $this, 'registerUserDataErasers' ) );
- // iCal rewrite
+ // iCal rewrite
iCalendar::initRewrite();
-
}
/**
- * Loads text domain for (from local file or wordpress plugin-dir)
+ * Loads text domain for (from local file or WordPress plugin-dir)
*
* @return void
*/
@@ -844,7 +850,7 @@ public function commonsbooking_load_textdomain() {
/**
* Removes cache item in connection to post_type.
- *
+ *
* @TODO: Add test if cache is cleared correctly.
*
* @param $post_id
@@ -919,13 +925,14 @@ function () {
* Adds bookingcode actions.
* They:
* - Hook appropriate function to button that downloads the booking codes in the backend.
+ *
* @see \CommonsBooking\View\BookingCodes::renderTable()
* - Hook appropriate function to button that sends out emails with booking codes to the station.
* @see \CommonsBooking\View\BookingCodes::renderDirectEmailRow()
*/
public function initBookingcodes() {
add_action( 'admin_action_cb_download-bookingscodes-csv', array( View\BookingCodes::class, 'renderCSV' ), 10, 0 );
- add_action( 'admin_action_cb_email-bookingcodes', array(View\BookingCodes::class, 'emailCodes'), 10, 0);
+ add_action( 'admin_action_cb_email-bookingcodes', array( View\BookingCodes::class, 'emailCodes' ), 10, 0 );
}
/**
@@ -951,12 +958,12 @@ public function setParentFile( $parent_file ): string {
if ( in_array( $current_screen->base, array( 'edit-tags' ) ) ) {
if (
$current_screen->taxonomy && in_array(
- $current_screen->taxonomy,
- [
+ $current_screen->taxonomy,
+ [
Location::$postType . 's_category',
Item::$postType . 's_category',
- ]
- )
+ ]
+ )
) {
return 'cb-dashboard';
}
@@ -1011,4 +1018,4 @@ function AddImageSizes() {
$crop
);
}
-}
\ No newline at end of file
+}
diff --git a/src/Repository/ApiShares.php b/src/Repository/ApiShares.php
index 5f9630a10..d5ce68a42 100644
--- a/src/Repository/ApiShares.php
+++ b/src/Repository/ApiShares.php
@@ -50,5 +50,4 @@ public static function getByKey( $key ) {
}
}
}
-
}
diff --git a/src/Repository/BookablePost.php b/src/Repository/BookablePost.php
index da5722275..ed50d9302 100644
--- a/src/Repository/BookablePost.php
+++ b/src/Repository/BookablePost.php
@@ -3,7 +3,6 @@
namespace CommonsBooking\Repository;
-
use CommonsBooking\Helper\Wordpress;
use CommonsBooking\Plugin;
use CommonsBooking\Wordpress\CustomPostType\Timeframe;
@@ -17,11 +16,12 @@ abstract class BookablePost extends PostRepository {
/**
* Types which can be connected to each other via a Timeframe
+ *
* @var string[]
*/
private static $relationalTypes = [
'item',
- 'location'
+ 'location',
];
/**
@@ -47,7 +47,7 @@ public static function getByCurrentUser( bool $publishedOnly = false ): array {
$args = array(
'post_type' => static::getPostType(),
'author' => $current_user->ID,
- 'nopaging' => true
+ 'nopaging' => true,
);
if ( $publishedOnly ) {
$args['post_status'] = 'publish';
@@ -62,7 +62,7 @@ public static function getByCurrentUser( bool $publishedOnly = false ): array {
// if user has admin-role get all available items
$args = array(
'post_type' => static::getPostType(),
- 'nopaging' => true
+ 'nopaging' => true,
);
} else {
// get all items where current user is assigned as admin
@@ -78,9 +78,9 @@ public static function getByCurrentUser( bool $publishedOnly = false ): array {
'key' => '_' . static::getPostType() . '_admins',
'value' => '"' . $current_user->ID . '"',
'compare' => 'like',
- )
+ ),
),
- 'nopaging' => true
+ 'nopaging' => true,
);
}
@@ -91,19 +91,21 @@ public static function getByCurrentUser( bool $publishedOnly = false ): array {
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
$items = array_merge( $items, $query->get_posts() );
- usort( $items, function ( $a, $b ) {
- $comparison = strcmp( strtolower( $a->post_title ), strtolower( $b->post_title ) );
-
- if ( $comparison < 0 ) {
- return - 1;
- }
- if ( $comparison > 0 ) {
- return 1;
- }
+ usort(
+ $items,
+ function ( $a, $b ) {
+ $comparison = strcmp( strtolower( $a->post_title ), strtolower( $b->post_title ) );
- return $comparison;
- } );
+ if ( $comparison < 0 ) {
+ return - 1;
+ }
+ if ( $comparison > 0 ) {
+ return 1;
+ }
+ return $comparison;
+ }
+ );
}
$tags = Wordpress::getPostIdArray( $items );
$tags[] = 'misc';
@@ -116,13 +118,16 @@ public static function getByCurrentUser( bool $publishedOnly = false ): array {
/**
* Gets all the defined terms for locations / items.
* Will return an empty array if there are no terms or an error occurred.
+ *
* @return int[]|string|string[]|\WP_Error|\WP_Term[]
*/
public static function getTerms() {
- $terms = get_terms( array(
- 'taxonomy' => static::getPostType() . 's_category',
- 'hide_empty' => false,
- ) );
+ $terms = get_terms(
+ array(
+ 'taxonomy' => static::getPostType() . 's_category',
+ 'hide_empty' => false,
+ )
+ );
if ( is_wp_error( $terms ) ) {
return [];
@@ -141,7 +146,7 @@ abstract protected static function getPostType();
* THIS METHOD DOES NOT SEEM TO BE USED ANYWHERE.
*
* @param $userId
- * @param false $asModel - Wether the posts should be returned as their respective model class or as WP_Post
+ * @param false $asModel - Wether the posts should be returned as their respective model class or as WP_Post
*
* @return array
*/
@@ -196,6 +201,7 @@ public static function getByUserId( $userId, bool $asModel = false ): array {
/**
* Will get the class name of the model class that belongs to this post type.
+ *
* @return mixed
*/
abstract protected static function getModelClass();
@@ -203,17 +209,16 @@ abstract protected static function getModelClass();
/**
* Returns an array of CB item post objects
*
- *
* @param array $args WP Post args
- * @param bool $bookable
+ * @param bool $bookable
*
* @return array
*/
public static function get( array $args = array(), bool $bookable = false ) {
$posts = [];
$args['post_type'] = static::getPostType();
- $args['nopaging'] = true;
-
+ $args['nopaging'] = true;
+
// Add custom taxonomy filter
if ( array_key_exists( 'category_slug', $args ) ) {
$args['taxonomy'] = static::getPostType() . 's_category';
@@ -261,7 +266,7 @@ public static function get( array $args = array(), bool $bookable = false ) {
* @param $postId
* @param $originType
* @param $relatedType
- * @param bool $bookable
+ * @param bool $bookable
*
* @return int[] Array of post ids
* @throws Exception
@@ -360,5 +365,4 @@ protected static function getRelatedPosts( $postId, $originType, $relatedType ):
return $relatedPosts;
}
}
-
}
diff --git a/src/Repository/Booking.php b/src/Repository/Booking.php
index 4b3842fd9..c3439e97d 100644
--- a/src/Repository/Booking.php
+++ b/src/Repository/Booking.php
@@ -37,7 +37,7 @@ protected static function getEndTimestamp( $startTimestamp ) {
/**
* Returns bookings ending at day of timestamp.
*
- * @param int $timestamp
+ * @param int $timestamp
* @param array $customArgs
*
* @return array|int[]|WP_Post[]
@@ -83,7 +83,7 @@ public static function getEndingBookingsByDate( int $timestamp, array $customArg
/**
* Returns bookings beginning at day of timestamp.
*
- * @param int $timestamp
+ * @param int $timestamp
* @param array $customArgs
*
* @return array|int[]|WP_Post[]
@@ -213,8 +213,8 @@ function ( $post ) {
* @param $endDate int
* @param $locationId
* @param $itemId
- * @param array $customArgs
- * @param array $postStatus
+ * @param array $customArgs
+ * @param array $postStatus
*
* @return \CommonsBooking\Model\Booking[]
* @throws Exception
@@ -351,12 +351,12 @@ public static function getForCurrentUser(
* Returns bookings. This uses the CommonsBooking\Repository\Timeframe::get() method which
* is not based on the WP_Query class but will perform its own SQL query.
*
- * @param array $locations
- * @param array $items
- * @param string|null $date Date-String in format YYYY-mm-dd
- * @param bool $returnAsModel
+ * @param array $locations
+ * @param array $items
+ * @param string|null $date Date-String in format YYYY-mm-dd
+ * @param bool $returnAsModel
* @param $minTimestamp
- * @param array $postStatus
+ * @param array $postStatus
*
* @return array
* @throws Exception
@@ -386,9 +386,9 @@ public static function get(
* this function will use the WP_Query class to perform the query allowing us to use the pagination features of WP_Query.
*
* @param \WP_User $user The user for which to get the bookings.
- * @param int $page The current page that is processed.
- * @param int $perPage The number of bookings per page. A lower number will result in faster queries.
- * @param array $customArgs Valid WP_Query args array.
+ * @param int $page The current page that is processed.
+ * @param int $perPage The number of bookings per page. A lower number will result in faster queries.
+ * @param array $customArgs Valid WP_Query args array.
*
* @return Booking[] An array of Booking models.
*/
@@ -424,7 +424,6 @@ public static function getForUserPaginated(
/**
* Gets all bookings that are affected by the given restriction.
*
- *
* @param \CommonsBooking\Model\Restriction $restriction
*
* @return \WP_Post[]|null
@@ -450,7 +449,7 @@ public static function getByRestriction( \CommonsBooking\Model\Restriction $rest
* @param $locationId
* @param $startDate
* @param $endDate
- * @param null $postId
+ * @param null $postId
*
* @return \CommonsBooking\Model\Booking[]|null
*/
@@ -474,7 +473,6 @@ public static function getExistingBookings( $itemId, $locationId, $startDate, $e
}
return $existingBookingsInRange;
-
}
/**
@@ -516,8 +514,8 @@ function ( $post ) use ( $args ) {
* and therefore do not have a valid timeframe anymore.
*
* @param int|null $startdate
- * @param int[] $items
- * @param int[] $locations
+ * @param int[] $items
+ * @param int[] $locations
*
* @return \CommonsBooking\Model\Booking[]|null
* @throws Exception
@@ -527,22 +525,23 @@ public static function getOrphaned(
array $items = [],
array $locations = []
): ?array {
- $startdate = $startdate ? $startdate : time(); //set startdate to now when no startdate is defined
+ $startdate = $startdate ? $startdate : time(); // set startdate to now when no startdate is defined
$bookings = self::get( $locations, $items, null, true, $startdate, [ 'confirmed' ] );
- //check for bookings where location does not exist anymore
+ // check for bookings where location does not exist anymore
- $bookings = array_filter( $bookings, function ( $booking ) {
- if ( $booking->getBookableTimeFrame() ) {
- return false;
- } else {
- return true;
+ $bookings = array_filter(
+ $bookings,
+ function ( $booking ) {
+ if ( $booking->getBookableTimeFrame() ) {
+ return false;
+ } else {
+ return true;
+ }
}
-
- } );
+ );
return $bookings;
}
-
}
diff --git a/src/Repository/BookingCodes.php b/src/Repository/BookingCodes.php
index a1ce9cf18..f2bf13b1c 100644
--- a/src/Repository/BookingCodes.php
+++ b/src/Repository/BookingCodes.php
@@ -3,7 +3,6 @@
namespace CommonsBooking\Repository;
-
use CommonsBooking\Exception\BookingCodeException;
use CommonsBooking\Helper\Wordpress;
use CommonsBooking\Model\BookingCode;
@@ -22,12 +21,14 @@ class BookingCodes {
/**
* Table name of booking codes.
+ *
* @var string
*/
public static string $tablename = 'cb_bookingcodes';
/**
* Days to advance generation of booking codes.
+ *
* @var int
*/
public const ADVANCE_GENERATION_DAYS = 365;
@@ -35,10 +36,10 @@ class BookingCodes {
/**
* Returns booking codes for timeframe to display in backend Timeframe window.
*
- * @param int $timeframeId - ID of timeframe to get codes for
+ * @param int $timeframeId - ID of timeframe to get codes for
* @param int|null $startDate - Where to get booking codes from (timestamp)
* @param int|null $endDate - Where to get booking codes to (timestamp)
- * @param int $advanceGenerationDays - Open-ended timeframes: If 0, generate code(s) until today. If >0, generate additional codes after today
+ * @param int $advanceGenerationDays - Open-ended timeframes: If 0, generate code(s) until today. If >0, generate additional codes after today
*
* @return array
* @throws BookingCodeException
@@ -53,7 +54,7 @@ public static function getCodes( int $timeframeId, int $startDate = null, int $e
$timeframeEndDate = $timeframe->getRawEndDate();
// If timeframe does not qualify for booking codes, return empty array
- if ( ! $timeframe->bookingCodesApplicable() ){
+ if ( ! $timeframe->bookingCodesApplicable() ) {
return [];
}
@@ -61,11 +62,11 @@ public static function getCodes( int $timeframeId, int $startDate = null, int $e
$startDate = $timeframeStartDate;
}
- if ($timeframeEndDate && (! $endDate || $endDate > $timeframeEndDate ) ) {
+ if ( $timeframeEndDate && ( ! $endDate || $endDate > $timeframeEndDate ) ) {
$endDate = $timeframeEndDate;
}
- //when we still don't have an end-date, we will just get the coming ADVANCE_GENERATION_DAYS (should default to 365 days)
- if (! $endDate ) {
+ // when we still don't have an end-date, we will just get the coming ADVANCE_GENERATION_DAYS (should default to 365 days)
+ if ( ! $endDate ) {
$endDate = strtotime( '+' . $advanceGenerationDays . ' days', null ); // null means date and time now
// a code will be generated for $endDate because time generally > 00:00:00 (due to initialitaion with current date and time)
}
@@ -73,19 +74,20 @@ public static function getCodes( int $timeframeId, int $startDate = null, int $e
$startDate = date( 'Y-m-d', $startDate );
$endDate = date( 'Y-m-d', $endDate );
- //check, if we have enough codes for the timeframe or if we need to generate more
- //we only need to check, if we have an open-ended timeframe
+ // check, if we have enough codes for the timeframe or if we need to generate more
+ // we only need to check, if we have an open-ended timeframe
// NOTE: there used to be a check if generation is necessary by checking the date of the last code. However,
// as the codes are never deleted anymore, it is possible that they get fragmented with date gaps and the
// check is not trivial anymore. Is is easier and safer to always try to generate codes. It is no serious
// performance issue as getCodes() is only used in admin pages on particular admin actions.
if ( ! $timeframe->getRawEndDate() ) {
$startGenerationPeriod = new \DateTime( $startDate );
- $endGenerationPeriod = new \DateTime( $endDate );
+ $endGenerationPeriod = new \DateTime( $endDate );
// set $endGenerationPeriod's time > 00:00:00 such that $endDate is included in DatePeriod iteration
// and code is generated for $endDate
- $endGenerationPeriod->setTime(0, 0, 1);
- static::generatePeriod( $timeframe,
+ $endGenerationPeriod->setTime( 0, 0, 1 );
+ static::generatePeriod(
+ $timeframe,
new DatePeriod(
$startGenerationPeriod,
new DateInterval( 'P1D' ),
@@ -97,7 +99,7 @@ public static function getCodes( int $timeframeId, int $startDate = null, int $e
global $wpdb;
$table_name = $wpdb->prefix . self::$tablename;
- $sql = $wpdb->prepare(
+ $sql = $wpdb->prepare(
"SELECT * FROM $table_name
WHERE item = %d
AND date BETWEEN %s AND %s
@@ -107,7 +109,7 @@ public static function getCodes( int $timeframeId, int $startDate = null, int $e
$startDate,
$endDate
);
- $bookingCodes = $wpdb->get_results($sql);
+ $bookingCodes = $wpdb->get_results( $sql );
self::backwardCompatibilityFilter( $bookingCodes, $timeframeId, $timeframe->getLocation()->ID ); // for backward compatibility: delete line in future cb
@@ -121,7 +123,7 @@ public static function getCodes( int $timeframeId, int $startDate = null, int $e
$codes[] = $bookingCodeObject;
}
- Plugin::setCacheItem( $codes, [$timeframeId] );
+ Plugin::setCacheItem( $codes, [ $timeframeId ] );
return $codes;
}
@@ -135,39 +137,42 @@ public static function getCodes( int $timeframeId, int $startDate = null, int $e
* The filtering can be omitted in future cb versions when backward compatibility with old cb is dropped.
*
* @param array &$bookingCodes reference of array of BookingCode|s. It is assumed that they all have the same itemId.
- * @param int $preferredTimeframeId timeframeId to prefer when filtering
- * @param int $preferredLocationId locationId to prefer when filtering
+ * @param int $preferredTimeframeId timeframeId to prefer when filtering
+ * @param int $preferredLocationId locationId to prefer when filtering
*
* @return void works by reference on param $bookingCodes
*/
- private static function backwardCompatibilityFilter(&$bookingCodes, $preferredTimeframeId, $preferredLocationId) {
+ private static function backwardCompatibilityFilter( &$bookingCodes, $preferredTimeframeId, $preferredLocationId ) {
$filteredCodes = [];
- $codesByDate = [];
+ $codesByDate = [];
// Group booking codes by date
foreach ( $bookingCodes as $code ) {
$date = $code->date;
- if (! isset($codesByDate[$date]) ) {
- $codesByDate[$date] = [];
+ if ( ! isset( $codesByDate[ $date ] ) ) {
+ $codesByDate[ $date ] = [];
}
- $codesByDate[$date][] = $code;
+ $codesByDate[ $date ][] = $code;
}
// For each date, filter out codes to ensure only one entry per date
foreach ( $codesByDate as $date => $codes ) {
- if ( count($codes) > 1 ) {
+ if ( count( $codes ) > 1 ) {
// Keep entries matching $preferredTimeframeId and $preferredLocationId
- $preferredCodes = array_filter( $codes, function($code) use ($preferredTimeframeId, $preferredLocationId ) {
- return $code->timeframe == $preferredTimeframeId && $code->location == $preferredLocationId;
- });
+ $preferredCodes = array_filter(
+ $codes,
+ function ( $code ) use ( $preferredTimeframeId, $preferredLocationId ) {
+ return $code->timeframe == $preferredTimeframeId && $code->location == $preferredLocationId;
+ }
+ );
// If there are preferred codes, use them. Otherwise, use all codes.
- $finalCodes = !empty($preferredCodes) ? $preferredCodes : $codes;
+ $finalCodes = ! empty( $preferredCodes ) ? $preferredCodes : $codes;
// Pick the first code if there are still multiple entries
- $filteredCodes[] = reset($finalCodes);
+ $filteredCodes[] = reset( $finalCodes );
} else {
- $filteredCodes[] = reset($codes);
+ $filteredCodes[] = reset( $codes );
}
}
@@ -177,14 +182,14 @@ private static function backwardCompatibilityFilter(&$bookingCodes, $preferredTi
/**
* Gets a specific booking code by item ID and date.
*
- * @param int $itemId - ID of item attached to timeframe
+ * @param int $itemId - ID of item attached to timeframe
* @param string $date - Date in format Y-m-d
- * @param int $preferredTimeframeId only for compatibility with database entries created by old cb version. delete in future
- * @param int $preferredLocationId see $preferredTimeframeId
+ * @param int $preferredTimeframeId only for compatibility with database entries created by old cb version. delete in future
+ * @param int $preferredLocationId see $preferredTimeframeId
*
* @return BookingCode|null
*/
- private static function lookupCode(int $itemId, string $date, int $preferredTimeframeId = 0, int $preferredLocationId = 0): ?BookingCode {
+ private static function lookupCode( int $itemId, string $date, int $preferredTimeframeId = 0, int $preferredLocationId = 0 ): ?BookingCode {
global $wpdb;
$table_name = $wpdb->prefix . self::$tablename;
@@ -198,11 +203,11 @@ private static function lookupCode(int $itemId, string $date, int $preferredTime
$date
);
- $bookingCodes = $wpdb->get_results($sql);
+ $bookingCodes = $wpdb->get_results( $sql );
self::backwardCompatibilityFilter( $bookingCodes, $preferredTimeframeId, $preferredLocationId ); // for backward compatibility: delete line in future cb
- if (count($bookingCodes)) {
+ if ( count( $bookingCodes ) ) {
return new BookingCode(
$bookingCodes[0]->date,
$bookingCodes[0]->item,
@@ -217,15 +222,15 @@ private static function lookupCode(int $itemId, string $date, int $preferredTime
* Returns booking code by timeframe, location, item and date. If no code exist yet and timeframe does not have end-date, generate it.
*
* @param Timeframe $timeframe - Timeframe object to get code for
- * @param int $itemId - ID of item attached to timeframe
- * @param int $locationId - ID of location attached to timeframe (DEPRECATED, has no effect)
- * @param string $date - Date in format Y-m-d
- * @param int $advanceGenerationDays - Open-ended timeframes: If 0, generates code(s) until $date. If >0, generate additional codes after $date.
+ * @param int $itemId - ID of item attached to timeframe
+ * @param int $locationId - ID of location attached to timeframe (DEPRECATED, has no effect)
+ * @param string $date - Date in format Y-m-d
+ * @param int $advanceGenerationDays - Open-ended timeframes: If 0, generates code(s) until $date. If >0, generate additional codes after $date.
*
* @return BookingCode|null
* @throws BookingCodeException
*/
- public static function getCode( Timeframe $timeframe, int $itemId, int $locationId, string $date, int $advanceGenerationDays = self::ADVANCE_GENERATION_DAYS ) : ?BookingCode {
+ public static function getCode( Timeframe $timeframe, int $itemId, int $locationId, string $date, int $advanceGenerationDays = self::ADVANCE_GENERATION_DAYS ): ?BookingCode {
$cacheItem = Plugin::getCacheItem();
if ( $cacheItem ) {
return $cacheItem;
@@ -234,22 +239,22 @@ public static function getCode( Timeframe $timeframe, int $itemId, int $location
$bookingCodeObject = static::lookupCode( $itemId, $date, $timeframe->ID, $locationId );
if ( ! $bookingCodeObject ) {
- //when we have a timeframe without end-date we generate as many codes as we need
- if (! $timeframe->getRawEndDate() && $timeframe->bookingCodesApplicable() ) {
- $begin = $timeframe->getUTCStartDateDateTime();
- $endDate = new \DateTime($date);
- $endDate->modify('+' . $advanceGenerationDays . ' days');
+ // when we have a timeframe without end-date we generate as many codes as we need
+ if ( ! $timeframe->getRawEndDate() && $timeframe->bookingCodesApplicable() ) {
+ $begin = $timeframe->getUTCStartDateDateTime();
+ $endDate = new \DateTime( $date );
+ $endDate->modify( '+' . $advanceGenerationDays . ' days' );
// set $endDate's time > 00:00:00 so it will included in DatePeriod iteration and a code will be
// generated for $endDate
- $endDate->setTime(0, 0, 1);
+ $endDate->setTime( 0, 0, 1 );
$interval = DateInterval::createFromDateString( '1 day' );
- $period = new DatePeriod( $begin, $interval, $endDate );
- static::generatePeriod($timeframe,$period);
+ $period = new DatePeriod( $begin, $interval, $endDate );
+ static::generatePeriod( $timeframe, $period );
$bookingCodeObject = static::lookupCode( $itemId, $date, $timeframe->ID, $locationId );
}
}
- Plugin::setCacheItem( $bookingCodeObject, [$timeframe->ID] );
+ Plugin::setCacheItem( $bookingCodeObject, [ $timeframe->ID ] );
return $bookingCodeObject;
}
@@ -258,7 +263,7 @@ public static function getCode( Timeframe $timeframe, int $itemId, int $location
/**
* Creates booking-codes table;
*/
- public static function initBookingCodesTable() :void {
+ public static function initBookingCodesTable(): void {
global $wpdb;
global $cb_db_version;
@@ -276,38 +281,37 @@ public static function initBookingCodesTable() :void {
) $charset_collate;";
// Include dbDelta since it's not part of autoloaded modules
- require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
+ require_once ABSPATH . 'wp-admin/includes/upgrade.php';
dbDelta( $sql );
add_option( COMMONSBOOKING_PLUGIN_SLUG . '_bookingcodes_db_version', $cb_db_version );
}
- /**
- * Generates booking codes for timeframe.
- *
- * @param Timeframe $timeframe
- * @param int $advanceGenerationDays - Open-ended timeframes: If 0, generate code(s) until today. If >0, generate additional codes after today.
+ /**
+ * Generates booking codes for timeframe.
+ *
+ * @param Timeframe $timeframe
+ * @param int $advanceGenerationDays - Open-ended timeframes: If 0, generate code(s) until today. If >0, generate additional codes after today.
*
- * @return bool
- * @return bool
- * @throws BookingCodeException
- */
+ * @return bool
+ * @return bool
+ * @throws BookingCodeException
+ */
public static function generate( Timeframe $timeframe, int $advanceGenerationDays = self::ADVANCE_GENERATION_DAYS ): bool {
- if (! $timeframe->bookingCodesApplicable() ){
+ if ( ! $timeframe->bookingCodesApplicable() ) {
return false;
}
$begin = Wordpress::getUTCDateTime();
$begin->setTimestamp( $timeframe->getStartDate() );
- if ($timeframe->getRawEndDate()){
+ if ( $timeframe->getRawEndDate() ) {
$end = Wordpress::getUTCDateTime();
$end->setTimestamp( $timeframe->getRawEndDate() );
// set $end's time > 00:00:00 such that DatePeriod-iteration will include $end:
- $end->setTime(0, 0, 1);
- }
- else {
+ $end->setTime( 0, 0, 1 );
+ } else {
$end = new \DateTime();
- $end->modify( '+' . $advanceGenerationDays . 'days');
+ $end->modify( '+' . $advanceGenerationDays . 'days' );
// a code will be generated for the date in $end because its time generally > 00:00:00 (due to initialitaion with current date and time)
}
@@ -319,51 +323,54 @@ public static function generate( Timeframe $timeframe, int $advanceGenerationDay
/**
* Generate booking codes for a given period
- * @param Timeframe $timeframe
+ *
+ * @param Timeframe $timeframe
* @param DatePeriod $period
*
* @return true
* @throws BookingCodeException
*/
- private static function generatePeriod( Timeframe $timeframe, DatePeriod $period): bool {
+ private static function generatePeriod( Timeframe $timeframe, DatePeriod $period ): bool {
$bookingCodesArray = static::getCodesArray();
- if (! $bookingCodesArray ){
- throw new BookingCodeException( __( "No booking codes could be created because there were no booking codes to choose from. Please set some booking codes in the CommonsBooking settings.", 'commonsbooking' ) );
+ if ( ! $bookingCodesArray ) {
+ throw new BookingCodeException( __( 'No booking codes could be created because there were no booking codes to choose from. Please set some booking codes in the CommonsBooking settings.', 'commonsbooking' ) );
}
try {
- //TODO #507
+ // TODO #507
$location = $timeframe->getLocation();
} catch ( \Exception $e ) {
- throw new BookingCodeException( __( "No booking codes could be created because the location of the timeframe could not be found.", 'commonsbooking' ) );
+ throw new BookingCodeException( __( 'No booking codes could be created because the location of the timeframe could not be found.', 'commonsbooking' ) );
}
try {
- //TODO #507
+ // TODO #507
$item = $timeframe->getItem();
} catch ( \Exception $e ) {
- throw new BookingCodeException( __( "No booking codes could be created because the item of the timeframe could not be found.", 'commonsbooking' ) );
+ throw new BookingCodeException( __( 'No booking codes could be created because the item of the timeframe could not be found.', 'commonsbooking' ) );
}
- $todayMidnight = new \DateTime('today midnight', $period->getStartDate()->getTimezone());
+ $todayMidnight = new \DateTime( 'today midnight', $period->getStartDate()->getTimezone() );
foreach ( $period as $dt ) {
// do not generate any codes for past days
- if ($dt < $todayMidnight) continue;
+ if ( $dt < $todayMidnight ) {
+ continue;
+ }
$day = new Day( $dt->format( 'Y-m-d' ) );
if ( $day->isInTimeframe( $timeframe ) ) {
// Check if a code already exists, if so DO NOT generate new
// timeframeid and locationid are only for backward compatibility with database entries from old cb
- if ( static::lookupCode($item->ID, $dt->format( 'Y-m-d' ), $timeframe->ID, $location->ID) ) {
+ if ( static::lookupCode( $item->ID, $dt->format( 'Y-m-d' ), $timeframe->ID, $location->ID ) ) {
continue;
}
$bookingCode = new BookingCode(
$dt->format( 'Y-m-d' ),
$item->ID,
- $bookingCodesArray[ random_int(0, count($bookingCodesArray) - 1) ]
+ $bookingCodesArray[ random_int( 0, count( $bookingCodesArray ) - 1 ) ]
);
self::persist(
$bookingCode,
@@ -378,7 +385,8 @@ private static function generatePeriod( Timeframe $timeframe, DatePeriod $period
/**
* Stores a booking code in database without checking if code already exists (please check before)
- * @param BookingCode $bookingCode
+ *
+ * @param BookingCode $bookingCode
* @param timeframeId deprecated (only necessary to make database compatible to former versions of cb)
* @param locationId deprecated (only necessary to make database compatible to former versions of cb)
*
@@ -395,7 +403,7 @@ public static function persist( BookingCode $bookingCode, $timeframeId = 0, $loc
'date' => $bookingCode->getDate(),
'location' => $locationId, // deprecated field, only for backward compatibility
'item' => $bookingCode->getItem(),
- 'code' => $bookingCode->getCode()
+ 'code' => $bookingCode->getCode(),
)
);
@@ -408,14 +416,16 @@ public static function persist( BookingCode $bookingCode, $timeframeId = 0, $loc
* @return array - Array of booking codes, empty array if no booking codes are configured.
*/
private static function getCodesArray(): array {
- $bookingCodes = Settings::getOption( 'commonsbooking_options_bookingcodes', 'bookingcodes' );
+ $bookingCodes = Settings::getOption( 'commonsbooking_options_bookingcodes', 'bookingcodes' );
if ( ! $bookingCodes ) {
return array();
}
$bookingCodesArray = array_filter( explode( ',', trim( $bookingCodes ) ) );
- return array_map( function ( $item ) {
- return preg_replace( "/\r|\n/", "", $item );
- }, $bookingCodesArray );
+ return array_map(
+ function ( $item ) {
+ return preg_replace( "/\r|\n/", '', $item );
+ },
+ $bookingCodesArray
+ );
}
-
}
diff --git a/src/Repository/CB1.php b/src/Repository/CB1.php
index 3eb2f402c..0b519ada2 100644
--- a/src/Repository/CB1.php
+++ b/src/Repository/CB1.php
@@ -3,7 +3,6 @@
namespace CommonsBooking\Repository;
-
use WP_Query;
/**
@@ -45,7 +44,7 @@ class CB1 {
*/
public static function isInstalled() {
// we check for pages, since they have to be set up for the plugin to function.
- $option_set_by_cb1 = esc_html(get_option('commons-booking-settings-pages'));
+ $option_set_by_cb1 = esc_html( get_option( 'commons-booking-settings-pages' ) );
if ( $option_set_by_cb1 ) {
return true;
@@ -56,6 +55,7 @@ public static function isInstalled() {
/**
* Get the old CB1 location post type posts
+ *
* @return array
*/
public static function getLocations() {
@@ -72,7 +72,7 @@ protected static function get( $postType ) {
$args = array(
'post_type' => $postType,
'post_status' => 'any',
- 'nopaging' => true
+ 'nopaging' => true,
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
@@ -84,6 +84,7 @@ protected static function get( $postType ) {
/**
* Get the old CB1 item post type posts
+ *
* @return array
*/
public static function getItems() {
@@ -92,6 +93,7 @@ public static function getItems() {
/**
* Get the old CB1 bookings
+ *
* @return mixed
*/
public static function getBookings() {
@@ -103,6 +105,7 @@ public static function getBookings() {
/**
* Get the old CB1 timeframes
+ *
* @return mixed
*/
public static function getTimeframes() {
@@ -114,6 +117,7 @@ public static function getTimeframes() {
/**
* Get the old CB1 bookingcodes
+ *
* @return mixed
*/
public static function getBookingCodes() {
@@ -148,7 +152,7 @@ public static function getBookingCode( $id ): ?string {
global $wpdb;
$table_bookingcodes = $wpdb->prefix . self::$BOOKINGCODES_TABLE;
- $sql = $wpdb->prepare( "SELECT bookingcode FROM $table_bookingcodes WHERE id = %d", $id);
+ $sql = $wpdb->prepare( "SELECT bookingcode FROM $table_bookingcodes WHERE id = %d", $id );
$result = $wpdb->get_results( $sql, ARRAY_A );
if ( $result && count( $result ) > 0 ) {
@@ -169,7 +173,7 @@ public static function getCB2LocationId( int $locationId ) {
}
/**
- * @param int $id
+ * @param int $id
* @param string $type
*
* @return false|int
@@ -179,7 +183,7 @@ protected static function getCB2PostIdByType( int $id, string $type ) {
$table_postmeta = $wpdb->prefix . 'postmeta';
$table_posts = $wpdb->prefix . 'posts';
- $sql = $wpdb->prepare(
+ $sql = $wpdb->prepare(
"SELECT post_id FROM $table_postmeta
WHERE
meta_key = '_cb_cb1_post_post_ID' AND
@@ -189,7 +193,7 @@ protected static function getCB2PostIdByType( int $id, string $type ) {
$id,
$type
);
- $result = $wpdb->get_results($sql);
+ $result = $wpdb->get_results( $sql );
if ( $result && count( $result ) > 0 ) {
return $result[0]->post_id;
@@ -229,7 +233,7 @@ public static function getCB2PostIdByCB1Id( $id ): ?int {
global $wpdb;
$table_postmeta = $wpdb->prefix . 'postmeta';
- $sql = $wpdb->prepare(
+ $sql = $wpdb->prepare(
"SELECT meta_value as cb1_id, post_id as cb2_id
FROM $table_postmeta
WHERE
@@ -249,6 +253,7 @@ public static function getCB2PostIdByCB1Id( $id ): ?int {
/**
* Returns CB1 taxonomies.
+ *
* @return mixed
*/
public static function getCB1Taxonomies() {
@@ -278,5 +283,4 @@ public static function getCB1Taxonomies() {
"
);
}
-
}
diff --git a/src/Repository/Item.php b/src/Repository/Item.php
index 1571a66b0..3a80cc660 100644
--- a/src/Repository/Item.php
+++ b/src/Repository/Item.php
@@ -11,13 +11,13 @@ class Item extends BookablePost {
*
* @param $locationId
*
- * @param bool $bookable
+ * @param bool $bookable
*
* @return array
* @throws Exception
*/
public static function getByLocation( $locationId, bool $bookable = false ): array {
- return self::getByRelatedPost($locationId, 'location', 'item', $bookable);
+ return self::getByRelatedPost( $locationId, 'location', 'item', $bookable );
}
/**
@@ -30,10 +30,10 @@ protected static function getPostType(): string {
/**
* This is the model class that belongs to the post type.
* With the model class, you are able to perform additional functions on the post type.
+ *
* @return string
*/
protected static function getModelClass(): string {
return \CommonsBooking\Model\Item::class;
}
-
}
diff --git a/src/Repository/Location.php b/src/Repository/Location.php
index 75af3e889..52bf03236 100644
--- a/src/Repository/Location.php
+++ b/src/Repository/Location.php
@@ -11,13 +11,13 @@ class Location extends BookablePost {
*
* @param $itemId
*
- * @param bool $bookable
+ * @param bool $bookable
*
* @return array
* @throws Exception
*/
public static function getByItem( $itemId, bool $bookable = false ): array {
- return self::getByRelatedPost($itemId, 'item', 'location', $bookable);
+ return self::getByRelatedPost( $itemId, 'item', 'location', $bookable );
}
/**
@@ -30,10 +30,10 @@ protected static function getPostType(): string {
/**
* This is the model class that belongs to the post type.
* With the model class, you are able to perform additional functions on the post type.
+ *
* @return string
*/
protected static function getModelClass(): string {
return \CommonsBooking\Model\Location::class;
}
-
}
diff --git a/src/Repository/PostRepository.php b/src/Repository/PostRepository.php
index b5686286d..95da650da 100644
--- a/src/Repository/PostRepository.php
+++ b/src/Repository/PostRepository.php
@@ -3,7 +3,6 @@
namespace CommonsBooking\Repository;
-
use CommonsBooking\Plugin;
use Exception;
use WP_Post;
@@ -31,9 +30,9 @@ public static function getPostById( $postId ) {
if ( $post->post_type == \CommonsBooking\Wordpress\CustomPostType\Timeframe::getPostType() ) {
$type = get_post_meta( $post->ID, 'type', true );
switch ( $type ) {
- case \CommonsBooking\Wordpress\CustomPostType\Timeframe::BOOKING_ID: //booking
+ case \CommonsBooking\Wordpress\CustomPostType\Timeframe::BOOKING_ID: // booking
return new \CommonsBooking\Model\Booking( $post );
- case \CommonsBooking\Wordpress\CustomPostType\Timeframe::BOOKING_CANCELED_ID: //booking canceled
+ case \CommonsBooking\Wordpress\CustomPostType\Timeframe::BOOKING_CANCELED_ID: // booking canceled
return new \CommonsBooking\Model\Booking( $post );
}
}
@@ -54,10 +53,9 @@ public static function getPostById( $postId ) {
return new \CommonsBooking\Model\Booking( $post );
}
}
- Plugin::setCacheItem( $post, [$postId] );
+ Plugin::setCacheItem( $post, [ $postId ] );
return $post;
}
}
-
}
diff --git a/src/Repository/Restriction.php b/src/Repository/Restriction.php
index 0f018f2c8..161079c56 100644
--- a/src/Repository/Restriction.php
+++ b/src/Repository/Restriction.php
@@ -3,7 +3,6 @@
namespace CommonsBooking\Repository;
-
use CommonsBooking\Helper\Wordpress;
use CommonsBooking\Plugin;
use Exception;
@@ -12,6 +11,7 @@ class Restriction extends PostRepository {
/**
* Returns active restrictions.
+ *
* @return \CommonsBooking\Model\Restriction[]
* @throws Exception
*/
@@ -29,7 +29,6 @@ public static function get(
if ( $cacheItem ) {
return $cacheItem;
} else {
-
$posts = self::queryPosts( $date, $minTimestamp, $postStatus );
if ( $posts && count( $posts ) ) {
@@ -41,14 +40,14 @@ public static function get(
$posts = self::filterPosts( $posts, $locations, $items );
}
- // if returnAsModel == TRUE the result is a timeframe model instead of a wordpress object
+ // if returnAsModel == TRUE the result is a timeframe model instead of a WordPress object
if ( $returnAsModel ) {
$posts = self::castPostsToRestrictions( $posts );
}
}
$posts = $posts ?: [];
- Plugin::setCacheItem( $posts, Wordpress::getTags($posts, $items, $locations), $customCacheKey );
+ Plugin::setCacheItem( $posts, Wordpress::getTags( $posts, $items, $locations ), $customCacheKey );
return $posts;
}
@@ -85,15 +84,15 @@ private static function queryPosts( $date, $minTimestamp, $postStatus ) {
// Complete query
$query = "
SELECT DISTINCT pm1.* from $table_posts pm1
- " . $dateQuery . "
- " . self::getActiveQuery() . "
+ " . $dateQuery . '
+ ' . self::getActiveQuery() . "
WHERE
pm1.post_type = '" . \CommonsBooking\Wordpress\CustomPostType\Restriction::getPostType() . "' AND
pm1.post_status IN ('" . implode( "','", $postStatus ) . "')
";
$posts = $wpdb->get_results( $query );
- Plugin::setCacheItem( $posts, Wordpress::getTags($posts) );
+ Plugin::setCacheItem( $posts, Wordpress::getTags( $posts ) );
return $posts;
}
@@ -110,7 +109,8 @@ private static function getMinTimestampQuery( $minTimestamp ): string {
global $wpdb;
$table_postmeta = $wpdb->prefix . 'postmeta';
- return $wpdb->prepare( "
+ return $wpdb->prepare(
+ "
INNER JOIN $table_postmeta pm4 ON
pm4.post_id = pm1.id AND (
(
@@ -142,7 +142,7 @@ private static function getDateQuery( $date ): string {
$table_postmeta = $wpdb->prefix . 'postmeta';
return $wpdb->prepare(
- "INNER JOIN $table_postmeta pm4 ON
+ "INNER JOIN $table_postmeta pm4 ON
pm4.post_id = pm1.id AND
pm4.meta_key = '" . \CommonsBooking\Model\Restriction::META_START . "' AND
pm4.meta_value BETWEEN 0 AND %d
@@ -168,6 +168,7 @@ private static function getDateQuery( $date ): string {
/**
* Returns query to filter only active restrictions.
+ *
* @return string
*/
private static function getActiveQuery(): string {
@@ -194,47 +195,49 @@ private static function getActiveQuery(): string {
* @return array
*/
private static function filterPosts( array $posts, array $locations, array $items ): array {
- return array_filter( $posts, function ( $post ) use ( $locations, $items ) {
- // Check if restriction is in relation to item and/or location
- $location = intval( get_post_meta( $post->ID, \CommonsBooking\Model\Restriction::META_LOCATION_ID, true ) );
- $restrictionHasLocation = $location !== 0;
- $restrictedLocationInLocations = $restrictionHasLocation && in_array( $location, $locations );
-
- $item = intval( get_post_meta( $post->ID, \CommonsBooking\Model\Restriction::META_ITEM_ID, true ) );
- $restrictionHasItem = $item !== 0;
- $restrictedItemInItems = $restrictionHasItem && in_array( $item, $items );
-
- // No item or location for restriction set
- $noLocationNoItem = ( ! $restrictionHasLocation && ! $restrictionHasItem );
-
- // No location, item matching
- $noLocationItemMatches = (
+ return array_filter(
+ $posts,
+ function ( $post ) use ( $locations, $items ) {
+ // Check if restriction is in relation to item and/or location
+ $location = intval( get_post_meta( $post->ID, \CommonsBooking\Model\Restriction::META_LOCATION_ID, true ) );
+ $restrictionHasLocation = $location !== 0;
+ $restrictedLocationInLocations = $restrictionHasLocation && in_array( $location, $locations );
+
+ $item = intval( get_post_meta( $post->ID, \CommonsBooking\Model\Restriction::META_ITEM_ID, true ) );
+ $restrictionHasItem = $item !== 0;
+ $restrictedItemInItems = $restrictionHasItem && in_array( $item, $items );
+
+ // No item or location for restriction set
+ $noLocationNoItem = ( ! $restrictionHasLocation && ! $restrictionHasItem );
+
+ // No location, item matching
+ $noLocationItemMatches = (
! $restrictionHasLocation &&
$restrictionHasItem &&
$restrictedItemInItems
- );
+ );
- // No item, location matching
- $noItemLocationMatches = (
+ // No item, location matching
+ $noItemLocationMatches = (
! $restrictionHasItem &&
$restrictionHasLocation &&
$restrictedLocationInLocations
- );
+ );
- // Item and location matching
- $itemAndLocationMatches = (
+ // Item and location matching
+ $itemAndLocationMatches = (
$restrictionHasLocation &&
$restrictedLocationInLocations &&
$restrictionHasItem &&
$restrictedItemInItems
- );
+ );
- return
- $noLocationNoItem ||
+ return $noLocationNoItem ||
$noLocationItemMatches ||
$noItemLocationMatches ||
$itemAndLocationMatches;
- } );
+ }
+ );
}
/**
@@ -252,5 +255,4 @@ private static function castPostsToRestrictions( $posts ) {
return $posts;
}
-
-}
\ No newline at end of file
+}
diff --git a/src/Repository/Timeframe.php b/src/Repository/Timeframe.php
index 4905cb1d6..48843aa06 100644
--- a/src/Repository/Timeframe.php
+++ b/src/Repository/Timeframe.php
@@ -3,7 +3,6 @@
namespace CommonsBooking\Repository;
-
use CommonsBooking\Helper\Helper;
use CommonsBooking\Helper\Wordpress;
use CommonsBooking\Model\Day;
@@ -20,12 +19,12 @@ class Timeframe extends PostRepository {
/**
* Returns only bookable timeframes.
*
- * @param array $locations
- * @param array $items
- * @param string|null $date
- * @param bool $returnAsModel
+ * @param array $locations
+ * @param array $items
+ * @param string|null $date
+ * @param bool $returnAsModel
* @param $minTimestamp
- * @param array $postStatus
+ * @param array $postStatus
*
* @return array
* @throws Exception
@@ -52,12 +51,12 @@ public static function getBookable(
/**
* Returns only bookable timeframes for current user.
*
- * @param array $locations
- * @param array $items
- * @param string|null $date
- * @param bool $returnAsModel
+ * @param array $locations
+ * @param array $items
+ * @param string|null $date
+ * @param bool $returnAsModel
* @param $minTimestamp
- * @param array $postStatus
+ * @param array $postStatus
*
* @return array
* @throws Exception
@@ -80,7 +79,7 @@ public static function getBookableForCurrentUser(
$postStatus
);
- $bookableTimeframes = self::filterTimeframesForCurrentUser($bookableTimeframes);
+ $bookableTimeframes = self::filterTimeframesForCurrentUser( $bookableTimeframes );
return $bookableTimeframes;
}
@@ -94,13 +93,13 @@ public static function getBookableForCurrentUser(
* 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 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
+ * @param bool $returnAsModel
+ * @param int|null $minTimestamp
+ * @param string[] $postStatus
*
* @return array
* @throws Exception
@@ -125,12 +124,11 @@ public static function get(
];
}
- $customId = md5( serialize( $types ) );
+ $customId = md5( serialize( $types ) );
$cacheItem = Plugin::getCacheItem( $customId );
if ( $cacheItem ) {
return $cacheItem;
} else {
-
$posts = [];
// Get Post-IDs considering types, items and locations
@@ -150,14 +148,14 @@ public static function get(
$posts = self::filterTimeframes( $posts, $date );
}
- // if returnAsModel == TRUE the result is a timeframe model instead of a wordpress object
+ // 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),
+ Wordpress::getTags( $posts, $items, $locations ),
$customId
);
return $posts;
@@ -167,8 +165,8 @@ public static function get(
/**
* Will get all timeframes in the database to perform mass operations on (like migrations).
*
- * @param int $page
- * @param int $perPage
+ * @param int $page
+ * @param int $perPage
* @param array $customArgs
*
* @return \stdClass Properties: array posts, int totalPosts, int totalPages, bool done
@@ -198,7 +196,7 @@ public static function getAllPaginated(
'posts' => $posts,
'totalPosts' => $query->found_posts,
'totalPages' => $query->max_num_pages,
- 'done' => $page >= $query->max_num_pages
+ 'done' => $page >= $query->max_num_pages,
]
);
}
@@ -208,7 +206,7 @@ public static function getAllPaginated(
'posts' => [],
'totalPosts' => 0,
'totalPages' => 0,
- 'done' => true
+ 'done' => true,
]
);
}
@@ -220,17 +218,17 @@ public static function getAllPaginated(
* We need this for the Timeframe Export, so that it does not time out on large datasets.
* This function is in general slower than the getInRange function. But it can be used in AJAX requests.
*
- * @param int $minTimestamp
+ * @param int $minTimestamp
* @param int|null $maxTimestamp
- * @param int $page
- * @param int $perPage
- * @param array $types
- * @param bool $asModel
- * @param array $customArgs
+ * @param int $page
+ * @param int $perPage
+ * @param array $types
+ * @param bool $asModel
+ * @param array $customArgs
*
* @return array An array with the keys 'posts', 'totalPages' and 'done' (bool) to indicate if there are more posts to fetch
*/
- public static function getInRangePaginated (
+ public static function getInRangePaginated(
int $minTimestamp,
int $maxTimestamp = null,
int $page = 1,
@@ -249,16 +247,16 @@ public static function getInRangePaginated (
$args = array(
'post_type' => [
\CommonsBooking\Wordpress\CustomPostType\Booking::$postType,
- \CommonsBooking\Wordpress\CustomPostType\Timeframe::$postType
+ \CommonsBooking\Wordpress\CustomPostType\Timeframe::$postType,
],
- //get posts within the range and also posts that do not have a repetition end
+ // get posts within the range and also posts that do not have a repetition end
'meta_query' => array(
'relation' => 'AND',
array(
'key' => \CommonsBooking\Model\Timeframe::REPETITION_START,
'value' => $maxTimestamp,
'compare' => '<=',
- 'type' => 'numeric'
+ 'type' => 'numeric',
),
array(
'relation' => 'OR',
@@ -266,7 +264,7 @@ public static function getInRangePaginated (
'key' => \CommonsBooking\Model\Timeframe::REPETITION_END,
'value' => $minTimestamp,
'compare' => '>=',
- 'type' => 'numeric'
+ 'type' => 'numeric',
),
array(
'key' => \CommonsBooking\Model\Timeframe::REPETITION_END,
@@ -293,7 +291,7 @@ public static function getInRangePaginated (
if ( $query->have_posts() ) {
$posts = $query->get_posts();
- if (! isset($args['fields']) || $args['fields'] !== 'ids') {
+ if ( ! isset( $args['fields'] ) || $args['fields'] !== 'ids' ) {
$posts = array_filter(
$posts,
function ( $post ) use ( $args ) {
@@ -309,14 +307,14 @@ function ( $post ) use ( $args ) {
'posts' => $posts,
'totalPages' => $query->max_num_pages,
'totalPosts' => $query->found_posts,
- 'done' => $page >= $query->max_num_pages
+ 'done' => $page >= $query->max_num_pages,
];
}
return [
'posts' => [],
'totalPages' => 0,
'totalPosts' => 0,
- 'done' => true
+ 'done' => true,
];
}
@@ -328,8 +326,8 @@ function ( $post ) use ( $args ) {
* @param array $types the types of timeframes to return, will return default set when not set
* @param array $items the items that the timeframes should be applicable to, will return all if not set
* @param array $locations the locations that the timeframes should be applicable to, will return all if not set
- *
- * @since 2.9.0 Supports now single and multi selection for items and locations
+ *
+ * @since 2.9.0 Supports now single and multi selection for items and locations
*
* @return mixed
* @throws \Psr\Cache\InvalidArgumentException
@@ -338,15 +336,15 @@ public static function getPostIdsByType( array $types = [], array $items = [], a
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,
- ];
+ \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 ) );
+ $customId = md5( serialize( $types ) );
$cacheItem = Plugin::getCacheItem( $customId );
if ( $cacheItem ) {
return $cacheItem;
@@ -357,15 +355,15 @@ public static function getPostIdsByType( array $types = [], array $items = [], a
$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' );
+ // additional sanitizing. Allow only integer
+ $items = commonsbooking_sanitizeArrayorString( $items, 'intval' );
+ $locations = commonsbooking_sanitizeArrayorString( $locations, 'intval' );
+ $types = commonsbooking_sanitizeArrayorString( $types, 'intval' );
- $itemQuery = "";
+ $itemQuery = '';
if ( count( $items ) > 0 ) {
$itemQuery = self::getEntityQuery(
- "pm2",
+ 'pm2',
$table_postmeta,
$items,
\CommonsBooking\Model\Timeframe::META_ITEM_ID,
@@ -373,10 +371,10 @@ public static function getPostIdsByType( array $types = [], array $items = [], a
);
}
- $locationQuery = "";
+ $locationQuery = '';
if ( count( $locations ) > 0 ) {
$locationQuery = self::getEntityQuery(
- "pm3",
+ 'pm3',
$table_postmeta,
$locations,
\CommonsBooking\Model\Timeframe::META_LOCATION_ID,
@@ -388,13 +386,13 @@ public static function getPostIdsByType( array $types = [], array $items = [], a
$query = "
SELECT DISTINCT pm1.post_id from $table_postmeta pm1
" .
- $itemQuery .
- $locationQuery .
- "
+ $itemQuery .
+ $locationQuery .
+ "
WHERE
pm1.meta_key = 'type' AND
- pm1.meta_value IN (" . implode( ',', $types ) . ")
- ";
+ pm1.meta_value IN (" . implode( ',', $types ) . ')
+ ';
// Run query
$postIds = $wpdb->get_results( $query, ARRAY_N );
@@ -405,13 +403,16 @@ public static function getPostIdsByType( array $types = [], array $items = [], a
}
// Get Posts
- $posts = array_map(function($post) {
- return get_post($post);
- }, $postIds);
+ $posts = array_map(
+ function ( $post ) {
+ return get_post( $post );
+ },
+ $postIds
+ );
Plugin::setCacheItem(
$postIds,
- Wordpress::getTags($posts, $items, $locations),
+ Wordpress::getTags( $posts, $items, $locations ),
$customId
);
@@ -420,36 +421,36 @@ public static function getPostIdsByType( array $types = [], array $items = [], a
}
/**
- * Returns entity query as join statement, which considers single and multi selection.
- *
- * @since 2.9.0 Supports now single and multi selection for items and locations
- *
- * @return string join statement
- */
+ * Returns entity query as join statement, which considers single and multi selection.
+ *
+ * @since 2.9.0 Supports now single and multi selection for items and locations
+ *
+ * @return string join statement
+ */
private static function getEntityQuery( string $joinAlias, string $table_postmeta, array $entities, string $singleEntityKey, string $multiEntityKey ): string {
$locationQueryParts = [];
// Single select
- $singleLocationQuery = "(
+ $singleLocationQuery = "(
$joinAlias.meta_key = '" . $singleEntityKey . "' AND
- $joinAlias.meta_value IN (" . implode( ',', $entities ) . ")
- )";
+ $joinAlias.meta_value IN (" . implode( ',', $entities ) . ')
+ )';
$locationQueryParts[] = $singleLocationQuery;
// Multi select
$multiLocationQueries = [];
- foreach( $entities as $entityId ) {
+ foreach ( $entities as $entityId ) {
$multiLocationQueries[] = "$joinAlias.meta_value LIKE '%:\"$entityId\";%'";
}
- $multiLocationQuery = "(
+ $multiLocationQuery = "(
$joinAlias.meta_key = '" . $multiEntityKey . "' AND
- (" . implode( ' OR ', $multiLocationQueries ) . ")
- )";
+ (" . implode( ' OR ', $multiLocationQueries ) . ')
+ )';
$locationQueryParts[] = $multiLocationQuery;
return "INNER JOIN $table_postmeta $joinAlias ON
$joinAlias.post_id = pm1.post_id AND
- (" . implode( ' OR ', $locationQueryParts ) . ")";
+ (" . implode( ' OR ', $locationQueryParts ) . ')';
}
/**
@@ -457,10 +458,10 @@ private static function getEntityQuery( string $joinAlias, string $table_postmet
* 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
+ * @param int|null $minTimestamp
+ * @param int|null $maxTimestamp
+ * @param array $postIds
+ * @param array $postStatus
*
* @return array
*/
@@ -472,7 +473,7 @@ private static function getPostsByBaseParams( ?string $date, ?int $minTimestamp,
global $wpdb;
$table_postmeta = $wpdb->prefix . 'postmeta';
$table_posts = $wpdb->prefix . 'posts';
- $dateQuery = "";
+ $dateQuery = '';
// Filter by date
if ( $date && ! $minTimestamp ) {
@@ -492,9 +493,9 @@ private static function getPostsByBaseParams( ?string $date, ?int $minTimestamp,
// Complete query
$query = "SELECT DISTINCT pm1.* from $table_posts pm1
- " . $dateQuery . "
+ " . $dateQuery . '
WHERE
- pm1.id in (" . implode( ",", $postIds ) . ") AND
+ pm1.id in (' . implode( ',', $postIds ) . ") AND
pm1.post_type IN ('" . implode( "','", \CommonsBooking\Wordpress\CustomPostType\Timeframe::getSimilarPostTypes() ) . "') AND
pm1.post_status IN ('" . implode( "','", $postStatus ) . "')
";
@@ -504,7 +505,7 @@ private static function getPostsByBaseParams( ?string $date, ?int $minTimestamp,
Plugin::setCacheItem(
$posts,
- Wordpress::getTags($posts, $postIds)
+ Wordpress::getTags( $posts, $postIds )
);
return $posts;
@@ -554,13 +555,13 @@ private static function getFilterByDateQuery( string $table_postmeta, string $da
* Returns query to get posts which end after $minTimestamp.
*
* @param string $table_postmeta
- * @param int $minTimestamp
+ * @param int $minTimestamp
*
* @return string
*/
private static function getFilterFromDateQuery( string $table_postmeta, int $minTimestamp ): string {
global $wpdb;
- $minTimestamp = Helper::getLastFullDayTimestamp($minTimestamp);
+ $minTimestamp = Helper::getLastFullDayTimestamp( $minTimestamp );
return $wpdb->prepare(
"INNER JOIN $table_postmeta pm4 ON
@@ -584,8 +585,8 @@ private static function getFilterFromDateQuery( string $table_postmeta, int $min
/**
* @param string $table_postmeta
- * @param int $minTimestamp
- * @param int $maxTimestamp
+ * @param int $minTimestamp
+ * @param int $maxTimestamp
*
* @return string
*/
@@ -623,7 +624,7 @@ private static function getTimerangeQuery( string $table_postmeta, int $minTimes
/**
* Wrapper function for all filters.
*
- * @param array $posts
+ * @param array $posts
* @param string|null $date
*
* @return array
@@ -641,7 +642,7 @@ private static function filterTimeframes( array $posts, ?string $date ): array {
* 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 array $posts
* @param string|null $date string format: YYYY-mm-dd
*
* @return array
@@ -653,18 +654,20 @@ private static function filterTimeframesByConfiguredDays( array $posts, ?string
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;
+ $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;
+ }
}
- }
);
}
@@ -683,21 +686,24 @@ private static function filterTimeframesByConfiguredDays( array $posts, ?string
* @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 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 $timeframe->isBookable();
+ } catch ( Exception $e ) {
+ error_log( $e->getMessage() );
- return false;
+ return false;
+ }
}
- }
- return true;
- } );
+ return true;
+ }
+ );
}
/**
@@ -709,44 +715,50 @@ private static function filterTimeframesByMaxBookingDays( $posts ): array {
* @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 array_filter(
+ $posts,
+ function ( $post ) {
+ try {
+ return commonsbooking_isCurrentUserAllowedToBook( $post->ID );
+ } catch ( Exception $e ) {
+ error_log( $e->getMessage() );
- return false;
+ return false;
+ }
}
- } );
+ );
}
/**
* Will filter out all timeframes that are not in the given timerange.
*
* @param \CommonsBooking\Model\Timeframe[] $timeframes
- * @param int $startTimestamp
- * @param int $endTimestamp
+ * @param int $startTimestamp
+ * @param int $endTimestamp
*
* @return \CommonsBooking\Model\Timeframe[]
* @throws Exception
*/
public static function filterTimeframesForTimerange( array $timeframes, int $startTimestamp, int $endTimestamp ): array {
- return array_filter( $timeframes, function ( $timeframe ) use ( $startTimestamp, $endTimestamp ) {
- //filter out anything in the future
- if ( $timeframe->getStartDate() > $endTimestamp ) {
- return false;
- }
- //always include infinite timeframes
- if ( ! $timeframe->getEndDate() ) {
+ return array_filter(
+ $timeframes,
+ function ( $timeframe ) use ( $startTimestamp, $endTimestamp ) {
+ // filter out anything in the future
+ if ( $timeframe->getStartDate() > $endTimestamp ) {
+ return false;
+ }
+ // always include infinite timeframes
+ if ( ! $timeframe->getEndDate() ) {
+ return true;
+ }
+ // filter out anything in the past
+ if ( $timeframe->getEndDate() < $startTimestamp ) {
+ return false;
+ }
+
return true;
}
- //filter out anything in the past
- if ( $timeframe->getEndDate() < $startTimestamp ) {
- return false;
- }
-
- return true;
- } );
+ );
}
/**
@@ -788,7 +800,7 @@ public static function getByLocationItemTimestamp( int $locationId, int $itemId,
if ( $cacheItem ) {
return $cacheItem;
} else {
- $time_format = esc_html(get_option( 'time_format' ));
+ $time_format = esc_html( get_option( 'time_format' ) );
$startTimestampTime = date( $time_format, $timestamp );
$endTimestampTime = date( $time_format, $timestamp + 1 );
@@ -796,7 +808,7 @@ public static function getByLocationItemTimestamp( int $locationId, int $itemId,
[ $locationId ],
[ $itemId ],
[ \CommonsBooking\Wordpress\CustomPostType\Timeframe::BOOKABLE_ID ],
- date('Y-m-d', $timestamp),
+ date( 'Y-m-d', $timestamp ),
true
);
@@ -806,7 +818,7 @@ public static function getByLocationItemTimestamp( int $locationId, int $itemId,
date( $time_format, strtotime( $timeframe->getStartTime() ) ) == $startTimestampTime ||
date( $time_format, strtotime( $timeframe->getEndTime() ) ) == $endTimestampTime
) {
- Plugin::setCacheItem( $timeframe, [$timeframe->ID, $itemId, $locationId] );
+ Plugin::setCacheItem( $timeframe, [ $timeframe->ID, $itemId, $locationId ] );
return $timeframe;
}
@@ -823,11 +835,11 @@ public static function getByLocationItemTimestamp( int $locationId, int $itemId,
*
* @param $minTimestamp
* @param $maxTimestamp
- * @param array $locations
- * @param array $items
- * @param array $types
- * @param false $returnAsModel
- * @param string[] $postStatus
+ * @param array $locations
+ * @param array $items
+ * @param array $types
+ * @param false $returnAsModel
+ * @param string[] $postStatus
*
* @return array
* @throws Exception
@@ -851,7 +863,7 @@ public static function getInRange(
];
}
- $customId = md5( serialize( $types ) );
+ $customId = md5( serialize( $types ) );
$cacheItem = Plugin::getCacheItem( $customId );
if ( $cacheItem ) {
return $cacheItem;
@@ -880,7 +892,7 @@ public static function getInRange(
Plugin::setCacheItem(
$posts,
- Wordpress::getTags($posts, $locations, $items),
+ Wordpress::getTags( $posts, $locations, $items ),
$customId
);
@@ -893,17 +905,16 @@ public static function getInRange(
*
* @param $minTimestamp
* @param $maxTimestamp
- * @param array $locations
- * @param array $items
- * @param array $types
- * @param false $returnAsModel
- * @param string[] $postStatus
+ * @param array $locations
+ * @param array $items
+ * @param array $types
+ * @param false $returnAsModel
+ * @param string[] $postStatus
*
* @return array
* @throws Exception
*/
-
- public static function getInRangeForCurrentUser(
+ public static function getInRangeForCurrentUser(
$minTimestamp,
$maxTimestamp,
array $locations = [],
@@ -912,9 +923,9 @@ public static function getInRangeForCurrentUser(
bool $returnAsModel = false,
array $postStatus = [ 'confirmed', 'unconfirmed', 'publish', 'inherit' ]
): array {
- $bookableTimeframes = self::getInRange($minTimestamp,$maxTimestamp,$locations,$items,$types,$returnAsModel,$postStatus);
+ $bookableTimeframes = self::getInRange( $minTimestamp, $maxTimestamp, $locations, $items, $types, $returnAsModel, $postStatus );
- $bookableTimeframes = self::filterTimeframesForCurrentUser($bookableTimeframes);
+ $bookableTimeframes = self::filterTimeframesForCurrentUser( $bookableTimeframes );
return $bookableTimeframes;
}
}
diff --git a/src/Repository/UserRepository.php b/src/Repository/UserRepository.php
index a2e3df960..539d5035a 100644
--- a/src/Repository/UserRepository.php
+++ b/src/Repository/UserRepository.php
@@ -3,7 +3,6 @@
namespace CommonsBooking\Repository;
-
use CommonsBooking\Plugin;
use WP_Query;
@@ -11,26 +10,29 @@ class UserRepository {
/**
* Returns all users with role that can be assigned to item / location.
+ *
* @return mixed
*/
public static function getSelectableCBManagers() {
- return get_users( ['role__in' => self::getManagerRoles()] );
+ return get_users( [ 'role__in' => self::getManagerRoles() ] );
}
- public static function getManagerRoles() : array {
- return apply_filters("commonsbooking_manager_roles",[Plugin::$CB_MANAGER_ID]);
+ public static function getManagerRoles(): array {
+ return apply_filters( 'commonsbooking_manager_roles', [ Plugin::$CB_MANAGER_ID ] );
}
/**
* Will get all roles that are considered by CommonsBooking as "Administrator" roles
+ *
* @return array
*/
- public static function getAdminRoles() : array {
- return apply_filters('commonsbooking_admin_roles', ['administrator']);
+ public static function getAdminRoles(): array {
+ return apply_filters( 'commonsbooking_admin_roles', [ 'administrator' ] );
}
/**
* Returns all users with items/locations.
+ *
* @return array
*/
public static function getOwners(): array {
@@ -40,7 +42,7 @@ public static function getOwners(): array {
'post_type' => array(
\CommonsBooking\Wordpress\CustomPostType\Item::$postType,
\CommonsBooking\Wordpress\CustomPostType\Location::$postType,
- )
+ ),
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
@@ -70,13 +72,13 @@ public static function getOwners(): array {
*/
public static function getUserRoles(): array {
global $wp_roles;
- if ( $wp_roles === null ){
+ if ( $wp_roles === null ) {
return [];
}
$rolesArray = $wp_roles->roles;
$roles = [];
foreach ( $rolesArray as $roleID => $value ) {
- if ($roleID == 'administrator') {
+ if ( $roleID == 'administrator' ) {
continue;
}
$roles[ $roleID ] = translate_user_role( $value['name'] );
@@ -91,11 +93,11 @@ public static function getUserRoles(): array {
*
* @since 2.9.0
*
- * @param int $userID
+ * @param int $userID
* @param string|array $roles
* @return bool
*/
- public static function userHasRoles(int $userID, $roles): bool {
+ public static function userHasRoles( int $userID, $roles ): bool {
$user = get_userdata( $userID );
if ( is_array( $roles ) ) {
return ! empty( array_intersect( $roles, $user->roles ) );
@@ -103,5 +105,4 @@ public static function userHasRoles(int $userID, $roles): bool {
return in_array( $roles, $user->roles );
}
}
-
}
diff --git a/src/Service/Booking.php b/src/Service/Booking.php
index bcdff1f7a..40c64c31b 100644
--- a/src/Service/Booking.php
+++ b/src/Service/Booking.php
@@ -14,6 +14,7 @@ class Booking {
/**
* Removes all unconfirmed bookings older than 10 minutes
* is triggered in Service\Scheduler initHooks()
+ *
* @return void
*/
public static function cleanupBookings() {
@@ -39,7 +40,7 @@ public static function cleanupBookings() {
}
}
- private static function sendMessagesForDay ( int $tsDate, bool $onStartDate, Message $message ) {
+ private static function sendMessagesForDay( int $tsDate, bool $onStartDate, Message $message ) {
if ( $onStartDate ) {
$bookings = \CommonsBooking\Repository\Booking::getBeginningBookingsByDate( $tsDate );
} else {
@@ -58,30 +59,32 @@ private static function sendMessagesForDay ( int $tsDate, bool $onStartDate, Mes
/**
* Send reminder mail, x days before start of booking.
- * is triggered in Service\Scheduler initHooks()
+ * is triggered in Service\Scheduler initHooks()
+ *
* @throws \Exception
*/
public static function sendReminderMessage() {
- if (Settings::getOption('commonsbooking_options_reminder', 'pre-booking-reminder-activate') != 'on') {
- return;
- }
+ if ( Settings::getOption( 'commonsbooking_options_reminder', 'pre-booking-reminder-activate' ) != 'on' ) {
+ return;
+ }
- $message = new BookingReminderMessage( 0, 'pre-booking-reminder' );
+ $message = new BookingReminderMessage( 0, 'pre-booking-reminder' );
$daysBeforeStart = Settings::getOption( 'commonsbooking_options_reminder', 'pre-booking-days-before' );
self::sendMessagesForDay( strtotime( '+' . $daysBeforeStart . ' days midnight' ), true, $message );
}
/**
* Send feedback mal on same day or the day after end of booking.
- * is triggered in Service\Scheduler initHooks()
+ * is triggered in Service\Scheduler initHooks()
+ *
* @throws \Exception
*/
public static function sendFeedbackMessage() {
- if (Settings::getOption('commonsbooking_options_reminder', 'post-booking-notice-activate') != 'on') {
- return;
- }
+ if ( Settings::getOption( 'commonsbooking_options_reminder', 'post-booking-notice-activate' ) != 'on' ) {
+ return;
+ }
// Yesterday at 23:59
$endDate = strtotime( 'midnight', time() ) - 1;
@@ -90,24 +93,24 @@ public static function sendFeedbackMessage() {
}
public static function sendBookingStartLocationReminderMessage() {
- self::sendLocationBookingReminderMessage('start');
+ self::sendLocationBookingReminderMessage( 'start' );
}
public static function sendBookingEndLocationReminderMessage() {
- self::sendLocationBookingReminderMessage('end');
+ self::sendLocationBookingReminderMessage( 'end' );
}
- protected static function sendLocationBookingReminderMessage(string $type) {
+ protected static function sendLocationBookingReminderMessage( string $type ) {
- if (Settings::getOption('commonsbooking_options_reminder', 'booking-'.$type.'-location-reminder-activate') != 'on') {
+ if ( Settings::getOption( 'commonsbooking_options_reminder', 'booking-' . $type . '-location-reminder-activate' ) != 'on' ) {
return;
}
// current day is saved in options as 1, this is because 0 is an unset value. Subtract 1 to get the correct day
- $daysBeforeStart = (int) Settings::getOption( 'commonsbooking_options_reminder', 'booking-'.$type.'-location-reminder-day' ) - 1;
- $startDate = strtotime( '+' . $daysBeforeStart . ' days midnight' );
+ $daysBeforeStart = (int) Settings::getOption( 'commonsbooking_options_reminder', 'booking-' . $type . '-location-reminder-day' ) - 1;
+ $startDate = strtotime( '+' . $daysBeforeStart . ' days midnight' );
- $message = new LocationBookingReminderMessage( 0, 'booking-'.$type.'-location-reminder' );
+ $message = new LocationBookingReminderMessage( 0, 'booking-' . $type . '-location-reminder' );
self::sendMessagesForDay( $startDate, $type === 'start', $message );
}
-}
\ No newline at end of file
+}
diff --git a/src/Service/BookingCodes.php b/src/Service/BookingCodes.php
index 2726e5b57..66f3a8aa5 100644
--- a/src/Service/BookingCodes.php
+++ b/src/Service/BookingCodes.php
@@ -13,42 +13,43 @@ class BookingCodes {
/**
* Send booking codes by E-mail.
- * is triggered in Service\Scheduler initHooks()
- *
+ * is triggered in Service\Scheduler initHooks()
*/
public static function sendBookingCodesMessage(): void {
- $query = new WP_Query( [
- 'post_type' => Timeframe::$postType,
- 'meta_query' => array(
+ $query = new WP_Query(
+ [
+ 'post_type' => Timeframe::$postType,
+ 'meta_query' => array(
array(
'key' => \CommonsBooking\View\BookingCodes::NEXT_CRON_EMAIL,
- 'value' => strtotime("today"),
+ 'value' => strtotime( 'today' ),
'type' => 'numeric',
- 'compare' => '<='
+ 'compare' => '<=',
),
),
- ] );
+ ]
+ );
- if($query->have_posts()){
- foreach( $query->posts as $post ) {
- $params=self::getCronParams($post->ID);
- if($params === false) continue;
+ if ( $query->have_posts() ) {
+ foreach ( $query->posts as $post ) {
+ $params = self::getCronParams( $post->ID );
+ if ( $params === false ) {
+ continue;
+ }
- $booking_msg = new BookingCodesMessage($post->ID, "codes",$params['from'],$params['to'] );
- if(!$booking_msg->sendMessage()) {
+ $booking_msg = new BookingCodesMessage( $post->ID, 'codes', $params['from'], $params['to'] );
+ if ( ! $booking_msg->sendMessage() ) {
set_transient(
BookingCode::ERROR_TYPE,
commonsbooking_sanitizeHTML(
- __( "Error sending booking codes by E-mail for Timeframe ", 'commonsbooking' ) . get_the_title($post) . " ({$post->ID})"
+ __( 'Error sending booking codes by E-mail for Timeframe ', 'commonsbooking' ) . get_the_title( $post ) . " ({$post->ID})"
),
0
);
+ } else {
+ update_post_meta( $post->ID, \CommonsBooking\View\BookingCodes::NEXT_CRON_EMAIL, $params['nextCronEventTs'] );
}
- else {
- update_post_meta( $post->ID, \CommonsBooking\View\BookingCodes::NEXT_CRON_EMAIL, $params['nextCronEventTs'] );
- }
-
- }
+ }
}
}
@@ -56,35 +57,36 @@ public static function sendBookingCodesMessage(): void {
* Retrieves Parameters of the next booking codes by Email Cron event.
*
* @param int $timeframeId
- *
- * @return array Parameters.
+ *
+ * @return array Parameters.
*/
- public static function getCronParams($timeframeId): array {
- $tsCurrentCronEvent=get_post_meta( $timeframeId, \CommonsBooking\View\BookingCodes::NEXT_CRON_EMAIL, true );
- if(empty($tsCurrentCronEvent)) return false;
-
- $cronEmailCodes=get_post_meta( $timeframeId, \CommonsBooking\View\BookingCodes::CRON_EMAIL_CODES, true);
- if(!is_numeric($cronEmailCodes['cron-email-booking-code-nummonth']) || empty(@$cronEmailCodes['cron-booking-codes-enabled']))
- return false;
-
- $dtCurrentCronEvent=new DateTimeImmutable("@" . $tsCurrentCronEvent);
- $dtFrom=$dtCurrentCronEvent->modify("midnight first day of next month");
- $dtTo=$dtCurrentCronEvent->modify("midnight last day of next month +" . ($cronEmailCodes['cron-email-booking-code-nummonth'] - 1) . " month");
+ public static function getCronParams( $timeframeId ): array {
+ $tsCurrentCronEvent = get_post_meta( $timeframeId, \CommonsBooking\View\BookingCodes::NEXT_CRON_EMAIL, true );
+ if ( empty( $tsCurrentCronEvent ) ) {
+ return false;
+ }
- $dtInitial=new DateTimeImmutable("@" . $cronEmailCodes['cron-email-booking-code-start']);
- $daydiff=$dtTo->format("j") - $dtInitial->format("j");
- if($daydiff > 0 ) {
- $dtNextCronEvent=$dtTo->modify("-" . $daydiff . " days");
- }
- else
- $dtNextCronEvent=$dtTo;
+ $cronEmailCodes = get_post_meta( $timeframeId, \CommonsBooking\View\BookingCodes::CRON_EMAIL_CODES, true );
+ if ( ! is_numeric( $cronEmailCodes['cron-email-booking-code-nummonth'] ) || empty( @$cronEmailCodes['cron-booking-codes-enabled'] ) ) {
+ return false;
+ }
- return array(
- "from" => $dtFrom->getTimestamp(),
- "to" => $dtTo->getTimestamp(),
- "nextCronEventTs" => $dtNextCronEvent->getTimestamp(),
- );
- }
+ $dtCurrentCronEvent = new DateTimeImmutable( '@' . $tsCurrentCronEvent );
+ $dtFrom = $dtCurrentCronEvent->modify( 'midnight first day of next month' );
+ $dtTo = $dtCurrentCronEvent->modify( 'midnight last day of next month +' . ( $cronEmailCodes['cron-email-booking-code-nummonth'] - 1 ) . ' month' );
+ $dtInitial = new DateTimeImmutable( '@' . $cronEmailCodes['cron-email-booking-code-start'] );
+ $daydiff = $dtTo->format( 'j' ) - $dtInitial->format( 'j' );
+ if ( $daydiff > 0 ) {
+ $dtNextCronEvent = $dtTo->modify( '-' . $daydiff . ' days' );
+ } else {
+ $dtNextCronEvent = $dtTo;
+ }
-}
\ No newline at end of file
+ return array(
+ 'from' => $dtFrom->getTimestamp(),
+ 'to' => $dtTo->getTimestamp(),
+ 'nextCronEventTs' => $dtNextCronEvent->getTimestamp(),
+ );
+ }
+}
diff --git a/src/Service/BookingRule.php b/src/Service/BookingRule.php
index 7ff167443..e29bd71dd 100644
--- a/src/Service/BookingRule.php
+++ b/src/Service/BookingRule.php
@@ -24,43 +24,51 @@
class BookingRule {
/**
* The name of the rule, needs to be unique and is used to identify the rule in the code
+ *
* @var String
*/
protected string $name;
/**
* The title of the rule, will be shown to the configuration admin
+ *
* @var String
*/
protected string $title;
/**
* A detailed description of the rule, will be shown to the configuration admin
+ *
* @var String
*/
protected string $description;
/**
* The static error message that will be shown to the booking user if the rule is not met
+ *
* @var String
*/
protected string $errorMessage;
/**
* Allows to set a custom error message that can be based on parameters (i.e. "You can only book for %s days")
+ *
* @var ?Closure
*/
protected ?Closure $errorFromArgs;
/**
* Array of associative arrays in which the key "title" is the title of the parameter and "description" is the description of the parameter.
* These parameters are text fields that can be used to configure the rule. We can currently only support 2 parameters
+ *
* @var array
*/
protected array $params = [];
/**
* Array where first element is the description of the select field and the second element is an associative array of the select options
+ *
* @var array
*/
protected array $selectParam;
/**
* The function that will be called to validate the rule. This is a closure that takes a Booking object, the passed args and an array of the selected terms as arguments
* and returns either null if the rule is met or an array of bookings that are in conflict with the current booking.
+ *
* @var Closure
*/
protected Closure $validationFunction;
@@ -68,21 +76,20 @@ class BookingRule {
/**
* The constructor for BookingRules before they are applied
*
- * @param String $name The name of the rule, needs to be unique and is used to identify the rule in the code
- * @param String $title The title of the rule, will be shown to the configuration admin
- * @param String $description A detailed description of the rule, will be shown to the configuration admin
- * @param String $errorMessage The static error message that will be shown to the booking user if the rule is not met
+ * @param String $name The name of the rule, needs to be unique and is used to identify the rule in the code
+ * @param String $title The title of the rule, will be shown to the configuration admin
+ * @param String $description A detailed description of the rule, will be shown to the configuration admin
+ * @param String $errorMessage The static error message that will be shown to the booking user if the rule is not met
* @param Closure $validationFunction The function that will be called to validate the rule. This is a closure that takes a Booking object, the passed args and an array of the selected terms as arguments
- * @param array $params Array of associative arrays in which the key "title" is the title of the parameter and "description" is the description of the parameter. Only 2 parameters are currently supported. They have to be integer values.
- * @param array $selectParam Array where first element is the description of the select field and the second element is an associative array of the select options
+ * @param array $params Array of associative arrays in which the key "title" is the title of the parameter and "description" is the description of the parameter. Only 2 parameters are currently supported. They have to be integer values.
+ * @param array $selectParam Array where first element is the description of the select field and the second element is an associative array of the select options
*
* @throws BookingRuleException
*/
public function __construct( string $name, string $title, string $description, string $errorMessage, Closure $validationFunction, array $params = [], array $selectParam = [], ?Closure $errorFromArgs = null ) {
if ( ! empty( $params ) ) {
-
if ( count( $params ) > 2 ) {
- throw new BookingRuleException( "No more than 2 parameters are currently supported" );
+ throw new BookingRuleException( 'No more than 2 parameters are currently supported' );
}
$this->params = $params;
@@ -98,6 +105,7 @@ public function __construct( string $name, string $title, string $description, s
/**
* Gets the sanitized version of the BookingRule title
+ *
* @return string
*/
public function getTitle(): string {
@@ -106,6 +114,7 @@ public function getTitle(): string {
/**
* Gets the sanitized version of the BookingRule description
+ *
* @return string
*/
public function getDescription(): string {
@@ -114,14 +123,15 @@ public function getDescription(): string {
/**
* Gets the sanitized version of the BookingRule error message
+ *
* @return string
*/
public function getErrorMessage( $args = [] ): string {
$errorMessage = commonsbooking_sanitizeHTML( $this->errorMessage );
if ( $this->errorFromArgs !== null ) {
$errorMessageFunction = $this->errorFromArgs;
- $errorMessage .= PHP_EOL;
- $errorMessage .= $errorMessageFunction( $args );
+ $errorMessage .= PHP_EOL;
+ $errorMessage .= $errorMessageFunction( $args );
}
return $errorMessage;
@@ -150,6 +160,7 @@ public function getValidationFunction(): Closure {
/**
* Create associative array for CMB2 select
+ *
* @return array
*/
public static function getRulesForSelect(): array {
@@ -188,10 +199,12 @@ public static function getRulesJSON(): string {
array_map(
function ( $rule ) {
return get_object_vars( $rule );
- }, $ruleObjects )
+ },
+ $ruleObjects
+ )
);
} else {
- return "";
+ return '';
}
}
@@ -199,119 +212,120 @@ function ( $rule ) {
* Returns an array with the default ruleset applied, can be filtered using a filter hook
*
* Closure::fromCallable can be replaced with First Class Callable Syntax in PHP8.1
+ *
* @return BookingRule[]
* @throws BookingRuleException
*/
public static function init(): array {
- $weekDays = __( 'Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday', 'cmb2' );
- $weekDaysSelect = array_combine( range( 1, 7 ), explode( ', ', $weekDays ) );
+ $weekDays = __( 'Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday', 'cmb2' );
+ $weekDaysSelect = array_combine( range( 1, 7 ), explode( ', ', $weekDays ) );
$monthDaysSelect = array_combine( range( 1, 31 ), range( 1, 31 ) );
- $defaultRuleSet = [
+ $defaultRuleSet = [
new BookingRule(
- "noSimultaneousBooking",
- __( "Forbid simultaneous Bookings", 'commonsbooking' ),
- __( "Users can no longer book two items on the same day.", 'commonsbooking' ),
- __( "You can not book more than one item at a time.", 'commonsbooking' ),
+ 'noSimultaneousBooking',
+ __( 'Forbid simultaneous Bookings', 'commonsbooking' ),
+ __( 'Users can no longer book two items on the same day.', 'commonsbooking' ),
+ __( 'You can not book more than one item at a time.', 'commonsbooking' ),
Closure::fromCallable( array( self::class, 'checkSimultaneousBookings' ) )
),
new BookingRule(
- "prohibitChainBooking",
- __( "Prohibit chain-bookings", 'commonsbooking' ),
- __( "Users can no longer work around the maximum booking limit by chaining two bookings directly after one another.", 'commonsbooking' ),
- __( "You have reached your booking limit. Please leave some time in between bookings.", 'commonsbooking' ),
+ 'prohibitChainBooking',
+ __( 'Prohibit chain-bookings', 'commonsbooking' ),
+ __( 'Users can no longer work around the maximum booking limit by chaining two bookings directly after one another.', 'commonsbooking' ),
+ __( 'You have reached your booking limit. Please leave some time in between bookings.', 'commonsbooking' ),
Closure::fromCallable( array( self::class, 'checkChainBooking' ) )
),
new BookingRule(
- "maxBookingDaysPerWeek",
- __( "Maximum booked days per week", 'commonsbooking' ),
- __( "Users are only allowed to book a limited amount of days per week.", 'commonsbooking' ),
- __( "You have reached your booking limit. Please leave some time in between bookings.", 'commonsbooking' ),
+ 'maxBookingDaysPerWeek',
+ __( 'Maximum booked days per week', 'commonsbooking' ),
+ __( 'Users are only allowed to book a limited amount of days per week.', 'commonsbooking' ),
+ __( 'You have reached your booking limit. Please leave some time in between bookings.', 'commonsbooking' ),
Closure::fromCallable( array( self::class, 'checkMaxBookingDaysPerWeek' ) ),
array(
array(
- "title" => __( "Maximum booked days per week", 'commonsbooking' ),
- "description" => __( "Number of days each user is allowed to book per week", 'commonsbooking' ),
- )
+ 'title' => __( 'Maximum booked days per week', 'commonsbooking' ),
+ 'description' => __( 'Number of days each user is allowed to book per week', 'commonsbooking' ),
+ ),
),
array(
- __( "At what day of the week should the counter be reset?", 'commonsbooking' ),
- $weekDaysSelect
+ __( 'At what day of the week should the counter be reset?', 'commonsbooking' ),
+ $weekDaysSelect,
),
Closure::fromCallable( array( self::class, 'maxDaysWeekErrorMessage' ) )
),
new BookingRule(
- "maxBookingDaysPerMonth",
- __( "Maximum booked days per month", 'commonsbooking' ),
- __( "Users are only allowed to book a limited amount of days per month.", 'commonsbooking' ),
- __( "You have reached your booking limit. Please leave some time in between bookings.", 'commonsbooking' ),
+ 'maxBookingDaysPerMonth',
+ __( 'Maximum booked days per month', 'commonsbooking' ),
+ __( 'Users are only allowed to book a limited amount of days per month.', 'commonsbooking' ),
+ __( 'You have reached your booking limit. Please leave some time in between bookings.', 'commonsbooking' ),
Closure::fromCallable( array( self::class, 'checkMaxBookingDaysPerMonth' ) ),
array(
array(
- "title" => __( "Maximum booked days per month", 'commonsbooking' ),
- "description" => __( "Number of days each user is allowed to book per month", 'commonsbooking' ),
- )
+ 'title' => __( 'Maximum booked days per month', 'commonsbooking' ),
+ 'description' => __( 'Number of days each user is allowed to book per month', 'commonsbooking' ),
+ ),
),
array(
- __( "At what day of the month should the counter be reset?", 'commonsbooking' ),
- $monthDaysSelect
+ __( 'At what day of the month should the counter be reset?', 'commonsbooking' ),
+ $monthDaysSelect,
),
Closure::fromCallable( array( self::class, 'maxDaysMonthErrorMessage' ) )
),
new BookingRule(
- "maxBookingDays",
- __( "Maximum of bookable days in time period", 'commonsbooking' ),
- __( "Allow x booked days over the period of y days for user.", 'commonsbooking' ),
- __( "Booking limit exceeded. ", 'commonsbooking' ),
+ 'maxBookingDays',
+ __( 'Maximum of bookable days in time period', 'commonsbooking' ),
+ __( 'Allow x booked days over the period of y days for user.', 'commonsbooking' ),
+ __( 'Booking limit exceeded. ', 'commonsbooking' ),
Closure::fromCallable( array( self::class, 'checkMaxBookingDays' ) ),
array(
array(
- "title" => __( "Allow x booked days", 'commonsbooking' ),
- "description" => __( "How many days are free to book in the given period of days", 'commonsbooking' ),
+ 'title' => __( 'Allow x booked days', 'commonsbooking' ),
+ 'description' => __( 'How many days are free to book in the given period of days', 'commonsbooking' ),
),
array(
- "title" => __( "In the period of y days", 'commonsbooking' ),
- "description" => __( "The length of the period for which the booking is limited. This period always lies in the middle, so if you define 30 days, the 15 days before and after will count towards the maximum quota.", 'commonsbooking' ),
- )
+ 'title' => __( 'In the period of y days', 'commonsbooking' ),
+ 'description' => __( 'The length of the period for which the booking is limited. This period always lies in the middle, so if you define 30 days, the 15 days before and after will count towards the maximum quota.', 'commonsbooking' ),
+ ),
),
[],
Closure::fromCallable( array( self::class, 'maxBookingDaysErrorMessage' ) )
),
new BookingRule(
- "maxBookingsWeek",
- __( "Maximum number of bookings per week", 'commonsbooking' ),
- __( "Users are only allowed to make that many bookings per week (Irrespective of their length).", 'commonsbooking' ),
- __( "You have reached your booking limit. Please leave some time in between bookings.", 'commonsbooking' ),
+ 'maxBookingsWeek',
+ __( 'Maximum number of bookings per week', 'commonsbooking' ),
+ __( 'Users are only allowed to make that many bookings per week (Irrespective of their length).', 'commonsbooking' ),
+ __( 'You have reached your booking limit. Please leave some time in between bookings.', 'commonsbooking' ),
Closure::fromCallable( array( self::class, 'checkMaxBookingsWeek' ) ),
array(
array(
- "title" => __( "Maximum number of bookings per week", 'commonsbooking' ),
- "description" => __( "Number of bookings each user is allowed to make per week", 'commonsbooking' ),
- )
+ 'title' => __( 'Maximum number of bookings per week', 'commonsbooking' ),
+ 'description' => __( 'Number of bookings each user is allowed to make per week', 'commonsbooking' ),
+ ),
),
array(
- __( "At what day of the week should the counter be reset?", 'commonsbooking' ),
- $weekDaysSelect
+ __( 'At what day of the week should the counter be reset?', 'commonsbooking' ),
+ $weekDaysSelect,
),
Closure::fromCallable( array( self::class, 'maxBookingsWeekErrorMessage' ) )
),
new BookingRule(
- "maxBookingsMonth",
- __( "Maximum number of bookings per month", 'commonsbooking' ),
- __( "Users are only allowed to make that many bookings per month (Irrespective of their length).", 'commonsbooking' ),
- __( "You have reached your booking limit. Please leave some time in between bookings.", 'commonsbooking' ),
+ 'maxBookingsMonth',
+ __( 'Maximum number of bookings per month', 'commonsbooking' ),
+ __( 'Users are only allowed to make that many bookings per month (Irrespective of their length).', 'commonsbooking' ),
+ __( 'You have reached your booking limit. Please leave some time in between bookings.', 'commonsbooking' ),
Closure::fromCallable( array( self::class, 'checkMaxBookingsMonth' ) ),
array(
array(
- "title" => __( "Maximum number of bookings per month", 'commonsbooking' ),
- "description" => __( "Number of bookings each user is allowed to make per month", 'commonsbooking' ),
- )
+ 'title' => __( 'Maximum number of bookings per month', 'commonsbooking' ),
+ 'description' => __( 'Number of bookings each user is allowed to make per month', 'commonsbooking' ),
+ ),
),
array(
- __( "At what day of the month should the counter be reset?", 'commonsbooking' ),
- $monthDaysSelect
+ __( 'At what day of the month should the counter be reset?', 'commonsbooking' ),
+ $monthDaysSelect,
),
Closure::fromCallable( array( self::class, 'maxBookingsMonthErrorMessage' ) )
- )
+ ),
];
return apply_filters( COMMONSBOOKING_PLUGIN_SLUG . '_booking-rules', $defaultRuleSet );
@@ -322,9 +336,8 @@ public static function init(): array {
* If the user has bookings at the same day it will return an array with conflicting bookings
* If there is no booking at the same day, will return null
*
- *
- * @param Booking $booking
- * @param array $args
+ * @param Booking $booking
+ * @param array $args
* @param bool|array $appliedTerms
*
* @return array|null
@@ -337,9 +350,12 @@ public static function checkSimultaneousBookings( Booking $booking, array $args
return null;
}
- return array_filter( $userBookings, function ( $userBooking ) use ( $booking ) {
- return $userBooking->hasTimeframeDateOverlap( $booking );
- } );
+ return array_filter(
+ $userBookings,
+ function ( $userBooking ) use ( $booking ) {
+ return $userBooking->hasTimeframeDateOverlap( $booking );
+ }
+ );
}
/**
@@ -347,8 +363,8 @@ public static function checkSimultaneousBookings( Booking $booking, array $args
* If the user has chained too many days in that timespan will return the conflicting bookings
* If the user bookings are NOT above the limit, will return null
*
- * @param Booking $booking
- * @param array $args
+ * @param Booking $booking
+ * @param array $args
* @param bool|array $appliedTerms
*
* @return array|null
@@ -373,23 +389,29 @@ public static function checkChainBooking( Booking $booking, array $args = [], $a
return null;
}
$bookingCollection = $booking->getBookingChain( $bookingUser );
- //add our current booking to the collection
+ // add our current booking to the collection
$bookingCollection[] = $booking;
- uasort( $bookingCollection, function ( Booking $a, Booking $b ) {
- return $a->getStartDate() <=> $b->getStartDate();
- } );
+ uasort(
+ $bookingCollection,
+ function ( Booking $a, Booking $b ) {
+ return $a->getStartDate() <=> $b->getStartDate();
+ }
+ );
$collectionStartDate = reset( $bookingCollection )->getStartDateDateTime();
- $collectionEndDate = end( $bookingCollection )->getEndDateDateTime()->modify( "+1 second" );
+ $collectionEndDate = end( $bookingCollection )->getEndDateDateTime()->modify( '+1 second' );
$collectionTotalDays = $collectionStartDate->diff( $collectionEndDate )->d;
- //checks if the collection of chained bookings ist still in the allowed limit
+ // checks if the collection of chained bookings ist still in the allowed limit
$max_days = $timeframe->getMaxDays();
if ( $collectionTotalDays <= $max_days ) {
return null;
} else {
- //remove the checked unallowed booking from the collection
- return array_filter( $bookingCollection, function ( Booking $collectionItem ) use ( $booking ) {
- return $collectionItem->ID !== $booking->ID;
- } );
+ // remove the checked unallowed booking from the collection
+ return array_filter(
+ $bookingCollection,
+ function ( Booking $collectionItem ) use ( $booking ) {
+ return $collectionItem->ID !== $booking->ID;
+ }
+ );
}
}
@@ -402,8 +424,8 @@ public static function checkChainBooking( Booking $booking, array $args = [], $a
* Params: $args[0} = The amount of days the user is allowed to book
* $args[1] = The period over which the user is allowed to book
*
- * @param Booking $booking
- * @param array $args
+ * @param Booking $booking
+ * @param array $args
* @param bool|array $appliedTerms
*
* @return array
@@ -412,7 +434,7 @@ public static function checkChainBooking( Booking $booking, array $args = [], $a
public static function checkMaxBookingDays( Booking $booking, array $args, $appliedTerms = false ): ?array {
$allowedBookedDays = $args[0];
$periodDays = $args[1];
- //split the period in half, when it is an uneven number, the left side will be one day longer
+ // split the period in half, when it is an uneven number, the left side will be one day longer
$daysHalf = $periodDays / 2;
if ( $periodDays % 2 ) {
$daysLeft = $daysHalf + 1;
@@ -420,8 +442,8 @@ public static function checkMaxBookingDays( Booking $booking, array $args, $appl
} else {
$daysLeft = $daysRight = $daysHalf;
}
- $startOfPeriod = $booking->getStartDateDateTime()->modify( "-" . $daysLeft . " days" );
- $endOfPeriod = $booking->getEndDateDateTime()->modify( "+" . $daysRight . " days" );
+ $startOfPeriod = $booking->getStartDateDateTime()->modify( '-' . $daysLeft . ' days' );
+ $endOfPeriod = $booking->getEndDateDateTime()->modify( '+' . $daysRight . ' days' );
return self::checkBookingRangeForDays( $startOfPeriod, $endOfPeriod, $booking, $appliedTerms, $allowedBookedDays );
}
@@ -438,21 +460,20 @@ public static function maxBookingDaysErrorMessage( $args ) {
* Will return the conflicting bookings if a user has too many in the week
*
* Params: $args[0] : The amount of days the user is allowed to book per week
- * $args[1] : Unused
+ * $args[1] : Unused
* $args[2]: The day on which the counter is reset, default: 1 = sunday, 2 = monday, ..., 7 = saturday
*
- *
- * @param Booking $booking
- * @param array $args
+ * @param Booking $booking
+ * @param array $args
* @param bool|array $appliedTerms
*
* @return array|null
*/
public static function checkMaxBookingDaysPerWeek( Booking $booking, array $args, $appliedTerms = false ): ?array {
$allowedBookableDays = $args[0];
- //default is sunday, we could not use 0 because it would be interpreted as an empty value
+ // default is sunday, we could not use 0 because it would be interpreted as an empty value
$resetDay = ( $args[2] < 7 && $args[2] >= 1 ) ? $args[2] : 1;
- $range = self::getBookingWeekRange( $booking, $resetDay );
+ $range = self::getBookingWeekRange( $booking, $resetDay );
return self::checkBookingRangeForDays( $range[0], $range[1], $booking, $appliedTerms, $allowedBookableDays );
}
@@ -468,9 +489,9 @@ public static function maxDaysWeekErrorMessage( array $args ): string {
public static function checkMaxBookingsWeek( Booking $booking, array $args, $appliedTerms = false ): ?array {
$allowedTotalBookings = $args[0];
- //default is sunday
+ // default is sunday
$resetDay = ( $args[2] < 6 && $args[2] >= 0 ) ? $args[2] : 0;
- $range = self::getBookingWeekRange( $booking, $resetDay );
+ $range = self::getBookingWeekRange( $booking, $resetDay );
return self::checkBookingAmount( $range[0], $range[1], $booking, $appliedTerms, $allowedTotalBookings );
}
@@ -492,9 +513,8 @@ public static function maxBookingsWeekErrorMessage( array $args ): string {
* $args[1] : Unused
* $args[2]: The day on which the counter is reset, from 0 to max 31.
*
- *
- * @param Booking $booking
- * @param array $args
+ * @param Booking $booking
+ * @param array $args
* @param bool|array $appliedTerms
*
* @return array|null
@@ -505,7 +525,6 @@ public static function checkMaxBookingDaysPerMonth( Booking $booking, array $arg
$range = self::getBookingMonthRange( $booking, $resetDay );
return self::checkBookingRangeForDays( $range[0], $range[1], $booking, $appliedTerms, $allowedBookableDays );
-
}
public static function maxDaysMonthErrorMessage( array $args ): string {
@@ -534,12 +553,12 @@ public static function maxBookingsMonthErrorMessage( array $args ): string {
* Will get two datetime objects that represent the start and end of the week in which the given booking is in.
*
* @param Booking $booking - The booking for which the week range should be determined
- * @param int $resetDay - The day of the week on which the counter should be reset (1 = sunday, 2 = monday, ..., 7 = saturday)
+ * @param int $resetDay - The day of the week on which the counter should be reset (1 = sunday, 2 = monday, ..., 7 = saturday)
*
* @return DateTime[] - [0] = start of the week, [1] = end of the week
*/
- private static function getBookingWeekRange(Booking $booking, int $resetDay): array {
- $resetDay--; // We couldn't use 0 for sunday because it would be interpreted as an empty value, so we subtract 1 here
+ private static function getBookingWeekRange( Booking $booking, int $resetDay ): array {
+ --$resetDay; // We couldn't use 0 for sunday because it would be interpreted as an empty value, so we subtract 1 here
$resetDayString = strtolower( date( 'l', strtotime( "Sunday +{$resetDay} days" ) ) );
$bookingDate = $booking->getStartDateDateTime();
@@ -554,25 +573,24 @@ private static function getBookingWeekRange(Booking $booking, int $resetDay): ar
$startOfWeek->modify( 'last ' . $resetDayString );
$endOfWeek->modify( 'next ' . $resetDayString );
}
- return [$startOfWeek, $endOfWeek];
+ return [ $startOfWeek, $endOfWeek ];
}
/**
* Will get two datetime objects that represent the start and end of the month in which the given booking is in.
*
* @param Booking $booking - The booking for which the month range should be determined
- * @param int $resetDay - The day of the month on which the counter should be reset
+ * @param int $resetDay - The day of the month on which the counter should be reset
*
* @return DateTime[] - [0] = start of the month, [1] = end of the month
*/
- private static function getBookingMonthRange(Booking $booking, int $resetDay): array {
- $bookingDate = $booking->getStartDateDateTime();
+ private static function getBookingMonthRange( Booking $booking, int $resetDay ): array {
+ $bookingDate = $booking->getStartDateDateTime();
// if the reset day is higher than the current max day of the month, we need to adjust the reset day
$maxDayOfMonth = $bookingDate->format( 't' );
$resetDay = ( $resetDay > $maxDayOfMonth ) ? $maxDayOfMonth : $resetDay;
-
- //get the current month and year
+ // get the current month and year
$day = $bookingDate->format( 'd' );
$month = $bookingDate->format( 'm' );
@@ -586,7 +604,7 @@ private static function getBookingMonthRange(Booking $booking, int $resetDay): a
} else {
$endDate->modify( '+1 month' );
}
- return [$startDate, $endDate];
+ return [ $startDate, $endDate ];
}
/**
@@ -596,14 +614,14 @@ private static function getBookingMonthRange(Booking $booking, int $resetDay): a
* Is often used by BookingRule to determine if a booking should be taken into consideration
*
* @param Booking[] $bookings
- * @param \WP_User $user
+ * @param \WP_User $user
* @param $terms
*
* @return array|null
*/
private static function filterBookingsForTermsAndUser( array $bookings, \WP_User $user, $terms ): ?array {
$filteredTerms = Booking::filterTermsApply( $bookings, $terms );
- if ( ! empty ( $filteredTerms ) ) {
+ if ( ! empty( $filteredTerms ) ) {
return Booking::filterForUser( $bookings, $user );
} else {
return null;
@@ -613,12 +631,13 @@ private static function filterBookingsForTermsAndUser( array $bookings, \WP_User
/**
* Check, if the BookingRules settings have been modified from what is defined by default.
* Used to check, if the setting has been touched by the user.
+ *
* @return bool
*/
public static function hasDefaultSettings(): bool {
$rulesConfig = Settings::getOption( 'commonsbooking_options_restrictions', 'rules_group' );
- return empty ( $rulesConfig );
+ return empty( $rulesConfig );
}
/**
@@ -640,11 +659,11 @@ private static function filterEmptyBookings( array $bookings ) {
* Will return the conflicting bookings if a user has too many in the range.
* Will also consider the setting if cancelled bookings should be considered.
*
- * @param DateTime $startOfRange
- * @param DateTime $endOfRange
- * @param Booking $booking
+ * @param DateTime $startOfRange
+ * @param DateTime $endOfRange
+ * @param Booking $booking
* @param array|false $appliedTerms
- * @param int $allowedBookableDays
+ * @param int $allowedBookableDays
*
* @return array|null - conflicting bookings in order of post_date
* @throws Exception
@@ -667,11 +686,11 @@ private static function checkBookingRangeForDays( DateTime $startOfRange, DateTi
$countedPostTypes
);
$rangeBookingsArray = self::filterBookingsForTermsAndUser( $rangeBookingsArray, $booking->getUserData(), $appliedTerms );
- if ( empty ( $rangeBookingsArray ) ) {
+ if ( empty( $rangeBookingsArray ) ) {
return null;
}
$rangeBookingsArray = self::filterEmptyBookings( $rangeBookingsArray );
- if ( empty ( $rangeBookingsArray ) ) {
+ if ( empty( $rangeBookingsArray ) ) {
return null;
}
$totalLength = Booking::getTotalDuration( $rangeBookingsArray );
@@ -691,11 +710,11 @@ private static function checkBookingRangeForDays( DateTime $startOfRange, DateTi
* Will return the conflicting bookings if a user has too many in the range.
* Cancelled bookings will be considered when they were cancelled after the start of the range.
*
- * @param DateTime $startOfRange
- * @param DateTime $endOfRange
- * @param Booking $booking
+ * @param DateTime $startOfRange
+ * @param DateTime $endOfRange
+ * @param Booking $booking
* @param $appliedTerms
- * @param int $allowedTotalBookings
+ * @param int $allowedTotalBookings
*
* @return Booking[]|null
* @throws Exception
@@ -718,11 +737,11 @@ private static function checkBookingAmount( DateTime $startOfRange, DateTime $en
$countedPostTypes
);
$rangeBookingsArray = self::filterBookingsForTermsAndUser( $rangeBookingsArray, $booking->getUserData(), $appliedTerms );
- if ( empty ( $rangeBookingsArray ) ) {
+ if ( empty( $rangeBookingsArray ) ) {
return null;
}
$rangeBookingsArray = self::filterEmptyBookings( $rangeBookingsArray );
- if ( empty ( $rangeBookingsArray ) ) {
+ if ( empty( $rangeBookingsArray ) ) {
return null;
}
$totalBookings = count( $rangeBookingsArray );
diff --git a/src/Service/BookingRuleApplied.php b/src/Service/BookingRuleApplied.php
index ed88e9e27..0c6ccb876 100644
--- a/src/Service/BookingRuleApplied.php
+++ b/src/Service/BookingRuleApplied.php
@@ -29,11 +29,12 @@ class BookingRuleApplied extends BookingRule {
/**
* Will construct a BookingRuleApplied object from an existing BookingRule.
+ *
* @param BookingRule $rule
*
* @throws BookingRuleException
*/
- public function __construct( BookingRule $rule) {
+ public function __construct( BookingRule $rule ) {
parent::__construct(
$rule->name,
$rule->title,
@@ -49,14 +50,14 @@ public function __construct( BookingRule $rule) {
/**
* Will set what this Booking Rule applies to, either needs to be all or at least one category
*
- * @param bool $appliesToAll
- * @param array $appliedTerms
+ * @param bool $appliesToAll
+ * @param array $appliedTerms
*
* @throws BookingRuleException
*/
- public function setAppliesToWhat(bool $appliesToAll, array $appliedTerms = []): void {
- if (! $appliesToAll && empty($appliedTerms)){
- throw new BookingRuleException(__("You need to specify a category, if the rule does not apply to all items", 'commonsbooking'));
+ public function setAppliesToWhat( bool $appliesToAll, array $appliedTerms = [] ): void {
+ if ( ! $appliesToAll && empty( $appliedTerms ) ) {
+ throw new BookingRuleException( __( 'You need to specify a category, if the rule does not apply to all items', 'commonsbooking' ) );
}
$this->appliesToAll = $appliesToAll;
$this->appliedTerms = $appliedTerms;
@@ -65,38 +66,36 @@ public function setAppliesToWhat(bool $appliesToAll, array $appliedTerms = []):
/**
* Will set the necessary params for the BookingRule to work
*
- * @param array $paramsToSet needs to be numeric
- * @param int|string $selectParam needs to be numeric
+ * @param array $paramsToSet needs to be numeric
+ * @param int|string $selectParam needs to be numeric
*
* @throws BookingRuleException - if not enough params were specified for the BookingRule
*/
public function setAppliedParams( array $paramsToSet, $selectParam ): void {
- if (! empty($this->params)){
- if (count($this->params) == count($paramsToSet) ){
+ if ( ! empty( $this->params ) ) {
+ if ( count( $this->params ) == count( $paramsToSet ) ) {
$this->appliedParams = $paramsToSet;
- }
- else {
- throw new BookingRuleException(__("Booking rules: Not enough parameters specified.", 'commonsbooking'));
+ } else {
+ throw new BookingRuleException( __( 'Booking rules: Not enough parameters specified.', 'commonsbooking' ) );
}
foreach ( $paramsToSet as $param ) {
if ( ! is_numeric( $param ) ) {
- throw new BookingRuleException( __( "Booking rules: Parameters need to be a number.", 'commonsbooking' ) );
+ throw new BookingRuleException( __( 'Booking rules: Parameters need to be a number.', 'commonsbooking' ) );
}
}
}
- if (! empty($this->selectParam)){
- if ( empty ( $selectParam ) || ! is_numeric($selectParam)){
- throw new BookingRuleException(__("Booking rules: Select parameter has not been properly set.", 'commonsbooking'));
+ if ( ! empty( $this->selectParam ) ) {
+ if ( empty( $selectParam ) || ! is_numeric( $selectParam ) ) {
+ throw new BookingRuleException( __( 'Booking rules: Select parameter has not been properly set.', 'commonsbooking' ) );
}
- $this->appliedSelectParam = $selectParam;
+ $this->appliedSelectParam = $selectParam;
}
}
/**
* Sets the roles that the rule will not apply to
*
- * @param array $excludedRoles
- *
+ * @param array $excludedRoles
*/
public function setExcludedRoles( array $excludedRoles ): void {
$this->excludedRoles = $excludedRoles;
@@ -112,23 +111,23 @@ public function setExcludedRoles( array $excludedRoles ): void {
* @return array|null - An array of conflicting bookings or an empty array if the booking complies with all rules
*/
public function checkBookingCompliance( Booking $booking ): ?array {
- if ($booking->isUserPrivileged()){
+ if ( $booking->isUserPrivileged() ) {
return null;
}
// Check if a rule is excluded for the user because of their role
- if (isset ($this->excludedRoles)){
+ if ( isset( $this->excludedRoles ) ) {
if (
UserRepository::userHasRoles(
$booking->getUserData()->ID,
$this->excludedRoles
)
- ){
+ ) {
return null;
}
}
- if (! $this->appliesToAll && ! $booking->termsApply($this->appliedTerms)){
+ if ( ! $this->appliesToAll && ! $booking->termsApply( $this->appliedTerms ) ) {
return null;
}
@@ -144,33 +143,31 @@ public function checkBookingCompliance( Booking $booking ): ?array {
* @return void
* @throws BookingDeniedException
*/
- public static function bookingConformsToRules( Booking $booking):void {
+ public static function bookingConformsToRules( Booking $booking ): void {
try {
$ruleset = self::init();
} catch ( BookingRuleException $e ) {
- //booking always conforms to rules if ruleset is not available / invalid
+ // booking always conforms to rules if ruleset is not available / invalid
return;
}
- if($booking->isUserPrivileged()){
+ if ( $booking->isUserPrivileged() ) {
return;
}
foreach ( $ruleset as $rule ) {
-
- if ( ! ($rule instanceof BookingRuleApplied )) {
- continue; //skip invalid rules during booking validation
+ if ( ! ( $rule instanceof BookingRuleApplied ) ) {
+ continue; // skip invalid rules during booking validation
}
$conflictingBookings = $rule->checkBookingCompliance( $booking );
- if ( $conflictingBookings ){
+ if ( $conflictingBookings ) {
$errorMessage =
- $rule->getErrorMessage($rule->getArgs()) .
+ $rule->getErrorMessage( $rule->getArgs() ) .
PHP_EOL .
- __( "This affects the following bookings:", 'commonsbooking' ) .
- PHP_EOL
- ;
+ __( 'This affects the following bookings:', 'commonsbooking' ) .
+ PHP_EOL;
/** @var Booking $conflictingBooking */
- foreach ($conflictingBookings as $conflictingBooking){
+ foreach ( $conflictingBookings as $conflictingBooking ) {
$errorMessage .= $conflictingBooking->bookingLink(
sprintf(
'%1s - %2s | %3s @ %4s',
@@ -190,6 +187,7 @@ public static function bookingConformsToRules( Booking $booking):void {
* Gets a string of all rule properties, so they can be displayed using CMB2
*
* Will ignore errors, so that the settings page can still display the selected values even if they are invalid
+ *
* @return string
*/
public static function getRulesJSON(): string {
@@ -198,13 +196,14 @@ public static function getRulesJSON(): string {
if ( isset( $ruleObjects ) ) {
return wp_json_encode(
array_map(
- function( $rule){
- return get_object_vars($rule);
- }, $ruleObjects )
+ function ( $rule ) {
+ return get_object_vars( $rule );
+ },
+ $ruleObjects
+ )
);
- }
- else {
- return "";
+ } else {
+ return '';
}
}
@@ -218,59 +217,58 @@ function( $rule){
* @throws BookingRuleException
* @OVERRIDE
*/
- public static function init( bool $ignoreErrors = false ):array{
- $validRules = parent::init();
- $rulesConfig = Settings::getOption('commonsbooking_options_restrictions', 'rules_group');
+ public static function init( bool $ignoreErrors = false ): array {
+ $validRules = parent::init();
+ $rulesConfig = Settings::getOption( 'commonsbooking_options_restrictions', 'rules_group' );
$appliedRules = [];
- if (!is_array($rulesConfig)) {
- if ($ignoreErrors){
+ if ( ! is_array( $rulesConfig ) ) {
+ if ( $ignoreErrors ) {
return [];
}
- throw new BookingRuleException('No valid booking rules found');
+ throw new BookingRuleException( 'No valid booking rules found' );
}
- foreach ($rulesConfig as $ruleConfig) {
+ foreach ( $rulesConfig as $ruleConfig ) {
/** @var BookingRule $validRule */
- foreach ($validRules as $validRule){
+ foreach ( $validRules as $validRule ) {
if ( ! isset( $ruleConfig['rule-type'] ) ) {
- if ($ignoreErrors){
- continue;
- }
+ if ( $ignoreErrors ) {
+ continue;
+ }
throw new BookingRuleException( __( 'Booking rules: No rule type specified.', 'commonsbooking' ) );
}
- if ($validRule->name !== $ruleConfig['rule-type']) {
+ if ( $validRule->name !== $ruleConfig['rule-type'] ) {
continue;
}
$ruleParams = [];
- if (
- ! empty($ruleConfig['rule-param1']) &&
- count($validRule->params) >= 1)
- {
- $ruleParams[] = $ruleConfig['rule-param1'];
- }
if (
- ! empty($ruleConfig['rule-param2']) &&
- count($validRule->params) >= 2
- )
- {
+ ! empty( $ruleConfig['rule-param1'] ) &&
+ count( $validRule->params ) >= 1 ) {
+ $ruleParams[] = $ruleConfig['rule-param1'];
+ }
+ if (
+ ! empty( $ruleConfig['rule-param2'] ) &&
+ count( $validRule->params ) >= 2
+ ) {
$ruleParams[] = $ruleConfig['rule-param2'];
}
- if (! empty ( $ruleConfig['rule-select-param'] )) { $selectParam = $ruleConfig['rule-select-param']; }
+ if ( ! empty( $ruleConfig['rule-select-param'] ) ) {
+ $selectParam = $ruleConfig['rule-select-param']; }
- if (! empty ( $ruleConfig['rule-applies-all'] ) && $ruleConfig['rule-applies-all'] === 'on'){
+ if ( ! empty( $ruleConfig['rule-applies-all'] ) && $ruleConfig['rule-applies-all'] === 'on' ) {
$appliesToAll = true;
}
- if ( ! empty ( $ruleConfig['rule-applies-categories'] ) ){
+ if ( ! empty( $ruleConfig['rule-applies-categories'] ) ) {
$appliedTerms = $ruleConfig['rule-applies-categories'];
}
- $ruleExemptRoles = empty($ruleConfig['rule-exempt-roles']) ? null : $ruleConfig['rule-exempt-roles'];
+ $ruleExemptRoles = empty( $ruleConfig['rule-exempt-roles'] ) ? null : $ruleConfig['rule-exempt-roles'];
- $bookingRule = new self($validRule);
+ $bookingRule = new self( $validRule );
try {
$bookingRule->setAppliesToWhat(
$appliesToAll ?? false,
@@ -279,8 +277,7 @@ public static function init( bool $ignoreErrors = false ):array{
} catch ( BookingRuleException $e ) {
if ( $ignoreErrors ) {
continue;
- }
- else {
+ } else {
throw $e;
}
}
@@ -292,26 +289,26 @@ public static function init( bool $ignoreErrors = false ):array{
} catch ( BookingRuleException $e ) {
if ( $ignoreErrors ) {
continue;
- }
- else {
+ } else {
throw $e;
}
}
$bookingRule->setExcludedRoles(
- $ruleExemptRoles ?? []);
+ $ruleExemptRoles ?? []
+ );
$appliedRules[] = $bookingRule;
-
- }
}
+ }
return $appliedRules;
}
/**
* Checks if it can create all the rules, sets an error transient if it can't
+ *
* @return void
*/
- public static function validateRules():void{
+ public static function validateRules(): void {
if ( self::hasDefaultSettings() ) {
return;
@@ -328,15 +325,16 @@ public static function validateRules():void{
/**
* Will get the args array that belongs to the rule
+ *
* @return null[]
*/
private function getArgs(): array {
$args = $this->appliedParams ?? [ null, null ];
- //add null value to array to keep the params in the right order
+ // add null value to array to keep the params in the right order
if ( count( $args ) == 1 ) {
$args[] = null;
}
- if ( ! empty ( $this->appliedSelectParam ) ) {
+ if ( ! empty( $this->appliedSelectParam ) ) {
$args[] = $this->appliedSelectParam;
} else {
$args[] = null;
@@ -344,4 +342,4 @@ private function getArgs(): array {
return $args;
}
-}
\ No newline at end of file
+}
diff --git a/src/Service/Cache.php b/src/Service/Cache.php
index bc6c151b6..ecdc486f1 100644
--- a/src/Service/Cache.php
+++ b/src/Service/Cache.php
@@ -19,6 +19,7 @@ trait Cache {
/**
* TODO: Refactor to constant after PHP 8.2
+ *
* @var string
*/
private static string $clearCacheHook = COMMONSBOOKING_PLUGIN_SLUG . '_clear_cache';
@@ -43,7 +44,8 @@ public static function getCacheItem( $custom_id = null ) {
if ( $cacheItem->isHit() ) {
return $cacheItem->get();
}
- } catch (\Exception $exception) {}
+ } catch ( \Exception $exception ) {
+ }
return false;
}
@@ -56,17 +58,16 @@ public static function getCacheItem( $custom_id = null ) {
* @return string
* @since 2.7.2 added Plugin_Dir to Namespace to avoid conflicts on multiple instances on same server
* @since 2.9.4 added support for multisite caches
- *
*/
public static function getCacheId( $custom_id = null ): string {
$backtrace = debug_backtrace()[2];
$backtrace = self::sanitizeArgsArray( $backtrace );
- $namespace = COMMONSBOOKING_PLUGIN_DIR; //To account for multiple instances on same server
- $namespace .= '_' . get_current_blog_id(); //To account for WP Multisite
- $namespace .= '_' . str_replace( '\\', '_', strtolower( $backtrace['class'] ) );
- $namespace .= '_' . $backtrace['function'];
+ $namespace = COMMONSBOOKING_PLUGIN_DIR; // To account for multiple instances on same server
+ $namespace .= '_' . get_current_blog_id(); // To account for WP Multisite
+ $namespace .= '_' . str_replace( '\\', '_', strtolower( $backtrace['class'] ) );
+ $namespace .= '_' . $backtrace['function'];
$backtraceArgs = $backtrace['args'];
- $namespace .= '_' . serialize( $backtraceArgs );
+ $namespace .= '_' . serialize( $backtraceArgs );
if ( $custom_id ) {
$namespace .= $custom_id;
}
@@ -81,8 +82,8 @@ public static function getCacheId( $custom_id = null ): string {
*/
private static function sanitizeArgsArray( $backtrace ) {
if ( array_key_exists( 'args', $backtrace ) &&
- count( $backtrace['args'] ) &&
- is_array( $backtrace['args'][0] )
+ count( $backtrace['args'] ) &&
+ is_array( $backtrace['args'][0] )
) {
if ( array_key_exists( 'taxonomy', $backtrace['args'][0] ) ) {
unset( $backtrace['args'][0]['taxonomy'] );
@@ -100,28 +101,28 @@ private static function sanitizeArgsArray( $backtrace ) {
/**
* Creates cache based on user settings or defaults.
- *
+ *
* At the moment filesystem and redis cache are supported.
*
- * @param string $namespace
- * @param int $defaultLifetime
+ * @param string $namespace
+ * @param int $defaultLifetime
* @param string|null $directory
*
* @return TagAwareAdapterInterface
*/
public static function getCache( string $namespace = '', int $defaultLifetime = 0, string $directory = null ): TagAwareAdapterInterface {
- if ( $directory === null ){
+ if ( $directory === null ) {
$customCachePath = commonsbooking_sanitizeArrayorString( Settings::getOption( COMMONSBOOKING_PLUGIN_SLUG . '_options_advanced-options', 'cache_path' ) );
- if ( $customCachePath ){
+ if ( $customCachePath ) {
$directory = $customCachePath;
}
- //Since this is the default cache path by Symfony we'd rather set it to null so that Symfony can take over with it's own default value.
- else if ( $customCachePath == '/tmp/symfony-cache/' ) {
+ // Since this is the default cache path by Symfony we'd rather set it to null so that Symfony can take over with it's own default value.
+ elseif ( $customCachePath == '/tmp/symfony-cache/' ) {
$directory = null;
}
}
- if (Settings::getOption( COMMONSBOOKING_PLUGIN_SLUG . '_options_advanced-options', 'redis_enabled' ) === 'on'){
+ if ( Settings::getOption( COMMONSBOOKING_PLUGIN_SLUG . '_options_advanced-options', 'redis_enabled' ) === 'on' ) {
try {
$adapter = new RedisTagAwareAdapter(
RedisAdapter::createConnection( Settings::getOption( COMMONSBOOKING_PLUGIN_SLUG . '_options_advanced-options', 'redis_dsn' ) ),
@@ -129,8 +130,7 @@ public static function getCache( string $namespace = '', int $defaultLifetime =
$defaultLifetime
);
return $adapter;
- }
- catch (Exception $e) {
+ } catch ( Exception $e ) {
commonsbooking_write_log( $e . 'Falling back to Filesystem adapter' );
set_transient( COMMONSBOOKING_PLUGIN_SLUG . '_adapter-error', $e->getMessage() );
}
@@ -145,8 +145,8 @@ public static function getCache( string $namespace = '', int $defaultLifetime =
* Saves cache item based on calling class, function and args.
*
* @param $value
- * @param array $tags
- * @param null $custom_id
+ * @param array $tags
+ * @param null $custom_id
* @param string|null $expirationString set expiration as timestamp or string 'midnight' to set expiration to 00:00 next day
*
* @return bool
@@ -158,11 +158,11 @@ public static function setCacheItem( $value, array $tags, $custom_id = null, ?st
// too much space
$expiration = 604800;
- $tags = array_map('strval', $tags);
- $tags = array_filter($tags);
+ $tags = array_map( 'strval', $tags );
+ $tags = array_filter( $tags );
- if(!count($tags)) {
- $tags = ['misc'];
+ if ( ! count( $tags ) ) {
+ $tags = [ 'misc' ];
}
// if expiration is set to 'midnight' we calculate the duration in seconds until midnight
@@ -175,9 +175,9 @@ public static function setCacheItem( $value, array $tags, $custom_id = null, ?st
/** @var CacheItem $cacheItem */
$cacheKey = self::getCacheId( $custom_id );
$cacheItem = $cache->getItem( $cacheKey );
- $cacheItem->tag($tags);
+ $cacheItem->tag( $tags );
$cacheItem->set( $value );
- $cacheItem->expiresAfter(intval( $expiration ));
+ $cacheItem->expiresAfter( intval( $expiration ) );
return $cache->save( $cacheItem );
}
@@ -190,18 +190,18 @@ public static function setCacheItem( $value, array $tags, $custom_id = null, ?st
* @throws InvalidArgumentException
*/
public static function clearCache( array $tags = [] ) {
- if(!count($tags)) {
+ if ( ! count( $tags ) ) {
self::getCache()->clear();
} else {
- self::getCache()->invalidateTags($tags);
+ self::getCache()->invalidateTags( $tags );
}
// Delete expired cache items (only for Pruneable Interfaces)
- if (is_a(self::getCache(),'Symfony\Component\Cache\PruneableInterface')) {
+ if ( is_a( self::getCache(), 'Symfony\Component\Cache\PruneableInterface' ) ) {
self::getCache()->prune();
}
- set_transient("clearCacheHasBeenDone", true, 45);
+ set_transient( 'clearCacheHasBeenDone', true, 45 );
}
/**
@@ -223,13 +223,14 @@ public static function scheduleClearCache( array $tags = [] ) {
/**
* Add js to frontend on cache clear.
+ *
* @return void
*/
public static function addWarmupAjaxToOutput() {
- if(get_transient("clearCacheHasBeenDone")) {
- delete_transient("clearCacheHasBeenDone");
- wp_register_script( 'cache_warmup', '', array("jquery"), '', true );
- wp_enqueue_script( 'cache_warmup' );
+ if ( get_transient( 'clearCacheHasBeenDone' ) ) {
+ delete_transient( 'clearCacheHasBeenDone' );
+ wp_register_script( 'cache_warmup', '', array( 'jquery' ), '', true );
+ wp_enqueue_script( 'cache_warmup' );
wp_add_inline_script(
'cache_warmup',
'
@@ -251,7 +252,7 @@ public static function warmupCache() {
$table_posts = $wpdb->prefix . 'posts';
// First get all pages with cb shortcodes
- $sql = "SELECT post_content FROM $table_posts WHERE
+ $sql = "SELECT post_content FROM $table_posts WHERE
post_content LIKE '%cb_items%' OR
post_content LIKE '%cb_locations%' OR
post_content LIKE '%cb_map%' OR
@@ -261,18 +262,18 @@ public static function warmupCache() {
// Now extract shortcode calles incl. attributes
$shortCodeCalls = [];
- foreach($pages as $page) {
+ foreach ( $pages as $page ) {
// Get cb_ shortcodes
- preg_match_all('/\[.*(cb\_.*)\]/i', $page->post_content, $cbShortCodes);
+ preg_match_all( '/\[.*(cb\_.*)\]/i', $page->post_content, $cbShortCodes );
// If there was found something between the brackets we continue
- if(count($cbShortCodes) > 1) {
+ if ( count( $cbShortCodes ) > 1 ) {
$cbShortCodes = $cbShortCodes[1];
// each result will be prepared and added as shortcode call
- foreach ($cbShortCodes as $shortCode) {
- list($shortCode, $args) = self::getShortcodeAndAttributes($shortCode);
- $shortCodeCalls[][$shortCode] = $args;
+ foreach ( $cbShortCodes as $shortCode ) {
+ list($shortCode, $args) = self::getShortcodeAndAttributes( $shortCode );
+ $shortCodeCalls[][ $shortCode ] = $args;
}
}
}
@@ -280,45 +281,44 @@ public static function warmupCache() {
// Filter duplicate calls
$shortCodeCalls = array_intersect_key(
$shortCodeCalls,
- array_unique(array_map('serialize', $shortCodeCalls))
+ array_unique( array_map( 'serialize', $shortCodeCalls ) )
);
- self::runShortcodeCalls($shortCodeCalls);
+ self::runShortcodeCalls( $shortCodeCalls );
- wp_send_json("cache successfully warmed up");
- } catch (\Exception $exception) {
- wp_send_json("something went wrong with cache warm up");
+ wp_send_json( 'cache successfully warmed up' );
+ } catch ( \Exception $exception ) {
+ wp_send_json( 'something went wrong with cache warm up' );
}
}
/**
- * Renders little connections status information for REDIS database
- * @param array $field_args
+ * Renders little connections status information for REDIS database
+ *
+ * @param array $field_args
* @param CMB2_Field $field
*/
- public static function renderREDISConnectionStatus( array $field_args, CMB2_Field $field ){
+ public static function renderREDISConnectionStatus( array $field_args, CMB2_Field $field ) {
?>
';
- echo sprintf( commonsbooking_sanitizeHTML(__('Directory %s could not be written to.', 'commonsbooking') ), $cachePath);
+ printf( commonsbooking_sanitizeHTML( __( 'Directory %s could not be written to.', 'commonsbooking' ) ), $cachePath );
echo '
';
}
?>
@@ -366,12 +364,12 @@ public static function renderClearCacheButton( $field_args, $field ) {
- 1) {
+ foreach ( $shortCodeParts as $part ) {
+ $parts = explode( '=', $part );
+ $key = $parts[0];
+ $value = '';
+ if ( count( $parts ) > 1 ) {
$value = $parts[1];
- if(preg_match('/^".*"$/', $value)) {
- $value = substr($value,1,-1);
+ if ( preg_match( '/^".*"$/', $value ) ) {
+ $value = substr( $value, 1, -1 );
}
}
- $args[$key] = $value;
+ $args[ $key ] = $value;
}
- return [$shortCode, $args];
+ return [ $shortCode, $args ];
}
private static $cbShortCodeFunctions = [
- "cb_items" => array( \CommonsBooking\View\Item::class, 'shortcode' ),
+ 'cb_items' => array( \CommonsBooking\View\Item::class, 'shortcode' ),
'cb_bookings' => array( \CommonsBooking\View\Booking::class, 'shortcode' ),
- "cb_locations" => array( \CommonsBooking\View\Location::class, 'shortcode' ),
- "cb_map" => array( MapShortcode::class, 'execute' ),
- 'cb_items_table' => array( Calendar::class, 'renderTable' )
+ 'cb_locations' => array( \CommonsBooking\View\Location::class, 'shortcode' ),
+ 'cb_map' => array( MapShortcode::class, 'execute' ),
+ 'cb_items_table' => array( Calendar::class, 'renderTable' ),
];
-
}
diff --git a/src/Service/Holiday.php b/src/Service/Holiday.php
index 54f4e3924..82338030e 100644
--- a/src/Service/Holiday.php
+++ b/src/Service/Holiday.php
@@ -7,6 +7,7 @@ class Holiday {
/**
* Will render the fields in the timeframe settings where the user can define the holidays to get for the different German states and years.
* The actual holidays will be loaded through feiertagejs.
+ *
* @param $field
* @param $value
* @param $object_id
@@ -18,36 +19,47 @@ class Holiday {
public static function renderFields( $field, $value, $object_id, $object_type, $field_type ) {
// make sure we specify each part of the value we need.
- $value = wp_parse_args( $value, array(
- 'holiday_year' => '',
- 'holiday_state' => '',
- ) );
+ $value = wp_parse_args(
+ $value,
+ array(
+ 'holiday_year' => '',
+ 'holiday_state' => '',
+ )
+ );
?>
';
+ ' . commonsbooking_sanitizeHTML( __( 'All codes for the entire timeframe will be emailed to the location email(s), given in bold below.', 'commonsbooking' ) )
+ . '
';
- $from=strtotime("midnight first day of this month");
- $to=strtotime("midnight last day of this month");
- echo '
+ $from = strtotime( 'midnight first day of this month' );
+ $to = strtotime( 'midnight last day of this month' );
+ echo '
';
- $from=strtotime("midnight first day of next month");
- $to=strtotime("midnight last day of next month");
+ ' . commonsbooking_sanitizeHTML( __( 'The codes of the current month will be sent to all the location email(s), given in bold below', 'commonsbooking' ) )
+ . '
';
+ $from = strtotime( 'midnight first day of next month' );
+ $to = strtotime( 'midnight last day of next month' );
- echo '
+ echo '
';
- }
- }
-
- echo '
+ ' . commonsbooking_sanitizeHTML( __( 'The codes of the next month will be sent to all the location email(s), given in bold below.', 'commonsbooking' ) ) .
+ '
' . commonsbooking_sanitizeHTML( sprintf( __( 'Will download all available booking codes for this timeframe. If the timeframe has no end-date, the booking codes for the next %s days will be retrieved.', 'commonsbooking' ), \CommonsBooking\Repository\BookingCodes::ADVANCE_GENERATION_DAYS ) ) . '
' . commonsbooking_sanitizeHTML( __( 'The file will be exported as tab delimited .txt file so you can choose wether you want to print it, open it in a separate application (like Word, Excel etc.)', 'commonsbooking' ) ) . '
-
':commonsbooking_sanitizeHTML( __('This timeframe has no booking codes. To generate booking codes you need to save the timeframe.', 'commonsbooking'))) . '
+ ' : commonsbooking_sanitizeHTML( __( 'This timeframe has no booking codes. To generate booking codes you need to save the timeframe.', 'commonsbooking' ) ) ) . '
';
- //This settings is the amount of booking codes that should be shown to the user
- $bcToShow=Settings::getOption( 'commonsbooking_options_bookingcodes','bookingcodes-listed-timeframe' );
- if($bcToShow > 0) {
- $tsStart=max(Wordpress::getUTCDateTime("today")->getTimestamp(), $timeframe->getStartDate());
- $tsEnd=strtotime(" +" . ( $bcToShow - 1 ) . " days",$tsStart);
- $bookingCodes = \CommonsBooking\Repository\BookingCodes::getCodes( $timeframeId,$tsStart,$tsEnd);
+ // This settings is the amount of booking codes that should be shown to the user
+ $bcToShow = Settings::getOption( 'commonsbooking_options_bookingcodes', 'bookingcodes-listed-timeframe' );
+ if ( $bcToShow > 0 ) {
+ $tsStart = max( Wordpress::getUTCDateTime( 'today' )->getTimestamp(), $timeframe->getStartDate() );
+ $tsEnd = strtotime( ' +' . ( $bcToShow - 1 ) . ' days', $tsStart );
+ $bookingCodes = \CommonsBooking\Repository\BookingCodes::getCodes( $timeframeId, $tsStart, $tsEnd );
- echo '
';
- echo sprintf( __('Only showing booking codes for the next %s days.', 'commonsbooking'), $bcToShow );
+ printf( __( 'Only showing booking codes for the next %s days.', 'commonsbooking' ), $bcToShow );
echo ' ';
- echo __('The amount of booking codes shown in the overview can be changed in the settings.', 'commonsbooking');
+ echo __( 'The amount of booking codes shown in the overview can be changed in the settings.', 'commonsbooking' );
echo '
';
- }
- else {
- echo commonsbooking_sanitizeHTML( __('This timeframe has no booking codes. To generate booking codes you need to save the timeframe.', 'commonsbooking'));
- }
- echo '
';
- }
-
- return true;
+ } else {
+ echo commonsbooking_sanitizeHTML( __( 'This timeframe has no booking codes. To generate booking codes you need to save the timeframe.', 'commonsbooking' ) );
+ }
+ echo '
';
+ }
+
+ return true;
}
/**
* Renders HTML table of bookingCodes List.
*
* @param $bookingCodes array : CommonsBooking\Model\BookingCode
- *
- * @return string HTML table
+ *
+ * @return string HTML table
*/
- public static function renderBookingCodesTable( $bookingCodes ) : string {
- if(empty($bookingCodes)) return '';
-
- $lines=[];
- foreach($bookingCodes as $bookingCode) {
- $lines[]='
' . commonsbooking_sanitizeHTML(wp_date("D j. F Y", strtotime ($bookingCode->getDate() )) ) .
- '
';
// Use td-tag when no table header description is given, to match semantics of header cells
- $accessible_table_header_tag = empty($desc) ? "td" : "th";
- $print .= "
' .
- commonsbooking_sanitizeHTML( __('Click this button to automatically set the GPS coordinates based on the given address and set the marker on the map. Save or update this location after setting the gps data.', 'commonsbooking' ) ) .
- '
+ commonsbooking_sanitizeHTML( __( 'Click this button to automatically set the GPS coordinates based on the given address and set the marker on the map. Save or update this location after setting the gps data.', 'commonsbooking' ) ) .
+ '
' .
- commonsbooking_sanitizeHTML( __('No GPS data could be found for the address entered. Please check if the address is written correctly. Alternatively, you can enter the GPS data manually into the corresponding fields.', 'commonsbooking' ) ) .
- '
+ commonsbooking_sanitizeHTML( __( 'No GPS data could be found for the address entered. Please check if the address is written correctly. Alternatively, you can enter the GPS data manually into the corresponding fields.', 'commonsbooking' ) ) .
+ '
';
}
-
-}
\ No newline at end of file
+}
diff --git a/src/View/MassOperations.php b/src/View/MassOperations.php
index f9d25b115..daee0e919 100644
--- a/src/View/MassOperations.php
+++ b/src/View/MassOperations.php
@@ -6,7 +6,7 @@ class MassOperations {
public static function index() {
global $templateData;
$templateData = [];
- $templateData["orphanedBookings"] = \CommonsBooking\Repository\Booking::getOrphaned();
+ $templateData['orphanedBookings'] = \CommonsBooking\Repository\Booking::getOrphaned();
ob_start();
commonsbooking_sanitizeHTML( commonsbooking_get_template_part( 'massoperations', 'index' ) );
@@ -34,18 +34,18 @@ public static function renderBookingViewTable( array $bookings ) {
-
';
- foreach ( $bookings as $booking ):
+ foreach ( $bookings as $booking ) :
try {
$itemTitle = $booking->getItem()->post_title;
} catch ( \Exception $e ) {
@@ -111,5 +111,4 @@ public static function renderOrphanedMigrationButton() {
';
}
-
-}
\ No newline at end of file
+}
diff --git a/src/View/Migration.php b/src/View/Migration.php
index df2f6190b..201ec729e 100644
--- a/src/View/Migration.php
+++ b/src/View/Migration.php
@@ -2,7 +2,6 @@
namespace CommonsBooking\View;
-
use CMB2_Field;
use CommonsBooking\Repository\CB1;
use CommonsBooking\Service\Upgrade;
@@ -15,21 +14,26 @@ class Migration {
/**
* Render Migration Form.
*
- * @param array $field_args Array of field arguments.
+ * @param array $field_args Array of field arguments.
* @param CMB2_Field $field The field object
*/
public static function renderMigrationForm( array $field_args, CMB2_Field $field ) {
$cb1Installed = CB1::isInstalled();
?>
-
+ ' . esc_html__( 'We could not detect a version of an older CommonsBooking Installation (Version 0.X).',
- 'commonsbooking' ) . '';
+ echo '' . esc_html__(
+ 'We could not detect a version of an older CommonsBooking Installation (Version 0.X).',
+ 'commonsbooking'
+ ) . '';
} else {
- echo '' . esc_html__( 'Found a version of an older CommonsBooking Installation (Version 0.X). You can migrate.',
- 'commonsbooking' ) . '';
+ echo '' . esc_html__(
+ 'Found a version of an older CommonsBooking Installation (Version 0.X). You can migrate.',
+ 'commonsbooking'
+ ) . '';
}
echo( '
@@ -45,7 +49,7 @@ public static function renderMigrationForm( array $field_args, CMB2_Field $field
- ' . commonsbooking_sanitizeHTML( __( 'migration in process .. please wait ... This could take several minutes. Do not close this browser tab', 'commonsbooking' ) ). '
+ ' . commonsbooking_sanitizeHTML( __( 'migration in process .. please wait ... This could take several minutes. Do not close this browser tab', 'commonsbooking' ) ) . '
@@ -57,31 +61,32 @@ public static function renderMigrationForm( array $field_args, CMB2_Field $field
if ( $cb1Installed ) {
?>
-
'
- );
+ );
}
public static function renderUpgradeForm( array $field_args, CMB2_Field $field ) {
- if (! Upgrade::isAJAXUpgrade() ) return false;
+ if ( ! Upgrade::isAJAXUpgrade() ) {
+ return false;
+ }
?>
@@ -131,5 +138,4 @@ public static function renderUpgradeForm( array $field_args, CMB2_Field $field )
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
+
+
-
+
-
-
-
+
+
+
-
-
-
+
+
+
@@ -54,5 +54,6 @@ public static function renderExportButton( $field_args, $field ) {
- '',
// Order: https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters
'order' => '',
- 'orderby' => '',
+ 'orderby' => '',
);
/**
@@ -51,7 +52,7 @@ abstract class View {
* This includes the availability timeframe, see assumptions in class docstring for more details.
*
* @param \CommonsBooking\Model\Item|\CommonsBooking\Model\Location $cpt location or item model object to retrieve timeframe data from.
- * @param string $type 'Item' or 'Location'.
+ * @param string $type 'Item' or 'Location'.
* @return array
* @throws Exception
*/
@@ -60,9 +61,12 @@ public static function getShortcodeData( $cpt, string $type ): array {
$timeframes = $cpt->getBookableTimeframes( true );
// sort by start date, to get latest possible booking date by first timeframe
- usort( $timeframes, function ( $a, $b ) {
- return $a->getStartDate() <=> $b->getStartDate();
- } );
+ usort(
+ $timeframes,
+ function ( $a, $b ) {
+ return $a->getStartDate() <=> $b->getStartDate();
+ }
+ );
$latestPossibleBookingDate = false;
/** @var Timeframe $timeframe */
@@ -73,18 +77,20 @@ public static function getShortcodeData( $cpt, string $type ): array {
// We only fetch the latest possible booking date from the first timeframe.
// This is ok, because the timeframes are sorted by their start date.
- if(!$latestPossibleBookingDate) {
+ if ( ! $latestPossibleBookingDate ) {
$latestPossibleBookingDate = $timeframe->getLatestPossibleBookingDateTimestamp();
}
// If start date is after latest possible booking date, we leave range out
- $endOfStartDay = strtotime('+1 day midnight', $timeframe->getStartDate()) - 1;
- if($endOfStartDay > $latestPossibleBookingDate) continue;
+ $endOfStartDay = strtotime( '+1 day midnight', $timeframe->getStartDate() ) - 1;
+ if ( $endOfStartDay > $latestPossibleBookingDate ) {
+ continue;
+ }
$item = $timeframe->{'get' . $type}();
// We need only published items
- if ( !$item || $item->post_status !== 'publish' ) {
+ if ( ! $item || $item->post_status !== 'publish' ) {
continue;
}
@@ -151,13 +157,16 @@ public static function getShortcodeData( $cpt, string $type ): array {
}
}
- //Remove duplicate ranges
+ // Remove duplicate ranges
$cptData[ $item->ID ]['ranges'] = array_unique( $cptData[ $item->ID ]['ranges'], SORT_REGULAR );
- //sort ranges by starting date
- usort( $cptData[ $item->ID ]['ranges'], function ( $a, $b ) {
- return $a['start_date'] <=> $b['start_date'];
- } );
+ // sort ranges by starting date
+ usort(
+ $cptData[ $item->ID ]['ranges'],
+ function ( $a, $b ) {
+ return $a['start_date'] <=> $b['start_date'];
+ }
+ );
}
return $cptData;
@@ -168,47 +177,43 @@ public static function getShortcodeData( $cpt, string $type ): array {
*
* @return string
*/
- public static function getColorCSS():string{
- $compiler = new Compiler();
- $var_import = COMMONSBOOKING_PLUGIN_DIR . 'assets/global/sass/partials/_variables.scss';
+ public static function getColorCSS(): string {
+ $compiler = new Compiler();
+ $var_import = COMMONSBOOKING_PLUGIN_DIR . 'assets/global/sass/partials/_variables.scss';
$import_path = COMMONSBOOKING_PLUGIN_DIR . 'assets/public/sass/partials/';
- $compiler ->setImportPaths($import_path);
+ $compiler->setImportPaths( $import_path );
$variables = [
- 'color-primary' => Settings::getOption('commonsbooking_options_templates', 'colorscheme_primarycolor'),
- 'color-secondary' => Settings::getOption('commonsbooking_options_templates', 'colorscheme_secondarycolor'),
- 'color-buttons' => Settings::getOption('commonsbooking_options_templates', 'colorscheme_buttoncolor'),
- 'color-accept' => Settings::getOption('commonsbooking_options_templates', 'colorscheme_acceptcolor'),
- 'color-cancel' => Settings::getOption('commonsbooking_options_templates', 'colorscheme_cancelcolor'),
- 'color-holiday' => Settings::getOption('commonsbooking_options_templates', 'colorscheme_holidaycolor'),
- 'color-greyedout' => Settings::getOption('commonsbooking_options_templates', 'colorscheme_greyedoutcolor'),
- 'color-bg' => Settings::getOption('commonsbooking_options_templates', 'colorscheme_backgroundcolor'),
- 'color-noticebg' => Settings::getOption('commonsbooking_options_templates', 'colorscheme_noticebackgroundcolor'),
- 'color-lighttext' => Settings::getOption('commonsbooking_options_templates', 'colorscheme_lighttext'),
- 'color-darktext' => Settings::getOption('commonsbooking_options_templates', 'colorscheme_darktext'),
+ 'color-primary' => Settings::getOption( 'commonsbooking_options_templates', 'colorscheme_primarycolor' ),
+ 'color-secondary' => Settings::getOption( 'commonsbooking_options_templates', 'colorscheme_secondarycolor' ),
+ 'color-buttons' => Settings::getOption( 'commonsbooking_options_templates', 'colorscheme_buttoncolor' ),
+ 'color-accept' => Settings::getOption( 'commonsbooking_options_templates', 'colorscheme_acceptcolor' ),
+ 'color-cancel' => Settings::getOption( 'commonsbooking_options_templates', 'colorscheme_cancelcolor' ),
+ 'color-holiday' => Settings::getOption( 'commonsbooking_options_templates', 'colorscheme_holidaycolor' ),
+ 'color-greyedout' => Settings::getOption( 'commonsbooking_options_templates', 'colorscheme_greyedoutcolor' ),
+ 'color-bg' => Settings::getOption( 'commonsbooking_options_templates', 'colorscheme_backgroundcolor' ),
+ 'color-noticebg' => Settings::getOption( 'commonsbooking_options_templates', 'colorscheme_noticebackgroundcolor' ),
+ 'color-lighttext' => Settings::getOption( 'commonsbooking_options_templates', 'colorscheme_lighttext' ),
+ 'color-darktext' => Settings::getOption( 'commonsbooking_options_templates', 'colorscheme_darktext' ),
];
- foreach ($variables as &$variable){ //iterate over array, convert valid values.
- if ($variable){ //values are only converted when set so ValueParser does not throw an error
- $variable = ValueConverter::parseValue($variable);
- }
- else {
- return false; //do not return CSS when no values are set
+ foreach ( $variables as &$variable ) { // iterate over array, convert valid values.
+ if ( $variable ) { // values are only converted when set so ValueParser does not throw an error
+ $variable = ValueConverter::parseValue( $variable );
+ } else {
+ return false; // do not return CSS when no values are set
}
}
- $compiler->replaceVariables($variables);
+ $compiler->replaceVariables( $variables );
$content = '@import "' . $var_import . '";';
- $result = $compiler->compileString($content);
- $css = $result->getCss();
+ $result = $compiler->compileString( $content );
+ $css = $result->getCss();
- if (!empty($css) && is_string($css)) {
+ if ( ! empty( $css ) && is_string( $css ) ) {
return $css;
- }
- else {
+ } else {
return false;
}
-
}
-
}
diff --git a/src/Wordpress/CustomPostType/Booking.php b/src/Wordpress/CustomPostType/Booking.php
index 445c0dd4f..17cf001ae 100644
--- a/src/Wordpress/CustomPostType/Booking.php
+++ b/src/Wordpress/CustomPostType/Booking.php
@@ -18,9 +18,9 @@
*/
class Booking extends Timeframe {
- //this is the error type for the validation that failed for the FRONTEND user
- //TODO: Switch the error type with the one from Model/Booking, because most functions regarding backend booking are in this class
- public const ERROR_TYPE = COMMONSBOOKING_PLUGIN_SLUG . '-bookingValidationError';
+ // this is the error type for the validation that failed for the FRONTEND user
+ // TODO: Switch the error type with the one from Model/Booking, because most functions regarding backend booking are in this class
+ public const ERROR_TYPE = COMMONSBOOKING_PLUGIN_SLUG . '-bookingValidationError';
private const SUBMIT_BUTTON_ID = 'booking-submit';
/**
@@ -30,7 +30,7 @@ class Booking extends Timeframe {
/**
* Position in backend menu.
- *
+ *
* @var int
*/
protected $menuPosition = 4;
@@ -39,19 +39,18 @@ public function __construct() {
// does not trigger when initiated in initHooks
add_action( 'post_updated', array( $this, 'postUpdated' ), 1, 3 );
-
}
- /**
+ /**
* Initiates needed hooks.
*/
public function initHooks() {
// Add Meta Boxes
add_action( 'cmb2_admin_init', array( $this, 'registerMetabox' ) );
- // we need to add some additional fields and modify the autor if admin booking is made
- add_action( 'save_post_' . self::$postType, array( $this, 'savePost' ), 10 );
+ // we need to add some additional fields and modify the autor if admin booking is made
+ add_action( 'save_post_' . self::$postType, array( $this, 'savePost' ), 10 );
// Set Tepmlates
add_filter( 'the_content', array( $this, 'getTemplate' ) );
@@ -69,102 +68,105 @@ public function initHooks() {
// show admin notice
add_action( 'admin_notices', array( $this, 'displayBookingsAdminListNotice' ) );
- add_action( 'edit_form_top', array( $this, 'displayOverlappingBookingNotice' ), 99 );
+ add_action( 'edit_form_top', array( $this, 'displayOverlappingBookingNotice' ), 99 );
}
- /**
- * Adds and modifies some booking CPT fields in order to make admin boookings
- * compatible to user made bookings via frontend.
- *
- * @param mixed $post_id
- * @param mixed $post
- * @param mixed $update
- * @return void
- */
- public function savePost( $post_id, $post = null, $update = null ) {
- global $pagenow;
-
- $post = $post ?? get_post( $post_id );
- $is_trash_action = str_contains(($_REQUEST ?? array())['action'] ?? '', 'trash');
-
- // we check if it's a new created post - TODO: This is not the case
- if (
+ /**
+ * Adds and modifies some booking CPT fields in order to make admin boookings
+ * compatible to user made bookings via frontend.
+ *
+ * @param mixed $post_id
+ * @param mixed $post
+ * @param mixed $update
+ * @return void
+ */
+ public function savePost( $post_id, $post = null, $update = null ) {
+ global $pagenow;
+
+ $post = $post ?? get_post( $post_id );
+ $is_trash_action = str_contains( ( $_REQUEST ?? array() )['action'] ?? '', 'trash' );
+
+ // we check if it's a new created post - TODO: This is not the case
+ if (
! empty( $_REQUEST ) &&
! $is_trash_action &&
$pagenow === 'post.php' &&
( commonsbooking_isCurrentUserAdmin() || commonsbooking_isCurrentUserCBManager() )
) {
- // set request variables
- $booking_user = isset( $_REQUEST['booking_user'] ) ? esc_html( $_REQUEST['booking_user'] ) : false;
+ // set request variables
+ $booking_user = isset( $_REQUEST['booking_user'] ) ? esc_html( $_REQUEST['booking_user'] ) : false;
- $post_status = esc_html( $_REQUEST['post_status'] ?? '' );
+ $post_status = esc_html( $_REQUEST['post_status'] ?? '' );
- $start_time = isset( $_REQUEST['repetition-start'] ) ? esc_html( $_REQUEST['repetition-start']['time'] ?? '' ) : false;
- $end_time = isset( $_REQUEST['repetition-end'] ) ? esc_html( $_REQUEST['repetition-end']['time'] ?? '' ) : false;
- $full_day = ( !$start_time || $start_time === '0:00' || $start_time === '00:00' ) && ( !$end_time || $end_time === '23:59' ) ? 'on' : '';
+ $start_time = isset( $_REQUEST['repetition-start'] ) ? esc_html( $_REQUEST['repetition-start']['time'] ?? '' ) : false;
+ $end_time = isset( $_REQUEST['repetition-end'] ) ? esc_html( $_REQUEST['repetition-end']['time'] ?? '' ) : false;
+ $full_day = ( ! $start_time || $start_time === '0:00' || $start_time === '00:00' ) && ( ! $end_time || $end_time === '23:59' ) ? 'on' : '';
- $postarr = array(
+ $postarr = array(
'post_title' => esc_html__( 'Admin-Booking', 'commonsbooking' ),
- 'post_author' => $booking_user,
- 'post_status' => $post_status,
- 'meta_input' => [
- 'admin_booking_id' => get_current_user_id(),
- 'start-time' => $start_time,
- 'end-time' => $end_time,
- 'type' => Timeframe::BOOKING_ID,
- 'grid' => '',
- 'full-day' => $full_day,
+ 'post_author' => $booking_user,
+ 'post_status' => $post_status,
+ 'meta_input' => [
+ 'admin_booking_id' => get_current_user_id(),
+ 'start-time' => $start_time,
+ 'end-time' => $end_time,
+ 'type' => Timeframe::BOOKING_ID,
+ 'grid' => '',
+ 'full-day' => $full_day,
],
- );
-
- // set post_name if new post
- if ( in_array( $post->post_status, array( 'auto-draft', 'new' ) ) || $post->post_name === '' ) {
- $postarr['post_name'] = Helper::generateRandomString();
- }
-
- $postarr['ID'] = $post_id;
-
- // unhook this function so it doesn't loop infinitely
- remove_action( 'save_post_' . self::$postType, array( $this, 'savePost' ) );
-
- // update this post
- wp_update_post( $postarr, true, true );
-
- //run validation only on new posts (the submit button is only available on new posts)
- if ( array_key_exists( self::SUBMIT_BUTTON_ID, $_REQUEST ) ) {
- try {
- $booking = new \CommonsBooking\Model\Booking( $post_id );
- $booking->isValid();
- wp_update_post( array(
- 'ID' => $post_id,
- 'post_status' => 'confirmed'
- )
- );
- $post_status = 'confirmed';
- } catch ( TimeframeInvalidException $e ) {
- // set to draft and display error message
- wp_update_post( array(
- 'ID' => $post_id,
- 'post_status' => 'draft',
- ) );
- set_transient(
- \CommonsBooking\Model\Booking::ERROR_TYPE,
- nl2br(commonsbooking_sanitizeHTML( $e->getMessage() )),
- 30 //Expires very quickly, so that outdated messsages will not be shown to the user
- );
- }
- }
-
- // readd the hook
- add_action( 'save_post_' . self::$postType, array( $this, 'savePost' ) );
-
- //if we just created a new confirmed booking we trigger the confirmation mail
- if ( $post_status == 'confirmed' ) {
- $booking_msg = new BookingMessage( $post_id, $post_status );
- $booking_msg->triggerMail();
- }
- }
- }
+ );
+
+ // set post_name if new post
+ if ( in_array( $post->post_status, array( 'auto-draft', 'new' ) ) || $post->post_name === '' ) {
+ $postarr['post_name'] = Helper::generateRandomString();
+ }
+
+ $postarr['ID'] = $post_id;
+
+ // unhook this function so it doesn't loop infinitely
+ remove_action( 'save_post_' . self::$postType, array( $this, 'savePost' ) );
+
+ // update this post
+ wp_update_post( $postarr, true, true );
+
+ // run validation only on new posts (the submit button is only available on new posts)
+ if ( array_key_exists( self::SUBMIT_BUTTON_ID, $_REQUEST ) ) {
+ try {
+ $booking = new \CommonsBooking\Model\Booking( $post_id );
+ $booking->isValid();
+ wp_update_post(
+ array(
+ 'ID' => $post_id,
+ 'post_status' => 'confirmed',
+ )
+ );
+ $post_status = 'confirmed';
+ } catch ( TimeframeInvalidException $e ) {
+ // set to draft and display error message
+ wp_update_post(
+ array(
+ 'ID' => $post_id,
+ 'post_status' => 'draft',
+ )
+ );
+ set_transient(
+ \CommonsBooking\Model\Booking::ERROR_TYPE,
+ nl2br( commonsbooking_sanitizeHTML( $e->getMessage() ) ),
+ 30 // Expires very quickly, so that outdated messsages will not be shown to the user
+ );
+ }
+ }
+
+ // readd the hook
+ add_action( 'save_post_' . self::$postType, array( $this, 'savePost' ) );
+
+ // if we just created a new confirmed booking we trigger the confirmation mail
+ if ( $post_status == 'confirmed' ) {
+ $booking_msg = new BookingMessage( $post_id, $post_status );
+ $booking_msg->triggerMail();
+ }
+ }
+ }
/**
* Handles frontend save-Request for timeframe.
@@ -218,7 +220,7 @@ function_exists( 'wp_verify_nonce' ) &&
* @param string|null $itemId
* @param string|null $locationId
* @param string|null $post_status
- * @param int|null $post_ID
+ * @param int|null $post_ID
* @param string|null $comment
* @param string|null $repetitionStart
* @param string|null $repetitionEnd
@@ -241,11 +243,11 @@ public static function handleBookingRequest(
int $overbookedDays = 0
): int {
- if ( isset ( $_POST['calendar-download'] ) ) {
+ if ( isset( $_POST['calendar-download'] ) ) {
try {
iCalendar::downloadICS( $post_ID );
} catch ( Exception $e ) {
- //redirect to booking page and do nothing
+ // redirect to booking page and do nothing
return $post_ID;
}
exit;
@@ -337,22 +339,21 @@ public static function handleBookingRequest(
'type' => Timeframe::BOOKING_ID,
);
- $postId = wp_insert_post( $postarr, true );
+ $postId = wp_insert_post( $postarr, true );
$needsValidation = true;
// Existing booking
} else {
$postarr['ID'] = $booking->ID;
if ( $postarr['post_status'] === 'canceled' ) {
- $postarr['meta_input']['cancellation_time'] = current_time('timestamp');
+ $postarr['meta_input']['cancellation_time'] = current_time( 'timestamp' );
}
- $postId = wp_update_post( $postarr );
+ $postId = wp_update_post( $postarr );
- //we check if this is an already denied booking and demand validation again
- if ($postarr["post_status"] == "unconfirmed"){
+ // we check if this is an already denied booking and demand validation again
+ if ( $postarr['post_status'] == 'unconfirmed' ) {
$needsValidation = true;
- }
- else {
+ } else {
$needsValidation = false;
}
}
@@ -363,29 +364,30 @@ public static function handleBookingRequest(
// we need some meta-fields from bookable-timeframe, so we assign them here to the booking-timeframe
try {
$bookingModel->assignBookableTimeframeFields();
- if ( $overbookedDays > 0 ) { //avoid setting the value when not present (for example when updating the booking)
+ if ( $overbookedDays > 0 ) { // avoid setting the value when not present (for example when updating the booking)
$bookingModel->setOverbookedDays( $overbookedDays );
}
} catch ( \Exception $e ) {
- throw new BookingDeniedException( __( 'There was an error while saving the booking. Please try again. Thrown error:', 'commonsbooking' ) .
- PHP_EOL . $e->getMessage()
+ throw new BookingDeniedException(
+ __( 'There was an error while saving the booking. Please try again. Thrown error:', 'commonsbooking' ) .
+ PHP_EOL . $e->getMessage()
);
}
- //check if the Booking we want to create conforms to the set booking rules
- if( $needsValidation){
+ // check if the Booking we want to create conforms to the set booking rules
+ if ( $needsValidation ) {
try {
BookingRuleApplied::bookingConformsToRules( $bookingModel );
- }
- catch (BookingDeniedException $e) {
- wp_delete_post($bookingModel->ID);
- throw new BookingDeniedException($e->getMessage());
+ } catch ( BookingDeniedException $e ) {
+ wp_delete_post( $bookingModel->ID );
+ throw new BookingDeniedException( $e->getMessage() );
}
}
if ( $postId instanceof \WP_Error ) {
- throw new BookingDeniedException( __( 'There was an error while saving the booking. Please try again. Resulting WP_ERROR: ', 'commonsbooking' ) .
- PHP_EOL . $postId->get_error_messages()
+ throw new BookingDeniedException(
+ __( 'There was an error while saving the booking. Please try again. Resulting WP_ERROR: ', 'commonsbooking' ) .
+ PHP_EOL . $postId->get_error_messages()
);
}
@@ -404,7 +406,7 @@ public static function handleBookingRequest(
*/
private static function saveGridSizes( $postId, $locationId, $itemId, $startDate, $endDate ): void {
$startTimeFrame = \CommonsBooking\Repository\Timeframe::getByLocationItemTimestamp( $locationId, $itemId, $startDate );
- if ( $startTimeFrame && !$startTimeFrame->isFullDay() && $startTimeFrame->getGrid() == 0 ) {
+ if ( $startTimeFrame && ! $startTimeFrame->isFullDay() && $startTimeFrame->getGrid() == 0 ) {
update_post_meta(
$postId,
\CommonsBooking\Model\Booking::START_TIMEFRAME_GRIDSIZE,
@@ -412,7 +414,7 @@ private static function saveGridSizes( $postId, $locationId, $itemId, $startDate
);
}
$endTimeFrame = \CommonsBooking\Repository\Timeframe::getByLocationItemTimestamp( $locationId, $itemId, $endDate );
- if ( $endTimeFrame && !$endTimeFrame->isFullDay() && $endTimeFrame->getGrid() == 0 ) {
+ if ( $endTimeFrame && ! $endTimeFrame->isFullDay() && $endTimeFrame->getGrid() == 0 ) {
update_post_meta(
$postId,
\CommonsBooking\Model\Booking::END_TIMEFRAME_GRIDSIZE,
@@ -484,16 +486,16 @@ public function getTemplate( $content ) {
*/
public function postUpdated( $post_ID, $post_after, $post_before ) {
- if ( ! $this->hasRunBefore( __FUNCTION__ ) ) {
+ if ( ! $this->hasRunBefore( __FUNCTION__ ) ) {
$isBooking = get_post_meta( $post_ID, 'type', true ) == Timeframe::BOOKING_ID;
- if ( $isBooking ) {
+ if ( $isBooking ) {
- // Trigger Mail, only send mail if status has changed
+ // Trigger Mail, only send mail if status has changed
if ( $post_before->post_status != $post_after->post_status and
- ! (
- $post_before->post_status === 'unconfirmed' and
- $post_after->post_status === 'canceled'
- )
+ ! (
+ $post_before->post_status === 'unconfirmed' and
+ $post_after->post_status === 'canceled'
+ )
) {
if ( $post_after->post_status == 'canceled' ) {
$booking = new \CommonsBooking\Model\Booking( $post_ID );
@@ -503,13 +505,13 @@ public function postUpdated( $post_ID, $post_after, $post_before ) {
$booking_msg->triggerMail();
}
}
- }
+ }
}
}
/**
* Returns CPT arguments.
- *
+ *
* @return array
*/
public function getArgs() {
@@ -596,15 +598,15 @@ public function getArgs() {
* @param $post_id
*/
public function setCustomColumnsData( $column, $post_id ) {
- global $pagenow;
+ global $pagenow;
- if ( $pagenow !== 'edit.php' || empty( esc_html( $_GET['post_type'] ) ) || esc_html( $_GET['post_type'] ) !== $this::$postType ) {
- return;
- }
+ if ( $pagenow !== 'edit.php' || empty( esc_html( $_GET['post_type'] ) ) || esc_html( $_GET['post_type'] ) !== $this::$postType ) {
+ return;
+ }
// we alter the author column data and link the username to the user profile
if ( $column == 'booking_user' ) {
- $post = get_post( $post_id );
+ $post = get_post( $post_id );
$bookingUser = get_user_by( 'id', $post->post_author );
echo '' . commonsbooking_sanitizeHTML( $bookingUser->user_login ) . '';
}
@@ -615,7 +617,7 @@ public function setCustomColumnsData( $column, $post_id ) {
case 'item-id':
if ( $post = get_post( $value ) ) {
if ( get_post_type( $post ) == Location::getPostType() ||
- get_post_type( $post ) == Item::getPostType()
+ get_post_type( $post ) == Item::getPostType()
) {
echo commonsbooking_sanitizeHTML( $post->post_title );
break;
@@ -660,15 +662,15 @@ public function setCustomColumnsData( $column, $post_id ) {
)
) {
- // get translated label for post status
- if ($column === 'post_status') {
- echo __( commonsbooking_sanitizeHTML( get_post_status_object( get_post_status( $post_id ) )->label ) );
- } else {
- echo __( commonsbooking_sanitizeHTML( $post->{$column} ) );
- }
- }
+ // get translated label for post status
+ if ( $column === 'post_status' ) {
+ echo __( commonsbooking_sanitizeHTML( get_post_status_object( get_post_status( $post_id ) )->label ) );
+ } else {
+ echo __( commonsbooking_sanitizeHTML( $post->{$column} ) );
+ }
+ }
}
- }
+ }
/**
* @param \WP_Query $query
@@ -676,7 +678,7 @@ public function setCustomColumnsData( $column, $post_id ) {
* @return void
*/
public function setCustomColumnSortOrder( \WP_Query $query ) {
- if (! parent::setCustomColumnSortOrder( $query ) ) {
+ if ( ! parent::setCustomColumnSortOrder( $query ) ) {
return;
}
@@ -692,7 +694,7 @@ public function setCustomColumnSortOrder( \WP_Query $query ) {
* Registers metaboxes for cpt.
*/
public function registerMetabox() {
- //do not render the metabox if the user is on the login page (not yet logged in)
+ // do not render the metabox if the user is on the login page (not yet logged in)
if ( ! is_user_logged_in() ) {
return;
}
@@ -711,7 +713,7 @@ public function registerMetabox() {
/**
* Returns custom (meta) fields for Costum Post Type Timeframe.
- *
+ *
* @return array
*/
protected function getCustomFields() {
@@ -725,15 +727,15 @@ protected function getCustomFields() {
$dateFormat = 'm/d/Y';
}
- $booking_user = get_user_by('ID', get_current_user_id());
+ $booking_user = get_user_by( 'ID', get_current_user_id() );
- // define form fields based on CMB2
+ // define form fields based on CMB2
return array(
array(
'name' => esc_html__( 'Edit booking', 'commonsbooking' ),
'desc' => '
' . commonsbooking_sanitizeHTML(
- __(
- '
Notice
In this view, you as an admin can create or modify existing bookings. Please use it with caution.
+ __(
+ '
Notice
In this view, you as an admin can create or modify existing bookings. Please use it with caution.
Click on the preview button on the right panel to view more booking details and to cancel the booking via the cancel button.
Click on the Submit booking button at the end of the page to submit a new booking.
@@ -741,9 +743,9 @@ protected function getCustomFields() {
Please note: Only a few basic checks against existing bookings are performed. Please be wary of overlapping bookings.
',
- 'commonsbooking'
- ) . '
'
- ),
+ 'commonsbooking'
+ ) . ''
+ ),
'id' => 'title-booking-hint',
'type' => 'title',
),
@@ -763,7 +765,7 @@ protected function getCustomFields() {
'name' => esc_html__( 'Book full day', 'commonsbooking' ),
'id' => 'full-day',
'type' => 'checkbox',
- 'desc' => esc_html__( 'The booking should apply to the entire day(s)', 'commonsbooking' ),
+ 'desc' => esc_html__( 'The booking should apply to the entire day(s)', 'commonsbooking' ),
),
array(
'name' => esc_html__( 'Start date', 'commonsbooking' ),
@@ -772,7 +774,7 @@ protected function getCustomFields() {
'type' => 'text_datetime_timestamp',
'time_format' => get_option( 'time_format' ),
'date_format' => $dateFormat,
- 'default' => '00:00',
+ 'default' => '00:00',
'attributes' => array(
'data-timepicker' => wp_json_encode(
array(
@@ -789,7 +791,7 @@ protected function getCustomFields() {
'type' => 'text_datetime_timestamp',
'time_format' => get_option( 'time_format' ),
'date_format' => $dateFormat,
- 'default' => '23:59',
+ 'default' => '23:59',
'attributes' => array(
'data-timepicker' => wp_json_encode(
array(
@@ -805,38 +807,38 @@ protected function getCustomFields() {
'type' => 'text',
'desc' => esc_html__( 'Valid booking code will be automatically retrieved for bookings that apply to the full day.', 'commonsbooking' ),
),
- array(
+ array(
'name' => esc_html__( 'Booking User', 'commonsbooking' ),
'id' => 'booking_user',
'type' => 'user_ajax_search',
- 'multiple-items' => true,
- 'default' => array( self::class, 'getFrontendBookingUser' ),
- 'desc' => commonsbooking_sanitizeHTML(
- __(
- 'Here you must select the user for whom the booking is made.
+ 'multiple-items' => true,
+ 'default' => array( self::class, 'getFrontendBookingUser' ),
+ 'desc' => commonsbooking_sanitizeHTML(
+ __(
+ 'Here you must select the user for whom the booking is made.
If the booking was made by a user via frontend booking process, the user will be shown in this field.
Notice:The user will receive a booking confirmation as soon as the booking is submitted.',
- 'commonsbooking'
- )
- ),
+ 'commonsbooking'
+ )
+ ),
),
- array(
+ array(
'name' => esc_html__( 'Admin Booking User', 'commonsbooking' ),
'id' => 'admin_booking_id',
'type' => 'select',
- 'default' => get_current_user_id(),
- 'options' => array (
- $booking_user->ID => $booking_user->get( 'user_nicename' ) . ' (' . $booking_user->first_name . ' ' . $booking_user->last_name . ')',
- ),
- 'attributes' => array(
- 'readonly' => true,
- ),
- 'desc' => commonsbooking_sanitizeHTML(
- __(
- 'This is the admin user who created or modified this booking.',
- 'commonsbooking'
- )
- ),
+ 'default' => get_current_user_id(),
+ 'options' => array(
+ $booking_user->ID => $booking_user->get( 'user_nicename' ) . ' (' . $booking_user->first_name . ' ' . $booking_user->last_name . ')',
+ ),
+ 'attributes' => array(
+ 'readonly' => true,
+ ),
+ 'desc' => commonsbooking_sanitizeHTML(
+ __(
+ 'This is the admin user who created or modified this booking.',
+ 'commonsbooking'
+ )
+ ),
),
array(
'name' => esc_html__( 'External comment', 'commonsbooking' ),
@@ -874,16 +876,16 @@ public function displayBookingsAdminListNotice() {
global $pagenow;
$notice = commonsbooking_sanitizeHTML(
- __(
- 'Bookings should be created via frontend booking calendar.
+ __(
+ 'Bookings should be created via frontend booking calendar.
As an admin you can create bookings via this admin interface. Please be aware that admin bookings are not validated
and checked. Use this function with care.
Click on preview to show booking details in frontend
To search and filter bookings please integrate the frontend booking list via shortcode.
See here How to display the booking list',
- 'commonsbooking'
- )
- );
+ 'commonsbooking'
+ )
+ );
if ( ( $pagenow == 'edit.php' ) && isset( $_GET['post_type'] ) ) {
if ( sanitize_text_field( $_GET['post_type'] ) == self::getPostType() ) {
@@ -893,17 +895,17 @@ public function displayBookingsAdminListNotice() {
}
- /**
- * Displays a permanent admin-notice if booking overlaps
- *
- * @return void
- */
- public function displayOverlappingBookingNotice( $post ) {
+ /**
+ * Displays a permanent admin-notice if booking overlaps
+ *
+ * @return void
+ */
+ public function displayOverlappingBookingNotice( $post ) {
- if ( get_transient( 'commonsbooking_booking_validation_failed_' . $post->ID ) ) {
- echo commonsbooking_sanitizeHTML( get_transient( 'commonsbooking_booking_validation_failed_' . $post->ID, 'warning' ) );
- }
- }
+ if ( get_transient( 'commonsbooking_booking_validation_failed_' . $post->ID ) ) {
+ echo commonsbooking_sanitizeHTML( get_transient( 'commonsbooking_booking_validation_failed_' . $post->ID, 'warning' ) );
+ }
+ }
/**
* Export user bookings using the supplied email. This is for integration with the WordPress personal data exporter.
@@ -914,30 +916,30 @@ public function displayOverlappingBookingNotice( $post ) {
* @return array
*/
public static function exportUserBookingsByEmail( string $emailAddress, $page = 1 ): array {
- $page = intval( $page );
+ $page = intval( $page );
$itemsPerPage = 10;
- $exportItems = array();
- //The internal group ID used by WordPress to group the data exported by this exporter.
- $groupID = 'bookings';
+ $exportItems = array();
+ // The internal group ID used by WordPress to group the data exported by this exporter.
+ $groupID = 'bookings';
$groupLabel = __( 'CommonsBooking Bookings', 'commonsbooking' );
$user = get_user_by( 'email', $emailAddress );
if ( ! $user ) {
- return array(
- 'data' => $exportItems,
- 'done' => true,
- );
+ return array(
+ 'data' => $exportItems,
+ 'done' => true,
+ );
}
$bookings = \CommonsBooking\Repository\Booking::getForUserPaginated( $user, $page, $itemsPerPage );
if ( ! $bookings ) {
- return array(
- 'data' => $exportItems,
- 'done' => true,
- );
+ return array(
+ 'data' => $exportItems,
+ 'done' => true,
+ );
}
- foreach ($bookings as $booking) {
+ foreach ( $bookings as $booking ) {
$bookingID = $booking->ID;
- //exclude bookings that the user is eligible to see but are not their own
+ // exclude bookings that the user is eligible to see but are not their own
// we are only concerned about one user's personal data
if ( $booking->getUserData()->user_email !== $emailAddress ) {
continue;
@@ -945,7 +947,7 @@ public static function exportUserBookingsByEmail( string $emailAddress, $page =
$bookingData = [
[
'name' => __( 'Booking start', 'commonsbooking' ),
- 'value' => $booking->pickupDatetime() ,
+ 'value' => $booking->pickupDatetime(),
],
[
'name' => __( 'Booking end', 'commonsbooking' ),
@@ -953,7 +955,7 @@ public static function exportUserBookingsByEmail( string $emailAddress, $page =
],
[
'name' => __( 'Time of booking', 'commonsbooking' ),
- 'value' => Helper::FormattedDateTime(get_post_timestamp( $bookingID ) ),
+ 'value' => Helper::FormattedDateTime( get_post_timestamp( $bookingID ) ),
],
[
'name' => __( 'Status', 'commonsbooking' ),
@@ -991,7 +993,7 @@ public static function exportUserBookingsByEmail( string $emailAddress, $page =
'item_id' => $bookingID,
'data' => $bookingData,
];
- }
+ }
$done = count( $bookings ) < $itemsPerPage;
return array(
'data' => $exportItems,
@@ -1001,14 +1003,15 @@ public static function exportUserBookingsByEmail( string $emailAddress, $page =
/**
* Remove user bookings using the supplied email. This is for integration with the WordPress personal data eraser.
- * @param string $emailAddress The email address
+ *
+ * @param string $emailAddress The email address
* @param $page This parameter has no real use in this function, we just use it to stick to WordPress expected parameters.
*
* @return array
*/
public static function removeUserBookingsByEmail( string $emailAddress, $page = 1 ): array {
- //we reset the page to 1, because we are deleting our results as we go. Therefore, increasing the page number would skip some results.
- $page = 1;
+ // we reset the page to 1, because we are deleting our results as we go. Therefore, increasing the page number would skip some results.
+ $page = 1;
$itemsPerPage = 10;
$removedItems = false;
@@ -1030,16 +1033,16 @@ public static function removeUserBookingsByEmail( string $emailAddress, $page =
'done' => true,
);
}
- foreach ($bookings as $booking) {
+ foreach ( $bookings as $booking ) {
$bookingID = $booking->ID;
- //exclude bookings that the user is eligible to see but are not their own
+ // exclude bookings that the user is eligible to see but are not their own
// we are only concerned about one user's personal data
if ( $booking->getUserData()->user_email !== $emailAddress ) {
continue;
}
- //Cancel the booking before deletion so that status change emails are sent
+ // Cancel the booking before deletion so that status change emails are sent
$booking->cancel();
- //Delete the booking
+ // Delete the booking
wp_delete_post( $bookingID, true );
$removedItems = true;
}
@@ -1053,21 +1056,21 @@ public static function removeUserBookingsByEmail( string $emailAddress, $page =
);
}
- /**
- * Returns the user that a specific booking is for if booking exists, otherwise returns current user.
- * The post_author of a booking is always who the booking is for but not always the one who MADE the booking.
- * A booking can be created by an admin but still be for a different user.
- * This is helper function
- *
- * @return int|string
- */
- public static function getFrontendBookingUser() {
- global $post;
- if ( $post ) {
- $authorID = $post->post_author;
- } else {
- $authorID = get_current_user_id();
- }
- return $authorID;
- }
+ /**
+ * Returns the user that a specific booking is for if booking exists, otherwise returns current user.
+ * The post_author of a booking is always who the booking is for but not always the one who MADE the booking.
+ * A booking can be created by an admin but still be for a different user.
+ * This is helper function
+ *
+ * @return int|string
+ */
+ public static function getFrontendBookingUser() {
+ global $post;
+ if ( $post ) {
+ $authorID = $post->post_author;
+ } else {
+ $authorID = get_current_user_id();
+ }
+ return $authorID;
+ }
}
diff --git a/src/Wordpress/CustomPostType/CustomPostType.php b/src/Wordpress/CustomPostType/CustomPostType.php
index c68aceddc..493f4633c 100644
--- a/src/Wordpress/CustomPostType/CustomPostType.php
+++ b/src/Wordpress/CustomPostType/CustomPostType.php
@@ -41,7 +41,7 @@ abstract class CustomPostType {
* @return string
*/
public static function getWPAction(): string {
- return static::getPostType() . "-custom-fields";
+ return static::getPostType() . '-custom-fields';
}
/**
@@ -55,7 +55,7 @@ public static function getPostType(): string {
* @return string
*/
public static function getWPNonceId(): string {
- return static::getPostType() . "-custom-fields" . '_wpnonce';
+ return static::getPostType() . '-custom-fields' . '_wpnonce';
}
/**
@@ -79,12 +79,10 @@ public static function sanitizeOptions( $data ) {
$key = $item->ID;
$label = $item->post_title . $statusLabel;
- }
- elseif ( $item instanceof \WP_Term){
- $key = $item->term_id;
+ } elseif ( $item instanceof \WP_Term ) {
+ $key = $item->term_id;
$label = $item->name . ' (' . $item->slug . ')';
- }
- else {
+ } else {
$label = $item;
}
$options[ $key ] = $label;
@@ -96,7 +94,7 @@ public static function sanitizeOptions( $data ) {
/**
* retrieve Custom Meta Data from CommonsBooking Options and convert them to cmb2 fields array
- * The content is managed by user via options -> metadata sets
+ * The content is managed by user via options -> metadata sets
*
* @param mixed $type (item or location)
*
@@ -111,8 +109,7 @@ public static function getCMB2FieldsArrayFromCustomMetadata( $type ): ?array {
foreach ( $metaDataLines as $metaDataLine ) {
$metaDataArray = explode( ';', $metaDataLine );
- if ( count( $metaDataArray ) == 5 )
- {
+ if ( count( $metaDataArray ) == 5 ) {
// $metaDataArray[0] = Type
$metaDataFields[ $metaDataArray[0] ][] = array(
'id' => $metaDataArray[1],
@@ -123,8 +120,8 @@ public static function getCMB2FieldsArrayFromCustomMetadata( $type ): ?array {
}
}
- //allows to programmatically add custom metaboxes
- $metaDataFields = apply_filters('commonsbooking_custom_metadata', $metaDataFields);
+ // allows to programmatically add custom metaboxes
+ $metaDataFields = apply_filters( 'commonsbooking_custom_metadata', $metaDataFields );
if ( array_key_exists( $type, $metaDataFields ) ) {
return $metaDataFields[ $type ];
@@ -143,14 +140,14 @@ public static function getCMB2FieldsArrayFromCustomMetadata( $type ): ?array {
public static function modifyRowActions( $actions, $post ) {
// remove quick edit for timeframes, restrictions and bookings
- if ( $post->post_type == Timeframe::getPostType()
- OR $post->post_type == Restriction::getPostType()
- OR $post->post_type == Booking::getPostType()) {
+ if ( $post->post_type == Timeframe::getPostType()
+ or $post->post_type == Restriction::getPostType()
+ or $post->post_type == Booking::getPostType() ) {
unset( $actions['inline hide-if-no-js'] );
}
// remove preview for timeframes and restrictions
- if ( $post->post_type == Timeframe::getPostType() OR $post->post_type == Restriction::getPostType() ) {
+ if ( $post->post_type == Timeframe::getPostType() or $post->post_type == Restriction::getPostType() ) {
unset( $actions['view'] );
}
@@ -164,6 +161,7 @@ abstract public static function getView();
/**
* Returns param for backend menu.
+ *
* @return array
*/
public function getMenuParams() {
@@ -174,7 +172,7 @@ public function getMenuParams() {
'manage_' . COMMONSBOOKING_PLUGIN_SLUG,
'edit.php?post_type=' . static::getPostType(),
'',
- $this->menuPosition ?: null
+ $this->menuPosition ?: null,
];
}
@@ -219,23 +217,29 @@ public function setSortableColumns( $columns ) {
* Removes title column from backend listing.
*/
public function removeListTitleColumn() {
- add_filter( 'manage_' . static::getPostType() . '_posts_columns', function ( $columns ) {
- unset( $columns['title'] );
+ add_filter(
+ 'manage_' . static::getPostType() . '_posts_columns',
+ function ( $columns ) {
+ unset( $columns['title'] );
- return $columns;
- } );
+ return $columns;
+ }
+ );
}
/**
* Removes date column from backend listing.
*/
public function removeListDateColumn() {
- add_filter( 'manage_' . static::getPostType() . '_posts_columns', function ( $columns ) {
- unset( $columns['date'] );
- unset ( $columns['author'] ); // = 'Nutzer*in';
+ add_filter(
+ 'manage_' . static::getPostType() . '_posts_columns',
+ function ( $columns ) {
+ unset( $columns['date'] );
+ unset( $columns['author'] ); // = 'Nutzer*in';
- return $columns;
- } );
+ return $columns;
+ }
+ );
}
/**
@@ -247,38 +251,49 @@ abstract public function initHooks();
* Configures list-view
*/
public function initListView() {
- if ( array_key_exists('post_type', $_GET) && static::$postType !== $_GET['post_type'] ) {
+ if ( array_key_exists( 'post_type', $_GET ) && static::$postType !== $_GET['post_type'] ) {
return;
}
// List-View
add_filter( 'manage_' . static::getPostType() . '_posts_columns', array( $this, 'setCustomColumns' ) );
- add_action( 'manage_' . static::getPostType() . '_posts_custom_column', array(
- $this,
- 'setCustomColumnsData'
- ), 10,
- 2 );
- add_filter( 'manage_edit-' . static::getPostType() . '_sortable_columns', array(
- $this,
- 'setSortableColumns'
- ) );
+ add_action(
+ 'manage_' . static::getPostType() . '_posts_custom_column',
+ array(
+ $this,
+ 'setCustomColumnsData',
+ ),
+ 10,
+ 2
+ );
+ add_filter(
+ 'manage_edit-' . static::getPostType() . '_sortable_columns',
+ array(
+ $this,
+ 'setSortableColumns',
+ )
+ );
if ( isset( $this->listColumns ) ) {
add_action( 'pre_get_posts', array( $this, 'setCustomColumnSortOrder' ) );
}
// add ability to use WP_QUERY orderby for post_status
- add_filter('posts_orderby', function ($args, $wp_query) {
- if(isset ($wp_query->query_vars['orderby']) && $wp_query->query_vars['orderby'] == 'post_status') {
- if($wp_query->query_vars['order']) {
- return 'post_status '.$wp_query->query_vars['order'];
- }
- else {
- return 'post_status ASC';
+ add_filter(
+ 'posts_orderby',
+ function ( $args, $wp_query ) {
+ if ( isset( $wp_query->query_vars['orderby'] ) && $wp_query->query_vars['orderby'] == 'post_status' ) {
+ if ( $wp_query->query_vars['order'] ) {
+ return 'post_status ' . $wp_query->query_vars['order'];
+ } else {
+ return 'post_status ASC';
+ }
}
- }
- return $args;
- }, 10,2);
+ return $args;
+ },
+ 10,
+ 2
+ );
}
/**
@@ -290,25 +305,24 @@ public function initListView() {
public function setCustomColumnsData( $column, $post_id ) {
if ( $value = get_post_meta( $post_id, $column, true ) ) {
- echo commonsbooking_sanitizeHTML($value);
+ echo commonsbooking_sanitizeHTML( $value );
+ } elseif ( property_exists( $post = get_post( $post_id ), $column ) ) {
+ echo commonsbooking_sanitizeHTML( $post->{$column} );
} else {
- if ( property_exists( $post = get_post( $post_id ), $column ) ) {
- echo commonsbooking_sanitizeHTML($post->{$column});
- } else {
- echo '-';
- }
+ echo '-';
}
}
/**
* Adds Category filter to backend list view
- *
*/
public static function addAdminCategoryFilter() {
$values = [];
- $terms = get_terms(array(
- 'taxonomy' => static::$postType . 's_category'
- ));
+ $terms = get_terms(
+ array(
+ 'taxonomy' => static::$postType . 's_category',
+ )
+ );
foreach ( $terms as $term ) {
$values[ $term->term_id ] = $term->name;
}
@@ -322,15 +336,16 @@ public static function addAdminCategoryFilter() {
/**
* Checks if method has been called before in current request.
+ *
* @param $methodName
*
* @return bool
*/
- protected function hasRunBefore($methodName): bool {
- if(array_key_exists($methodName, $_REQUEST)) {
+ protected function hasRunBefore( $methodName ): bool {
+ if ( array_key_exists( $methodName, $_REQUEST ) ) {
return true;
}
- $_REQUEST[$methodName] = true;
+ $_REQUEST[ $methodName ] = true;
return false;
}
@@ -346,27 +361,27 @@ public static function getModel( $post ) {
if ( $post instanceof CustomPost ) {
return $post;
}
- if (is_int($post)) {
- $post = get_post($post);
+ if ( is_int( $post ) ) {
+ $post = get_post( $post );
}
- if (! $post instanceof WP_Post) {
- throw new PostException('No suitable post object.');
+ if ( ! $post instanceof WP_Post ) {
+ throw new PostException( 'No suitable post object.' );
}
- switch($post->post_type) {
+ switch ( $post->post_type ) {
case Booking::$postType:
- return new \CommonsBooking\Model\Booking($post);
+ return new \CommonsBooking\Model\Booking( $post );
case Item::$postType:
- return new \CommonsBooking\Model\Item($post);
+ return new \CommonsBooking\Model\Item( $post );
case Location::$postType:
- return new \CommonsBooking\Model\Location($post);
+ return new \CommonsBooking\Model\Location( $post );
case Restriction::$postType:
- return new \CommonsBooking\Model\Restriction($post);
+ return new \CommonsBooking\Model\Restriction( $post );
case Timeframe::$postType:
- return new \CommonsBooking\Model\Timeframe($post);
+ return new \CommonsBooking\Model\Timeframe( $post );
case Map::$postType:
- return new \CommonsBooking\Model\Map($post);
+ return new \CommonsBooking\Model\Map( $post );
}
- throw new PostException('No suitable model found for ' . $post->post_type);
+ throw new PostException( 'No suitable model found for ' . $post->post_type );
}
/**
@@ -384,5 +399,4 @@ public function setCustomColumnSortOrder( \WP_Query $query ) {
}
return true;
}
-
}
diff --git a/src/Wordpress/CustomPostType/Item.php b/src/Wordpress/CustomPostType/Item.php
index 5b5b43096..d3077bbd6 100644
--- a/src/Wordpress/CustomPostType/Item.php
+++ b/src/Wordpress/CustomPostType/Item.php
@@ -22,7 +22,7 @@ public function initHooks() {
// Listing of locations for item
add_shortcode( 'cb_locations', array( \CommonsBooking\View\Location::class, 'shortcode' ) );
- //Add filter to backend list view
+ // Add filter to backend list view
add_action( 'restrict_manage_posts', array( self::class, 'addAdminCategoryFilter' ) );
// Filter only for current user allowed posts
@@ -34,15 +34,16 @@ public function initHooks() {
/**
* Handles the creation and editing of the terms in the taxonomy for the location post type
+ *
* @param $term_id
* @param $tt_id
* @param $taxonomy
*
* @return void
*/
- public static function termChange($term_id, $tt_id, $taxonomy) {
+ public static function termChange( $term_id, $tt_id, $taxonomy ) {
if ( $taxonomy == self::$postType . 's_category' ) {
- //update all dynamic timeframes
+ // update all dynamic timeframes
Timeframe::updateAllTimeframes();
}
}
@@ -50,9 +51,9 @@ public static function termChange($term_id, $tt_id, $taxonomy) {
/**
* Handles save-Request for items.
*/
- public function savePost($post_id, \WP_Post $post) {
+ public function savePost( $post_id, \WP_Post $post ) {
if ( $post->post_type == self::$postType && $post_id ) {
- //update all dynamic timeframes
+ // update all dynamic timeframes
Timeframe::updateAllTimeframes();
}
}
@@ -91,11 +92,11 @@ function ( &$item, $key ) {
$_GET['admin_filter_post_category'] != ''
) {
$query->query_vars['tax_query'] = array(
- array(
- 'taxonomy' => self::$postType . 's_category',
- 'field' => 'term_id',
- 'terms' => $_GET['admin_filter_post_category']
- )
+ array(
+ 'taxonomy' => self::$postType . 's_category',
+ 'field' => 'term_id',
+ 'terms' => $_GET['admin_filter_post_category'],
+ ),
);
}
}
@@ -107,6 +108,7 @@ public static function getView() {
/**
* Returns CPT args.
+ *
* @return array
*/
public function getArgs(): array {
@@ -183,7 +185,6 @@ public function getArgs(): array {
'author',
),
-
// Soll der Post Type Kategorien haben?
'taxonomies' => array( self::$postType . 's_category' ),
@@ -202,17 +203,17 @@ public function getArgs(): array {
}
public function getTemplate( $content ) {
- $cb_content = '';
+ $cb_content = '';
$errormessage = '';
if ( is_singular( self::getPostType() ) && is_main_query() && get_post_type() == self::getPostType() ) {
ob_start();
global $post;
- $item = new \CommonsBooking\Model\Item( $post );
+ $item = new \CommonsBooking\Model\Item( $post );
$errormessage = \CommonsBooking\View\Booking::getError();
set_query_var( 'item', $item );
commonsbooking_get_template_part( 'item', 'single' );
- $cb_content = ob_get_clean();
+ $cb_content = ob_get_clean();
}
return $errormessage . $content . $cb_content;
@@ -226,45 +227,52 @@ public function getTemplate( $content ) {
*/
public function registerMetabox() {
// Initiate the metabox Adress
- $cmb = new_cmb2_box( array(
- 'id' => COMMONSBOOKING_METABOX_PREFIX . 'item_info',
- 'title' => esc_html__( 'Item Info', 'commonsbooking' ),
- 'object_types' => array( self::$postType ), // Post type
- 'context' => 'normal',
- 'priority' => 'high',
- 'show_names' => true, // Show field names on the left
- ) );
-
+ $cmb = new_cmb2_box(
+ array(
+ 'id' => COMMONSBOOKING_METABOX_PREFIX . 'item_info',
+ 'title' => esc_html__( 'Item Info', 'commonsbooking' ),
+ 'object_types' => array( self::$postType ), // Post type
+ 'context' => 'normal',
+ 'priority' => 'high',
+ 'show_names' => true, // Show field names on the left
+ )
+ );
// Show selection only to admins
if ( commonsbooking_isCurrentUserAdmin() || commonsbooking_isCurrentUserCBManager() ) {
$users = UserRepository::getSelectableCBManagers();
$userOptions = [];
foreach ( $users as $user ) {
- $userOptions[ $user->ID ] = $user->get( 'user_nicename' ) . " (" . $user->first_name . " " . $user->last_name . ")";
+ $userOptions[ $user->ID ] = $user->get( 'user_nicename' ) . ' (' . $user->first_name . ' ' . $user->last_name . ')';
}
- //Item Administrators
- $cmb->add_field( array(
- 'name' => esc_html__( 'Item Admin(s)', 'commonsbooking' ),
- 'desc' => esc_html__( 'choose one or more users to give them the permisssion to edit and manage this specific item. Only users with the role cb_manager can be selected here', 'commonsbooking' ),
- 'id' => COMMONSBOOKING_METABOX_PREFIX . 'item_admins',
- 'type' => 'pw_multiselect',
- 'options' => $userOptions,
- 'attributes' => array(
- 'placeholder' => esc_html__( 'Select item admins.', 'commonsbooking' )
- ),
- ) );
+ // Item Administrators
+ $cmb->add_field(
+ array(
+ 'name' => esc_html__( 'Item Admin(s)', 'commonsbooking' ),
+ 'desc' => esc_html__( 'choose one or more users to give them the permisssion to edit and manage this specific item. Only users with the role cb_manager can be selected here', 'commonsbooking' ),
+ 'id' => COMMONSBOOKING_METABOX_PREFIX . 'item_admins',
+ 'type' => 'pw_multiselect',
+ 'options' => $userOptions,
+ 'attributes' => array(
+ 'placeholder' => esc_html__( 'Select item admins.', 'commonsbooking' ),
+ ),
+ )
+ );
// item maintainer(s) emails
- $cmb->add_field( array(
- 'name' => esc_html__( 'Item maintainer email', 'commonsbooking' ),
- 'desc' => esc_html__( 'Email addresses to which notifications about a change of item status (restriction, breakdown) shall be sent. You can enter multiple addresses separated by commas.',
- 'commonsbooking' ),
- 'id' => COMMONSBOOKING_METABOX_PREFIX . 'item_maintainer_email',
- 'type' => 'text',
- 'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
- ) );
+ $cmb->add_field(
+ array(
+ 'name' => esc_html__( 'Item maintainer email', 'commonsbooking' ),
+ 'desc' => esc_html__(
+ 'Email addresses to which notifications about a change of item status (restriction, breakdown) shall be sent. You can enter multiple addresses separated by commas.',
+ 'commonsbooking'
+ ),
+ 'id' => COMMONSBOOKING_METABOX_PREFIX . 'item_maintainer_email',
+ 'type' => 'text',
+ 'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
+ )
+ );
}
// Check if custom meta fields are set in CB Options and generate MetaData-Box and fields
@@ -272,27 +280,28 @@ public function registerMetabox() {
$customMetaData = self::getCMB2FieldsArrayFromCustomMetadata( 'item' );
// Initiate the metabox Adress
- $cmb = new_cmb2_box( array(
- 'id' => COMMONSBOOKING_METABOX_PREFIX . 'item_custom_meta',
- 'title' => esc_html__( 'Item Meta-Data', 'commonsbooking' ),
- 'object_types' => array( self::$postType ), // Post type
- 'context' => 'normal',
- 'priority' => 'high',
- 'show_names' => true, // Show field names on the left
- ) );
+ $cmb = new_cmb2_box(
+ array(
+ 'id' => COMMONSBOOKING_METABOX_PREFIX . 'item_custom_meta',
+ 'title' => esc_html__( 'Item Meta-Data', 'commonsbooking' ),
+ 'object_types' => array( self::$postType ), // Post type
+ 'context' => 'normal',
+ 'priority' => 'high',
+ 'show_names' => true, // Show field names on the left
+ )
+ );
// Add Custom Meta Fields defined in CommonsBooking Options (Tab MetaData)
foreach ( $customMetaData as $customMetaDataField ) {
$cmb->add_field( $customMetaDataField );
}
-
}
// we store registered metaboxes to options table to be able to retrieve it in export function
$metabox_fields = [];
- foreach ($cmb->meta_box['fields'] as $metabox_field) {
- $metabox_fields[$metabox_field['id']] = $metabox_field['name'];
+ foreach ( $cmb->meta_box['fields'] as $metabox_field ) {
+ $metabox_fields[ $metabox_field['id'] ] = $metabox_field['name'];
}
- Settings::updateOption('commonsbooking_settings_metaboxfields', $this->getPostType(), $metabox_fields);
+ Settings::updateOption( 'commonsbooking_settings_metaboxfields', $this->getPostType(), $metabox_fields );
}
-}
\ No newline at end of file
+}
diff --git a/src/Wordpress/CustomPostType/Location.php b/src/Wordpress/CustomPostType/Location.php
index 179165d9f..40c7bb6e5 100644
--- a/src/Wordpress/CustomPostType/Location.php
+++ b/src/Wordpress/CustomPostType/Location.php
@@ -20,7 +20,7 @@ public function initHooks() {
// Listing of items for location
add_shortcode( 'cb_items', array( \CommonsBooking\View\Item::class, 'shortcode' ) );
- //Add filter to backend list view
+ // Add filter to backend list view
add_action( 'restrict_manage_posts', array( self::class, 'addAdminCategoryFilter' ) );
// Filter only for current user allowed posts
@@ -33,27 +33,28 @@ public function initHooks() {
/**
* Handles save-Request for location.
*/
- public function savePost($post_id, \WP_Post $post) {
+ public function savePost( $post_id, \WP_Post $post ) {
if ( $post->post_type == self::$postType && $post_id ) {
$location = new \CommonsBooking\Model\Location( intval( $post_id ) );
$location->updateGeoLocation();
- //update all dynamic timeframes
+ // update all dynamic timeframes
Timeframe::updateAllTimeframes();
}
}
/**
* Handles the creation and editing of the terms in the taxonomy for the location post type
+ *
* @param $term_id
* @param $tt_id
* @param $taxonomy
*
* @return void
*/
- public static function termChange($term_id, $tt_id, $taxonomy) {
+ public static function termChange( $term_id, $tt_id, $taxonomy ) {
if ( $taxonomy == self::$postType . 's_category' ) {
- //update all dynamic timeframes
+ // update all dynamic timeframes
Timeframe::updateAllTimeframes();
}
}
@@ -91,11 +92,11 @@ function ( &$item, $key ) {
$_GET['admin_filter_post_category'] != ''
) {
$query->query_vars['tax_query'] = array(
- array(
- 'taxonomy' => self::$postType . 's_category',
- 'field' => 'term_id',
- 'terms' => $_GET['admin_filter_post_category']
- )
+ array(
+ 'taxonomy' => self::$postType . 's_category',
+ 'field' => 'term_id',
+ 'terms' => $_GET['admin_filter_post_category'],
+ ),
);
}
}
@@ -186,7 +187,7 @@ public function getArgs() {
'custom-fields',
'revisions',
'excerpt',
- 'author'
+ 'author',
),
// Soll der Post Type Kategien haben?
@@ -214,157 +215,192 @@ public function getArgs() {
*/
public function registerMetabox() {
// Initiate the metabox address
- $cmb = new_cmb2_box( array(
- 'id' => COMMONSBOOKING_METABOX_PREFIX . 'location_adress',
- 'title' => esc_html__( 'Address', 'commonsbooking' ),
- 'object_types' => array( self::$postType ), // Post type
- 'context' => 'normal',
- 'priority' => 'high',
- 'show_names' => true, // Show field names on the left
- ) );
+ $cmb = new_cmb2_box(
+ array(
+ 'id' => COMMONSBOOKING_METABOX_PREFIX . 'location_adress',
+ 'title' => esc_html__( 'Address', 'commonsbooking' ),
+ 'object_types' => array( self::$postType ), // Post type
+ 'context' => 'normal',
+ 'priority' => 'high',
+ 'show_names' => true, // Show field names on the left
+ )
+ );
// Adress
- $cmb->add_field( array(
- 'name' => esc_html__( 'Street / No.', 'commonsbooking' ),
- 'id' => COMMONSBOOKING_METABOX_PREFIX . 'location_street',
- 'type' => 'text',
- 'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
- 'attributes' => array(
- 'required' => 'required',
- ),
- ) );
+ $cmb->add_field(
+ array(
+ 'name' => esc_html__( 'Street / No.', 'commonsbooking' ),
+ 'id' => COMMONSBOOKING_METABOX_PREFIX . 'location_street',
+ 'type' => 'text',
+ 'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
+ 'attributes' => array(
+ 'required' => 'required',
+ ),
+ )
+ );
// Postcode
- $cmb->add_field( array(
- 'name' => esc_html__( 'Postcode', 'commonsbooking' ),
- 'id' => COMMONSBOOKING_METABOX_PREFIX . 'location_postcode',
- 'type' => 'text',
- 'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
- 'attributes' => array(
- 'required' => 'required',
- ),
- ) );
+ $cmb->add_field(
+ array(
+ 'name' => esc_html__( 'Postcode', 'commonsbooking' ),
+ 'id' => COMMONSBOOKING_METABOX_PREFIX . 'location_postcode',
+ 'type' => 'text',
+ 'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
+ 'attributes' => array(
+ 'required' => 'required',
+ ),
+ )
+ );
// City
- $cmb->add_field( array(
- 'name' => esc_html__( 'City', 'commonsbooking' ),
- 'id' => COMMONSBOOKING_METABOX_PREFIX . 'location_city',
- 'type' => 'text',
- 'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
- 'attributes' => array(
- 'required' => 'required',
- ),
- ) );
+ $cmb->add_field(
+ array(
+ 'name' => esc_html__( 'City', 'commonsbooking' ),
+ 'id' => COMMONSBOOKING_METABOX_PREFIX . 'location_city',
+ 'type' => 'text',
+ 'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
+ 'attributes' => array(
+ 'required' => 'required',
+ ),
+ )
+ );
// Country
- $cmb->add_field( array(
- 'name' => esc_html__( 'Country', 'commonsbooking' ),
- //'desc' => esc_html__('field description (optional)', 'commonsbooking'),
- 'id' => COMMONSBOOKING_METABOX_PREFIX . 'location_country',
- 'type' => 'text',
- 'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
- ) );
+ $cmb->add_field(
+ array(
+ 'name' => esc_html__( 'Country', 'commonsbooking' ),
+ // 'desc' => esc_html__('field description (optional)', 'commonsbooking'),
+ 'id' => COMMONSBOOKING_METABOX_PREFIX . 'location_country',
+ 'type' => 'text',
+ 'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
+ )
+ );
// Generate Geo-Coordinates
- $cmb->add_field( array(
- 'name' => esc_html__( 'Set / Update GPS and map', 'commonsbooking' ),
- //'desc' => esc_html__('field description (optional)', 'commonsbooking'),
- 'id' => COMMONSBOOKING_METABOX_PREFIX . 'get_gps',
- 'type' => 'text',
- 'render_row_cb' => array( Map::class, 'renderGeoRefreshButton' ),
- 'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
- ) );
-
+ $cmb->add_field(
+ array(
+ 'name' => esc_html__( 'Set / Update GPS and map', 'commonsbooking' ),
+ // 'desc' => esc_html__('field description (optional)', 'commonsbooking'),
+ 'id' => COMMONSBOOKING_METABOX_PREFIX . 'get_gps',
+ 'type' => 'text',
+ 'render_row_cb' => array( Map::class, 'renderGeoRefreshButton' ),
+ 'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
+ )
+ );
// Latitude
- $cmb->add_field( array(
- 'name' => esc_html__( 'Latitude', 'commonsbooking' ),
- 'desc' => commonsbooking_sanitizeHTML( __('The latitude is calculated automatically when you click the "set / update GPS" button after entering the street, postal code and city.', 'commonsbooking') ),
- 'id' => 'geo_latitude',
- 'type' => 'text',
- 'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
- ) );
+ $cmb->add_field(
+ array(
+ 'name' => esc_html__( 'Latitude', 'commonsbooking' ),
+ 'desc' => commonsbooking_sanitizeHTML( __( 'The latitude is calculated automatically when you click the "set / update GPS" button after entering the street, postal code and city.', 'commonsbooking' ) ),
+ 'id' => 'geo_latitude',
+ 'type' => 'text',
+ 'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
+ )
+ );
// Longitude
- $cmb->add_field( array(
- 'name' => esc_html__( 'Longitude', 'commonsbooking' ),
- 'desc' => commonsbooking_sanitizeHTML( __('The longitude is calculated automatically when you click the "set / update GPS" button after entering the street, postal code and city.', 'commonsbooking') ),
- 'id' => 'geo_longitude',
- 'type' => 'text',
- 'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
- ) );
+ $cmb->add_field(
+ array(
+ 'name' => esc_html__( 'Longitude', 'commonsbooking' ),
+ 'desc' => commonsbooking_sanitizeHTML( __( 'The longitude is calculated automatically when you click the "set / update GPS" button after entering the street, postal code and city.', 'commonsbooking' ) ),
+ 'id' => 'geo_longitude',
+ 'type' => 'text',
+ 'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
+ )
+ );
// Map
- $cmb->add_field( array(
- 'name' => esc_html__( 'Position', 'commonsbooking' ),
- //'desc' => esc_html__('field description (optional)', 'commonsbooking'),
- 'id' => COMMONSBOOKING_METABOX_PREFIX . '_map_position',
- 'type' => 'cb_map',
- 'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
- ) );
+ $cmb->add_field(
+ array(
+ 'name' => esc_html__( 'Position', 'commonsbooking' ),
+ // 'desc' => esc_html__('field description (optional)', 'commonsbooking'),
+ 'id' => COMMONSBOOKING_METABOX_PREFIX . '_map_position',
+ 'type' => 'cb_map',
+ 'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
+ )
+ );
// Show map on item view checkbox
- $cmb->add_field( array(
- 'name' => esc_html__( 'Show location map on item view', 'commonsbooking' ),
- 'desc' => esc_html__('If enabled, a map showing the location will be displayed on the location details page.', 'commonsbooking'),
- 'id' => 'loc_showmap',
- 'type' => 'checkbox',
- 'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
- ) );
+ $cmb->add_field(
+ array(
+ 'name' => esc_html__( 'Show location map on item view', 'commonsbooking' ),
+ 'desc' => esc_html__( 'If enabled, a map showing the location will be displayed on the location details page.', 'commonsbooking' ),
+ 'id' => 'loc_showmap',
+ 'type' => 'checkbox',
+ 'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
+ )
+ );
// Initiate the metabox Information
- $cmb = new_cmb2_box( array(
- 'id' => COMMONSBOOKING_METABOX_PREFIX . 'location_info',
- 'title' => esc_html__( 'General Location information', 'commonsbooking' ),
- 'object_types' => array( self::$postType ), // Post type
- 'context' => 'normal',
- 'priority' => 'high',
- 'show_names' => true, // Show field names on the left
- ) );
+ $cmb = new_cmb2_box(
+ array(
+ 'id' => COMMONSBOOKING_METABOX_PREFIX . 'location_info',
+ 'title' => esc_html__( 'General Location information', 'commonsbooking' ),
+ 'object_types' => array( self::$postType ), // Post type
+ 'context' => 'normal',
+ 'priority' => 'high',
+ 'show_names' => true, // Show field names on the left
+ )
+ );
// location email
- $cmb->add_field( array(
- 'name' => esc_html__( 'Location email', 'commonsbooking' ),
- 'desc' => esc_html__( 'Email addresses of the owner of the station. Can be reminded about bookings / cancellations and will receive the booking codes (when configured in the timeframe). You can enter multiple addresses separated by commas.',
- 'commonsbooking' ),
- 'id' => COMMONSBOOKING_METABOX_PREFIX . 'location_email',
- 'type' => 'text',
- 'attributes' => array(
- 'class' => "regular-text cmb2-oembed",
- ),
- 'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
+ $cmb->add_field(
+ array(
+ 'name' => esc_html__( 'Location email', 'commonsbooking' ),
+ 'desc' => esc_html__(
+ 'Email addresses of the owner of the station. Can be reminded about bookings / cancellations and will receive the booking codes (when configured in the timeframe). You can enter multiple addresses separated by commas.',
+ 'commonsbooking'
+ ),
+ 'id' => COMMONSBOOKING_METABOX_PREFIX . 'location_email',
+ 'type' => 'text',
+ 'attributes' => array(
+ 'class' => 'regular-text cmb2-oembed',
+ ),
+ 'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
// 'repeatable' => true,
- ) );
+ )
+ );
// checkbox BCC bookings / cancellations to location email
- $cmb->add_field( array(
- 'name' => esc_html__( 'Send copy of bookings / cancellations to location email', 'commonsbooking' ),
- 'desc' => esc_html__( 'If enabled, the location email will receive a copy of all booking and cancellation notifications.', 'commonsbooking' ),
- 'id' => COMMONSBOOKING_METABOX_PREFIX . 'location_email_bcc',
- 'type' => 'checkbox',
- 'default_cb' => 'cmb2_set_checkbox_default_for_new_post'
- ) );
+ $cmb->add_field(
+ array(
+ 'name' => esc_html__( 'Send copy of bookings / cancellations to location email', 'commonsbooking' ),
+ 'desc' => esc_html__( 'If enabled, the location email will receive a copy of all booking and cancellation notifications.', 'commonsbooking' ),
+ 'id' => COMMONSBOOKING_METABOX_PREFIX . 'location_email_bcc',
+ 'type' => 'checkbox',
+ 'default_cb' => 'cmb2_set_checkbox_default_for_new_post',
+ )
+ );
// pickup description
- $cmb->add_field( array(
- 'name' => esc_html__( 'Pickup instructions', 'commonsbooking' ),
- 'desc' => esc_html__( 'Type in information about the pickup process (e.g. detailed route description, opening hours, etc.). This will be shown to user in booking process and booking confirmation mail',
- 'commonsbooking' ),
- 'id' => COMMONSBOOKING_METABOX_PREFIX . 'location_pickupinstructions',
- 'type' => 'textarea_small',
- 'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
+ $cmb->add_field(
+ array(
+ 'name' => esc_html__( 'Pickup instructions', 'commonsbooking' ),
+ 'desc' => esc_html__(
+ 'Type in information about the pickup process (e.g. detailed route description, opening hours, etc.). This will be shown to user in booking process and booking confirmation mail',
+ 'commonsbooking'
+ ),
+ 'id' => COMMONSBOOKING_METABOX_PREFIX . 'location_pickupinstructions',
+ 'type' => 'textarea_small',
+ 'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
// 'repeatable' => true,
- ) );
+ )
+ );
// location contact
- $cmb->add_field( array(
- 'name' => esc_html__( 'Location contact information', 'commonsbooking' ),
- 'desc' => esc_html__( 'information about how to contact the location (e.g. contact person, phone number, e-mail etc.). This will be shown to user in booking process and booking confirmation mail',
- 'commonsbooking' ),
- 'id' => COMMONSBOOKING_METABOX_PREFIX . 'location_contact',
- 'type' => 'textarea_small',
- 'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
- ) );
+ $cmb->add_field(
+ array(
+ 'name' => esc_html__( 'Location contact information', 'commonsbooking' ),
+ 'desc' => esc_html__(
+ 'information about how to contact the location (e.g. contact person, phone number, e-mail etc.). This will be shown to user in booking process and booking confirmation mail',
+ 'commonsbooking'
+ ),
+ 'id' => COMMONSBOOKING_METABOX_PREFIX . 'location_contact',
+ 'type' => 'textarea_small',
+ 'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
+ )
+ );
// Show selection only to admins
if ( commonsbooking_isCurrentUserAdmin() || commonsbooking_isCurrentUserCBManager() ) {
@@ -372,74 +408,85 @@ public function registerMetabox() {
$users = UserRepository::getSelectableCBManagers();
$userOptions = [];
foreach ( $users as $user ) {
- $userOptions[ $user->ID ] = $user->get( 'user_nicename' ) . " (" . $user->first_name . " " . $user->last_name . ")";
+ $userOptions[ $user->ID ] = $user->get( 'user_nicename' ) . ' (' . $user->first_name . ' ' . $user->last_name . ')';
}
- $cmb->add_field( array(
- 'name' => esc_html__( 'Location Admin(s)', 'commonsbooking' ),
- 'desc' => esc_html__( 'choose one or more users to give them the permisssion to edit and manage this specific location. Only users with the role CommonsBooking Manager can be selected here.',
- 'commonsbooking' ),
- 'id' => COMMONSBOOKING_METABOX_PREFIX . 'location_admins',
- 'type' => 'pw_multiselect',
- 'options' => $userOptions,
- 'attributes' => array(
- 'placeholder' => esc_html__( 'Select location admins.', 'commonsbooking' )
- ),
- ) );
+ $cmb->add_field(
+ array(
+ 'name' => esc_html__( 'Location Admin(s)', 'commonsbooking' ),
+ 'desc' => esc_html__(
+ 'choose one or more users to give them the permisssion to edit and manage this specific location. Only users with the role CommonsBooking Manager can be selected here.',
+ 'commonsbooking'
+ ),
+ 'id' => COMMONSBOOKING_METABOX_PREFIX . 'location_admins',
+ 'type' => 'pw_multiselect',
+ 'options' => $userOptions,
+ 'attributes' => array(
+ 'placeholder' => esc_html__( 'Select location admins.', 'commonsbooking' ),
+ ),
+ )
+ );
}
- $cmb->add_field( array (
- 'name' => esc_html__( 'Use global location settings', 'commonsbooking' ),
- 'desc' => esc_html__( 'If selected, the global location settings (under the "General" tab) will be used for this location. If not selected, the settings below will be used.', 'commonsbooking' ),
- 'id' => COMMONSBOOKING_METABOX_PREFIX . 'use_global_settings',
- 'type' => 'checkbox',
- 'default_cb' => 'cmb2_set_checkbox_default_for_new_post',
- ) );
+ $cmb->add_field(
+ array(
+ 'name' => esc_html__( 'Use global location settings', 'commonsbooking' ),
+ 'desc' => esc_html__( 'If selected, the global location settings (under the "General" tab) will be used for this location. If not selected, the settings below will be used.', 'commonsbooking' ),
+ 'id' => COMMONSBOOKING_METABOX_PREFIX . 'use_global_settings',
+ 'type' => 'checkbox',
+ 'default_cb' => 'cmb2_set_checkbox_default_for_new_post',
+ )
+ );
foreach ( self::getOverbookingSettingsMetaboxes() as $metabox ) {
$cmb->add_field( $metabox );
}
- $cmb->add_field( array(
- 'name' => esc_html__( 'Receive booking start reminder', 'commonsbooking' ),
- 'desc' => commonsbooking_sanitizeHTML( __( 'If selected, this location receives reminder emails of bookings starting soon. The notifications are sent to all addresses specified in the location email list (first as receiver, all following as BCC). This type of reminder needs to be activated in the general CommonsBooking settings.', 'commonsbooking' ) ),
- 'id' => COMMONSBOOKING_METABOX_PREFIX . 'receive_booking_start_reminder',
- 'type' => 'checkbox',
- ) );
+ $cmb->add_field(
+ array(
+ 'name' => esc_html__( 'Receive booking start reminder', 'commonsbooking' ),
+ 'desc' => commonsbooking_sanitizeHTML( __( 'If selected, this location receives reminder emails of bookings starting soon. The notifications are sent to all addresses specified in the location email list (first as receiver, all following as BCC). This type of reminder needs to be activated in the general CommonsBooking settings.', 'commonsbooking' ) ),
+ 'id' => COMMONSBOOKING_METABOX_PREFIX . 'receive_booking_start_reminder',
+ 'type' => 'checkbox',
+ )
+ );
- $cmb->add_field( array(
- 'name' => esc_html__( 'Receive booking end reminder', 'commonsbooking' ),
- 'desc' => commonsbooking_sanitizeHTML( __( 'If selected, this location receives reminder emails of bookings ending soon. The notifications are sent to all addresses specified in the location email list (first as receiver, all following as BCC). This type of reminder needs to be activated in the general CommonsBooking settings.', 'commonsbooking' ) ),
- 'id' => COMMONSBOOKING_METABOX_PREFIX . 'receive_booking_end_reminder',
- 'type' => 'checkbox',
- ) );
+ $cmb->add_field(
+ array(
+ 'name' => esc_html__( 'Receive booking end reminder', 'commonsbooking' ),
+ 'desc' => commonsbooking_sanitizeHTML( __( 'If selected, this location receives reminder emails of bookings ending soon. The notifications are sent to all addresses specified in the location email list (first as receiver, all following as BCC). This type of reminder needs to be activated in the general CommonsBooking settings.', 'commonsbooking' ) ),
+ 'id' => COMMONSBOOKING_METABOX_PREFIX . 'receive_booking_end_reminder',
+ 'type' => 'checkbox',
+ )
+ );
// Check if custom meta fields are set in CB Options and generate MetaData-Box and fields
if ( is_array( self::getCMB2FieldsArrayFromCustomMetadata( 'location' ) ) ) {
$customMetaData = self::getCMB2FieldsArrayFromCustomMetadata( 'location' );
// Initiate the metabox Adress
- $cmb = new_cmb2_box( array(
- 'id' => COMMONSBOOKING_METABOX_PREFIX . 'location_custom_meta',
- 'title' => esc_html__( 'Location Meta-Data', 'commonsbooking' ),
- 'object_types' => array( self::$postType ), // Post type
- 'context' => 'normal',
- 'priority' => 'high',
- 'show_names' => true, // Show field names on the left
- ) );
+ $cmb = new_cmb2_box(
+ array(
+ 'id' => COMMONSBOOKING_METABOX_PREFIX . 'location_custom_meta',
+ 'title' => esc_html__( 'Location Meta-Data', 'commonsbooking' ),
+ 'object_types' => array( self::$postType ), // Post type
+ 'context' => 'normal',
+ 'priority' => 'high',
+ 'show_names' => true, // Show field names on the left
+ )
+ );
// Add Custom Meta Fields defined in CommonsBooking Options (Tab MetaData)
foreach ( $customMetaData as $customMetaDataField ) {
$cmb->add_field( $customMetaDataField );
}
-
}
// we store registered metaboxes to options table to be able to retrieve it in export function
$metabox_fields = [];
- foreach ($cmb->meta_box['fields'] as $metabox_field) {
- $metabox_fields[$metabox_field['id']] = $metabox_field['name'];
+ foreach ( $cmb->meta_box['fields'] as $metabox_field ) {
+ $metabox_fields[ $metabox_field['id'] ] = $metabox_field['name'];
}
- Settings::updateOption('commonsbooking_settings_metaboxfields', $this->getPostType(), $metabox_fields);
+ Settings::updateOption( 'commonsbooking_settings_metaboxfields', $this->getPostType(), $metabox_fields );
}
/**
@@ -468,9 +515,7 @@ public static function getOverbookingSettingsMetaboxes() {
'id' => COMMONSBOOKING_METABOX_PREFIX . 'count_lockdays_maximum',
'default' => '0',
'type' => 'text_small',
- )
+ ),
];
-
}
-
}
diff --git a/src/Wordpress/CustomPostType/Map.php b/src/Wordpress/CustomPostType/Map.php
index e08886057..c1bb33f95 100644
--- a/src/Wordpress/CustomPostType/Map.php
+++ b/src/Wordpress/CustomPostType/Map.php
@@ -3,7 +3,6 @@
namespace CommonsBooking\Wordpress\CustomPostType;
-
use CommonsBooking\Map\MapShortcode;
use CommonsBooking\Repository\CB1;
use CommonsBooking\Repository\Item;
@@ -24,7 +23,7 @@ class Map extends CustomPostType {
* Is used when no other coordinates are set.
* These are currently the coordinates of Cologne, Germany.
*/
- const LATITUDE_DEFAULT = 50.937531;
+ const LATITUDE_DEFAULT = 50.937531;
const LONGITUDE_DEFAULT = 6.960279;
/**
@@ -41,13 +40,12 @@ public function initHooks() {
public function registerMetabox() {
$cmb = new_cmb2_box(
[
- 'id' => static::getPostType() . "-custom-fields",
+ 'id' => static::getPostType() . '-custom-fields',
'title' => esc_html__( 'Map settings', 'commonsbooking' ),
'object_types' => array( static::getPostType() ),
]
);
-
foreach ( self::getCustomFields() as $customField ) {
$cmb->add_field( $customField );
}
@@ -65,12 +63,12 @@ public static function getCustomFields(): array {
'type' => 'text',
'id' => 'shortcode',
),
- //Begin group presentation
+ // Begin group presentation
array(
'name' => esc_html__( 'Presentation', 'commonsbooking' ),
'type' => 'title',
'id' => 'presentation_info',
- 'classes' => 'map-organizer'
+ 'classes' => 'map-organizer',
),
array(
'name' => esc_html__( 'base map', 'commonsbooking' ),
@@ -79,7 +77,7 @@ public static function getCustomFields(): array {
'type' => 'select',
'options' => array(
'1' => esc_html__( 'OSM - mapnik', 'commonsbooking' ),
- '2' => esc_html__( 'OSM - german style', 'commonsbooking' )
+ '2' => esc_html__( 'OSM - german style', 'commonsbooking' ),
/*
* Reenable the map styles if neede
'3' => esc_html__( 'OSM - hike and bike', 'commonsbooking' ),
@@ -118,12 +116,12 @@ public static function getCustomFields(): array {
'id' => 'enable_map_data_export',
'type' => 'checkbox',
),
- //Begin group Zoom
+ // Begin group Zoom
array(
'name' => esc_html__( 'Zoom', 'commonsbooking' ),
'type' => 'title',
'id' => 'zoom_info',
- 'classes' => 'map-organizer'
+ 'classes' => 'map-organizer',
),
array(
'name' => esc_html__( 'min. zoom level', 'commonsbooking' ),
@@ -136,7 +134,7 @@ public static function getCustomFields(): array {
'pattern' => '\d*',
'min' => '1',
'max' => '19',
- )
+ ),
),
array(
'name' => esc_html__( 'max. zoom level', 'commonsbooking' ),
@@ -149,7 +147,7 @@ public static function getCustomFields(): array {
'pattern' => '\d*',
'min' => '1',
'max' => '19',
- )
+ ),
),
array(
'name' => esc_html__( 'start zoom level', 'commonsbooking' ),
@@ -162,7 +160,7 @@ public static function getCustomFields(): array {
'pattern' => '\d*',
'min' => '1',
'max' => '19',
- )
+ ),
),
array(
'name' => esc_html__( 'enable scroll wheel zoom', 'commonsbooking' ),
@@ -171,13 +169,13 @@ public static function getCustomFields(): array {
'type' => 'checkbox',
'default_cb' => 'commonsbooking_cmb2_set_checkbox_default_for_new_post',
),
- //End group Zoom
- //Begin group Positioning
+ // End group Zoom
+ // Begin group Positioning
array(
'name' => esc_html__( 'Positioning', 'commonsbooking' ),
'type' => 'title',
'id' => 'positioning_info',
- 'classes' => 'map-organizer'
+ 'classes' => 'map-organizer',
),
array(
'name' => esc_html__( 'start latitude', 'commonsbooking' ),
@@ -207,13 +205,13 @@ public static function getCustomFields(): array {
'type' => 'checkbox',
'default_cb' => 'commonsbooking_cmb2_set_checkbox_default_for_new_post',
),
- //End group Positioning
- //Begin group Tooltip
+ // End group Positioning
+ // Begin group Tooltip
array(
'name' => esc_html__( 'Marker Tooltip', 'commonsbooking' ),
'type' => 'title',
'id' => 'marker_tooltip_info',
- 'classes' => 'map-organizer'
+ 'classes' => 'map-organizer',
),
array(
'name' => esc_html__( 'Show marker tooltip permanently', 'commonsbooking' ),
@@ -221,19 +219,19 @@ public static function getCustomFields(): array {
'id' => 'marker_tooltip_permanent',
'type' => 'checkbox',
),
- //End group Tooltip
- //Begin group popup
+ // End group Tooltip
+ // Begin group popup
array(
'name' => esc_html__( 'Marker Popup', 'commonsbooking' ),
'type' => 'title',
'id' => 'marker_popup_info',
- 'classes' => 'map-organizer'
+ 'classes' => 'map-organizer',
),
array(
'name' => esc_html__( 'show item availability', 'commonsbooking' ),
'desc' => esc_html__( 'activate to show the item availability in the marker popup', 'commonsbooking' ),
'id' => 'show_item_availability',
- 'type' => 'checkbox'
+ 'type' => 'checkbox',
),
array(
'name' => esc_html__( 'Max. available days in popup', 'commonsbooking' ),
@@ -245,7 +243,7 @@ public static function getCustomFields(): array {
'type' => 'number',
'pattern' => '\d*',
'min' => '1',
- )
+ ),
),
array(
'name' => esc_html__( 'Maximum days to choose in map availabilty filter ', 'commonsbooking' ),
@@ -256,15 +254,15 @@ public static function getCustomFields(): array {
'attributes' => array(
'type' => 'number',
'pattern' => '\d*',
- )
+ ),
),
- //End group popup
- //Begin group custom marker
+ // End group popup
+ // Begin group custom marker
array(
'name' => esc_html__( 'Custom Marker', 'commonsbooking' ),
'type' => 'title',
'id' => 'custom_marker_info',
- 'classes' => 'map-organizer'
+ 'classes' => 'map-organizer',
),
array(
'name' => esc_html__( 'image file', 'commonsbooking' ),
@@ -322,13 +320,13 @@ public static function getCustomFields(): array {
'pattern' => '\d*',
),
),
- //End group custom marker
- //Begin group cluster
+ // End group custom marker
+ // Begin group cluster
array(
'name' => esc_html__( 'Cluster', 'commonsbooking' ),
'type' => 'title',
'id' => 'cluster_info',
- 'classes' => 'map-organizer'
+ 'classes' => 'map-organizer',
),
array(
'name' => esc_html__( 'max. cluster radius', 'commonsbooking' ),
@@ -340,7 +338,7 @@ public static function getCustomFields(): array {
'type' => 'number',
'pattern' => '\d*',
'min' => 0,
- 'max' => 1000
+ 'max' => 1000,
),
),
array(
@@ -379,13 +377,13 @@ public static function getCustomFields(): array {
'min' => '1',
),
),
- //End group cluster
- //Begin group Appearance
+ // End group cluster
+ // Begin group Appearance
array(
'name' => esc_html__( 'Appearance by Item Status', 'commonsbooking' ),
'type' => 'title',
'id' => 'item_status_appearance_info',
- 'classes' => 'map-organizer'
+ 'classes' => 'map-organizer',
),
array(
'name' => esc_html__( 'appearance', 'commonsbooking' ),
@@ -455,13 +453,13 @@ public static function getCustomFields(): array {
'pattern' => '\d*',
),
),
- //End group Appearance
- //Begin group Filters
+ // End group Appearance
+ // Begin group Filters
array(
'name' => esc_html__( 'Filter for Users', 'commonsbooking' ),
'type' => 'title',
'id' => 'filter_info',
- 'classes' => 'map-organizer'
+ 'classes' => 'map-organizer',
),
array(
'name' => esc_html__( 'show location distance filter', 'commonsbooking' ),
@@ -476,7 +474,7 @@ public static function getCustomFields(): array {
'type' => 'text',
'attributes' => array(
'placeholder' => esc_html__( 'distance', 'commonsbooking' ),
- )
+ ),
),
array(
'name' => esc_html__( 'address search bounds - left bottom', 'commonsbooking' ) . ' ' . esc_html__( 'longitude', 'commonsbooking' ),
@@ -515,7 +513,7 @@ public static function getCustomFields(): array {
'type' => 'text',
'attributes' => array(
'placeholder' => esc_html__( 'availability', 'commonsbooking' ),
- )
+ ),
),
array(
'name' => esc_html__( 'label for item category filter', 'commonsbooking' ),
@@ -524,7 +522,7 @@ public static function getCustomFields(): array {
'type' => 'text',
'attributes' => array(
'placeholder' => esc_html__( 'categories', 'commonsbooking' ),
- )
+ ),
),
array(
'name' => esc_html__( 'custom text for filter button', 'commonsbooking' ),
@@ -533,7 +531,7 @@ public static function getCustomFields(): array {
'type' => 'text',
'attributes' => array(
'placeholder' => esc_html__( 'filter', 'commonsbooking' ),
- )
+ ),
),
array(
'name' => commonsbooking_sanitizeHTML( __( 'Filter groups', 'commonsbooking' ) ),
@@ -565,9 +563,9 @@ public static function getCustomFields(): array {
'postmeta' => commonsbooking_sanitizeHTML( __( 'Post-meta', 'commonsbooking' ) ),
),
'default' => 'taxonomy',
- //TODO: disabled until postmeta is implemented
+ // TODO: disabled until postmeta is implemented
'attributes' => array(
- 'disabled' => true
+ 'disabled' => true,
),
),
array(
@@ -586,9 +584,9 @@ public static function getCustomFields(): array {
),
),
),
- //TODO: Add available categories & filtergroups
- //End group Filters
- //Begin group Presets
+ // TODO: Add available categories & filtergroups
+ // End group Filters
+ // Begin group Presets
array(
'name' => esc_html__( 'Filter Item Presets', 'commonsbooking' ),
'desc' => esc_html__( 'select the categories that are used to prefilter the items that are shown on the map - none for all items', 'commonsbooking' ),
@@ -605,7 +603,7 @@ public static function getCustomFields(): array {
'options' => CustomPostType::sanitizeOptions( Location::getTerms() ),
'select_all_button' => false,
),
- //End group Presets
+ // End group Presets
);
}
@@ -669,17 +667,15 @@ public function getArgs() {
/**
* Renders the shortcode for the map
- *
*/
public static function getShortcode( array $field_args, CMB2_Field $field ) {
$id = get_the_ID();
?>
Shortcode:
- [cb_map id=]
-
+ [cb_map id=]
+
listColumns = [
@@ -54,12 +54,10 @@ public function __construct() {
\CommonsBooking\Model\Restriction::META_ITEM_ID => esc_html__( 'Item', 'commonsbooking' ),
\CommonsBooking\Model\Restriction::META_LOCATION_ID => esc_html__( 'Location', 'commonsbooking' ),
\CommonsBooking\Model\Restriction::META_START => esc_html__( 'Start Date', 'commonsbooking' ),
- \CommonsBooking\Model\Restriction::META_END => esc_html__( 'End Date', 'commonsbooking' ),
+ \CommonsBooking\Model\Restriction::META_END => esc_html__( 'End Date', 'commonsbooking' ),
\CommonsBooking\Model\Restriction::META_STATE => esc_html__( 'Restriction Status', 'commonsbooking' ),
];
-
-
// List settings
$this->removeListDateColumn();
}
@@ -87,7 +85,7 @@ public static function addAdminItemFilter() {
'post_status' => 'any',
'orderby' => 'post_title',
'order' => 'asc',
- 'nopaging' => true
+ 'nopaging' => true,
]
);
if ( $items ) {
@@ -97,7 +95,7 @@ public static function addAdminItemFilter() {
}
Filter::renderFilter(
- static::$postType,
+ static::$postType,
esc_html__( 'Filter By Item ', 'commonsbooking' ),
'filter_item',
$values
@@ -114,7 +112,7 @@ public static function addAdminLocationFilter() {
'post_status' => 'any',
'orderby' => 'post_title',
'order' => 'asc',
- 'nopaging' => true
+ 'nopaging' => true,
]
);
if ( $locations ) {
@@ -133,7 +131,7 @@ public static function addAdminLocationFilter() {
}
/**
- * Adds filter dropdown // filter by status in restrictions list
+ * Adds filter dropdown // filter by status in restrictions list
*/
public static function addAdminStatusFilter() {
Filter::renderFilter(
@@ -158,16 +156,16 @@ public function setCustomColumnsData( $column, $post_id ) {
case \CommonsBooking\Model\Restriction::META_ITEM_ID:
if ( $post = get_post( $value ) ) {
if ( get_post_type( $post ) == Location::getPostType() || get_post_type(
- $post
- ) == Item::getPostType() ) {
- echo commonsbooking_sanitizeHTML($post->post_title);
+ $post
+ ) == Item::getPostType() ) {
+ echo commonsbooking_sanitizeHTML( $post->post_title );
break;
}
}
echo '-';
break;
case \CommonsBooking\Model\Restriction::META_TYPE:
- $output = "-";
+ $output = '-';
foreach ( $this->getCustomFields() as $customField ) {
if ( $customField['id'] == \CommonsBooking\Model\Restriction::META_TYPE ) {
@@ -178,10 +176,10 @@ public function setCustomColumnsData( $column, $post_id ) {
}
}
}
- echo commonsbooking_sanitizeHTML($output);
+ echo commonsbooking_sanitizeHTML( $output );
break;
case \CommonsBooking\Model\Restriction::META_STATE:
- $output = "-";
+ $output = '-';
foreach ( $this->getCustomFields() as $customField ) {
if ( $customField['id'] == \CommonsBooking\Model\Restriction::META_STATE ) {
@@ -192,14 +190,14 @@ public function setCustomColumnsData( $column, $post_id ) {
}
}
}
- echo commonsbooking_sanitizeHTML($output);
+ echo commonsbooking_sanitizeHTML( $output );
break;
case \CommonsBooking\Model\Restriction::META_START:
case \CommonsBooking\Model\Restriction::META_END:
echo date( 'd.m.Y H:i', $value );
break;
default:
- echo commonsbooking_sanitizeHTML($value);
+ echo commonsbooking_sanitizeHTML( $value );
break;
}
} else {
@@ -214,13 +212,13 @@ public function setCustomColumnsData( $column, $post_id ) {
get_post_meta( $post_id, \CommonsBooking\Model\Restriction::META_TYPE, true ) == Timeframe::BOOKING_ID
)
) {
- echo commonsbooking_sanitizeHTML($post->{$column});
+ echo commonsbooking_sanitizeHTML( $post->{$column} );
}
}
}
/**
- * Filters admin list by type, timerange, user
+ * Filters admin list by type, timerange, user
*
* @param \WP_Query $query for admin list objects
*
@@ -231,7 +229,7 @@ public static function filterAdminList( $query ) {
if (
is_admin() && $query->is_main_query() &&
- isset( $_GET['post_type'] ) && static::$postType == sanitize_text_field( $_GET['post_type'] ) &&
+ isset( $_GET['post_type'] ) && static::$postType == sanitize_text_field( $_GET['post_type'] ) &&
$pagenow == 'edit.php'
) {
// Meta value filtering
@@ -240,14 +238,14 @@ public static function filterAdminList( $query ) {
);
$meta_filters = [
\CommonsBooking\Model\Restriction::META_TYPE => 'admin_filter_type',
- \CommonsBooking\Model\Restriction::META_STATE => 'admin_filter_state',
+ \CommonsBooking\Model\Restriction::META_STATE => 'admin_filter_state',
\CommonsBooking\Model\Restriction::META_ITEM_ID => 'admin_filter_item',
\CommonsBooking\Model\Restriction::META_LOCATION_ID => 'admin_filter_location',
];
foreach ( $meta_filters as $key => $filter ) {
if (
- isset( $_GET[ $filter ] ) &&
+ isset( $_GET[ $filter ] ) &&
$_GET[ $filter ] != ''
) {
$query->query_vars['meta_query'][] = array(
@@ -257,7 +255,6 @@ public static function filterAdminList( $query ) {
}
}
-
// Post field filtering
$post_filters = [
'post_status' => 'admin_filter_post_status',
@@ -274,25 +271,31 @@ public static function filterAdminList( $query ) {
// Check if current user is allowed to see posts
if ( ! commonsbooking_isCurrentUserAdmin() ) {
$locations = \CommonsBooking\Repository\Location::getByCurrentUser();
- array_walk( $locations, function ( &$item, $key ) {
- $item = $item->ID;
- } );
+ array_walk(
+ $locations,
+ function ( &$item, $key ) {
+ $item = $item->ID;
+ }
+ );
$items = \CommonsBooking\Repository\Item::getByCurrentUser();
- array_walk( $items, function ( &$item, $key ) {
- $item = $item->ID;
- } );
+ array_walk(
+ $items,
+ function ( &$item, $key ) {
+ $item = $item->ID;
+ }
+ );
$query->query_vars['meta_query'][] = array(
'relation' => 'OR',
array(
'key' => \CommonsBooking\Model\Restriction::META_LOCATION_ID,
'value' => $locations,
- 'compare' => 'IN'
+ 'compare' => 'IN',
),
array(
'key' => \CommonsBooking\Model\Restriction::META_ITEM_ID,
'value' => $items,
- 'compare' => 'IN'
+ 'compare' => 'IN',
),
);
}
@@ -376,7 +379,7 @@ public function getArgs() {
// dieser Wert wird später in der URL stehen
'rewrite' => array( 'slug' => self::getPostType() ),
- 'show_in_rest' => true
+ 'show_in_rest' => true,
);
}
@@ -386,7 +389,7 @@ public function getArgs() {
public function registerMetabox() {
$cmb = new_cmb2_box(
[
- 'id' => static::getPostType() . "-custom-fields",
+ 'id' => static::getPostType() . '-custom-fields',
'title' => esc_html__( 'Restriction', 'commonsbooking' ),
'object_types' => array( static::getPostType() ),
]
@@ -399,48 +402,54 @@ public function registerMetabox() {
/**
* Returns custom (meta) fields for Costum Post Type Timeframe.
+ *
* @return array
*/
protected function getCustomFields(): array {
// We need static types, because german month names dont't work for datepicker
- $dateFormat = "d/m/Y";
+ $dateFormat = 'd/m/Y';
if ( strpos( get_locale(), 'de_' ) !== false ) {
- $dateFormat = "d.m.Y";
+ $dateFormat = 'd.m.Y';
}
if ( strpos( get_locale(), 'en_' ) !== false ) {
- $dateFormat = "m/d/Y";
+ $dateFormat = 'm/d/Y';
}
return array(
array(
'name' => esc_html__( 'Type', 'commonsbooking' ),
- 'desc' => commonsbooking_sanitizeHTML( __( 'Select the type of restriction.
+ 'desc' => commonsbooking_sanitizeHTML(
+ __(
+ 'Select the type of restriction.
Select Notice, the item can still be used and if e.g. only one part is missing or defective.
Select total breakdown if the defect means that the item can no longer be used. If you select total breakdown
all affected bookings will be automatically canceled after activating this restriction and after clicking send the information email.
- ', 'commonsbooking' ) ),
+ ',
+ 'commonsbooking'
+ )
+ ),
'id' => \CommonsBooking\Model\Restriction::META_TYPE,
'type' => 'select',
'options' => self::getTypes(),
),
array(
- 'name' => esc_html__( "Location", 'commonsbooking' ),
+ 'name' => esc_html__( 'Location', 'commonsbooking' ),
'id' => \CommonsBooking\Model\Restriction::META_LOCATION_ID,
'type' => 'select',
'options' => self::sanitizeOptions( \CommonsBooking\Repository\Location::getByCurrentUser() ),
),
array(
- 'name' => esc_html__( "Item", 'commonsbooking' ),
+ 'name' => esc_html__( 'Item', 'commonsbooking' ),
'id' => \CommonsBooking\Model\Restriction::META_ITEM_ID,
'type' => 'select',
'options' => self::sanitizeOptions( \CommonsBooking\Repository\Item::getByCurrentUser() ),
),
array(
- 'name' => esc_html__( "Hint", 'commonsbooking' ),
+ 'name' => esc_html__( 'Hint', 'commonsbooking' ),
'id' => \CommonsBooking\Model\Restriction::META_HINT,
'desc' => commonsbooking_sanitizeHTML( __( 'Please enter here a short information about the reason and possible effects of the usage restriction. The explanation will be displayed on the article page and in the notification e-mail.', 'commonsbooking' ) ),
- 'type' => 'textarea'
+ 'type' => 'textarea',
),
array(
'name' => esc_html__( 'Start date', 'commonsbooking' ),
@@ -466,17 +475,22 @@ protected function getCustomFields(): array {
array(
'type' => 'hidden',
'id' => 'restriction-prevent_delete_meta_movetotrash',
- 'default' => wp_create_nonce( plugin_basename( __FILE__ ) )
+ 'default' => wp_create_nonce( plugin_basename( __FILE__ ) ),
),
array(
- 'name' => esc_html__( "Status", 'commonsbooking' ),
+ 'name' => esc_html__( 'Status', 'commonsbooking' ),
'id' => \CommonsBooking\Model\Restriction::META_STATE,
- 'desc' => commonsbooking_sanitizeHTML( __( 'Choose status of this restriction.
+ 'desc' => commonsbooking_sanitizeHTML(
+ __(
+ 'Choose status of this restriction.
Set to None if you want to deactivate the restriction.
Set to Active if the restriction is active.
Set to Problem Solved, if the restriction is no longer in effect.
Depending on the selected status, affected users will receive corresponding notification emails.
-Select the desired status and then click the "Send" button to send the e-mail. ', 'commonsbooking' ) ),
+Select the desired status and then click the "Send" button to send the e-mail. ',
+ 'commonsbooking'
+ )
+ ),
'type' => 'select',
'show_option_none' => false,
'options' => self::getStates(),
@@ -491,7 +505,7 @@ protected function getCustomFields(): array {
array(
'id' => \CommonsBooking\Model\Restriction::META_SENT,
'type' => 'hidden',
- )
+ ),
);
}
@@ -538,5 +552,4 @@ public function savePost( $post_id, $post ) {
}
}
}
-
}
diff --git a/src/Wordpress/CustomPostType/Timeframe.php b/src/Wordpress/CustomPostType/Timeframe.php
index caaae53f3..5dfe079d1 100644
--- a/src/Wordpress/CustomPostType/Timeframe.php
+++ b/src/Wordpress/CustomPostType/Timeframe.php
@@ -66,12 +66,14 @@ class Timeframe extends CustomPostType {
/**
* CPT type.
+ *
* @var string
*/
public static $postType = 'cb_timeframe';
/**
* Timeframetypes which cannot be "overbooked".
+ *
* @var int[]
*/
public static $multiDayBlockingFrames = [
@@ -80,6 +82,7 @@ class Timeframe extends CustomPostType {
];
/**
* Position in backend menu.
+ *
* @var int
*/
protected $menuPosition = 1;
@@ -93,6 +96,7 @@ public function __construct() {
/**
* Backend listing columns.
+ *
* @var string[]
*/
$this->listColumns = [
@@ -105,7 +109,6 @@ public function __construct() {
\CommonsBooking\Model\Timeframe::META_TIMEFRAME_ADVANCE_BOOKING_DAYS => esc_html__( 'Max. Booking Duration', 'commonsbooking' ),
];
-
// List settings
$this->removeListDateColumn();
}
@@ -121,18 +124,18 @@ public static function getTypes( bool $includeAll = false ): array {
$typeOptions = [];
if ( $includeAll ) {
$typeOptions += [
- 'all' => esc_html__( 'All timeframe types', 'commonsbooking' )
+ 'all' => esc_html__( 'All timeframe types', 'commonsbooking' ),
];
}
$typeOptions += [
// Opening Hours disabled as its not implemented yet
- //self::OPENING_HOURS_ID => esc_html__("Opening Hours", 'commonsbooking'),
- self::BOOKABLE_ID => esc_html__( "Bookable", 'commonsbooking' ),
- self::HOLIDAYS_ID => esc_html__( "Holidays or location closed", 'commonsbooking' ),
+ // self::OPENING_HOURS_ID => esc_html__("Opening Hours", 'commonsbooking'),
+ self::BOOKABLE_ID => esc_html__( 'Bookable', 'commonsbooking' ),
+ self::HOLIDAYS_ID => esc_html__( 'Holidays or location closed', 'commonsbooking' ),
// Off Holidays disabled as its not implemented yet
- //self::OFF_HOLIDAYS_ID => esc_html__("Official Holiday", 'commonsbooking'),
- self::REPAIR_ID => esc_html__( "Blocked (not overbookable)", 'commonsbooking' ),
- self::BOOKING_ID => esc_html__( "Booking", 'commonsbooking' ),
+ // self::OFF_HOLIDAYS_ID => esc_html__("Official Holiday", 'commonsbooking'),
+ self::REPAIR_ID => esc_html__( 'Blocked (not overbookable)', 'commonsbooking' ),
+ self::BOOKING_ID => esc_html__( 'Booking', 'commonsbooking' ),
];
return $typeOptions;
@@ -140,8 +143,8 @@ public static function getTypes( bool $includeAll = false ): array {
public static function getSimilarPostTypes() {
return [
- Timeframe::$postType,
- Booking::$postType
+ self::$postType,
+ Booking::$postType,
];
}
@@ -158,7 +161,7 @@ public static function renderBookingCodeList( $field_args, $field ) {
public static function renderDateSelector( $field_args, $field ) {
?>
@@ -227,14 +230,15 @@ public static function isOverBookable( WP_Post $timeframe ) {
/**
* Returns view-class.
+ *
* @return null
*/
public static function getView() {
// @TODO implement view.
}
-
- /**
+
+ /**
* Adds filter dropdown // filter by type (eg. bookable, repair etc.) in timeframe List
*
* @return void
@@ -244,7 +248,7 @@ public static function addAdminTypeFilter() {
static::$postType,
esc_html__( 'Filter By Type ', 'commonsbooking' ),
'filter_type',
- static::getTypesforSelectField(),
+ static::getTypesforSelectField(),
);
}
@@ -257,7 +261,7 @@ public static function addAdminItemFilter() {
'post_status' => 'any',
'orderby' => 'post_title',
'order' => 'asc',
- 'nopaging' => true
+ 'nopaging' => true,
]
);
if ( $items ) {
@@ -284,7 +288,7 @@ public static function addAdminLocationFilter() {
'post_status' => 'any',
'orderby' => 'post_title',
'order' => 'asc',
- 'nopaging' => true
+ 'nopaging' => true,
]
);
if ( $locations ) {
@@ -304,7 +308,6 @@ public static function addAdminLocationFilter() {
/**
* Adds filter dropdown // filter by location in booking list
- *
*/
public static function addAdminStatusFilter() {
$values = [];
@@ -374,7 +377,7 @@ public static function filterAdminList( $query ) {
}
}
- //post status filtering
+ // post status filtering
$post_filters = [
'post_status' => 'admin_filter_post_status',
@@ -387,7 +390,7 @@ public static function filterAdminList( $query ) {
$query->query_vars[ $key ] = sanitize_text_field( $_GET[ $filter ] );
}
}
-
+
// Timerange filtering
// Start date
if (
@@ -397,7 +400,7 @@ public static function filterAdminList( $query ) {
$query->query_vars['meta_query'][] = array(
'key' => \CommonsBooking\Model\Timeframe::REPETITION_START,
'value' => strtotime( sanitize_text_field( $_GET['admin_filter_startdate'] ) ),
- 'compare' => ">=",
+ 'compare' => '>=',
);
}
@@ -409,32 +412,38 @@ public static function filterAdminList( $query ) {
$query->query_vars['meta_query'][] = array(
'key' => \CommonsBooking\Model\Timeframe::REPETITION_END,
'value' => strtotime( sanitize_text_field( $_GET['admin_filter_enddate'] ) ),
- 'compare' => "<=",
+ 'compare' => '<=',
);
}
// Check if current user is allowed to see posts
if ( ! commonsbooking_isCurrentUserAdmin() ) {
$locations = \CommonsBooking\Repository\Location::getByCurrentUser();
- array_walk( $locations, function ( &$item, $key ) {
- $item = $item->ID;
- } );
+ array_walk(
+ $locations,
+ function ( &$item, $key ) {
+ $item = $item->ID;
+ }
+ );
$items = \CommonsBooking\Repository\Item::getByCurrentUser();
- array_walk( $items, function ( &$item, $key ) {
- $item = $item->ID;
- } );
+ array_walk(
+ $items,
+ function ( &$item, $key ) {
+ $item = $item->ID;
+ }
+ );
$query->query_vars['meta_query'][] = array(
'relation' => 'OR',
array(
'key' => \CommonsBooking\Model\Timeframe::META_LOCATION_ID,
'value' => $locations,
- 'compare' => 'IN'
+ 'compare' => 'IN',
),
array(
'key' => \CommonsBooking\Model\Timeframe::META_ITEM_ID,
'value' => $items,
- 'compare' => 'IN'
+ 'compare' => 'IN',
),
);
}
@@ -447,13 +456,12 @@ public static function filterAdminList( $query ) {
public function registerMetabox() {
$cmb = new_cmb2_box(
[
- 'id' => static::getPostType() . "-custom-fields",
+ 'id' => static::getPostType() . '-custom-fields',
'title' => esc_html__( 'Timeframe', 'commonsbooking' ),
'object_types' => array( static::getPostType() ),
]
);
-
foreach ( $this->getCustomFields() as $customField ) {
$cmb->add_field( $customField );
}
@@ -461,31 +469,32 @@ public function registerMetabox() {
/**
* Returns custom (meta) fields for Costum Post Type Timeframe.
+ *
* @return array
*/
protected function getCustomFields() {
// We need static types, because german month names dont't work for datepicker
- $dateFormat = "d/m/Y";
+ $dateFormat = 'd/m/Y';
if ( strpos( get_locale(), 'de_' ) !== false ) {
- $dateFormat = "d.m.Y";
+ $dateFormat = 'd.m.Y';
}
if ( strpos( get_locale(), 'en_' ) !== false ) {
- $dateFormat = "m/d/Y";
+ $dateFormat = 'm/d/Y';
}
return array(
array(
- 'name' => esc_html__( "Comment", 'commonsbooking' ),
+ 'name' => esc_html__( 'Comment', 'commonsbooking' ),
'desc' => esc_html__( 'This comment is internal for timeframes like bookable, repair, holiday. If timeframe is a booking this comment can be set by users during the booking confirmation process.', 'commonsbooking' ),
- 'id' => "comment",
+ 'id' => 'comment',
'type' => 'textarea_small',
'default_cb' => 'commonsbooking_filter_from_cmb2',
),
array(
'name' => esc_html__( 'Type', 'commonsbooking' ),
'desc' => esc_html__( 'Select Type of this timeframe: Bookable or Location Closed. See Documentation for detailed information.', 'commonsbooking' ),
- 'id' => "type",
+ 'id' => 'type',
'type' => 'select',
'options' => self::getTypesforSelectField(),
'default_cb' => 'commonsbooking_filter_from_cmb2',
@@ -499,7 +508,7 @@ protected function getCustomFields() {
'default_cb' => 'commonsbooking_filter_from_cmb2',
),
array(
- 'name' => esc_html__( "Location Category Selection", 'commonsbooking' ),
+ 'name' => esc_html__( 'Location Category Selection', 'commonsbooking' ),
'id' => \CommonsBooking\Model\Timeframe::META_LOCATION_CATEGORY_IDS,
'type' => 'multicheck',
'options' => self::sanitizeOptions( \CommonsBooking\Repository\Location::getTerms() ),
@@ -507,7 +516,7 @@ protected function getCustomFields() {
'default_cb' => 'commonsbooking_filter_from_cmb2',
),
array(
- 'name' => esc_html__( "Location Selection", 'commonsbooking' ),
+ 'name' => esc_html__( 'Location Selection', 'commonsbooking' ),
'id' => \CommonsBooking\Model\Timeframe::META_LOCATION_ID,
'type' => 'select',
'show_option_none' => esc_html__( 'Please select', 'commonsbooking' ),
@@ -515,7 +524,7 @@ protected function getCustomFields() {
'default_cb' => 'commonsbooking_filter_from_cmb2',
),
array(
- 'name' => esc_html__( "Select one or more locations", 'commonsbooking' ),
+ 'name' => esc_html__( 'Select one or more locations', 'commonsbooking' ),
'id' => \CommonsBooking\Model\Timeframe::META_LOCATION_ID_LIST,
'type' => 'multicheck',
'options' => self::sanitizeOptions( \CommonsBooking\Repository\Location::getByCurrentUser() ),
@@ -530,14 +539,14 @@ protected function getCustomFields() {
'default_cb' => 'commonsbooking_filter_from_cmb2',
),
array(
- 'name' => esc_html__( "Select one or more items", 'commonsbooking' ),
+ 'name' => esc_html__( 'Select one or more items', 'commonsbooking' ),
'id' => \CommonsBooking\Model\Timeframe::META_ITEM_ID_LIST,
'type' => 'multicheck',
'options' => self::sanitizeOptions( \CommonsBooking\Repository\Item::getByCurrentUser() ),
'default_cb' => 'commonsbooking_filter_from_cmb2',
),
array(
- 'name' => esc_html__( "Item Category Selection", 'commonsbooking' ),
+ 'name' => esc_html__( 'Item Category Selection', 'commonsbooking' ),
'id' => \CommonsBooking\Model\Timeframe::META_ITEM_CATEGORY_IDS,
'type' => 'multicheck',
'options' => self::sanitizeOptions( \CommonsBooking\Repository\Item::getTerms() ),
@@ -545,7 +554,7 @@ protected function getCustomFields() {
'default_cb' => 'commonsbooking_filter_from_cmb2',
),
array(
- 'name' => esc_html__( "Item selection", 'commonsbooking' ),
+ 'name' => esc_html__( 'Item selection', 'commonsbooking' ),
'id' => \CommonsBooking\Model\Timeframe::META_ITEM_ID,
'type' => 'select',
'show_option_none' => esc_html__( 'Please select', 'commonsbooking' ),
@@ -553,8 +562,8 @@ protected function getCustomFields() {
'default_cb' => 'commonsbooking_filter_from_cmb2',
),
array(
- 'name' => esc_html__( "Configure bookings", 'commonsbooking' ),
- 'id' => "title-bookings-config",
+ 'name' => esc_html__( 'Configure bookings', 'commonsbooking' ),
+ 'id' => 'title-bookings-config',
'type' => 'title',
),
array(
@@ -570,9 +579,9 @@ protected function getCustomFields() {
'default_value' => 3,
'default_cb' => 'commonsbooking_filter_from_cmb2',
),
- array(
+ array(
'name' => esc_html__( 'Lead time:', 'commonsbooking' ),
- 'desc' => commonsbooking_sanitizeHTML(__( 'Enter the number of days that should be blocked for bookings as a booking lead time (calculated from the current day).', 'commonsbooking' ) ),
+ 'desc' => commonsbooking_sanitizeHTML( __( 'Enter the number of days that should be blocked for bookings as a booking lead time (calculated from the current day).', 'commonsbooking' ) ),
'id' => \CommonsBooking\Model\Timeframe::META_BOOKING_START_DAY_OFFSET,
'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
'type' => 'text_small',
@@ -597,9 +606,9 @@ protected function getCustomFields() {
'default_cb' => 'commonsbooking_filter_from_cmb2',
),
array(
- 'name' => esc_html__( "Allowed for", 'commonsbooking' ),
+ 'name' => esc_html__( 'Allowed for', 'commonsbooking' ),
'id' => \CommonsBooking\Model\Timeframe::META_ALLOWED_USER_ROLES,
- 'desc' => commonsbooking_sanitizeHTML(__( ' Select one or more user roles that will be allowed to book the item exclusively. Leave this blank to allow all users to book the item. ', 'commonsbooking' ) ),
+ 'desc' => commonsbooking_sanitizeHTML( __( ' Select one or more user roles that will be allowed to book the item exclusively. Leave this blank to allow all users to book the item. ', 'commonsbooking' ) ),
'type' => 'pw_multiselect',
'options' => self::sanitizeOptions( UserRepository::getUserRoles() ),
'attributes' => array(
@@ -608,31 +617,32 @@ protected function getCustomFields() {
'default_cb' => 'commonsbooking_filter_from_cmb2',
),
array(
- 'name' => esc_html__( "Configure timeframe", 'commonsbooking' ),
- 'id' => "title-timeframe-config",
+ 'name' => esc_html__( 'Configure timeframe', 'commonsbooking' ),
+ 'id' => 'title-timeframe-config',
'type' => 'title',
),
array(
'name' => esc_html__( 'Full day', 'commonsbooking' ),
'desc' => esc_html__(
- 'If this option is selected, users can choose only whole days for pickup and return. No specific time slots for pickup or return are offered. Select this option if the pickup/return should be arranged personally between the location and the user. '
- , 'commonsbooking' ),
- 'id' => "full-day",
+ 'If this option is selected, users can choose only whole days for pickup and return. No specific time slots for pickup or return are offered. Select this option if the pickup/return should be arranged personally between the location and the user. ',
+ 'commonsbooking'
+ ),
+ 'id' => 'full-day',
'type' => 'checkbox',
'default_value' => '',
'default_cb' => 'commonsbooking_filter_from_cmb2',
),
array(
- 'name' => esc_html__( "Grid", 'commonsbooking' ),
+ 'name' => esc_html__( 'Grid', 'commonsbooking' ),
'desc' => commonsbooking_sanitizeHTML( __( 'Choose whether users can only select the entire from/to time period when booking (full slot) or book within the time period in an hourly grid. See the documentation: Manage Booking Timeframes', 'commonsbooking' ) ),
- 'id' => "grid",
+ 'id' => 'grid',
'type' => 'select',
'options' => self::getGridOptions(),
'default_cb' => 'commonsbooking_filter_from_cmb2',
),
array(
- 'name' => esc_html__( "Start time", 'commonsbooking' ),
- 'id' => "start-time",
+ 'name' => esc_html__( 'Start time', 'commonsbooking' ),
+ 'id' => 'start-time',
'type' => 'text_time',
'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value
'attributes' => array(
@@ -643,15 +653,15 @@ protected function getCustomFields() {
)
),
),
- 'time_format' => esc_html(get_option( 'time_format' )),
+ 'time_format' => esc_html( get_option( 'time_format' ) ),
'date_format' => $dateFormat,
'default_cb' => 'commonsbooking_filter_from_cmb2',
),
array(
- 'name' => esc_html__( "End time", 'commonsbooking' ),
- 'id' => "end-time",
+ 'name' => esc_html__( 'End time', 'commonsbooking' ),
+ 'id' => 'end-time',
'type' => 'text_time',
- 'timeFormat' => 'HH:mm',
+ 'timeFormat' => 'HH:mm',
'attributes' => array(
'data-timepicker' => wp_json_encode(
array(
@@ -660,41 +670,43 @@ protected function getCustomFields() {
)
),
),
- 'time_format' => esc_html(get_option( 'time_format' )),
+ 'time_format' => esc_html( get_option( 'time_format' ) ),
'date_format' => $dateFormat,
'default_cb' => 'commonsbooking_filter_from_cmb2',
),
array(
'name' => esc_html__( 'Timeframe Repetition', 'commonsbooking' ),
'desc' => esc_html__(
- 'Choose whether the time frame should repeat at specific intervals. The repetitions refer to the unit of a day. With the start and end date you define when the repetition interval starts and ends. If you choose "weekly", you can select specific days of the week below. Read the documentation for more information and examples.'
- , 'commonsbooking' ),
+ 'Choose whether the time frame should repeat at specific intervals. The repetitions refer to the unit of a day. With the start and end date you define when the repetition interval starts and ends. If you choose "weekly", you can select specific days of the week below. Read the documentation for more information and examples.',
+ 'commonsbooking'
+ ),
'id' => \CommonsBooking\Model\Timeframe::META_REPETITION,
'type' => 'select',
'options' => self::getTimeFrameRepetitions(),
'default_cb' => 'commonsbooking_filter_from_cmb2',
- 'default' => 'w',
+ 'default' => 'w',
),
array(
'name' => esc_html__( 'Import holidays', 'commonsbooking' ),
'desc' => esc_html__(
- 'Select the year and state to import holidays for (as of now only German holidays are supported)'
- , 'commonsbooking' ),
- 'id' => "_cmb2_holiday",
- 'type' => 'holiday_get_fields'
+ 'Select the year and state to import holidays for (as of now only German holidays are supported)',
+ 'commonsbooking'
+ ),
+ 'id' => '_cmb2_holiday',
+ 'type' => 'holiday_get_fields',
),
array(
- 'name' => esc_html__( "Configure repetition", 'commonsbooking' ),
+ 'name' => esc_html__( 'Configure repetition', 'commonsbooking' ),
'desc' => esc_html__( 'Below you can make settings regarding the time frame repetition. ', 'commonsbooking' ),
- 'id' => "title-timeframe-rep-config",
+ 'id' => 'title-timeframe-rep-config',
'type' => 'title',
),
array(
- 'name' => esc_html__( "Selected manual dates", 'commonsbooking' ),
- 'desc' => commonsbooking_sanitizeHTML( __( "Enter the dates in the YYYY-MM-DD format here, the dates are separated by a comma. Example: 2023-05-24,2023-06-24 You can also use the datepicker above to pick dates for this field.", 'commonsbooking' ) ),
+ 'name' => esc_html__( 'Selected manual dates', 'commonsbooking' ),
+ 'desc' => commonsbooking_sanitizeHTML( __( 'Enter the dates in the YYYY-MM-DD format here, the dates are separated by a comma. Example: 2023-05-24,2023-06-24 You can also use the datepicker above to pick dates for this field.', 'commonsbooking' ) ),
'id' => \CommonsBooking\Model\Timeframe::META_MANUAL_SELECTION,
'type' => 'textarea_small',
- 'before_row' => array( self::class, 'renderDateSelector' )
+ 'before_row' => array( self::class, 'renderDateSelector' ),
),
array(
'name' => esc_html__( 'Start date', 'commonsbooking' ),
@@ -707,37 +719,47 @@ protected function getCustomFields() {
),
array(
'name' => esc_html__( 'Weekdays', 'commonsbooking' ),
- 'id' => "weekdays",
+ 'id' => 'weekdays',
'type' => 'multicheck',
'options' => [
- 1 => esc_html__( "Monday", 'commonsbooking' ),
- 2 => esc_html__( "Tuesday", 'commonsbooking' ),
- 3 => esc_html__( "Wednesday", 'commonsbooking' ),
- 4 => esc_html__( "Thursday", 'commonsbooking' ),
- 5 => esc_html__( "Friday", 'commonsbooking' ),
- 6 => esc_html__( "Saturday", 'commonsbooking' ),
- 7 => esc_html__( "Sunday", 'commonsbooking' ),
+ 1 => esc_html__( 'Monday', 'commonsbooking' ),
+ 2 => esc_html__( 'Tuesday', 'commonsbooking' ),
+ 3 => esc_html__( 'Wednesday', 'commonsbooking' ),
+ 4 => esc_html__( 'Thursday', 'commonsbooking' ),
+ 5 => esc_html__( 'Friday', 'commonsbooking' ),
+ 6 => esc_html__( 'Saturday', 'commonsbooking' ),
+ 7 => esc_html__( 'Sunday', 'commonsbooking' ),
],
'default_cb' => 'commonsbooking_filter_from_cmb2',
),
array(
'name' => esc_html__( 'End date', 'commonsbooking' ),
- 'desc' => commonsbooking_sanitizeHTML( __('Set the end date. If you have selected repetition, this is the end date of the interval. Leave blank if you do not want to set an end date.
- Notice: If you want to select only one day (e.g. for holidays or blocked days) set the start and the end date to same day.', 'commonsbooking') ),
+ 'desc' => commonsbooking_sanitizeHTML(
+ __(
+ 'Set the end date. If you have selected repetition, this is the end date of the interval. Leave blank if you do not want to set an end date.
+ Notice: If you want to select only one day (e.g. for holidays or blocked days) set the start and the end date to same day.',
+ 'commonsbooking'
+ )
+ ),
'id' => \CommonsBooking\Model\Timeframe::REPETITION_END,
'type' => 'text_date_timestamp',
- 'time_format' => esc_html(get_option( 'time_format' )),
+ 'time_format' => esc_html( get_option( 'time_format' ) ),
'date_format' => $dateFormat,
'default_cb' => 'commonsbooking_filter_from_cmb2',
),
array(
- 'name' => esc_html__( "Booking Codes", 'commonsbooking' ),
- 'desc' => commonsbooking_sanitizeHTML( __( 'You can automatically generate booking codes. Codes can be generated only with the following settings:
+ 'name' => esc_html__( 'Booking Codes', 'commonsbooking' ),
+ 'desc' => commonsbooking_sanitizeHTML(
+ __(
+ 'You can automatically generate booking codes. Codes can be generated only with the following settings:
- Whole day is enabled
- Timeframe is bookable
More Information in the documentation
- ', 'commonsbooking' ) ),
- 'id' => "title-timeframe-booking-codes",
+ ',
+ 'commonsbooking'
+ )
+ ),
+ 'id' => 'title-timeframe-booking-codes',
'type' => 'title',
),
array(
@@ -758,24 +780,24 @@ protected function getCustomFields() {
'name' => esc_html__( 'Booking Codes', 'commonsbooking' ),
'id' => 'direct-email-booking-codes-list',
'type' => 'title',
- 'render_row_cb' => ['\CommonsBooking\View\BookingCodes','renderDirectEmailRow'],
+ 'render_row_cb' => [ '\CommonsBooking\View\BookingCodes', 'renderDirectEmailRow' ],
),
array(
'name' => esc_html__( 'Send booking codes automated by email', 'commonsbooking' ),
- 'desc_cb' => esc_html__("Enable automated sending of booking codes by email", 'commonsbooking' ),
+ 'desc_cb' => esc_html__( 'Enable automated sending of booking codes by email', 'commonsbooking' ),
'name_start' => esc_html__( 'Start Date', 'commonsbooking' ),
- 'desc_start' => commonsbooking_sanitizeHTML( __('First day to send Codes (List starts at next month) (Same day will be used for subsequent messages) ', 'commonsbooking')) ,
+ 'desc_start' => commonsbooking_sanitizeHTML( __( 'First day to send Codes (List starts at next month) (Same day will be used for subsequent messages) ', 'commonsbooking' ) ),
'date_format_start' => $dateFormat,
- 'default_start' => strtotime("now"),
- 'name_nummonth' => esc_html__( "Months to send", 'commonsbooking' ),
+ 'default_start' => strtotime( 'now' ),
+ 'name_nummonth' => esc_html__( 'Months to send', 'commonsbooking' ),
'desc_nummonth' => esc_html__( "Send booking codes for this amount of month's in one email", 'commonsbooking' ),
- 'default_nummonth' => 1,
- 'msg_next_email' => esc_html__( 'Next email planned for: ', 'commonsbooking' ),
- 'msg_email_not_planned' => esc_html__( '(not planned)', 'commonsbooking' ),
+ 'default_nummonth' => 1,
+ 'msg_next_email' => esc_html__( 'Next email planned for: ', 'commonsbooking' ),
+ 'msg_email_not_planned' => esc_html__( '(not planned)', 'commonsbooking' ),
'id' => \CommonsBooking\View\BookingCodes::CRON_EMAIL_CODES,
'type' => 'booking_codes_email_fields',
- 'sanitization_cb' => ['\CommonsBooking\View\BookingCodes','sanitizeCronEmailCodes'],
- 'escape_cb' => ['\CommonsBooking\View\BookingCodes','escapeCronEmailCodes'],
+ 'sanitization_cb' => [ '\CommonsBooking\View\BookingCodes', 'sanitizeCronEmailCodes' ],
+ 'escape_cb' => [ '\CommonsBooking\View\BookingCodes', 'escapeCronEmailCodes' ],
),
array(
'name' => esc_html__( 'Booking Codes', 'commonsbooking' ),
@@ -787,7 +809,7 @@ protected function getCustomFields() {
array(
'type' => 'hidden',
'id' => 'prevent_delete_meta_movetotrash',
- 'default' => wp_create_nonce( plugin_basename( __FILE__ ) )
+ 'default' => wp_create_nonce( plugin_basename( __FILE__ ) ),
),
);
}
@@ -801,11 +823,11 @@ protected function getCustomFields() {
public static function getTypesforSelectField() {
$types = self::getTypes();
- // remove unused types
+ // remove unused types
unset(
$types[ self::BOOKING_ID ],
$types[ self::BOOKING_CANCELED_ID ],
- //$types[ self::REPAIR_ID ],
+ // $types[ self::REPAIR_ID ],
);
return $types;
@@ -813,39 +835,42 @@ public static function getTypesforSelectField() {
/**
* Returns style of item / location selection
+ *
* @return array
*/
public static function getSelectionOptions() {
return [
- \CommonsBooking\Model\Timeframe::SELECTION_MANUAL_ID => esc_html__( "Manual selection", 'commonsbooking' ),
- \CommonsBooking\Model\Timeframe::SELECTION_CATEGORY_ID => esc_html__( "Select by category", 'commonsbooking' ),
- \CommonsBooking\Model\Timeframe::SELECTION_ALL_ID => esc_html__( "All", 'commonsbooking' ),
+ \CommonsBooking\Model\Timeframe::SELECTION_MANUAL_ID => esc_html__( 'Manual selection', 'commonsbooking' ),
+ \CommonsBooking\Model\Timeframe::SELECTION_CATEGORY_ID => esc_html__( 'Select by category', 'commonsbooking' ),
+ \CommonsBooking\Model\Timeframe::SELECTION_ALL_ID => esc_html__( 'All', 'commonsbooking' ),
];
}
/**
* Returns grid options.
+ *
* @return array
*/
public static function getGridOptions() {
return [
- 0 => esc_html__( "Full slot", 'commonsbooking' ),
- 1 => esc_html__( "Hourly", 'commonsbooking' ),
+ 0 => esc_html__( 'Full slot', 'commonsbooking' ),
+ 1 => esc_html__( 'Hourly', 'commonsbooking' ),
];
}
/**
* Returns array with repetition options.
+ *
* @return array
*/
public static function getTimeFrameRepetitions() {
return [
- 'norep' => esc_html__( "No repetition", 'commonsbooking' ),
- 'manual' => esc_html__( "Manual repetition", 'commonsbooking' ),
- 'd' => esc_html__( "Daily", 'commonsbooking' ),
- 'w' => esc_html__( "Weekly", 'commonsbooking' ),
- 'm' => esc_html__( "Monthly", 'commonsbooking' ),
- 'y' => esc_html__( "Yearly", 'commonsbooking' ),
+ 'norep' => esc_html__( 'No repetition', 'commonsbooking' ),
+ 'manual' => esc_html__( 'Manual repetition', 'commonsbooking' ),
+ 'd' => esc_html__( 'Daily', 'commonsbooking' ),
+ 'w' => esc_html__( 'Weekly', 'commonsbooking' ),
+ 'm' => esc_html__( 'Monthly', 'commonsbooking' ),
+ 'y' => esc_html__( 'Yearly', 'commonsbooking' ),
];
}
@@ -866,7 +891,7 @@ public function savePost( $post_id, WP_Post $post ) {
return;
}
- //assign the startDate and EndDate for manual repetition (needs to be done before validation in order for validation to work)
+ // assign the startDate and EndDate for manual repetition (needs to be done before validation in order for validation to work)
try {
$timeframe = new \CommonsBooking\Model\Timeframe( $post_id );
} catch ( Exception $e ) {
@@ -883,20 +908,19 @@ public function savePost( $post_id, WP_Post $post ) {
$isValid = self::validateTimeFrame( $timeframe );
if ( $isValid ) {
-
self::sanitizeRepetitionEndDate( $post_id );
// Update postmeta related to dynamic selection fields
- Timeframe::manageTimeframeMeta( $post_id );
+ self::manageTimeframeMeta( $post_id );
- //delete unused postmeta
+ // delete unused postmeta
self::removeIrrelevantPostmeta( $timeframe );
if ( $timeframe->usesBookingCodes() && $timeframe->bookingCodesApplicable() ) {
try {
BookingCodes::generate( $timeframe );
} catch ( BookingCodeException $e ) {
- //unset checkboxes if booking codes could not be generated
+ // unset checkboxes if booking codes could not be generated
delete_post_meta( $post_id, \CommonsBooking\Model\Timeframe::META_CREATE_BOOKING_CODES );
delete_post_meta( $post_id, \CommonsBooking\Model\Timeframe::META_SHOW_BOOKING_CODES );
@@ -911,19 +935,18 @@ public function savePost( $post_id, WP_Post $post ) {
}
- public function updatedPostMeta($meta_id,$object_id,$meta_key,$meta_value)
- {
- //make sure, that action is only executed if timeframe is changed
- if (get_post($object_id)->post_type !== Timeframe::getPostType()) {
+ public function updatedPostMeta( $meta_id, $object_id, $meta_key, $meta_value ) {
+ // make sure, that action is only executed if timeframe is changed
+ if ( get_post( $object_id )->post_type !== self::getPostType() ) {
return;
}
- if ($meta_key == \CommonsBooking\Model\Timeframe::META_LOCATION_ID){ //Location ID was changed, the only evidence we still have is the item ID
- $correspondingItems = get_post_meta( $object_id, \CommonsBooking\Model\Timeframe::META_ITEM_ID );
- $item_id = reset( $correspondingItems ); //value has to be reset in order to retrieve first value
- $orphanedBookings = \CommonsBooking\Repository\Booking::getOrphaned(null,[$item_id]);
- if ($orphanedBookings) {
- foreach ($orphanedBookings as $booking) {
- update_post_meta($booking->ID,\CommonsBooking\Model\Booking::META_LAST_TIMEFRAME,$object_id);
+ if ( $meta_key == \CommonsBooking\Model\Timeframe::META_LOCATION_ID ) { // Location ID was changed, the only evidence we still have is the item ID
+ $correspondingItems = get_post_meta( $object_id, \CommonsBooking\Model\Timeframe::META_ITEM_ID );
+ $item_id = reset( $correspondingItems ); // value has to be reset in order to retrieve first value
+ $orphanedBookings = \CommonsBooking\Repository\Booking::getOrphaned( null, [ $item_id ] );
+ if ( $orphanedBookings ) {
+ foreach ( $orphanedBookings as $booking ) {
+ update_post_meta( $booking->ID, \CommonsBooking\Model\Booking::META_LAST_TIMEFRAME, $object_id );
}
set_transient(
\CommonsBooking\Model\Timeframe::ORPHANED_TYPE,
@@ -947,7 +970,7 @@ public function updatedPostMeta($meta_id,$object_id,$meta_key,$meta_value)
*
* @return void
*/
- private static function sanitizeRepetitionEndDate( $postId ) : void {
+ private static function sanitizeRepetitionEndDate( $postId ): void {
$repetitionEnd = get_post_meta( $postId, \CommonsBooking\Model\Timeframe::REPETITION_END, true );
if ( $repetitionEnd ) {
$repetitionEnd = strtotime( '+23 Hours +59 Minutes +59 Seconds', $repetitionEnd );
@@ -965,12 +988,12 @@ private static function sanitizeRepetitionEndDate( $postId ) : void {
protected static function validateTimeFrame( $timeframe ): bool {
try {
$timeframe->isValid();
- }
- catch (TimeframeInvalidException $e){
+ } catch ( TimeframeInvalidException $e ) {
set_transient(
\CommonsBooking\Model\Timeframe::ERROR_TYPE,
- commonsbooking_sanitizeHTML($e->getMessage()),
- 45 );
+ commonsbooking_sanitizeHTML( $e->getMessage() ),
+ 45
+ );
// set post_status to draft if not valid
$post = $timeframe->getPost();
if ( $post->post_status !== 'draft' ) {
@@ -994,8 +1017,8 @@ public static function updateAllTimeframes() {
[],
[],
[
- Timeframe::HOLIDAYS_ID,
- Timeframe::REPAIR_ID
+ self::HOLIDAYS_ID,
+ self::REPAIR_ID,
]
);
foreach ( $timeframes as $timeframe ) {
@@ -1021,73 +1044,83 @@ public static function updateAllTimeframes() {
*
* @return void
*/
- public static function manageTimeframeMeta ( $post_id ) {
- $postModel = get_post($post_id);
+ public static function manageTimeframeMeta( $post_id ) {
+ $postModel = get_post( $post_id );
// This is just for timeframes
if ( $postModel->post_type !== static::getPostType() ) {
return;
}
- $timeframe = new \CommonsBooking\Model\Timeframe( $post_id );
- $itemSelectionType = intval ( $timeframe->getMeta( \CommonsBooking\Model\Timeframe::META_ITEM_SELECTION_TYPE ) );
- $locationSelectionType = intval ( $timeframe->getMeta( \CommonsBooking\Model\Timeframe::META_LOCATION_SELECTION_TYPE ) );
+ $timeframe = new \CommonsBooking\Model\Timeframe( $post_id );
+ $itemSelectionType = intval( $timeframe->getMeta( \CommonsBooking\Model\Timeframe::META_ITEM_SELECTION_TYPE ) );
+ $locationSelectionType = intval( $timeframe->getMeta( \CommonsBooking\Model\Timeframe::META_LOCATION_SELECTION_TYPE ) );
- //we only need to update the timeframes which have the dynamic selection type
+ // we only need to update the timeframes which have the dynamic selection type
if ( $itemSelectionType === \CommonsBooking\Model\Timeframe::SELECTION_MANUAL_ID && $locationSelectionType === \CommonsBooking\Model\Timeframe::SELECTION_MANUAL_ID ) {
return;
}
- if ($itemSelectionType === \CommonsBooking\Model\Timeframe::SELECTION_CATEGORY_ID) {
+ if ( $itemSelectionType === \CommonsBooking\Model\Timeframe::SELECTION_CATEGORY_ID ) {
$itemCategorySelection = $timeframe->getMeta( \CommonsBooking\Model\Timeframe::META_ITEM_CATEGORY_IDS );
- $taxQuery = array (
+ $taxQuery = array(
'tax_query' => array(
array(
- 'taxonomy' => Item::getPostType() . 's_category',
- 'field' => 'term_id',
- 'terms' => $itemCategorySelection
+ 'taxonomy' => Item::getPostType() . 's_category',
+ 'field' => 'term_id',
+ 'terms' => $itemCategorySelection,
),
- )
+ ),
+ );
+ $items = \CommonsBooking\Repository\Item::get( $taxQuery );
+ // for some reason, the item ids need to be saved as strings
+ $itemIds = array_map(
+ function ( $item ) {
+ return strval( $item->ID );
+ },
+ $items
);
- $items = \CommonsBooking\Repository\Item::get( $taxQuery );
- //for some reason, the item ids need to be saved as strings
- $itemIds = array_map( function ( $item ) {
- return strval ($item->ID);
- }, $items );
update_post_meta( $post_id, \CommonsBooking\Model\Timeframe::META_ITEM_ID_LIST, $itemIds );
- }
- else if ($itemSelectionType === \CommonsBooking\Model\Timeframe::SELECTION_ALL_ID) {
+ } elseif ( $itemSelectionType === \CommonsBooking\Model\Timeframe::SELECTION_ALL_ID ) {
$items = \CommonsBooking\Repository\Item::get();
- //for some reason, the item ids need to be saved as strings
- $itemIds = array_map( function ( $item ) {
- return strval ($item->ID);
- }, $items );
+ // for some reason, the item ids need to be saved as strings
+ $itemIds = array_map(
+ function ( $item ) {
+ return strval( $item->ID );
+ },
+ $items
+ );
update_post_meta( $post_id, \CommonsBooking\Model\Timeframe::META_ITEM_ID_LIST, $itemIds );
}
- if ($locationSelectionType === \CommonsBooking\Model\Timeframe::SELECTION_CATEGORY_ID) {
+ if ( $locationSelectionType === \CommonsBooking\Model\Timeframe::SELECTION_CATEGORY_ID ) {
$locationCategorySelection = $timeframe->getMeta( \CommonsBooking\Model\Timeframe::META_LOCATION_CATEGORY_IDS );
- $taxQuery = array (
+ $taxQuery = array(
'tax_query' => array(
array(
- 'taxonomy' => Location::getPostType() . 's_category',
- 'field' => 'term_id',
- 'terms' => $locationCategorySelection
+ 'taxonomy' => Location::getPostType() . 's_category',
+ 'field' => 'term_id',
+ 'terms' => $locationCategorySelection,
),
- )
+ ),
+ );
+ $locations = \CommonsBooking\Repository\Location::get( $taxQuery );
+ // for some reason, the location ids need to be saved as strings
+ $locationIds = array_map(
+ function ( $location ) {
+ return strval( $location->ID );
+ },
+ $locations
);
- $locations = \CommonsBooking\Repository\Location::get( $taxQuery );
- //for some reason, the location ids need to be saved as strings
- $locationIds = array_map( function ( $location ) {
- return strval ($location->ID);
- }, $locations );
update_post_meta( $post_id, \CommonsBooking\Model\Timeframe::META_LOCATION_ID_LIST, $locationIds );
- }
- else if ($locationSelectionType === \CommonsBooking\Model\Timeframe::SELECTION_ALL_ID) {
+ } elseif ( $locationSelectionType === \CommonsBooking\Model\Timeframe::SELECTION_ALL_ID ) {
$locations = \CommonsBooking\Repository\Location::get();
- //for some reason, the location ids need to be saved as strings
- $locationIds = array_map( function ( $location ) {
- return strval ($location->ID);
- }, $locations );
+ // for some reason, the location ids need to be saved as strings
+ $locationIds = array_map(
+ function ( $location ) {
+ return strval( $location->ID );
+ },
+ $locations
+ );
update_post_meta( $post_id, \CommonsBooking\Model\Timeframe::META_LOCATION_ID_LIST, $locationIds );
}
}
@@ -1109,7 +1142,7 @@ public static function removeIrrelevantPostmeta( \CommonsBooking\Model\Timeframe
\CommonsBooking\Model\Timeframe::META_CREATE_BOOKING_CODES,
\CommonsBooking\Model\Timeframe::META_SHOW_BOOKING_CODES,
];
- //remove multi-select postmeta if not relevant (#507)
+ // remove multi-select postmeta if not relevant (#507)
$onlyRelevantForHolidays = [
\CommonsBooking\Model\Timeframe::META_ITEM_ID_LIST,
\CommonsBooking\Model\Timeframe::META_LOCATION_ID_LIST,
@@ -1119,24 +1152,25 @@ public static function removeIrrelevantPostmeta( \CommonsBooking\Model\Timeframe
\CommonsBooking\Model\Timeframe::META_LOCATION_SELECTION_TYPE,
];
- if ($timeframe->getType() != Timeframe::BOOKABLE_ID) {
+ if ( $timeframe->getType() != self::BOOKABLE_ID ) {
foreach ( $onlyRelevantForBookable as $metaKey ) {
delete_post_meta( $timeframe->ID, $metaKey );
}
}
- if ($timeframe->getType() != Timeframe::HOLIDAYS_ID) {
+ if ( $timeframe->getType() != self::HOLIDAYS_ID ) {
foreach ( $onlyRelevantForHolidays as $metaKey ) {
delete_post_meta( $timeframe->ID, $metaKey );
}
- //reset to manual selection
- update_post_meta($timeframe->ID, \CommonsBooking\Model\Timeframe::META_ITEM_SELECTION_TYPE, \CommonsBooking\Model\Timeframe::SELECTION_MANUAL_ID);
- update_post_meta($timeframe->ID, \CommonsBooking\Model\Timeframe::META_LOCATION_SELECTION_TYPE, \CommonsBooking\Model\Timeframe::SELECTION_MANUAL_ID);
+ // reset to manual selection
+ update_post_meta( $timeframe->ID, \CommonsBooking\Model\Timeframe::META_ITEM_SELECTION_TYPE, \CommonsBooking\Model\Timeframe::SELECTION_MANUAL_ID );
+ update_post_meta( $timeframe->ID, \CommonsBooking\Model\Timeframe::META_LOCATION_SELECTION_TYPE, \CommonsBooking\Model\Timeframe::SELECTION_MANUAL_ID );
}
}
/**
* Returns CPT arguments.
+ *
* @return array
*/
public function getArgs() {
@@ -1212,7 +1246,7 @@ public function getArgs() {
// dieser Wert wird später in der URL stehen
'rewrite' => array( 'slug' => self::getPostType() ),
- 'show_in_rest' => true
+ 'show_in_rest' => true,
);
}
@@ -1225,29 +1259,28 @@ public function getArgs() {
public function setCustomColumnsData( $column, $post_id ) {
// we alter the author column data and link the username to the user profile
- if ( $column == "timeframe-author" ) {
+ if ( $column == 'timeframe-author' ) {
$post = get_post( $post_id );
$timeframe_user = get_user_by( 'id', $post->post_author );
echo '' . commonsbooking_sanitizeHTML( $timeframe_user->user_login ) . '';
}
-
if ( $value = get_post_meta( $post_id, $column, true ) ) {
switch ( $column ) {
case 'location-id':
case 'item-id':
if ( $post = get_post( $value ) ) {
if ( get_post_type( $post ) == Location::getPostType() ||
- get_post_type( $post ) == Item::getPostType()
+ get_post_type( $post ) == Item::getPostType()
) {
- echo commonsbooking_sanitizeHTML($post->post_title);
+ echo commonsbooking_sanitizeHTML( $post->post_title );
break;
}
}
echo '-';
break;
case 'type':
- $output = "-";
+ $output = '-';
foreach ( $this->getCustomFields() as $customField ) {
if ( $customField['id'] == 'type' ) {
@@ -1258,14 +1291,14 @@ public function setCustomColumnsData( $column, $post_id ) {
}
}
}
- echo commonsbooking_sanitizeHTML($output);
+ echo commonsbooking_sanitizeHTML( $output );
break;
case \CommonsBooking\Model\Timeframe::REPETITION_START:
case \CommonsBooking\Model\Timeframe::REPETITION_END:
echo date( 'd.m.Y', $value );
break;
default:
- echo commonsbooking_sanitizeHTML($value);
+ echo commonsbooking_sanitizeHTML( $value );
break;
}
} else {
@@ -1277,10 +1310,10 @@ public function setCustomColumnsData( $column, $post_id ) {
if (
property_exists( $post = get_post( $post_id ), $column ) && (
! in_array( $column, $bookingColumns ) ||
- get_post_meta( $post_id, 'type', true ) == Timeframe::BOOKING_ID
+ get_post_meta( $post_id, 'type', true ) == self::BOOKING_ID
)
) {
- echo commonsbooking_sanitizeHTML($post->{$column});
+ echo commonsbooking_sanitizeHTML( $post->{$column} );
}
}
}
@@ -1291,54 +1324,66 @@ public function setCustomColumnsData( $column, $post_id ) {
* @return true|void returns true if inheriting method should set sort order, void if this method sets it
*/
public function setCustomColumnSortOrder( \WP_Query $query ) {
- if (! parent::setCustomColumnSortOrder( $query ) ) {
+ if ( ! parent::setCustomColumnSortOrder( $query ) ) {
return;
}
- switch ($query->get( 'orderby' )) {
+ switch ( $query->get( 'orderby' ) ) {
case 'item-id':
- add_filter('posts_join', function ($join) {
- global $wp_query, $wpdb;
+ add_filter(
+ 'posts_join',
+ function ( $join ) {
+ global $wp_query, $wpdb;
+
+ if ( ! empty( $wp_query->query_vars['orderby'] ) && $wp_query->query_vars['orderby'] === \CommonsBooking\Model\Timeframe::META_ITEM_ID ) {
+ $join .= "LEFT JOIN $wpdb->postmeta joined_meta_items "
+ . "ON $wpdb->posts.ID = joined_meta_items.post_id AND joined_meta_items.meta_key = '" . \CommonsBooking\Model\Timeframe::META_ITEM_ID . "' ";
+ $join .= "JOIN $wpdb->posts joined_items ON joined_meta_items.meta_value = joined_items.ID ";
+ }
- if ( ! empty( $wp_query->query_vars['orderby'] ) && $wp_query->query_vars['orderby'] === \CommonsBooking\Model\Timeframe::META_ITEM_ID ) {
- $join .= "LEFT JOIN $wpdb->postmeta joined_meta_items "
- . "ON $wpdb->posts.ID = joined_meta_items.post_id AND joined_meta_items.meta_key = '" . \CommonsBooking\Model\Timeframe::META_ITEM_ID . "' ";
- $join .= "JOIN $wpdb->posts joined_items ON joined_meta_items.meta_value = joined_items.ID ";
+ return $join;
}
+ );
+ add_filter(
+ 'posts_orderby',
+ function ( $orderby ) {
+ global $wp_query;
- return $join;
- });
- add_filter( 'posts_orderby', function ( $orderby ) {
- global $wp_query;
+ if ( ! empty( $wp_query->query_vars['orderby'] ) && $wp_query->query_vars['orderby'] === \CommonsBooking\Model\Timeframe::META_ITEM_ID ) {
+ $orderby = 'joined_items.post_title ' . $wp_query->query_vars['order'];
+ }
- if ( ! empty( $wp_query->query_vars['orderby'] ) && $wp_query->query_vars['orderby'] === \CommonsBooking\Model\Timeframe::META_ITEM_ID ) {
- $orderby = 'joined_items.post_title ' . $wp_query->query_vars['order'];
+ return $orderby;
}
-
- return $orderby;
- });
+ );
break;
case 'location-id':
- add_filter('posts_join', function ($join) {
- global $wp_query, $wpdb;
+ add_filter(
+ 'posts_join',
+ function ( $join ) {
+ global $wp_query, $wpdb;
+
+ if ( ! empty( $wp_query->query_vars['orderby'] ) && $wp_query->query_vars['orderby'] === \CommonsBooking\Model\Timeframe::META_LOCATION_ID ) {
+ $join .= "LEFT JOIN $wpdb->postmeta joined_meta_locations "
+ . "ON $wpdb->posts.ID = joined_meta_locations.post_id AND joined_meta_locations.meta_key = '" . \CommonsBooking\Model\Timeframe::META_LOCATION_ID . "' ";
+ $join .= "JOIN $wpdb->posts joined_locations ON joined_meta_locations.meta_value = joined_locations.ID ";
+ }
- if ( ! empty( $wp_query->query_vars['orderby'] ) && $wp_query->query_vars['orderby'] === \CommonsBooking\Model\Timeframe::META_LOCATION_ID ) {
- $join .= "LEFT JOIN $wpdb->postmeta joined_meta_locations "
- . "ON $wpdb->posts.ID = joined_meta_locations.post_id AND joined_meta_locations.meta_key = '" . \CommonsBooking\Model\Timeframe::META_LOCATION_ID . "' ";
- $join .= "JOIN $wpdb->posts joined_locations ON joined_meta_locations.meta_value = joined_locations.ID ";
+ return $join;
}
+ );
+ add_filter(
+ 'posts_orderby',
+ function ( $orderby ) {
+ global $wp_query;
- return $join;
- });
- add_filter( 'posts_orderby', function ( $orderby ) {
- global $wp_query;
+ if ( ! empty( $wp_query->query_vars['orderby'] ) && $wp_query->query_vars['orderby'] === \CommonsBooking\Model\Timeframe::META_LOCATION_ID ) {
+ $orderby = 'joined_locations.post_title ' . $wp_query->query_vars['order'];
+ }
- if ( ! empty( $wp_query->query_vars['orderby'] ) && $wp_query->query_vars['orderby'] === \CommonsBooking\Model\Timeframe::META_LOCATION_ID ) {
- $orderby = 'joined_locations.post_title ' . $wp_query->query_vars['order'];
+ return $orderby;
}
-
- return $orderby;
- });
+ );
break;
case 'type':
$query->set( 'meta_key', 'type' );
@@ -1350,7 +1395,7 @@ public function setCustomColumnSortOrder( \WP_Query $query ) {
$query->set( 'orderby', 'meta_value_num' );
break;
default:
- //this means, that further sorting is done by the inheriting method
+ // this means, that further sorting is done by the inheriting method
return true;
}
}
@@ -1363,17 +1408,17 @@ public function setCustomColumnSortOrder( \WP_Query $query ) {
*/
public function initHooks() {
// Add custom cmb2 type for email booking codes by cron
- add_action( 'cmb2_render_booking_codes_email_fields', ['\CommonsBooking\View\BookingCodes','renderCronEmailFields'], 10, 5 );
- add_action("cmb2_save_field_" . \CommonsBooking\View\BookingCodes::CRON_EMAIL_CODES,['\CommonsBooking\View\BookingCodes','cronEmailCodesSaved'],10,3);
-
+ add_action( 'cmb2_render_booking_codes_email_fields', [ '\CommonsBooking\View\BookingCodes','renderCronEmailFields' ], 10, 5 );
+ add_action( 'cmb2_save_field_' . \CommonsBooking\View\BookingCodes::CRON_EMAIL_CODES, [ '\CommonsBooking\View\BookingCodes','cronEmailCodesSaved' ], 10, 3 );
+
// Add Meta Boxes
add_action( 'cmb2_admin_init', array( $this, 'registerMetabox' ) );
// must be 'save_post' only because of priority in relation to cmb2
add_action( 'save_post', array( $this, 'savePost' ), 11, 2 );
- add_action('updated_post_meta',array($this, 'updatedPostMeta'),11,4);
-
+ add_action( 'updated_post_meta', array( $this, 'updatedPostMeta' ), 11, 4 );
+
// Add type filter to backend list view
add_action( 'restrict_manage_posts', array( self::class, 'addAdminTypeFilter' ) );
add_action( 'restrict_manage_posts', array( self::class, 'addAdminItemFilter' ) );
@@ -1384,7 +1429,7 @@ public function initHooks() {
// Listing of available items/locations
add_shortcode( 'cb_items_table', array( Calendar::class, 'shortcode' ) );
- //rendering callback for field with id _cmb2_holiday
- add_filter( 'cmb2_render_holiday_get_fields', array( Holiday::class, 'renderFields'), 10, 5 );
+ // rendering callback for field with id _cmb2_holiday
+ add_filter( 'cmb2_render_holiday_get_fields', array( Holiday::class, 'renderFields' ), 10, 5 );
}
}
diff --git a/src/Wordpress/Options/AdminOptions.php b/src/Wordpress/Options/AdminOptions.php
index 8f22ad01c..e30a1112b 100644
--- a/src/Wordpress/Options/AdminOptions.php
+++ b/src/Wordpress/Options/AdminOptions.php
@@ -20,7 +20,7 @@ class AdminOptions {
*/
public static function setOptionsDefaultValues() {
- $options_array = include( COMMONSBOOKING_PLUGIN_DIR . '/includes/OptionsArray.php' );
+ $options_array = include COMMONSBOOKING_PLUGIN_DIR . '/includes/OptionsArray.php';
$restored_fields = array();
foreach ( $options_array as $tab_id => $tab ) {
@@ -31,7 +31,6 @@ public static function setOptionsDefaultValues() {
$fields = $group['fields'];
foreach ( $fields as $field ) {
-
$field_id = $field['id'];
// set to current value from wp_options
@@ -40,7 +39,7 @@ public static function setOptionsDefaultValues() {
// we check if there is a default value set in OptionsArray.php and if the field type is not checkbox (cause checkboxes have empty values if unchecked )
if ( array_key_exists( 'default', $field ) && $field['type'] != 'checkbox' ) {
// if field-value is not set already we add the default value to the options array
- if ( empty ( $field_value ) ) {
+ if ( empty( $field_value ) ) {
Settings::updateOption( $option_key, $field_id, $field['default'] );
$restored_fields[] = $field['name'];
}
@@ -50,9 +49,9 @@ public static function setOptionsDefaultValues() {
}
// maybe show admin notice if fields are restored to their default value
- if ( ! empty($restored_fields) ) {
- $message = commonsbooking_sanitizeHTML( __( 'Default values for following fields automatically set or restored, because they were empty: ', 'commonsbooking' ) );
- $message .= implode( " ", $restored_fields );
+ if ( ! empty( $restored_fields ) ) {
+ $message = commonsbooking_sanitizeHTML( __( 'Default values for following fields automatically set or restored, because they were empty: ', 'commonsbooking' ) );
+ $message .= implode( ' ', $restored_fields );
new AdminMessage( $message );
}
}
diff --git a/src/Wordpress/Options/OptionsTab.php b/src/Wordpress/Options/OptionsTab.php
index 9cbb78935..b5b9787cb 100644
--- a/src/Wordpress/Options/OptionsTab.php
+++ b/src/Wordpress/Options/OptionsTab.php
@@ -21,9 +21,9 @@ class OptionsTab {
public $groups;
// Error type for backend error output
- public const ERROR_TYPE = "commonsbooking-options-error";
+ public const ERROR_TYPE = 'commonsbooking-options-error';
- public const SUCCESS_TYPE = "commonsbooking-options-success";
+ public const SUCCESS_TYPE = 'commonsbooking-options-success';
/**
* @var \CMB2
*/
@@ -38,7 +38,6 @@ public function __construct( string $id, array $content ) {
add_action( 'cmb2_admin_init', array( $this, 'register' ) );
add_action( 'cmb2_save_options-page_fields', array( self::class, 'savePostOptions' ), 10 );
-
}
public function register() {
@@ -58,16 +57,16 @@ public function registerOptionsTab() {
'option_key' => $this->option_key . '_' . $this->id,
'tab_group' => $this->option_key,
'tab_title' => $this->tab_title,
- 'parent_slug' => $this->option_key
+ 'parent_slug' => $this->option_key,
);
$top_level_args = array(
'option_key' => $this->option_key,
- 'parent_slug' => 'options-general.php'
+ 'parent_slug' => 'options-general.php',
);
/* set first option as top level parent */
- if ( isset ( $this->content['is_top_level'] ) && $this->content['is_top_level'] ) {
+ if ( isset( $this->content['is_top_level'] ) && $this->content['is_top_level'] ) {
$args = array_merge( $default_args, $top_level_args );
} else {
$args = $default_args;
@@ -82,7 +81,6 @@ public function registerOptionsTab() {
public function registerOptionsGroups() {
foreach ( $this->groups as $group ) {
-
$group = $this->prependTitle( $group ); /* prepend title + description html */
// Add Fields
@@ -103,13 +101,14 @@ public function registerOptionsGroups() {
*/
public static function prependTitle( array $metabox_group ): array {
- if ( isset ( $metabox_group['title'] ) or isset ( $metabox_group['desc'] ) ) {
-
+ if ( isset( $metabox_group['title'] ) or isset( $metabox_group['desc'] ) ) {
$title = $metabox_group['title'] ?? '';
$desc = $metabox_group['desc'] ?? '';
$header_html = sprintf(
- '
%s
%s', $title, $desc
+ '
%s
%s',
+ $title,
+ $desc
);
$header_field = array(
@@ -138,14 +137,13 @@ public static function savePostOptions() {
// (CMB2-Hook 'cmb2_save_options-page_field') is too late for rendering of the admin page.
// So if you want to refactor this, savePostOptions needs to be hooked into an action which fires earlier.
- if ( array_key_exists( 'action', $_REQUEST ) && $_REQUEST['action'] == "commonsbooking_options_export" ) {
+ if ( array_key_exists( 'action', $_REQUEST ) && $_REQUEST['action'] == 'commonsbooking_options_export' ) {
// Check for export action
- if ( array_key_exists( 'export-filepath', $_REQUEST ) && $_REQUEST['export-filepath'] !== "" ) {
-
+ if ( array_key_exists( 'export-filepath', $_REQUEST ) && $_REQUEST['export-filepath'] !== '' ) {
if ( ! is_dir( $_REQUEST['export-filepath'] ) ) {
set_transient(
self::ERROR_TYPE,
- commonsbooking_sanitizeHTML( __( "The export path does not exist or is not readable.", 'commonsbooking' ) ),
+ commonsbooking_sanitizeHTML( __( 'The export path does not exist or is not readable.', 'commonsbooking' ) ),
45
);
}
@@ -153,32 +151,34 @@ public static function savePostOptions() {
if ( ! is_writable( $_REQUEST['export-filepath'] ) ) {
set_transient(
self::ERROR_TYPE,
- commonsbooking_sanitizeHTML( __( "The export path is not writeable.", 'commonsbooking' ) ),
- 45 );
+ commonsbooking_sanitizeHTML( __( 'The export path is not writeable.', 'commonsbooking' ) ),
+ 45
+ );
}
}
- } elseif ( array_key_exists( 'action', $_REQUEST ) && $_REQUEST['action'] == "commonsbooking_options_advanced-options" ) {
- //Check for request to clear cache
- if ( array_key_exists( 'submit-cmb', $_REQUEST ) && $_REQUEST['submit-cmb'] == "clear-cache" ) {
+ } elseif ( array_key_exists( 'action', $_REQUEST ) && $_REQUEST['action'] == 'commonsbooking_options_advanced-options' ) {
+ // Check for request to clear cache
+ if ( array_key_exists( 'submit-cmb', $_REQUEST ) && $_REQUEST['submit-cmb'] == 'clear-cache' ) {
try {
Plugin::clearCache();
set_transient(
self::SUCCESS_TYPE,
- commonsbooking_sanitizeHTML( __( "Cache cleared.", 'commonsbooking' ) ),
- 45 );
+ commonsbooking_sanitizeHTML( __( 'Cache cleared.', 'commonsbooking' ) ),
+ 45
+ );
} catch ( Exception $e ) {
if ( WP_DEBUG ) {
error_log( $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
}
set_transient(
self::ERROR_TYPE,
- commonsbooking_sanitizeHTML( __( "Error while clearing the cache.", 'commonsbooking' ) ),
- 45 );
+ commonsbooking_sanitizeHTML( __( 'Error while clearing the cache.', 'commonsbooking' ) ),
+ 45
+ );
}
}
}
-
// we set transient to be able to flush rewrites at an ini hook in Plugin.php to set permalinks properly
set_transient( 'commonsbooking_options_saved', 1 );
}
diff --git a/src/Wordpress/PostStatus/PostStatus.php b/src/Wordpress/PostStatus/PostStatus.php
index 1ac0c0028..4c1b925bf 100644
--- a/src/Wordpress/PostStatus/PostStatus.php
+++ b/src/Wordpress/PostStatus/PostStatus.php
@@ -24,7 +24,7 @@ class PostStatus {
*
* @param $name
* @param $label
- * @param bool $public
+ * @param bool $public
*/
public function __construct( $name, $label, bool $public = true ) {
$this->name = $name;
@@ -39,14 +39,17 @@ public function __construct( $name, $label, bool $public = true ) {
* Registers current post status.
*/
public function registerPostStatus() {
- register_post_status( $this->name, array(
- 'label' => $this->label,
- 'public' => $this->public,
- 'label_count' => _n_noop(
- $this->label . ' (%s)',
- $this->label . ' (%s)'
+ register_post_status(
+ $this->name,
+ array(
+ 'label' => $this->label,
+ 'public' => $this->public,
+ 'label_count' => _n_noop(
+ $this->label . ' (%s)',
+ $this->label . ' (%s)'
+ ),
)
- ) );
+ );
}
/**
@@ -63,7 +66,7 @@ public function addActions() {
public function addOption() {
global $post;
- $active = "";
+ $active = '';
if ( $post ) {
if ( $post->post_status == $this->name ) {
$active = "jQuery( '#post-status-display' ).text( '" . $this->label . "' ); jQuery( 'select[name=\"post_status\"]' ).val('" . $this->name . "');";
@@ -71,10 +74,10 @@ public function addOption() {
echo "";
+ ';
}
}
@@ -84,9 +87,8 @@ public function addOption() {
public function addQuickedit() {
echo "";
}
-
}
diff --git a/src/Wordpress/Widget/UserWidget.php b/src/Wordpress/Widget/UserWidget.php
index e62c62f2a..14c7ace02 100644
--- a/src/Wordpress/Widget/UserWidget.php
+++ b/src/Wordpress/Widget/UserWidget.php
@@ -15,46 +15,46 @@ function __construct() {
parent::__construct(
'commonsbooking-user-widget', // Base ID
'CommonsBooking User Widget', // Name
- array( 'description' => esc_html__( 'Shows links to My Bookings, Login, Logout. Please set the Bookings Page in CommonsBooking Settings (General-Tab)', 'commonsbooking' ), )
+ array( 'description' => esc_html__( 'Shows links to My Bookings, Login, Logout. Please set the Bookings Page in CommonsBooking Settings (General-Tab)', 'commonsbooking' ) )
);
- add_action( 'widgets_init', function () {
- register_widget( '\CommonsBooking\Wordpress\Widget\UserWidget' );
- } );
-
+ add_action(
+ 'widgets_init',
+ function () {
+ register_widget( '\CommonsBooking\Wordpress\Widget\UserWidget' );
+ }
+ );
}
public $args = array(
'before_title' => '
- ';
- if ( ! is_user_logged_in() ) {
- printf( '%s',
- esc_url( wp_login_url()),
- esc_html__('Login to your account', 'commonsbooking')
- );
- }
- ?>
+ ';
+ if ( ! is_user_logged_in() ) {
+ printf(
+ '%s',
+ esc_url( wp_login_url() ),
+ esc_html__( 'Login to your account', 'commonsbooking' )
+ );
+ }
+ ?>
diff --git a/templates/booking-single.php b/templates/booking-single.php
index 74c1b0fef..3c94b2e72 100644
--- a/templates/booking-single.php
+++ b/templates/booking-single.php
@@ -71,16 +71,16 @@
formattedAddressOneLine();
- if (!empty($location_address)){
+ if ( ! empty( $location_address ) ) {
?>
- formattedPickupInstructionsOneLine();
- if (!empty($location_pickup_instructions)){
+ if ( ! empty( $location_pickup_instructions ) ) {
?>
@@ -90,13 +90,13 @@
}
// show contact details only after booking is confirmed or if options are set to show contactinfo even on unconfirmed booking status
if ( $post->post_status == 'confirmed' or $show_contactinfo_unconfirmed == 'on' ) {
- ?>
+ ?>
post_status() == 'unconfirmed' ) {
- $form_action = 'delete_unconfirmed';
- include COMMONSBOOKING_PLUGIN_DIR . 'templates/booking-single-form.php';
+ $form_action = 'delete_unconfirmed';
+ include COMMONSBOOKING_PLUGIN_DIR . 'templates/booking-single-form.php';
} else {
// if booking is confirmed we display the cancel booking button
$form_action = 'cancel';
diff --git a/templates/calendar-key.php b/templates/calendar-key.php
index 66f325249..4a8485675 100644
--- a/templates/calendar-key.php
+++ b/templates/calendar-key.php
@@ -2,16 +2,15 @@
/**
* Template: calendar-key
- *
- * This template part is used by timeframe-calendar and the item table
*
+ * This template part is used by timeframe-calendar and the item table
*/
- ?>
+?>
- :
- |
- |
- |
-
+ :
+ |
+ |
+ |
+
\ No newline at end of file
diff --git a/templates/dashboard-index.php b/templates/dashboard-index.php
index f49b386fb..61bb78c31 100644
--- a/templates/dashboard-index.php
+++ b/templates/dashboard-index.php
@@ -1,26 +1,26 @@
Dashboard
-
+
.
+ echo esc_html__( 'Welcome to CommonsBooking', 'commonsbooking' );?>.
-
+
-
+
-
-
-
+
+
+
-
+
@@ -28,35 +28,35 @@
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
-
-
-
+
+
+
+
-
+
-
+
@@ -66,27 +66,27 @@
-
+
-
+
diff --git a/templates/item-calendar-header.php b/templates/item-calendar-header.php
index 950d194ac..d15640d7a 100644
--- a/templates/item-calendar-header.php
+++ b/templates/item-calendar-header.php
@@ -1,15 +1,15 @@
thumbnail('cb_listing_medium')); // div.thumbnail is printed by function
+ echo commonsbooking_sanitizeHTML( $item->thumbnail( 'cb_listing_medium' ) ); // div.thumbnail is printed by function
?>
-
post_title); ?>
+
post_title ); ?>
\ No newline at end of file
diff --git a/templates/item-single-meta.php b/templates/item-single-meta.php
index 2e479f9f8..a4df19fa9 100644
--- a/templates/item-single-meta.php
+++ b/templates/item-single-meta.php
@@ -1,12 +1,10 @@
property
- * item Model methods are available as $item->myMethod()
- *
+ * item Model methods are available as $item->myMethod()
*/
global $templateData;
$item = $templateData['item'];
-?>
diff --git a/templates/item-single.php b/templates/item-single.php
index ebb4ad908..2765ea19f 100644
--- a/templates/item-single.php
+++ b/templates/item-single.php
@@ -1,50 +1,53 @@
' . esc_html__( $bookThisItemText, 'commonsbooking') . '';
- commonsbooking_get_template_part( 'location', 'calendar-header' ); // file: item-calendar-header.php
- commonsbooking_get_template_part( 'timeframe', 'calendar' ); // file: timeframe-calendar.php
- }
+ // Single Item View
+if ( array_key_exists( 'location', $templateData ) && $templateData['location'] ) { // item selected, so we display the booking calendar
+ echo '
+ ID, get_the_permalink($item->ID) ); // booking link set to item detail page with location ID
+$permalink = add_query_arg( 'cb-location', $location->ID, get_the_permalink( $item->ID ) ); // booking link set to item detail page with location ID
-$timeframes = $location->getBookableTimeframesByItem($item->ID, true);
+$timeframes = $location->getBookableTimeframesByItem( $item->ID, true );
?>
-thumbnail('cb_listing_small')); // div.thumbnail is printed by function ?>
+thumbnail( 'cb_listing_small' ) ); // div.thumbnail is printed by function ?>
-
post_title); ?>
-
-
- formattedBookableDate()); ?>
-
-
+
post_title ); ?>
+
+
+ formattedBookableDate() ); ?>
+
+
-
+
diff --git a/templates/location-calendar-header.php b/templates/location-calendar-header.php
index eed77d487..516ab6995 100644
--- a/templates/location-calendar-header.php
+++ b/templates/location-calendar-header.php
@@ -1,39 +1,41 @@
thumbnail('cb_listing_small')); // div.thumbnail is printed by function
+ echo commonsbooking_sanitizeHTML( $location->thumbnail( 'cb_listing_small' ) ); // div.thumbnail is printed by function
?>
+ ID, get_the_permalink($item->ID) ); // booking link set to item detail page with location ID
+$item = $templateData['item'];
+$button_label = Settings::getOption( 'commonsbooking_options_templates', 'label-booking-button' );
+$permalink = add_query_arg( 'cb-location', $location->ID, get_the_permalink( $item->ID ) ); // booking link set to item detail page with location ID
-$timeframes = $item->getBookableTimeframesByLocation($location->ID, true);
+$timeframes = $item->getBookableTimeframesByLocation( $location->ID, true );
?>
-thumbnail('cb_listing_medium')); // div.thumbnail is printed by function ?>
+thumbnail( 'cb_listing_medium' ) ); // div.thumbnail is printed by function ?>
';
- // Remove line breaks and whitespaces between tags
- $response = preg_replace( "/\r|\n/", "", $response);
- $response = preg_replace('/\>\s+\<', $response);
- echo commonsbooking_sanitizeHTML($response);
-
+ // Remove line breaks and whitespaces between tags
+ $response = preg_replace( "/\r|\n/", '', $response );
+ $response = preg_replace( '/\>\s+\<', $response );
+ echo commonsbooking_sanitizeHTML( $response );
} else {
- echo commonsbooking_sanitizeHTML($noResultText);
+ echo commonsbooking_sanitizeHTML( $noResultText );
}
diff --git a/templates/shortcode-items.php b/templates/shortcode-items.php
index 67e62349a..4ddbfc0a3 100644
--- a/templates/shortcode-items.php
+++ b/templates/shortcode-items.php
@@ -8,13 +8,12 @@
*
* WP Post properties for locations are available as $item->property
* location Model methods are available as $item->myMethod()
- *
*/
global $templateData;
-$item = new \CommonsBooking\Model\Item($templateData['item']);
-$hasTimeFrames = (array_key_exists('data', $templateData) && count($templateData['data']));
+$item = new \CommonsBooking\Model\Item( $templateData['item'] );
+$hasTimeFrames = ( array_key_exists( 'data', $templateData ) && count( $templateData['data'] ) );
// the item-not-available message (if item ist currently not available) can be defined via plugin options -> message templates
$noResultText = \CommonsBooking\Settings\Settings::getOption( COMMONSBOOKING_PLUGIN_SLUG . '_options_templates', 'item-not-available' );
@@ -22,27 +21,27 @@
?>
- thumbnail('cb_listing_medium')); ?>
-
-
titleLink() ); ?>
- excerpt()); ?>
-
-
-
-
+ thumbnail( 'cb_listing_medium' ) ); ?>
+
+
titleLink() ); ?>
+ excerpt() ); ?>
+
+
+
+
$data ) {
- $location = new \CommonsBooking\Model\Location($locationId);
- set_query_var( 'item', $item );
- set_query_var( 'location', $location );
- set_query_var( 'data', $data );
- commonsbooking_get_template_part( 'timeframe', 'withlocation' );
- }
- } // end if ($timeframes) ?>
\ No newline at end of file
+ foreach ( $templateData['data'] as $locationId => $data ) {
+ $location = new \CommonsBooking\Model\Location( $locationId );
+ set_query_var( 'item', $item );
+ set_query_var( 'location', $location );
+ set_query_var( 'data', $data );
+ commonsbooking_get_template_part( 'timeframe', 'withlocation' );
+ }
+} // end if ($timeframes) ?>
\ No newline at end of file
diff --git a/templates/shortcode-items_table.php b/templates/shortcode-items_table.php
index 43d7a7e55..a47194b38 100644
--- a/templates/shortcode-items_table.php
+++ b/templates/shortcode-items_table.php
@@ -5,8 +5,6 @@
* Model: Calendar
*
* Shows an availability table for items
- *
- *
*/
@@ -16,7 +14,7 @@
?>
-
+
diff --git a/templates/shortcode-locations.php b/templates/shortcode-locations.php
index 342c08c54..40148abd4 100644
--- a/templates/shortcode-locations.php
+++ b/templates/shortcode-locations.php
@@ -7,32 +7,32 @@
*
* WP Post properties for locations are available as $location->property
* location Model methods are available as $location->myMethod()
- *
*/
global $templateData;
-$location = new \CommonsBooking\Model\Location($templateData['location']);
+$location = new \CommonsBooking\Model\Location( $templateData['location'] );
// the location without items message is shown if there are currently no available items at this location. Can be defined via plugin options -> message templates
$noResultText = \CommonsBooking\Settings\Settings::getOption( COMMONSBOOKING_PLUGIN_SLUG . '_options_templates', 'location-without-items' );
?>
diff --git a/templates/timeframe-calendar.php b/templates/timeframe-calendar.php
index 0fedf00ba..25448a752 100644
--- a/templates/timeframe-calendar.php
+++ b/templates/timeframe-calendar.php
@@ -7,154 +7,154 @@
* We recommend not to edit this file as it might be modified and enhancend during updates
*/
- global $templateData;
+ global $templateData;
- // we check if template is used not used in backend ...
+ // we check if template is used not used in backend ...
if ( ! array_key_exists( 'backend', $templateData ) || $templateData['backend'] != true ) {
- do_action( 'commonsbooking_before_timeframe-calendar' );
- ?>
-
-
-
+ do_action( 'commonsbooking_before_timeframe-calendar' );
+ ?>
+
+
+
-
-
+ getDays() as $day ) {
+ if ( $day->getDayOfWeek() == $dayNr ) {
+ include __DIR__ . 'timeframe-calendar-day.php';
+ }
+ }
+ }
+ ?>
+
- ';
- if ( ! is_user_logged_in() ) {
- printf( '%s',
- esc_url( wp_login_url()),
- esc_html__('Login to your account', 'commonsbooking')
- );
- }
- ?>
+ ';
+ if ( ! is_user_logged_in() ) {
+ printf(
+ '%s',
+ esc_url( wp_login_url() ),
+ esc_html__( 'Login to your account', 'commonsbooking' )
+ );
+ }
+ ?>
diff --git a/templates/timeframe-withitem.php b/templates/timeframe-withitem.php
index 9571f9e17..071231cde 100644
--- a/templates/timeframe-withitem.php
+++ b/templates/timeframe-withitem.php
@@ -1,31 +1,31 @@
ID, get_the_permalink($item->ID) ); // booking link set to item detail page with location ID
+$button_label = Settings::getOption( 'commonsbooking_options_templates', 'label-booking-button' );
+$permalink = add_query_arg( 'cb-location', $location->ID, get_the_permalink( $item->ID ) ); // booking link set to item detail page with location ID
?>
-thumbnail('cb_listing_small')); // div.thumbnail is printed by function ?>
+thumbnail( 'cb_listing_small' ) ); // div.thumbnail is printed by function ?>
diff --git a/templates/timeframe-withlocation.php b/templates/timeframe-withlocation.php
index c642f3351..241cff508 100644
--- a/templates/timeframe-withlocation.php
+++ b/templates/timeframe-withlocation.php
@@ -2,7 +2,7 @@
/**
* Template: timeframe-withlocation
- *
+ *
* This template is included in parent template shortcode-items or shortcode-locations
*
* $data is set in parent template
@@ -11,37 +11,37 @@
use CommonsBooking\Settings\Settings;
-$button_label = \CommonsBooking\Settings\Settings::getOption( COMMONSBOOKING_PLUGIN_SLUG . '_options_templates', 'label-booking-button');
-$permalink = add_query_arg ( 'cb-location', $location->ID, get_the_permalink($item->ID) ); // booking link set to item detail page with location ID
+$button_label = \CommonsBooking\Settings\Settings::getOption( COMMONSBOOKING_PLUGIN_SLUG . '_options_templates', 'label-booking-button' );
+$permalink = add_query_arg( 'cb-location', $location->ID, get_the_permalink( $item->ID ) ); // booking link set to item detail page with location ID
?>
-thumbnail('cb_listing_small')); // div.thumbnail is printed by function ?>
+thumbnail( 'cb_listing_small' ) ); // div.thumbnail is printed by function ?>
- | - | - | -
+ :
+ | + | + | +
Dashboard
- +.
+ echo esc_html__( 'Welcome to CommonsBooking', 'commonsbooking' );?>.-
-
-
+
+
+
---
+
-
- -
+
-
- -
+
-
--
+
-
- -
+
-
- --
+
+
+ +-
- -
+
-
-
+
post_title); ?>
+post_title ); ?>
' . esc_html__( $bookThisItemText, 'commonsbooking' ) . '
'; + commonsbooking_get_template_part( 'location', 'calendar-header' ); // file: item-calendar-header.php + commonsbooking_get_template_part( 'timeframe', 'calendar' ); // file: timeframe-calendar.php +} + + // Multi item view +if ( array_key_exists( 'locations', $templateData ) && $templateData['locations'] ) { + foreach ( $templateData['locations'] as $location ) { + $templateData['location'] = $location; + commonsbooking_get_template_part( 'item', 'withlocation' ); // file: location-withitem.php + } // end foreach $timeframes +} // $item_is_selected - // Multi item view - if(array_key_exists('locations', $templateData) && $templateData['locations']) { - foreach ($templateData['locations'] as $location ) { - $templateData['location'] = $location; - commonsbooking_get_template_part( 'item', 'withlocation' ); // file: location-withitem.php - } // end foreach $timeframes - } // $item_is_selected - // item not available if no valid location reference found - if( !array_key_exists('location', $templateData) && empty( $templateData['locations'] ) ) { ?> -post_title); ?>
- -post_title ); ?>
+ +- - post_title); ?> - -
++ + post_title ); ?> + +
formattedAddressOneLine(); - if (!empty($locationAddress)){ + if ( ! empty( $locationAddress ) ) { ?> - hasMap() ) { - \CommonsBooking\View\Location::renderLocationMap( $location ); - } + if ( $location->hasMap() ) { + \CommonsBooking\View\Location::renderLocationMap( $location ); + } ?> -' . esc_html__( $bookThisItemText, 'commonsbooking' ) . '
'; + commonsbooking_get_template_part( 'item', 'calendar-header' ); // file: item-calendar-header.php + commonsbooking_get_template_part( 'timeframe', 'calendar' ); // file: timeframe-calendar.php +} - // Multi item view - if(array_key_exists('items', $templateData) && $templateData['items']) { - foreach ($templateData['items'] as $item ) { - $templateData['item'] = $item; - commonsbooking_get_template_part( 'location', 'withitem' ); // file: location-withitem.php - } // end foreach $timeframes - } // $item_is_selected + // Multi item view +if ( array_key_exists( 'items', $templateData ) && $templateData['items'] ) { + foreach ( $templateData['items'] as $item ) { + $templateData['item'] = $item; + commonsbooking_get_template_part( 'location', 'withitem' ); // file: location-withitem.php + } // end foreach $timeframes +} // $item_is_selected - if(!array_key_exists('item', $templateData) && !array_key_exists('items', $templateData)) { ?> -post_title); ?>
- -post_title ); ?>
+ +.
++ + .
diff --git a/templates/shortcode-bookings.php b/templates/shortcode-bookings.php index 0799faca1..1980c35ac 100644 --- a/templates/shortcode-bookings.php +++ b/templates/shortcode-bookings.php @@ -4,90 +4,90 @@ * Model: Booking * View: Booking::shortcode * $templateData is set in + * * @see \CommonsBooking\View\Booking::getBookingListData() * * List all allowed bookings with filter - * */ global $templateData; -if ( !is_user_logged_in() ) { - $current_url = $_SERVER['REQUEST_URI']; - $noResultText = sprintf( commonsbooking_sanitizeHTML( __('Please login to see your bookings.', 'commonsbooking') ), wp_login_url( $current_url ) ); -} else { - $noResultText = commonsbooking_sanitizeHTML( __("No bookings available.", "commonsbooking") ); +if ( ! is_user_logged_in() ) { + $current_url = $_SERVER['REQUEST_URI']; + $noResultText = sprintf( commonsbooking_sanitizeHTML( __( 'Please login to see your bookings.', 'commonsbooking' ) ), wp_login_url( $current_url ) ); +} else { + $noResultText = commonsbooking_sanitizeHTML( __( 'No bookings available.', 'commonsbooking' ) ); } $response = ''; -if ($templateData && $templateData['total'] > 0) { - $showFilters = !commonsbooking_isCurrentUserSubscriber(); +if ( $templateData && $templateData['total'] > 0 ) { + $showFilters = ! commonsbooking_isCurrentUserSubscriber(); - $response .= ' + $response .= '
titleLink() ); ?>
- excerpt()); ?> - - - -titleLink() ); ?>
+ excerpt() ); ?> + + + +titleLink() ); ?>
- excerpt()); ?> -titleLink() ); ?>
+ excerpt() ); ?> +- getDays() as $day ) { - if ( $day->getDayOfWeek() == $dayNr ) { - include __DIR__ . 'timeframe-calendar-day.php'; - } - } - } - ?> -
+ foreach ( $templateData['calendar']['weeks'] as $week ) { + ?> ++ getDays() as $day ) { + if ( $day->getDayOfWeek() == $dayNr ) { + include __DIR__ . 'timeframe-calendar-day.php'; + } + } + } + ?> +
- - post_title); ?> - -
-+ + post_title ); ?> + +
+- - post_title); ?> - -
-+ + post_title ); ?> + +
+