Skip to content

Commit

Permalink
Merge pull request #1686 from janschoenherr/patch-7
Browse files Browse the repository at this point in the history
code cleanup
  • Loading branch information
hansmorb authored Feb 5, 2025
2 parents 00db6fa + 6acb975 commit 9201ba4
Show file tree
Hide file tree
Showing 14 changed files with 55 additions and 56 deletions.
36 changes: 18 additions & 18 deletions src/Messages/BookingCodesMessage.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,32 +39,32 @@ public function __construct( $postId, string $action, int $tsFrom=null, int $tsT

/**
* prepares Message and sends by E-mail
*
*
* @return bool true if message was sent, false otherwise. If the message is not sent, an error is raised.
*/
public function sendMessage(): bool {
$timeframeId=(int)$this->getPostId();
$timeframe=new Timeframe($timeframeId);

if(!$this->prepareReceivers($timeframe)) return $this->raiseError(
if(!$this->prepareReceivers($timeframe)) return $this->raiseError(
__( "Unable to send Emails. No location email(s) configured, check location", "commonsbooking" ));

$bookingCodes = BookingCodes::getCodes($timeframeId, $this->tsFrom,$this->tsTo);
if(empty($bookingCodes)) return $this->raiseError( __( "Could not find booking codes for this timeframe/period", "commonsbooking" ));

$bookingTable=apply_filters('commonsbooking_emailcodes_rendertable',
\CommonsBooking\View\BookingCodes::renderBookingCodesTable( $bookingCodes ),
$bookingCodes,'email');

$bAddIcal=apply_filters('commonsbooking_emailcodes_addical',
Settings::getOption( 'commonsbooking_options_bookingcodes', 'mail-booking-' . $this->action . '-attach-ical' ),
$timeframe);
$attachment=$bAddIcal?$this->getIcalAttachment($bookingCodes):null;

//Workaround: arbitrary object for template parser
$codes=new \WP_User((object)array( "ID" => -1));
$codes->codeTable=$bookingTable;

$dispTo= wp_date("M-Y",strtotime(end($bookingCodes)->getDate()));
$dispFrom= wp_date("M-Y",strtotime(reset($bookingCodes)->getDate()));
$codes->formatDateRange=($dispFrom == $dispTo)?$dispFrom:$dispFrom . " - " . $dispTo;
Expand Down Expand Up @@ -97,19 +97,19 @@ public function sendMessage(): bool {
],
$attachment
);

add_action( 'commonsbooking_mail_sent',array($this,'updateEmailSent'), 5, 2 );

if(count($this->locationAdmins) > 1) {
add_filter('commonsbooking_mail_to', array($this,'addMultiTo'), 25);
$this->SendNotificationMail();
$this->sendNotificationMail();
remove_filter('commonsbooking_mail_to', array($this,'addMultiTo'), 25);
}
else
$this->SendNotificationMail();
$this->sendNotificationMail();

remove_action( 'commonsbooking_mail_sent',array($this,'updateEmailSent'), 5 );

return true;
}

Expand All @@ -126,17 +126,17 @@ public function sendMessage(): bool {
public function updateEmailSent($action,$result)
{
if($this->action != $action) return;

if($result === true)
{
update_post_meta( (int)$this->getPostId(), \CommonsBooking\View\BookingCodes::LAST_CODES_EMAIL, time() );
update_post_meta( (int)$this->getPostId(), \CommonsBooking\View\BookingCodes::LAST_CODES_EMAIL, time() );
}

}

/**
* filter commonsbooking_mail_to for adding multiple to email addresses
*
*
* @return array
*/
public function addMultiTo(): array {
Expand All @@ -163,18 +163,18 @@ protected function prepareReceivers(Timeframe $timeframe): bool {
foreach(array_map('trim', explode(',', $location_emails)) as $email) {
$dUser=$this->locationAdmins[]=new \WP_User((object)array( "ID" => $dummy_id--));
$dUser->user_nicename='';
$dUser->user_email=$email;
$dUser->user_email=$email;
}
}

return !empty($this->locationAdmins);
}

/**
* generates iCalendar attachment with all requested booking codes
*
* @param BookingCode[] $bookingCodes List of BookingCode objects
*
*
* @return array
*/
protected function getIcalAttachment( array $bookingCodes): array {
Expand All @@ -199,7 +199,7 @@ protected function getIcalAttachment( array $bookingCodes): array {
];

return $attachment;

}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/Messages/BookingMessage.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ public function sendMessage() {
$template_objects,
$attachment
);
$this->SendNotificationMail();
$this->sendNotificationMail();
}

}
2 changes: 1 addition & 1 deletion src/Messages/BookingReminderMessage.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public function sendMessage() {
'user' => $booking_user,
]
);
$this->SendNotificationMail();
$this->sendNotificationMail();
}

}
24 changes: 12 additions & 12 deletions src/Messages/Message.php
Original file line number Diff line number Diff line change
Expand Up @@ -146,33 +146,33 @@ protected function prepareMail(
// Setup email: From
$this->headers[] = $from_headers;

// add bcc adresses
// add bcc adresses
if ( ! empty ( $bcc_adresses ) ) {
$addresses_array = explode( ',', $bcc_adresses );
$this->add_bcc( $addresses_array );
}

//add attachment when it exists
if (!empty($attachment)) {
$this->attachment = $attachment;
}
}


/**
* Send the email using wp_mail function
*
* You need to run prepareMail() before calling this function
*
* @return void
*/
public function SendNotificationMail() {
public function sendNotificationMail() {
$to = $this->getTo();
$subject = $this->getSubject();
$body = $this->getBody();
$attachment = $this->getAttachment();
$headers = implode( "\r\n", $this->headers );

if (!empty($attachment)) { //When attachment exists, modify wp_mail function to support attachment strings
add_filter('wp_mail', array($this,'addStringAttachments'), 25); //add arbitrary priority to identify filter for removal
$result = wp_mail($to, $subject, $body, $headers, $attachment);
Expand Down Expand Up @@ -237,7 +237,7 @@ public function getValidActions(): array {
* Adds support for defining attachments as data arrays in wp_mail().
* Allows us to send string-based or binary attachments (non-filesystem)
* and gives us more control over the attachment data.
*
*
* @param array $atts Array of the `wp_mail()` arguments.
* - string|string[] $to Array or comma-separated list of email addresses to send message.
* - string $subject Email subject.
Expand All @@ -253,12 +253,12 @@ public function addStringAttachments($atts)
if (array_key_exists('attachments', $atts) && isset($atts['attachments']) && $atts['attachments']) {
$attachments = $atts['attachments'];
if (is_array($attachments) && !empty($attachments)) {
// Is the $attachments array a single array of attachment data, or an array containing multiple arrays of
// Is the $attachments array a single array of attachment data, or an array containing multiple arrays of
// attachment data? (note that the array may also be a one-dimensional array of file paths, as-per default usage).
$is_multidimensional_array = count($attachments) == count($attachments, COUNT_RECURSIVE) ? false : true;
if (!$is_multidimensional_array) $attachments = [$attachments];
// Work out which attachments we want to process here. If the value is an array with either
// a 'path' or 'path' key, then we'll process it separately and remove it from the
// Work out which attachments we want to process here. If the value is an array with either
// a 'path' or 'path' key, then we'll process it separately and remove it from the
// $atts['attachments'] so that WP doesn't try to process it in wp_mail().
foreach ($attachments as $index => $attachment) {
if (is_array($attachment) && (array_key_exists('path', $attachment) || array_key_exists('string', $attachment))) {
Expand All @@ -279,9 +279,9 @@ public function addStringAttachments($atts)
global $wp_mail_attachments;
$wp_mail_attachments = $attachment_arrays;

// We can't use the global $phpmailer to add our attachments directly in the 'wp_mail' filter callback because WP calls $phpmailer->clearAttachments()
// after this filter runs. Instead, we now hook into the 'phpmailer_init' action (triggered right before the email is sent), and read
// the $wp_mail_attachments global to check for any additional attachments to add.
// We can't use the global $phpmailer to add our attachments directly in the 'wp_mail' filter callback because WP calls $phpmailer->clearAttachments()
// after this filter runs. Instead, we now hook into the 'phpmailer_init' action (triggered right before the email is sent), and read
// the $wp_mail_attachments global to check for any additional attachments to add.
add_action('phpmailer_init', function ( $phpmailer) {
// Check the $wp_mail_attachments global for any attachment data, and reset it for good measure.
$attachment_arrays = [];
Expand Down
6 changes: 3 additions & 3 deletions src/Messages/RestrictionMessage.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ protected function sendHintMail() {
$subject
);

$this->SendNotificationMail();
$this->sendNotificationMail();
}

/**
Expand All @@ -90,7 +90,7 @@ protected function sendRepairMail() {
$subject
);

$this->SendNotificationMail();
$this->sendNotificationMail();
}

/**
Expand All @@ -105,7 +105,7 @@ protected function sendRestrictionCancelationMail() {
$subject
);

$this->SendNotificationMail();
$this->sendNotificationMail();
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/Model/Booking.php
Original file line number Diff line number Diff line change
Expand Up @@ -883,7 +883,7 @@ public function hasTotalBreakdown(): bool {
/**
* Returns formatted user info based on the template field in settings -> templates
*
* @return void
* @return mixed
*/
public static function getFormattedUserInfo() {
return commonsbooking_parse_template(
Expand Down
2 changes: 1 addition & 1 deletion src/Model/CustomPost.php
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ public function getUserData() {
* Checks if the given user is the author of the current post.
* @param \WP_User $user
*
* @return boolean - true if user is author, false if not.
* @return bool - true if user is author, false if not.
*/
public function isAuthor (\WP_User $user): bool {
return $user->ID === intval( $this->post_author );
Expand Down
10 changes: 5 additions & 5 deletions src/Model/Day.php
Original file line number Diff line number Diff line change
Expand Up @@ -221,15 +221,15 @@ protected function getStartSlot( int $grid, \CommonsBooking\Model\Timeframe $tim
*
* @param int $grid
* @param Restriction $restriction
* @return float|int
*/
protected function getRestrictionStartSlot( int $grid, \CommonsBooking\Model\Restriction $restriction ) {
protected function getRestrictionStartSlot( int $grid, Restriction $restriction ) {

$startTime = $restriction->getStartTimeDateTime();
$startSlot = $this->getSlotByTime( $startTime, $grid );

$startDateBooking = intval( $restriction->getStartDate() );
$startDateBooking = $restriction->getStartDate();
$startDateDay = strtotime( $this->getDate() );

// if restriction starts on day before, we set startslot to 0
Expand Down Expand Up @@ -285,7 +285,7 @@ protected function getEndSlot( array $slots, int $grid, \CommonsBooking\Model\Ti
* @return float|int
* @throws Exception
*/
protected function getRestrictionEndSlot( array $slots, int $grid, \CommonsBooking\Model\Restriction $restriction ) {
protected function getRestrictionEndSlot( array $slots, int $grid, Restriction $restriction ) {
$endTime = $restriction->getEndTimeDateTime( $this->getDateObject()->getTimestamp() );
$endDate = $restriction->getEndDateDateTime();

Expand Down Expand Up @@ -440,7 +440,7 @@ protected function mapRestrictions( array &$slots ) {
$grid = 24 / count( $slots );

// Iterate through timeframes and fill slots
/** @var \CommonsBooking\Model\Restriction $restriction */
/** @var Restriction $restriction */
foreach ( $this->getRestrictions() as $restriction ) {

// Only if there is a repair we block the timeframe
Expand Down
3 changes: 1 addition & 2 deletions src/Model/Timeframe.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
use CommonsBooking\Exception\OverlappingException;
use CommonsBooking\Exception\TimeframeInvalidException;
use CommonsBooking\Helper\Wordpress;
use CommonsBooking\Tests\Repository\TimeframeTest;
use DateTime;
use Exception;

Expand Down Expand Up @@ -898,7 +897,7 @@ public function getGrid(): int {
* 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.
Expand Down
4 changes: 2 additions & 2 deletions src/Model/Week.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@
class Week {

/**
* @var integer
* @var int
*/
protected $year;

/**
* Day in the year to start the week from (0-365)
* @var integer
* @var int
*/
protected $dayOfYear;

Expand Down
2 changes: 1 addition & 1 deletion src/Plugin.php
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ public static function admin_init() {

// Check if we need to run post options updated actions
if ( get_transient( 'commonsbooking_options_saved' ) == 1 ) {
AdminOptions::SetOptionsDefaultValues();
AdminOptions::setOptionsDefaultValues();

flush_rewrite_rules();

Expand Down
10 changes: 5 additions & 5 deletions src/Service/Scheduler.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@
*/
class Scheduler {

protected string $jobhook;
protected string $reccurence;
protected string $jobhook;
protected string $reccurence;
protected int $timestamp;

const UNSCHEDULER_HOOK = COMMONSBOOKING_PLUGIN_SLUG . '_unschedule';
Expand Down Expand Up @@ -45,7 +45,7 @@ function __construct(
// Add custom cron intervals
add_filter( 'cron_schedules', array( self::class, 'initIntervals' ) );

$this->jobhook = COMMONSBOOKING_PLUGIN_SLUG . '_' .$jobhook; //Prepends plugin slug so that hooks can be found easily afterwards
$this->jobhook = COMMONSBOOKING_PLUGIN_SLUG . '_' .$jobhook; //Prepends plugin slug so that hooks can be found easily afterwards

if ((count($option) == 2) && Settings::getOption($option[0],$option[1]) != 'on' ) { //removes job if option unset
$this->unscheduleJob();
Expand All @@ -54,7 +54,7 @@ function __construct(

if (empty($executionTime)){
$this->timestamp = time();
}
}
elseif ($reccurence == 'daily'){
$this->timestamp = strtotime($executionTime);
if($this->timestamp < time()) { //if timestamp is in the past, add one day
Expand Down Expand Up @@ -226,7 +226,7 @@ public function getTimestamp(): int {
* - The job is no longer needed
* - The job has been updated and needs to be rescheduled
* - The plugin has been deactivated
* @return boolean
* @return int|false|\WP_Error
*/
private function unscheduleJob() {
return wp_clear_scheduled_hook($this->jobhook);
Expand Down
2 changes: 1 addition & 1 deletion src/Service/Upgrade.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ class Upgrade {
*/
private function runEveryUpgrade(): void {
// set Options default values (e.g. if there are new fields added)
AdminOptions::SetOptionsDefaultValues();
AdminOptions::setOptionsDefaultValues();

// flush rewrite rules
flush_rewrite_rules();
Expand Down
Loading

0 comments on commit 9201ba4

Please sign in to comment.