15 Commits
v0.1.7 ... dev

Author SHA1 Message Date
69faa9a17e Use TONY_SPORTSPRESS_ENHANCEMENTS_DIR constant in requires; localize JS strings
- Replace repeated plugin_dir_path(__FILE__) calls with the already-defined
  TONY_SPORTSPRESS_ENHANCEMENTS_DIR constant
- Localize 'Open ICS Feed' and 'Open Feed URL' JS strings in sp-url-builder.php
  via wp_json_encode() so they pass through the translation system

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 08:41:07 -05:00
7fc040d87a Prefix generic function names, normalize style in featured-image-generator
- Rename generate_bisected_image, handle_image_request, serve_image,
  save_image_to_cache, add_image_generator_endpoint to tony_sportspress_*
  to avoid global namespace collisions
- Guard $team1/$team2 against null before accessing ->post_modified
- Unify the two logo-placement loops into a single foreach
- Normalize indentation to tabs throughout
- Fix missing space before => in sp-event-export normalize_request_args

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 08:39:09 -05:00
7cde030f0e Refactor open-graph-tags.php for correctness and standards compliance
- Early-return instead of deeply nested if blocks
- Fix $the_outcome used outside the foreach loop (undefined variable risk)
- Remove unused variables ($results, $publish_date, $i, $result_string,
  $title_string, $labels)
- Remove no-op $description = $description assignment
- Normalize indentation to tabs throughout
- Use strict comparison (===) consistently
- Guard $venue_terms with is_wp_error() check

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 08:37:54 -05:00
6eb51a89b2 Replace old plugin headers with proper file docblocks, add ABSPATH guards
- open-graph-tags.php: replace Plugin Name header with package docblock
- featured-image-generator.php: same cleanup
- sp-event-permalink.php: same cleanup, normalize indentation to tabs,
  collapse redundant switch cases (league/tournament both map to 'game')

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 08:33:15 -05:00
7f0d0457e1 Fix security and logic bugs in image generator and OG tags
- Fix null-dereference: check !$post with || before accessing post_type
- Sanitize $_GET['post'] with absint() before use
- Escape OG tag attribute values with esc_attr()/esc_url()

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 08:19:57 -05:00
dbe3048af7 Improve webhook testing and provider UI 2026-04-05 14:28:17 -04:00
4ed968a045 Add configurable event webhook notifications 2026-04-05 14:14:12 -04:00
360b971880 Update schedule exporter and bump version to 0.1.9
Some checks failed
Release Plugin Zip / release (push) Has been cancelled
2026-04-04 09:17:24 -04:00
2dbdc5fae9 Bump version to 0.1.8
Some checks failed
Release Plugin Zip / release (push) Has been cancelled
2026-04-02 14:45:48 -05:00
4c07787a44 Add GitHub releases updater 2026-04-02 14:44:10 -05:00
25014f6368 Add quick week filter options 2026-04-02 13:11:28 -05:00
37d1037238 Align admin filter labels with venue wording 2026-04-02 13:07:32 -05:00
65df3525a4 Disable event title links for officials managers 2026-04-02 12:29:37 -05:00
bc0e913dfb Refine admin week filter behavior 2026-04-02 12:23:29 -05:00
2baebf9c30 Add officials manager role and event officials column 2026-04-02 11:28:08 -05:00
13 changed files with 3286 additions and 660 deletions

View File

@@ -1,207 +1,224 @@
<?php
/*
Plugin Name: SP Event Image Generator
Description: Auto-generates featured images for SP Events by combining team colors and logos.
Version: 1.0
Author: Your Name
/**
* SP Event featured-image generator.
*
* Auto-generates bisected team-color images for SP Events.
*
* @package Tonys_Sportspress_Enhancements
*/
function generate_bisected_image($color1, $color2, $logo1_path, $logo2_path) {
$width = 1200;
$height = 628;
$x_margin = 0.1 * ($width / 2); // 10% of half the width
$y_margin = 0.1 * $height; // 10% of the height
$image = imagecreatetruecolor($width, $height);
// Allocate colors
$rgb1 = sscanf($color1, "#%02x%02x%02x");
$rgb2 = sscanf($color2, "#%02x%02x%02x");
$color1_alloc = imagecolorallocate($image, $rgb1[0], $rgb1[1], $rgb1[2]);
$color2_alloc = imagecolorallocate($image, $rgb2[0], $rgb2[1], $rgb2[2]);
// Fill halves with a 15-degree angled bisection
$points1 = [
0, 0,
0, $height,
$width*.40, $height,
$width*.60, 0,
];
$points2 = [
$width, 0,
$width, $height,
$width*.40, $height,
$width*.60, 0,
];
imagefilledpolygon($image, $points1, $color1_alloc);
imagefilledpolygon($image, $points2, $color2_alloc);
// Add logos with resizing and positioning if paths are not empty
if (!empty($logo1_path)) {
$logo1 = imagecreatefrompng($logo1_path);
$logo1_width = imagesx($logo1);
$logo1_height = imagesy($logo1);
// Calculate max dimensions for logo 1
$max_width = ($width / 2) - (2 * $x_margin);
$max_height = $height - (2 * $y_margin);
// Resize logo 1
$new_logo1_width = $logo1_width;
$new_logo1_height = $logo1_height;
if ($logo1_width > $max_width || $logo1_height > $max_height) {
$aspect_ratio1 = $logo1_width / $logo1_height;
if ($logo1_width / $max_width > $logo1_height / $max_height) {
$new_logo1_width = $max_width;
$new_logo1_height = $max_width / $aspect_ratio1;
} else {
$new_logo1_height = $max_height;
$new_logo1_width = $max_height * $aspect_ratio1;
}
}
// Center logo 1
$logo1_x = (int) ($width / 4) - ($new_logo1_width / 2);
$logo1_y = (int) ($height / 2) - ($new_logo1_height / 2);
imagecopyresampled($image, $logo1, $logo1_x, $logo1_y, 0, 0, $new_logo1_width, $new_logo1_height, $logo1_width, $logo1_height);
imagedestroy($logo1);
}
if (!empty($logo2_path)) {
$logo2 = imagecreatefrompng($logo2_path);
$logo2_width = imagesx($logo2);
$logo2_height = imagesy($logo2);
// Calculate max dimensions for logo 2
$max_width = ($width / 2) - (2 * $x_margin);
$max_height = $height - (2 * $y_margin);
// Resize logo 2
$new_logo2_width = $logo2_width;
$new_logo2_height = $logo2_height;
if ($logo2_width > $max_width || $logo2_height > $max_height) {
$aspect_ratio2 = $logo2_width / $logo2_height;
if ($logo2_width / $max_width > $logo2_height / $max_height) {
$new_logo2_width = $max_width;
$new_logo2_height = $max_width / $aspect_ratio2;
} else {
$new_logo2_height = $max_height;
$new_logo2_width = $max_height * $aspect_ratio2;
}
}
// Center logo 2
$logo2_x = (int) (3 * $width / 4) - ($new_logo2_width / 2);
$logo2_y = (int) ($height / 2) - ($new_logo2_height / 2);
imagecopyresampled($image, $logo2, $logo2_x, $logo2_y, 0, 0, $new_logo2_width, $new_logo2_height, $logo2_width, $logo2_height);
imagedestroy($logo2);
}
// Start output buffering to capture the image data
ob_start();
imagepng($image); // Output the image as PNG
$image_data = ob_get_clean(); // Get the image data from the buffer
// Clean up memory
imagedestroy($image);
return $image_data;
}
function add_image_generator_endpoint() {
add_rewrite_endpoint('head-to-head', EP_ROOT, true);
}
add_action('init', 'add_image_generator_endpoint');
function handle_image_request() {
if (!isset($_GET['post'])) return;
$post_id = $_GET['post'];
$post = get_post($post_id);
// Verify post type
if (!$post && $post->post_type !== 'sp_event') return;
// Get associated teams from post meta
$team_ids = get_post_meta($post_id, 'sp_team', false); // false to get an array of values
// Ensure we have exactly two teams
if (count($team_ids) < 2) return;
$team1_id = $team_ids[0];
$team2_id = $team_ids[1];
$team1 = get_post($team1_id);
$team2 = get_post($team2_id);
$team1_postmodified = strtotime($team1->post_modified);
$team2_postmodified = strtotime($team2->post_modified);
$cache_key = "team_image_{$team1_id}_{$team1_postmodified}-{$team2_id}_{$team2_postmodified}";
$cached_image_path = get_transient($cache_key);
if ($cached_image_path && file_exists($cached_image_path)) {
serve_image($cached_image_path);
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
// Get team colors and logos
/**
* Register the head-to-head rewrite endpoint.
*
* @return void
*/
function tony_sportspress_add_image_generator_endpoint() {
add_rewrite_endpoint( 'head-to-head', EP_ROOT, true );
}
add_action( 'init', 'tony_sportspress_add_image_generator_endpoint' );
/**
* Serve the generated matchup image on template_redirect.
*
* @return void
*/
function tony_sportspress_handle_image_request() {
if ( ! isset( $_GET['post'] ) ) {
return;
}
$post_id = absint( $_GET['post'] );
if ( $post_id <= 0 ) {
return;
}
$post = get_post( $post_id );
if ( ! $post || $post->post_type !== 'sp_event' ) {
return;
}
$team_ids = get_post_meta( $post_id, 'sp_team', false );
if ( count( $team_ids ) < 2 ) {
return;
}
$team1_id = (int) $team_ids[0];
$team2_id = (int) $team_ids[1];
$team1 = get_post( $team1_id );
$team2 = get_post( $team2_id );
if ( ! $team1 || ! $team2 ) {
return;
}
$team1_modified = strtotime( $team1->post_modified );
$team2_modified = strtotime( $team2->post_modified );
$cache_key = "team_image_{$team1_id}_{$team1_modified}-{$team2_id}_{$team2_modified}";
$cached_path = get_transient( $cache_key );
if ( $cached_path && file_exists( $cached_path ) ) {
tony_sportspress_serve_image( $cached_path );
exit;
}
$default_color = '#FFFFFF';
$team1_colors = get_post_meta( $team1_id, 'sp_colors', true );
$team2_colors = get_post_meta( $team2_id, 'sp_colors', true );
$default_color = '#FFFFFF'; // Default color (black)
$team1_color = ! empty( $team1_colors['primary'] ) ? $team1_colors['primary'] : $default_color;
$team2_color = ! empty( $team2_colors['primary'] ) ? $team2_colors['primary'] : $default_color;
// Security check for hex color
$team1_color = preg_match('/^#[a-fA-F0-9]{6}$/', $team1_color) ? $team1_color : '#FFFFFF';
$team2_color = preg_match('/^#[a-fA-F0-9]{6}$/', $team2_color) ? $team2_color : '#FFFFFF';
// Validate hex colors.
if ( ! preg_match( '/^#[a-fA-F0-9]{6}$/', $team1_color ) ) {
$team1_color = $default_color;
}
if ( ! preg_match( '/^#[a-fA-F0-9]{6}$/', $team2_color ) ) {
$team2_color = $default_color;
}
$team1_logo_url = get_the_post_thumbnail_url( $team1_id, 'full' );
$team2_logo_url = get_the_post_thumbnail_url( $team2_id, 'full' );
// Check if both team colors are default and both logos are empty
if (($team1_color === $default_color && empty($team1_logo_url)) && ($team2_color === $default_color && empty($team2_logo_url))) {
return; // Do nothing if both teams have no valid color or logo
// Skip if both teams have no distinguishable color or logo.
if ( $team1_color === $default_color && empty( $team1_logo_url )
&& $team2_color === $default_color && empty( $team2_logo_url ) ) {
return;
}
$team1_logo_thumbnail_id = get_post_thumbnail_id($team1_id, 'full');
$team2_logo_thumbnail_id = get_post_thumbnail_id($team2_id, 'full');
$team1_logo = get_attached_file($team1_logo_thumbnail_id);
$team2_logo = get_attached_file($team2_logo_thumbnail_id);
$team1_logo = get_attached_file( get_post_thumbnail_id( $team1_id ) );
$team2_logo = get_attached_file( get_post_thumbnail_id( $team2_id ) );
// Generate the image if no valid cache exists
$image_data = generate_bisected_image($team1_color, $team2_color, $team1_logo, $team2_logo);
$image_path = save_image_to_cache($image_data, $cache_key);
set_transient($cache_key, $image_path, DAY_IN_SECONDS * 30); // Cache for 30 days
serve_image($image_path);
$image_data = tony_sportspress_generate_bisected_image( $team1_color, $team2_color, $team1_logo, $team2_logo );
$image_path = tony_sportspress_save_image_to_cache( $image_data, $cache_key );
set_transient( $cache_key, $image_path, DAY_IN_SECONDS * 30 );
tony_sportspress_serve_image( $image_path );
exit;
}
add_action('template_redirect', 'handle_image_request');
add_action( 'template_redirect', 'tony_sportspress_handle_image_request' );
function serve_image($image_path) {
/**
* Send a cached PNG image file to the browser.
*
* @param string $image_path Absolute path to the image file.
* @return void
*/
function tony_sportspress_serve_image( $image_path ) {
header( 'Content-Type: image/png' );
if ( file_exists( $image_path ) ) {
status_header( 200 );
} else {
status_header( 404 );
die("Image not found.");
exit( 'Image not found.' );
}
// Clear all output buffering to prevent any extra output
while ( ob_get_level() ) {
ob_end_clean();
}
readfile($image_path);
readfile( $image_path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_readfile
}
function save_image_to_cache($image_data, $cache_key) {
/**
* Write raw image data to the uploads directory and return the file path.
*
* @param string $image_data Raw PNG data.
* @param string $cache_key Cache key used as the filename stem.
* @return string
*/
function tony_sportspress_save_image_to_cache( $image_data, $cache_key ) {
$upload_dir = wp_get_upload_dir();
$file_path = $upload_dir['path'] . '/' . $cache_key . '.png';
// Assuming $image_data is raw image data
file_put_contents($file_path, $image_data);
file_put_contents( $file_path, $image_data ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
return $file_path;
}
/**
* Generate a bisected two-color PNG with optional team logos.
*
* @param string $color1 Hex color for the left half (e.g. #FF0000).
* @param string $color2 Hex color for the right half.
* @param string $logo1_path Absolute path to team 1 PNG logo (or empty).
* @param string $logo2_path Absolute path to team 2 PNG logo (or empty).
* @return string Raw PNG image data.
*/
function tony_sportspress_generate_bisected_image( $color1, $color2, $logo1_path, $logo2_path ) {
$width = 1200;
$height = 628;
$x_margin = 0.1 * ( $width / 2 );
$y_margin = 0.1 * $height;
$image = imagecreatetruecolor( $width, $height );
$rgb1 = sscanf( $color1, '#%02x%02x%02x' );
$rgb2 = sscanf( $color2, '#%02x%02x%02x' );
$color1_alloc = imagecolorallocate( $image, $rgb1[0], $rgb1[1], $rgb1[2] );
$color2_alloc = imagecolorallocate( $image, $rgb2[0], $rgb2[1], $rgb2[2] );
// Left trapezoid.
imagefilledpolygon(
$image,
array( 0, 0, 0, $height, $width * 0.40, $height, $width * 0.60, 0 ),
$color1_alloc
);
// Right trapezoid.
imagefilledpolygon(
$image,
array( $width, 0, $width, $height, $width * 0.40, $height, $width * 0.60, 0 ),
$color2_alloc
);
$max_logo_width = ( $width / 2 ) - ( 2 * $x_margin );
$max_logo_height = $height - ( 2 * $y_margin );
foreach ( array(
array( 'path' => $logo1_path, 'center_x' => $width / 4 ),
array( 'path' => $logo2_path, 'center_x' => 3 * $width / 4 ),
) as $logo ) {
if ( empty( $logo['path'] ) ) {
continue;
}
$src = imagecreatefrompng( $logo['path'] );
if ( ! $src ) {
continue;
}
$src_w = imagesx( $src );
$src_h = imagesy( $src );
$dst_w = $src_w;
$dst_h = $src_h;
if ( $src_w > $max_logo_width || $src_h > $max_logo_height ) {
$ratio = $src_w / $src_h;
if ( $src_w / $max_logo_width > $src_h / $max_logo_height ) {
$dst_w = $max_logo_width;
$dst_h = $max_logo_width / $ratio;
} else {
$dst_h = $max_logo_height;
$dst_w = $max_logo_height * $ratio;
}
}
$dst_x = (int) ( $logo['center_x'] - $dst_w / 2 );
$dst_y = (int) ( $height / 2 - $dst_h / 2 );
imagecopyresampled( $image, $src, $dst_x, $dst_y, 0, 0, (int) $dst_w, (int) $dst_h, $src_w, $src_h );
imagedestroy( $src );
}
ob_start();
imagepng( $image );
$image_data = (string) ob_get_clean();
imagedestroy( $image );
return $image_data;
}

View File

@@ -1,18 +1,47 @@
<?php
/*
Plugin Name: Custom Open Graph Tags with SportsPress Integration
Description: Adds custom Open Graph tags to posts based on their type, specifically handling sp_event post types with methods from the SportsPress SP_Event class.
Version: 1.0
Author: Your Name
/**
* Open Graph tags with SportsPress integration.
*
* Adds custom Open Graph meta tags to sp_event single pages.
*
* @package Tonys_Sportspress_Enhancements
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
add_action( 'wp_head', 'custom_open_graph_tags_with_sportspress_integration' );
function asc_generate_sp_event_title( $post ) {
// See https://github.com/ThemeBoy/SportsPress/blob/770fa8c6654d7d6648791e877709c2428677635b/includes/admin/post-types/class-sp-admin-cpt-event.php#L99C40-L99C55
/**
* Return the head-to-head matchup image URL for an event.
*
* @param int|WP_Post $post Post ID or object.
* @return string
*/
function asc_sp_event_matchup_image_url( $post ) {
if ( is_numeric( $post ) ) {
$post = get_post( $post );
}
if ( ! $post || 'sp_event' !== $post->post_type ) {
return '';
}
return get_site_url() . '/head-to-head?post=' . $post->ID;
}
/**
* Generate a display title for an sp_event using team short names.
*
* @param int|WP_Post $post Post ID or object.
* @return string
*/
function asc_generate_sp_event_title( $post ) {
if ( is_numeric( $post ) ) {
$post = get_post( $post );
}
if ( ! $post || $post->post_type !== 'sp_event' ) {
return get_the_title();
}
@@ -41,6 +70,13 @@ function asc_generate_sp_event_title( $post ) {
return implode( $delimiter, $team_names );
}
/**
* Format a short date string for an event.
*
* @param int|WP_Post $post Post ID or object.
* @param bool $withTime Whether to include the time.
* @return string
*/
function asc_generate_short_date( $post, $withTime = true ) {
$formatted_date = get_the_date( 'D n/j/y', $post );
@@ -48,140 +84,136 @@ function asc_generate_short_date( $post, $withTime = true ) {
return $formatted_date;
}
if ( get_the_date('i', $post) == "00") {
if ( get_the_date( 'i', $post ) === '00' ) {
$formatted_time = get_the_date( 'gA', $post );
} else {
$formatted_time = get_the_date( 'g:iA', $post );
}
return $formatted_date . " " . $formatted_time ;
return $formatted_date . ' ' . $formatted_time;
}
/**
* Output Open Graph meta tags for sp_event single pages.
*
* @return void
*/
function custom_open_graph_tags_with_sportspress_integration() {
if (is_single()) {
global $post;
if ($post->post_type === 'sp_event') {
// Instantiate SP_Event object
$event = new SP_Event($post->ID);
if ( ! is_single() ) {
return;
}
// Fetch details using SP_Event methods
$publish_date = get_the_date('F j, Y', $post);
global $post;
if ( ! $post || $post->post_type !== 'sp_event' ) {
return;
}
$event = new SP_Event( $post->ID );
$venue_terms = get_the_terms( $post->ID, 'sp_venue' );
$venue_name = $venue_terms ? $venue_terms[0]->name : 'Venue TBD';
$results = $event->results(); // Using SP_Event method
$venue_name = ( $venue_terms && ! is_wp_error( $venue_terms ) ) ? $venue_terms[0]->name : 'Venue TBD';
$title = asc_generate_sp_event_title( $post );
$sp_status = get_post_meta( $post->ID, 'sp_status', true );
$status = $event->status(); // Using SP_Event method
$status = $event->status();
$publish_date_and_time = get_the_date( 'F j, Y g:i A', $post );
$description = "{$publish_date_and_time} at {$venue_name}.";
if ( 'postponed' == $sp_status || 'cancelled' == $sp_status || 'tbd' == $sp_status) {
$description = strtoupper($sp_status) . "" . $description;
$title = strtoupper($sp_status) . "" . $title . "" . asc_generate_short_date($post) . "" . $venue_name;
}
if ( 'future' == $status ) {
$description = $description;
$title = $title . "" . asc_generate_short_date($post) . "" . $venue_name;
}
if ( 'results' == $status ) { // checks if there is a final score
// Get event result data
if ( in_array( $sp_status, array( 'postponed', 'cancelled', 'tbd' ), true ) ) {
$label = strtoupper( $sp_status );
$description = "{$label}{$description}";
$title = "{$label}{$title}" . asc_generate_short_date( $post ) . "{$venue_name}";
} elseif ( 'future' === $status ) {
$title = $title . ' — ' . asc_generate_short_date( $post ) . ' — ' . $venue_name;
} elseif ( 'results' === $status ) {
$data = $event->results();
// The first row should be column labels
$labels = $data[0];
// Remove the first row to leave us with the actual data
// First row is column labels; remove it.
unset( $data[0] );
$data = array_filter( $data );
if ( empty( $data ) ) {
return false;
}
// Initialize
$i = 0;
$result_string = '';
$title_string = '';
// Reverse teams order if the option "Events > Teams > Order > Reverse order" is enabled.
$reverse_teams = get_option( 'sportspress_event_reverse_teams', 'no' ) === 'yes' ? true : false;
if ( $reverse_teams ) {
if ( ! empty( $data ) ) {
if ( get_option( 'sportspress_event_reverse_teams', 'no' ) === 'yes' ) {
$data = array_reverse( $data, true );
}
$teams_result_array = [];
$teams_result_array = array();
foreach ( $data as $team_id => $result ) :
$outcomes = array();
foreach ( $data as $team_id => $result ) {
$result_outcome = sp_array_value( $result, 'outcome' );
if ( ! is_array( $result_outcome ) ) :
$outcomes = array( '&mdash;' );
else :
foreach ( $result_outcome as $outcome ) :
$the_outcome = get_page_by_path( $outcome, OBJECT, 'sp_outcome' );
if ( is_object( $the_outcome ) ) :
$outcomes[] = $the_outcome->post_title;
endif;
endforeach;
endif;
$the_outcome = null;
if ( is_array( $result_outcome ) ) {
foreach ( $result_outcome as $outcome_slug ) {
$found = get_page_by_path( $outcome_slug, OBJECT, 'sp_outcome' );
if ( is_object( $found ) ) {
$the_outcome = $found;
break;
}
}
}
unset( $result['outcome'] );
$team_name = sp_team_short_name( $team_id );
$team_abbreviation = sp_team_abbreviation( $team_id );
$outcome_title = $the_outcome ? $the_outcome->post_title : '';
$outcome_abbreviation = '';
if ( $the_outcome ) {
$outcome_abbreviation = get_post_meta( $the_outcome->ID, 'sp_abbreviation', true );
if ( ! $outcome_abbreviation ) {
$outcome_abbreviation = sp_substr( $the_outcome->post_title, 0, 1 );
}
}
array_push($teams_result_array, [
"result" => $result,
"outcome" => $the_outcome->post_title,
"outcome_abbreviation" => $outcome_abbreviation,
"team_name" => $team_name,
"team_abbreviation" => $team_abbreviation
]
$teams_result_array[] = array(
'result' => $result,
'outcome' => $outcome_title,
'outcome_abbreviation' => $outcome_abbreviation,
'team_name' => sp_team_short_name( $team_id ),
'team_abbreviation' => sp_team_abbreviation( $team_id ),
);
$i++;
endforeach;
$publish_date = asc_generate_short_date($post, false);
}
$special_result_suffix_abbreviation = '';
$special_result_suffix= '';
if ( count( $teams_result_array ) >= 2 ) {
$special_abbreviation = '';
$special_label = '';
foreach ( $teams_result_array as $team ) {
$outcome_abbreviation = strtoupper( $team['outcome_abbreviation'] ); // Normalize case
$abbr = strtoupper( $team['outcome_abbreviation'] );
if ( $outcome_abbreviation === 'TF-W' ) {
$special_result_suffix_abbreviation = 'TF-W';
$special_result_suffix = 'Technical Forfeit Win';
if ( 'TF-W' === $abbr ) {
$special_abbreviation = 'TF-W';
$special_label = 'Technical Forfeit Win';
break;
} elseif ( $outcome_abbreviation === 'TF-L' ) {
$special_result_suffix_abbreviation = 'TF';
$special_result_suffix = 'Technical Forfeit';
} elseif ( 'TF-L' === $abbr ) {
$special_abbreviation = 'TF';
$special_label = 'Technical Forfeit';
break;
} elseif ( $outcome_abbreviation === 'F-W' || $outcome_abbreviation === 'F-L' ) {
$special_result_suffix_abbreviation = 'Forfeit';
$special_result_suffix = 'Forfeit';
} elseif ( 'F-W' === $abbr || 'F-L' === $abbr ) {
$special_abbreviation = 'Forfeit';
$special_label = 'Forfeit';
break;
}
}
$title = "{$teams_result_array[0]['team_name']} {$teams_result_array[0]['result']['r']}-{$teams_result_array[1]['result']['r']} {$teams_result_array[1]['team_name']}{$publish_date}" . ($special_result_suffix ? "({$special_result_suffix_abbreviation})" : "");
$description .= " " . "{$teams_result_array[0]['team_name']} ({$teams_result_array[0]['outcome']}), {$teams_result_array[1]['team_name']} ({$teams_result_array[1]['outcome']})." ;
$short_date = asc_generate_short_date( $post, false );
$t0 = $teams_result_array[0];
$t1 = $teams_result_array[1];
$score = isset( $t0['result']['r'] ) && isset( $t1['result']['r'] )
? "{$t0['result']['r']}-{$t1['result']['r']}"
: '';
$suffix = $special_label ? " ({$special_abbreviation})" : '';
$title = "{$t0['team_name']} {$score} {$t1['team_name']}{$short_date}{$suffix}";
$description .= " {$t0['team_name']} ({$t0['outcome']}), {$t1['team_name']} ({$t1['outcome']}).";
}
$description .= " " . $post->post_content;
$image = get_site_url() . "/head-to-head?post={$post->ID}";
}
}
$description .= ' ' . $post->post_content;
$image = asc_sp_event_matchup_image_url( $post );
echo '<meta property="og:type" content="article" />' . "\n";
echo '<meta property="og:image" content="'. $image . '" />' . "\n";
echo '<meta property="og:title" content="' . $title . '" />' . "\n";
echo '<meta property="og:description" content="' . $description . '" />' . "\n";
echo '<meta property="og:url" content="' . get_permalink() . '" />' . "\n";
echo '<meta property="og:image" content="' . esc_url( $image ) . '" />' . "\n";
echo '<meta property="og:title" content="' . esc_attr( $title ) . '" />' . "\n";
echo '<meta property="og:description" content="' . esc_attr( $description ) . '" />' . "\n";
echo '<meta property="og:url" content="' . esc_url( get_permalink() ) . '" />' . "\n";
}
}
}
?>

View File

@@ -18,7 +18,7 @@ if ( ! defined( 'ABSPATH' ) ) {
function tony_sportspress_event_filter_defaults() {
return array(
'month' => true,
'week' => true,
'week' => false,
'team' => true,
'venue' => true,
'league' => true,
@@ -37,6 +37,52 @@ function tony_sportspress_event_filter_meta_key( $key ) {
return 'tony_sp_event_filter_' . $key;
}
/**
* Get the current singular label for event venues.
*
* @return string
*/
function tony_sportspress_get_event_venue_label() {
$taxonomy = get_taxonomy( 'sp_venue' );
if ( $taxonomy && ! empty( $taxonomy->labels->singular_name ) ) {
return (string) $taxonomy->labels->singular_name;
}
return __( 'Venue', 'sportspress' );
}
/**
* Get the current plural label for event venues.
*
* @return string
*/
function tony_sportspress_get_event_venue_label_plural() {
$taxonomy = get_taxonomy( 'sp_venue' );
if ( $taxonomy && ! empty( $taxonomy->labels->name ) ) {
return (string) $taxonomy->labels->name;
}
return __( 'Venues', 'sportspress' );
}
/**
* Normalize event filter visibility rules.
*
* Month/Year and Week are mutually exclusive.
*
* @param array<string, bool> $filters Filter states keyed by filter name.
* @return array<string, bool>
*/
function tony_sportspress_normalize_event_filter_states( $filters ) {
if ( ! empty( $filters['month'] ) && ! empty( $filters['week'] ) ) {
$filters['week'] = false;
}
return $filters;
}
/**
* Check whether a filter is enabled for the current user.
*
@@ -44,7 +90,7 @@ function tony_sportspress_event_filter_meta_key( $key ) {
* @return bool
*/
function tony_sportspress_event_filter_enabled( $key ) {
$defaults = tony_sportspress_event_filter_defaults();
$defaults = tony_sportspress_normalize_event_filter_states( tony_sportspress_event_filter_defaults() );
if ( ! array_key_exists( $key, $defaults ) ) {
return true;
}
@@ -59,7 +105,15 @@ function tony_sportspress_event_filter_enabled( $key ) {
return (bool) $defaults[ $key ];
}
return '1' === (string) $stored;
$states = array();
foreach ( $defaults as $filter_key => $enabled ) {
$current = get_user_meta( $user_id, tony_sportspress_event_filter_meta_key( $filter_key ), true );
$states[ $filter_key ] = '' === $current ? (bool) $enabled : '1' === (string) $current;
}
$states = tony_sportspress_normalize_event_filter_states( $states );
return ! empty( $states[ $key ] );
}
/**
@@ -72,13 +126,21 @@ function tony_sportspress_save_event_filter_screen_options_ajax() {
check_ajax_referer( 'tony_sp_event_filters', 'nonce' );
$defaults = tony_sportspress_event_filter_defaults();
$defaults = tony_sportspress_normalize_event_filter_states( tony_sportspress_event_filter_defaults() );
$filters = isset( $_POST['filters'] ) && is_array( $_POST['filters'] ) ? $_POST['filters'] : array();
$user_id = get_current_user_id();
$states = array();
foreach ( $defaults as $key => $_enabled ) {
$value = isset( $filters[ $key ] ) ? sanitize_text_field( wp_unslash( $filters[ $key ] ) ) : '0';
update_user_meta( $user_id, tony_sportspress_event_filter_meta_key( $key ), '1' === $value ? '1' : '0' );
$states[ $key ] = '1' === $value;
}
$states = tony_sportspress_normalize_event_filter_states( $states );
foreach ( $states as $key => $enabled ) {
update_user_meta( $user_id, tony_sportspress_event_filter_meta_key( $key ), $enabled ? '1' : '0' );
}
wp_send_json_success();
@@ -99,9 +161,9 @@ function tony_sportspress_event_filter_screen_options_markup( $settings, $screen
$labels = array(
'month' => __( 'Month/Year', 'tonys-sportspress-enhancements' ),
'week' => __( 'Week', 'tonys-sportspress-enhancements' ),
'week' => __( 'Year/Week', 'tonys-sportspress-enhancements' ),
'team' => __( 'Team', 'tonys-sportspress-enhancements' ),
'venue' => __( 'Venue', 'tonys-sportspress-enhancements' ),
'venue' => tony_sportspress_get_event_venue_label(),
'league' => __( 'League', 'tonys-sportspress-enhancements' ),
'season' => __( 'Season', 'tonys-sportspress-enhancements' ),
'match_day' => __( 'Match Day', 'tonys-sportspress-enhancements' ),
@@ -136,6 +198,20 @@ function tony_sportspress_parse_admin_week_filter() {
}
$raw = sanitize_text_field( wp_unslash( $_GET['sp_week_filter'] ) );
$timezone = wp_timezone();
if ( 'this-week' === $raw || 'next-week' === $raw ) {
$base = new DateTimeImmutable( 'now', $timezone );
if ( 'next-week' === $raw ) {
$base = $base->modify( '+1 week' );
}
return array(
'year' => (int) $base->format( 'o' ),
'week' => (int) $base->format( 'W' ),
);
}
if ( ! preg_match( '/^(\d{4})-W(0[1-9]|[1-4][0-9]|5[0-3])$/', $raw, $matches ) ) {
return null;
}
@@ -149,6 +225,66 @@ function tony_sportspress_parse_admin_week_filter() {
);
}
/**
* Get available ISO week options from event post dates.
*
* @return array<int, array{value:string,label:string}>
*/
function tony_sportspress_get_admin_week_filter_options() {
global $wpdb;
$results = $wpdb->get_results(
$wpdb->prepare(
"SELECT DISTINCT DATE_FORMAT(post_date, '%%x-W%%v') AS iso_week
FROM {$wpdb->posts}
WHERE post_type = %s
AND post_status NOT IN ('auto-draft', 'trash')
AND post_date IS NOT NULL
AND post_date <> '0000-00-00 00:00:00'
ORDER BY iso_week DESC",
'sp_event'
),
ARRAY_A
);
if ( ! is_array( $results ) || empty( $results ) ) {
return array();
}
$options = array();
$timezone = wp_timezone();
foreach ( $results as $result ) {
if ( empty( $result['iso_week'] ) || ! preg_match( '/^(\d{4})-W(0[1-9]|[1-4][0-9]|5[0-3])$/', $result['iso_week'], $matches ) ) {
continue;
}
$year = (int) $matches[1];
$week = (int) $matches[2];
$monday = ( new DateTimeImmutable( 'now', $timezone ) )->setISODate( $year, $week, 1 )->setTime( 0, 0, 0 );
$sunday = $monday->modify( '+6 days' );
$start_label = wp_date( 'M j', $monday->getTimestamp(), $timezone );
$end_label = wp_date(
$monday->format( 'n' ) === $sunday->format( 'n' ) ? 'j' : 'M j',
$sunday->getTimestamp(),
$timezone
);
$options[] = array(
'value' => $result['iso_week'],
/* translators: 1: ISO week code, 2: Monday date, 3: Sunday date. */
'label' => sprintf(
__( '%1$s (%2$s to %3$s)', 'tonys-sportspress-enhancements' ),
$result['iso_week'],
$start_label,
$end_label
),
);
}
return $options;
}
/**
* Render week filter control in event admin list.
*
@@ -166,31 +302,24 @@ function tony_sportspress_render_admin_week_filter( $post_type ) {
if ( ! empty( $_GET['sp_week_filter'] ) ) {
$value = sanitize_text_field( wp_unslash( $_GET['sp_week_filter'] ) );
}
$summary_text = __( 'Select a week', 'tonys-sportspress-enhancements' );
$parsed = tony_sportspress_parse_admin_week_filter();
if ( is_array( $parsed ) ) {
$timezone = wp_timezone();
$monday = ( new DateTimeImmutable( 'now', $timezone ) )->setISODate( $parsed['year'], $parsed['week'], 1 )->setTime( 0, 0, 0 );
$sunday = $monday->modify( '+6 days' )->setTime( 23, 59, 59 );
/* translators: 1: Monday label/date, 2: Sunday label/date. */
$summary_text = sprintf(
__( '%1$s to %2$s', 'tonys-sportspress-enhancements' ),
wp_date( 'D M j, Y', $monday->getTimestamp(), $timezone ),
wp_date( 'D M j, Y', $sunday->getTimestamp(), $timezone )
);
}
$options = tony_sportspress_get_admin_week_filter_options();
?>
<label for="sp_week_filter" class="screen-reader-text"><?php esc_html_e( 'Filter by week', 'tonys-sportspress-enhancements' ); ?></label>
<input
type="week"
<select
id="sp_week_filter"
name="sp_week_filter"
class="sp-week-filter-field"
value="<?php echo esc_attr( $value ); ?>"
title="<?php esc_attr_e( 'Week (Monday start)', 'tonys-sportspress-enhancements' ); ?>"
/>
<span id="sp-week-filter-summary" class="sp-week-filter-summary"><?php echo esc_html( $summary_text ); ?></span>
>
<option value=""><?php esc_html_e( 'Year/Week', 'tonys-sportspress-enhancements' ); ?></option>
<option value="this-week" <?php selected( $value, 'this-week' ); ?>><?php esc_html_e( 'This week', 'tonys-sportspress-enhancements' ); ?></option>
<option value="next-week" <?php selected( $value, 'next-week' ); ?>><?php esc_html_e( 'Next week', 'tonys-sportspress-enhancements' ); ?></option>
<?php foreach ( $options as $option ) : ?>
<option value="<?php echo esc_attr( $option['value'] ); ?>" <?php selected( $value, $option['value'] ); ?>>
<?php echo esc_html( $option['label'] ); ?>
</option>
<?php endforeach; ?>
</select>
<?php
}
add_action( 'restrict_manage_posts', 'tony_sportspress_render_admin_week_filter' );
@@ -241,8 +370,7 @@ function tony_sportspress_admin_week_filter_styles() {
.post-type-sp_event .tablenav.top .alignleft.actions:not(.bulkactions) input[name="match_day"] { display: none !important; }
<?php endif; ?>
<?php if ( $hide['week'] ) : ?>
.post-type-sp_event .tablenav.top .alignleft.actions:not(.bulkactions) #sp_week_filter,
.post-type-sp_event .tablenav.top .alignleft.actions:not(.bulkactions) #sp-week-filter-summary { display: none !important; }
.post-type-sp_event .tablenav.top .alignleft.actions:not(.bulkactions) #sp_week_filter { display: none !important; }
<?php endif; ?>
@media (max-width: 1200px) {
.post-type-sp_event .tablenav.top .alignleft.actions:not(.bulkactions) {
@@ -258,14 +386,6 @@ function tony_sportspress_admin_week_filter_styles() {
.post-type-sp_event .tablenav.top .alignleft.actions:not(.bulkactions) .sp-week-filter-field {
min-width: 145px;
}
.post-type-sp_event .tablenav.top .alignleft.actions:not(.bulkactions) .sp-week-filter-summary {
display: block;
width: 100%;
margin-top: 2px;
color: #50575e;
font-size: 12px;
line-height: 1.4;
}
}
</style>
<?php
@@ -273,19 +393,41 @@ function tony_sportspress_admin_week_filter_styles() {
add_action( 'admin_head-edit.php', 'tony_sportspress_admin_week_filter_styles' );
/**
* Update week summary text when week input changes.
* Update admin filter labels and persist screen options.
*/
function tony_sportspress_admin_week_filter_script() {
$screen = get_current_screen();
if ( ! $screen || 'edit-sp_event' !== $screen->id ) {
return;
}
$venue_filter_text = sprintf(
/* translators: %s: plural venue label. */
__( 'Show all %s', 'sportspress' ),
strtolower( tony_sportspress_get_event_venue_label_plural() )
);
?>
<script>
(function() {
const filterCheckboxes = Array.from(
document.querySelectorAll('#screen-options-wrap input[type="checkbox"][id^="tony_sp_event_filter_"]')
);
const monthCheckbox = document.getElementById('tony_sp_event_filter_month');
const weekCheckbox = document.getElementById('tony_sp_event_filter_week');
function syncExclusiveFilters(changedCheckbox) {
if (!changedCheckbox || !changedCheckbox.checked) {
return;
}
if (changedCheckbox === monthCheckbox && weekCheckbox) {
weekCheckbox.checked = false;
}
if (changedCheckbox === weekCheckbox && monthCheckbox) {
monthCheckbox.checked = false;
}
}
function saveFilterPrefs() {
if (!filterCheckboxes.length || typeof ajaxurl === 'undefined') {
@@ -313,7 +455,10 @@ function tony_sportspress_admin_week_filter_script() {
}
filterCheckboxes.forEach(function(checkbox) {
checkbox.addEventListener('change', saveFilterPrefs);
checkbox.addEventListener('change', function() {
syncExclusiveFilters(checkbox);
saveFilterPrefs();
});
});
const monthSelect = document.querySelector('select[name="m"]');
@@ -324,46 +469,13 @@ function tony_sportspress_admin_week_filter_script() {
}
}
const input = document.getElementById('sp_week_filter');
const summary = document.getElementById('sp-week-filter-summary');
if (!input || !summary) {
return;
const venueSelect = document.querySelector('select[name="sp_venue"]');
if (venueSelect) {
const allVenues = venueSelect.querySelector('option[value="0"]');
if (allVenues) {
allVenues.textContent = <?php echo wp_json_encode( $venue_filter_text ); ?>;
}
function updateSummary() {
const raw = (input.value || '').trim();
const match = raw.match(/^(\d{4})-W(\d{2})$/);
if (!match) {
summary.textContent = 'Select a week';
return;
}
const year = parseInt(match[1], 10);
const week = parseInt(match[2], 10);
const jan4 = new Date(Date.UTC(year, 0, 4));
const jan4Day = jan4.getUTCDay() || 7;
const mondayWeek1 = new Date(jan4);
mondayWeek1.setUTCDate(jan4.getUTCDate() - jan4Day + 1);
const monday = new Date(mondayWeek1);
monday.setUTCDate(mondayWeek1.getUTCDate() + (week - 1) * 7);
const sunday = new Date(monday);
sunday.setUTCDate(monday.getUTCDate() + 6);
const fmt = new Intl.DateTimeFormat(undefined, {
weekday: 'short',
month: 'short',
day: 'numeric',
year: 'numeric',
timeZone: 'UTC'
});
summary.textContent = fmt.format(monday) + ' to ' + fmt.format(sunday);
}
input.addEventListener('change', updateSummary);
updateSummary();
})();
</script>
<?php

View File

@@ -53,6 +53,7 @@ function tse_sp_event_export_get_column_definitions() {
'away_team' => __( 'Away Team', 'tonys-sportspress-enhancements' ),
'home_team' => __( 'Home Team', 'tonys-sportspress-enhancements' ),
'field_name' => __( 'Field Name', 'tonys-sportspress-enhancements' ),
'field_address' => __( 'Field Address', 'tonys-sportspress-enhancements' ),
'officials' => __( 'Officials', 'tonys-sportspress-enhancements' ),
),
'team' => array(
@@ -65,6 +66,7 @@ function tse_sp_event_export_get_column_definitions() {
'opponent_name' => __( 'Opponent', 'tonys-sportspress-enhancements' ),
'location_flag' => __( 'Home/Away', 'tonys-sportspress-enhancements' ),
'field_name' => __( 'Field Name', 'tonys-sportspress-enhancements' ),
'field_address' => __( 'Field Address', 'tonys-sportspress-enhancements' ),
'field_abbreviation' => __( 'Field Abbreviation', 'tonys-sportspress-enhancements' ),
'field_short_name' => __( 'Field Short Name', 'tonys-sportspress-enhancements' ),
'officials' => __( 'Officials', 'tonys-sportspress-enhancements' ),
@@ -332,6 +334,7 @@ function tse_sp_event_export_get_events( $filters ) {
'home_team' => $home_id > 0 ? get_the_title( $home_id ) : '',
'away_team' => $away_id > 0 ? get_the_title( $away_id ) : '',
'field_name' => isset( $venue['name'] ) ? $venue['name'] : '',
'field_address' => isset( $venue['address'] ) ? $venue['address'] : '',
'field_abbreviation' => isset( $venue['abbreviation'] ) ? $venue['abbreviation'] : '',
'field_short_name' => isset( $venue['short_name'] ) ? $venue['short_name'] : '',
'season' => tse_sp_event_export_get_event_term_names( $event_id, 'sp_season' ),
@@ -380,15 +383,18 @@ function tse_sp_event_export_get_primary_field( $event_id ) {
if ( ! is_array( $venues ) || ! isset( $venues[0] ) || ! $venues[0] instanceof WP_Term ) {
return array(
'name' => '',
'address' => '',
'abbreviation' => '',
'short_name' => '',
);
}
$venue = $venues[0];
$meta = get_option( 'taxonomy_' . $venue->term_id );
return array(
'name' => isset( $venue->name ) ? (string) $venue->name : '',
'address' => is_array( $meta ) && isset( $meta['sp_address'] ) ? trim( (string) $meta['sp_address'] ) : '',
'abbreviation' => trim( (string) get_term_meta( $venue->term_id, 'tse_abbreviation', true ) ),
'short_name' => trim( (string) get_term_meta( $venue->term_id, 'tse_short_name', true ) ),
);

View File

@@ -1,16 +1,19 @@
<?php
/*
Plugin Name: Custom Event Permalinks
Description: Adds a custom permalink structure for the sp_event post type.
Version: 1.0
Author: Your Name
/**
* Custom permalink structure for sp_event post type.
*
* @package Tonys_Sportspress_Enhancements
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
exit;
}
// Register custom rewrite rules
/**
* Register custom rewrite rules for sp_event.
*
* @return void
*/
function custom_event_rewrite_rules() {
add_rewrite_rule(
'(?:event|game)/.*?[/]?([0-9]+)[/]?$',
@@ -20,54 +23,58 @@ function custom_event_rewrite_rules() {
}
add_action( 'init', 'custom_event_rewrite_rules' );
// Customize the permalink structure
/**
* Customize the permalink structure for sp_event posts.
*
* @param string $permalink Existing permalink.
* @param WP_Post $post Post object.
* @return string
*/
function custom_event_permalink( $permalink, $post ) {
if ( $post->post_type !== 'sp_event' ) {
return $permalink;
}
$event = new SP_Event($post->ID);
$teams = get_post_meta( $post->ID, 'sp_team', false );
$format = get_post_meta( $post->ID, 'sp_format', true );
sort( $teams );
$seasons = get_the_terms( $post->ID, 'sp_season', true );
if ( $seasons ) {
$seasons_slug = implode(
"-",
array_map(function($season){return $season->slug;},$seasons),
'-',
array_map( function( $season ) { return $season->slug; }, $seasons )
);
} else {
$seasons_slug = "no-season";
};
$seasons_slug = 'no-season';
}
// Get the teams associated with the event
$team_1 = get_post($teams[0]);
$team_2 = get_post($teams[1]);
$team_1 = isset( $teams[0] ) ? get_post( $teams[0] ) : null;
$team_2 = isset( $teams[1] ) ? get_post( $teams[1] ) : null;
switch ( $format ) {
case 'league':
$format_string = 'game';
break;
case 'tournament':
$format_string = 'game';
break;
case 'friendly':
$format_string = 'event';
break;
default:
$format_string = 'event';
break;
}
if ( $team_1 && $team_2 ) {
$permalink = home_url($format_string ."/". $seasons_slug . '/' . $team_1->post_name . '-' . $team_2->post_name . '/' . $post->ID);
$permalink = home_url( $format_string . '/' . $seasons_slug . '/' . $team_1->post_name . '-' . $team_2->post_name . '/' . $post->ID );
}
return $permalink;
}
add_filter( 'post_type_link', 'custom_event_permalink', 10, 2 );
// Flush rewrite rules on activation and deactivation
/**
* Flush rewrite rules on activation.
*
* @return void
*/
function custom_event_rewrite_flush() {
custom_event_rewrite_rules();
flush_rewrite_rules();
@@ -75,7 +82,12 @@ function custom_event_rewrite_flush() {
register_activation_hook( __FILE__, 'custom_event_rewrite_flush' );
register_deactivation_hook( __FILE__, 'flush_rewrite_rules' );
// Modify the front-end single event query to allow scheduled events to resolve.
/**
* Allow scheduled events to resolve on the frontend.
*
* @param WP_Query $query Current query.
* @return void
*/
function custom_event_parse_request( $query ) {
if ( ! $query instanceof WP_Query ) {
return;

View File

@@ -7,6 +7,89 @@ if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Add an Officials column to the event admin list.
*
* @param array $columns Existing columns.
* @return array
*/
function tony_sportspress_event_add_officials_column( $columns ) {
$updated = array();
foreach ( $columns as $key => $label ) {
$updated[ $key ] = $label;
if ( 'sp_team' === $key ) {
$updated['tony_sp_officials'] = esc_html__( 'Officials', 'tonys-sportspress-enhancements' );
}
}
if ( ! isset( $updated['tony_sp_officials'] ) ) {
$updated['tony_sp_officials'] = esc_html__( 'Officials', 'tonys-sportspress-enhancements' );
}
return $updated;
}
add_filter( 'manage_edit-sp_event_columns', 'tony_sportspress_event_add_officials_column', 20 );
/**
* Build a display-ready officials map for an event.
*
* @param int $post_id Post ID.
* @return array<int, array{name: string, officials: string[]}>
*/
function tony_sportspress_event_get_officials_display( $post_id ) {
$officials_by_duty = get_post_meta( $post_id, 'sp_officials', true );
if ( ! is_array( $officials_by_duty ) || empty( $officials_by_duty ) ) {
return array();
}
$duties = get_terms(
array(
'taxonomy' => 'sp_duty',
'hide_empty' => false,
)
);
$duty_names = array();
if ( is_array( $duties ) ) {
foreach ( $duties as $duty ) {
if ( isset( $duty->term_id, $duty->name ) ) {
$duty_names[ (int) $duty->term_id ] = $duty->name;
}
}
}
$rows = array();
foreach ( $officials_by_duty as $duty_id => $official_ids ) {
$duty_id = absint( $duty_id );
$official_ids = array_filter( array_map( 'absint', (array) $official_ids ) );
if ( $duty_id <= 0 || empty( $official_ids ) ) {
continue;
}
$names = array();
foreach ( $official_ids as $official_id ) {
$title = get_the_title( $official_id );
if ( is_string( $title ) && '' !== $title ) {
$names[] = $title;
}
}
if ( empty( $names ) ) {
continue;
}
$rows[] = array(
'name' => isset( $duty_names[ $duty_id ] ) ? $duty_names[ $duty_id ] : (string) $duty_id,
'officials' => $names,
);
}
return $rows;
}
/**
* Print hidden officials data on each event row for quick edit prefill.
*
@@ -14,7 +97,7 @@ if ( ! defined( 'ABSPATH' ) ) {
* @param int $post_id Post ID.
*/
function tony_sportspress_event_quick_edit_officials_row_data( $column, $post_id ) {
if ( 'sp_team' !== $column ) {
if ( 'tony_sp_officials' !== $column ) {
return;
}
@@ -28,6 +111,18 @@ function tony_sportspress_event_quick_edit_officials_row_data( $column, $post_id
$serialized = '{}';
}
$rows = tony_sportspress_event_get_officials_display( $post_id );
if ( empty( $rows ) ) {
echo '&mdash;';
} else {
foreach ( $rows as $row ) {
echo '<div class="tony-sp-event-official-row">';
echo '<strong>' . esc_html( $row['name'] ) . ':</strong> ';
echo esc_html( implode( ', ', $row['officials'] ) );
echo '</div>';
}
}
echo '<span class="hidden tony-event-officials-data" data-officials="' . esc_attr( $serialized ) . '"></span>';
}
add_action( 'manage_sp_event_posts_custom_column', 'tony_sportspress_event_quick_edit_officials_row_data', 20, 2 );
@@ -39,7 +134,7 @@ add_action( 'manage_sp_event_posts_custom_column', 'tony_sportspress_event_quick
* @param string $post_type Post type key.
*/
function tony_sportspress_event_quick_edit_officials_field( $column_name, $post_type ) {
if ( 'sp_event' !== $post_type || 'sp_team' !== $column_name ) {
if ( 'sp_event' !== $post_type || 'tony_sp_officials' !== $column_name ) {
return;
}

View File

@@ -0,0 +1,306 @@
<?php
/**
* GitHub release updater for the plugin.
*
* @package Tonys_Sportspress_Enhancements
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! defined( 'TONY_SPORTSPRESS_ENHANCEMENTS_GITHUB_REPO' ) ) {
define( 'TONY_SPORTSPRESS_ENHANCEMENTS_GITHUB_REPO', 'anthonyscorrea/tonys-sportspress-enhancements' );
}
if ( ! class_exists( 'Tony_Sportspress_GitHub_Updater' ) ) {
/**
* Integrates WordPress plugin updates with GitHub Releases.
*/
class Tony_Sportspress_GitHub_Updater {
/**
* GitHub API URL for the latest release.
*
* @var string
*/
private $release_api_url;
/**
* Plugin basename.
*
* @var string
*/
private $plugin_basename;
/**
* Plugin slug.
*
* @var string
*/
private $plugin_slug;
/**
* Cache key for release metadata.
*
* @var string
*/
private $cache_key = 'tony_sportspress_github_release';
/**
* Constructor.
*/
public function __construct() {
$this->release_api_url = sprintf(
'https://api.github.com/repos/%s/releases/latest',
TONY_SPORTSPRESS_ENHANCEMENTS_GITHUB_REPO
);
$this->plugin_basename = TONY_SPORTSPRESS_ENHANCEMENTS_PLUGIN_BASENAME;
$this->plugin_slug = dirname( $this->plugin_basename );
add_filter( 'pre_set_site_transient_update_plugins', array( $this, 'inject_update' ) );
add_filter( 'plugins_api', array( $this, 'plugin_information' ), 20, 3 );
add_filter( 'upgrader_source_selection', array( $this, 'normalize_source_directory' ), 10, 4 );
add_action( 'upgrader_process_complete', array( $this, 'purge_release_cache' ), 10, 2 );
}
/**
* Adds plugin update data to WordPress' update transient.
*
* @param stdClass $transient Existing update transient.
* @return stdClass
*/
public function inject_update( $transient ) {
if ( ! is_object( $transient ) || empty( $transient->checked ) ) {
return $transient;
}
$release = $this->get_latest_release();
if ( ! $release ) {
return $transient;
}
$remote_version = $this->normalize_version( $release['version'] );
$current_version = $this->normalize_version( TONY_SPORTSPRESS_ENHANCEMENTS_VERSION );
if ( version_compare( $remote_version, $current_version, '<=' ) ) {
return $transient;
}
$transient->response[ $this->plugin_basename ] = (object) array(
'id' => $release['url'],
'slug' => $this->plugin_slug,
'plugin' => $this->plugin_basename,
'new_version' => $remote_version,
'url' => $release['url'],
'package' => $release['package'],
'tested' => '',
'requires_php' => '',
'icons' => array(),
'banners' => array(),
'banners_rtl' => array(),
'translations' => array(),
);
return $transient;
}
/**
* Provides plugin information for the update details modal.
*
* @param false|object|array $result Existing result.
* @param string $action API action.
* @param object $args API args.
* @return false|object|array
*/
public function plugin_information( $result, $action, $args ) {
if ( 'plugin_information' !== $action || empty( $args->slug ) || $this->plugin_slug !== $args->slug ) {
return $result;
}
$release = $this->get_latest_release();
if ( ! $release ) {
return $result;
}
return (object) array(
'name' => 'Tonys SportsPress Enhancements',
'slug' => $this->plugin_slug,
'version' => $this->normalize_version( $release['version'] ),
'author' => '<a href="https://github.com/anthonyscorrea/">Tony Correa</a>',
'author_profile'=> 'https://github.com/anthonyscorrea/',
'homepage' => $release['url'],
'download_link' => $release['package'],
'sections' => array(
'description' => wp_kses_post( wpautop( 'Suite of SportsPress Enhancements.' ) ),
'changelog' => wp_kses_post( wpautop( $release['body'] ) ),
),
);
}
/**
* Ensures GitHub's extracted directory name matches the installed plugin slug.
*
* @param string $source Source file location.
* @param string $remote_source Remote file source location.
* @param WP_Upgrader $upgrader Upgrader instance.
* @param array $hook_extra Extra hook arguments.
* @return string|WP_Error
*/
public function normalize_source_directory( $source, $remote_source, $upgrader, $hook_extra ) {
global $wp_filesystem;
if ( empty( $hook_extra['plugin'] ) || $this->plugin_basename !== $hook_extra['plugin'] ) {
return $source;
}
$expected_dir = trailingslashit( $remote_source ) . $this->plugin_slug;
if ( untrailingslashit( $source ) === untrailingslashit( $expected_dir ) ) {
return $source;
}
if ( ! $wp_filesystem ) {
return $source;
}
if ( $wp_filesystem->exists( $expected_dir ) ) {
$wp_filesystem->delete( $expected_dir, true );
}
if ( ! $wp_filesystem->move( $source, $expected_dir ) ) {
return new WP_Error(
'tony_sportspress_updater_rename_failed',
__( 'The plugin update package could not be prepared for installation.', 'tonys-sportspress-enhancements' )
);
}
return $expected_dir;
}
/**
* Clears cached release metadata after plugin updates complete.
*
* @param WP_Upgrader $upgrader Upgrader instance.
* @param array $hook_extra Extra hook arguments.
* @return void
*/
public function purge_release_cache( $upgrader, $hook_extra ) {
if ( empty( $hook_extra['type'] ) || 'plugin' !== $hook_extra['type'] ) {
return;
}
if ( empty( $hook_extra['plugins'] ) || ! in_array( $this->plugin_basename, (array) $hook_extra['plugins'], true ) ) {
return;
}
delete_site_transient( $this->cache_key );
}
/**
* Reads and caches the latest GitHub release metadata.
*
* @return array|null
*/
private function get_latest_release() {
$cached = get_site_transient( $this->cache_key );
if ( is_array( $cached ) ) {
return $cached;
}
$response = wp_remote_get(
$this->release_api_url,
array(
'timeout' => 15,
'headers' => array(
'Accept' => 'application/vnd.github+json',
'User-Agent' => 'WordPress/' . get_bloginfo( 'version' ) . '; ' . home_url( '/' ),
),
)
);
if ( is_wp_error( $response ) ) {
return null;
}
if ( 200 !== (int) wp_remote_retrieve_response_code( $response ) ) {
return null;
}
$data = json_decode( wp_remote_retrieve_body( $response ), true );
if ( ! is_array( $data ) || empty( $data['tag_name'] ) || empty( $data['html_url'] ) ) {
return null;
}
$release = array(
'version' => $data['tag_name'],
'url' => $data['html_url'],
'body' => isset( $data['body'] ) ? (string) $data['body'] : '',
'package' => $this->determine_package_url( $data ),
);
if ( empty( $release['package'] ) ) {
return null;
}
set_site_transient( $this->cache_key, $release, 6 * HOUR_IN_SECONDS );
return $release;
}
/**
* Selects the best package URL from a release payload.
*
* @param array $release GitHub release payload.
* @return string
*/
private function determine_package_url( $release ) {
if ( ! empty( $release['assets'] ) && is_array( $release['assets'] ) ) {
$fallback_asset = '';
foreach ( $release['assets'] as $asset ) {
if ( empty( $asset['browser_download_url'] ) || empty( $asset['name'] ) ) {
continue;
}
if ( '.zip' !== strtolower( substr( $asset['name'], -4 ) ) ) {
continue;
}
if ( false !== strpos( $asset['name'], $this->plugin_slug ) ) {
return $asset['browser_download_url'];
}
if ( empty( $fallback_asset ) ) {
$fallback_asset = $asset['browser_download_url'];
}
}
if ( ! empty( $fallback_asset ) ) {
return $fallback_asset;
}
}
if ( ! empty( $release['zipball_url'] ) ) {
return $release['zipball_url'];
}
return '';
}
/**
* Normalizes release versions so Git tags like v1.2.3 compare correctly.
*
* @param string $version Version string.
* @return string
*/
private function normalize_version( $version ) {
return ltrim( (string) $version, "vV \t\n\r\0\x0B" );
}
}
new Tony_Sportspress_GitHub_Updater();
}

View File

@@ -0,0 +1,420 @@
<?php
/**
* Officials Manager role and capability restrictions.
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! defined( 'TONY_SPORTSPRESS_OFFICIALS_MANAGER_ROLE' ) ) {
define( 'TONY_SPORTSPRESS_OFFICIALS_MANAGER_ROLE', 'sp_officials_manager' );
}
/**
* Build the primitive capabilities for a custom post type.
*
* @param string $singular Singular capability base.
* @param string $plural Plural capability base.
* @return string[]
*/
function tony_sportspress_build_post_type_caps( $singular, $plural ) {
return array(
"edit_{$singular}",
"read_{$singular}",
"delete_{$singular}",
"edit_{$plural}",
"edit_others_{$plural}",
"publish_{$plural}",
"read_private_{$plural}",
"delete_{$plural}",
"delete_private_{$plural}",
"delete_published_{$plural}",
"delete_others_{$plural}",
"edit_private_{$plural}",
"edit_published_{$plural}",
);
}
/**
* Get officials manager role capabilities.
*
* @return array<string, bool>
*/
function tony_sportspress_get_officials_manager_caps() {
$caps = array(
'read' => true,
'edit_posts' => true,
'delete_posts' => true,
'edit_published_posts' => true,
);
foreach ( tony_sportspress_build_post_type_caps( 'sp_official', 'sp_officials' ) as $cap ) {
$caps[ $cap ] = true;
}
// Allow access to the event list and quick edit for assignments, without full event management.
$caps['read_sp_event'] = true;
$caps['edit_sp_event'] = true;
$caps['edit_sp_events'] = true;
$caps['edit_others_sp_events'] = true;
$caps['edit_published_sp_events'] = true;
$caps['read_private_sp_events'] = true;
return $caps;
}
/**
* Get the capabilities managed for the officials manager role.
*
* @return string[]
*/
function tony_sportspress_get_officials_manager_managed_caps() {
return array_keys( tony_sportspress_get_officials_manager_caps() );
}
/**
* Grant custom official caps to existing roles that already have matching event caps.
*
* This preserves existing access after moving officials off the `sp_event` capability type.
*
* @return void
*/
function tony_sportspress_sync_official_caps_to_existing_roles() {
global $wp_roles;
if ( ! class_exists( 'WP_Roles' ) ) {
return;
}
if ( ! isset( $wp_roles ) ) {
$wp_roles = wp_roles();
}
if ( ! $wp_roles instanceof WP_Roles ) {
return;
}
$cap_map = array(
'edit_sp_event' => 'edit_sp_official',
'read_sp_event' => 'read_sp_official',
'delete_sp_event' => 'delete_sp_official',
'edit_sp_events' => 'edit_sp_officials',
'edit_others_sp_events' => 'edit_others_sp_officials',
'publish_sp_events' => 'publish_sp_officials',
'read_private_sp_events' => 'read_private_sp_officials',
'delete_sp_events' => 'delete_sp_officials',
'delete_private_sp_events' => 'delete_private_sp_officials',
'delete_published_sp_events' => 'delete_published_sp_officials',
'delete_others_sp_events' => 'delete_others_sp_officials',
'edit_private_sp_events' => 'edit_private_sp_officials',
'edit_published_sp_events' => 'edit_published_sp_officials',
);
foreach ( $wp_roles->role_objects as $role ) {
if ( ! $role instanceof WP_Role ) {
continue;
}
foreach ( $cap_map as $event_cap => $official_cap ) {
if ( $role->has_cap( $event_cap ) ) {
$role->add_cap( $official_cap );
}
}
}
}
/**
* Create or update the officials manager role.
*
* @return void
*/
function tony_sportspress_sync_officials_manager_roles() {
$role = get_role( TONY_SPORTSPRESS_OFFICIALS_MANAGER_ROLE );
if ( ! $role ) {
$role = add_role(
TONY_SPORTSPRESS_OFFICIALS_MANAGER_ROLE,
__( 'Officials Manager', 'tonys-sportspress-enhancements' ),
array()
);
}
if ( ! $role instanceof WP_Role ) {
return;
}
$desired_caps = tony_sportspress_get_officials_manager_caps();
foreach ( tony_sportspress_get_officials_manager_managed_caps() as $cap ) {
if ( ! empty( $desired_caps[ $cap ] ) ) {
$role->add_cap( $cap );
} else {
$role->remove_cap( $cap );
}
}
tony_sportspress_sync_official_caps_to_existing_roles();
}
add_action( 'init', 'tony_sportspress_sync_officials_manager_roles' );
/**
* Assign custom capabilities to the officials post type.
*
* @param array $args Post type registration args.
* @return array
*/
function tony_sportspress_officials_post_type_caps( $args ) {
$args['capability_type'] = array( 'sp_official', 'sp_officials' );
$args['map_meta_cap'] = true;
$args['capabilities'] = array(
'create_posts' => 'edit_sp_officials',
);
return $args;
}
add_filter( 'sportspress_register_post_type_official', 'tony_sportspress_officials_post_type_caps' );
/**
* Determine whether the current user should be restricted to assignment-only event access.
*
* @return bool
*/
function tony_sportspress_is_officials_manager_user() {
$user = wp_get_current_user();
if ( ! $user instanceof WP_User || empty( $user->roles ) ) {
return false;
}
if ( ! in_array( TONY_SPORTSPRESS_OFFICIALS_MANAGER_ROLE, $user->roles, true ) ) {
return false;
}
if ( current_user_can( 'manage_options' ) || current_user_can( 'manage_sportspress' ) ) {
return false;
}
return true;
}
/**
* Prevent assignment-only users from opening full event edit screens.
*
* @return void
*/
function tony_sportspress_lock_event_editor_for_officials_manager() {
global $pagenow;
if ( ! is_admin() || ! tony_sportspress_is_officials_manager_user() ) {
return;
}
if ( 'post-new.php' === $pagenow ) {
$post_type = isset( $_GET['post_type'] ) ? sanitize_key( wp_unslash( $_GET['post_type'] ) ) : 'post';
if ( 'sp_event' === $post_type ) {
wp_safe_redirect( admin_url( 'edit.php?post_type=sp_event&tse_event_editor_locked=1' ) );
exit;
}
}
if ( 'post.php' !== $pagenow ) {
return;
}
$post_id = isset( $_GET['post'] ) ? absint( wp_unslash( $_GET['post'] ) ) : 0;
if ( $post_id > 0 && 'sp_event' === get_post_type( $post_id ) ) {
wp_safe_redirect( admin_url( 'edit.php?post_type=sp_event&tse_event_editor_locked=1' ) );
exit;
}
}
add_action( 'admin_init', 'tony_sportspress_lock_event_editor_for_officials_manager' );
/**
* Show an admin notice when event editor access is blocked.
*
* @return void
*/
function tony_sportspress_officials_manager_admin_notice() {
if ( ! tony_sportspress_is_officials_manager_user() ) {
return;
}
if ( empty( $_GET['tse_event_editor_locked'] ) ) {
return;
}
echo '<div class="notice notice-info is-dismissible"><p>' . esc_html__( 'Officials Managers can assign officials from the events list via Quick Edit, but cannot open the full event editor.', 'tonys-sportspress-enhancements' ) . '</p></div>';
}
add_action( 'admin_notices', 'tony_sportspress_officials_manager_admin_notice' );
/**
* Remove event row actions that would expose broader editing.
*
* @param array $actions Row actions.
* @param WP_Post $post Post object.
* @return array
*/
function tony_sportspress_limit_event_row_actions_for_officials_manager( $actions, $post ) {
if ( ! tony_sportspress_is_officials_manager_user() || ! $post instanceof WP_Post || 'sp_event' !== $post->post_type ) {
return $actions;
}
$allowed = array();
if ( isset( $actions['inline hide-if-no-js'] ) ) {
$allowed['inline hide-if-no-js'] = $actions['inline hide-if-no-js'];
}
if ( isset( $actions['view'] ) ) {
$allowed['view'] = $actions['view'];
}
return $allowed;
}
add_filter( 'post_row_actions', 'tony_sportspress_limit_event_row_actions_for_officials_manager', 10, 2 );
/**
* Remove bulk actions from the events list for assignment-only users.
*
* @param array $actions Bulk actions.
* @return array
*/
function tony_sportspress_limit_event_bulk_actions_for_officials_manager( $actions ) {
if ( ! tony_sportspress_is_officials_manager_user() ) {
return $actions;
}
return array();
}
add_filter( 'bulk_actions-edit-sp_event', 'tony_sportspress_limit_event_bulk_actions_for_officials_manager' );
/**
* Remove the Add New events submenu for assignment-only users.
*
* @return void
*/
function tony_sportspress_limit_event_admin_menu_for_officials_manager() {
if ( ! tony_sportspress_is_officials_manager_user() ) {
return;
}
remove_submenu_page( 'edit.php?post_type=sp_event', 'post-new.php?post_type=sp_event' );
}
add_action( 'admin_menu', 'tony_sportspress_limit_event_admin_menu_for_officials_manager', 99 );
/**
* Hide event Add New buttons on the list screen for assignment-only users.
*
* @return void
*/
function tony_sportspress_limit_event_admin_ui_for_officials_manager() {
$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
if ( ! $screen || 'edit-sp_event' !== $screen->id || ! tony_sportspress_is_officials_manager_user() ) {
return;
}
?>
<style>
.post-type-sp_event .page-title-action,
.post-type-sp_event .wrap .bulkactions {
display: none;
}
.post-type-sp_event .wp-list-table .column-title .row-title {
color: inherit;
cursor: default;
text-decoration: none;
}
</style>
<script>
(function() {
const replaceTitleLinks = function() {
document.querySelectorAll('.post-type-sp_event .wp-list-table .column-title a.row-title').forEach(function(link) {
const text = document.createTextNode(link.textContent || '');
const span = document.createElement('span');
span.className = link.className;
span.appendChild(text);
link.replaceWith(span);
});
};
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', replaceTitleLinks);
} else {
replaceTitleLinks();
}
})();
</script>
<?php
}
add_action( 'admin_head', 'tony_sportspress_limit_event_admin_ui_for_officials_manager' );
/**
* Prevent clickable edit links to events for assignment-only users.
*
* This keeps the list-table title as plain text while preserving Quick Edit.
*
* @param string|false $link Edit link.
* @param int $post_id Post ID.
* @param string $context Link context.
* @return string|false
*/
function tony_sportspress_disable_event_edit_links_for_officials_manager( $link, $post_id, $context ) {
if ( ! is_admin() || ! tony_sportspress_is_officials_manager_user() ) {
return $link;
}
if ( 'sp_event' !== get_post_type( $post_id ) ) {
return $link;
}
return false;
}
add_filter( 'get_edit_post_link', 'tony_sportspress_disable_event_edit_links_for_officials_manager', 10, 3 );
/**
* Preserve core event fields so assignment-only users cannot alter them via Quick Edit.
*
* @param array $data Sanitized post data.
* @param array $postarr Raw post array.
* @return array
*/
function tony_sportspress_protect_event_fields_for_officials_manager( $data, $postarr ) {
if ( ! is_admin() || ! tony_sportspress_is_officials_manager_user() ) {
return $data;
}
if ( empty( $postarr['ID'] ) || 'sp_event' !== $data['post_type'] ) {
return $data;
}
$existing_post = get_post( (int) $postarr['ID'], ARRAY_A );
if ( ! is_array( $existing_post ) ) {
return $data;
}
$protected_fields = array(
'post_author',
'post_content',
'post_content_filtered',
'post_date',
'post_date_gmt',
'post_excerpt',
'post_name',
'post_parent',
'post_password',
'post_status',
'post_title',
);
foreach ( $protected_fields as $field ) {
if ( isset( $existing_post[ $field ] ) ) {
$data[ $field ] = $existing_post[ $field ];
}
}
return $data;
}
add_filter( 'wp_insert_post_data', 'tony_sportspress_protect_event_fields_for_officials_manager', 20, 2 );

View File

@@ -1,6 +1,6 @@
<?php
/**
* SportsPress schedule exporter admin page.
* SportsPress schedule exporter frontend and shared helpers.
*
* @package Tonys_Sportspress_Enhancements
*/
@@ -9,22 +9,6 @@ if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Register the schedule exporter admin page.
*
* @return void
*/
function tse_sp_schedule_exporter_add_admin_page() {
add_submenu_page(
'sportspress',
__( 'Schedule Exporter', 'tonys-sportspress-enhancements' ),
__( 'Schedule Exporter', 'tonys-sportspress-enhancements' ),
'manage_sportspress',
'tse-schedule-exporter',
'tse_sp_schedule_exporter_render_admin_page'
);
}
add_action( 'admin_menu', 'tse_sp_schedule_exporter_add_admin_page' );
add_shortcode( 'tse_schedule_exporter', 'tse_sp_schedule_exporter_render_shortcode' );
add_action( 'init', 'tse_sp_schedule_exporter_register_block' );
@@ -91,175 +75,6 @@ function tse_sp_schedule_exporter_register_block() {
);
}
/**
* Render the schedule exporter page.
*
* @return void
*/
function tse_sp_schedule_exporter_render_admin_page() {
if ( ! current_user_can( 'manage_sportspress' ) ) {
return;
}
$leagues = tse_sp_schedule_exporter_get_leagues();
$league_id = tse_sp_schedule_exporter_resolve_league_id( $leagues );
$seasons = tse_sp_schedule_exporter_get_seasons();
$season_id = tse_sp_schedule_exporter_resolve_season_id( $seasons );
$teams = tse_sp_schedule_exporter_get_teams( $league_id, $season_id );
$team_id = tse_sp_schedule_exporter_resolve_team_id( $teams );
$fields = tse_sp_schedule_exporter_get_fields();
$field_id = tse_sp_schedule_exporter_resolve_field_id( $fields );
$export_type = tse_sp_schedule_exporter_resolve_export_type();
$subformat = tse_sp_schedule_exporter_resolve_subformat();
echo '<div class="wrap">';
echo '<h1>' . esc_html__( 'Schedule Exporter', 'tonys-sportspress-enhancements' ) . '</h1>';
echo '<p>' . esc_html__( 'Choose filters once, then generate the CSV feed, iCal link, or printable page URL from the same controls.', 'tonys-sportspress-enhancements' ) . '</p>';
echo '<form method="get" action="' . esc_url( admin_url( 'admin.php' ) ) . '" class="tse-schedule-exporter-form" style="max-width:720px;margin:20px 0 28px;">';
echo '<input type="hidden" name="page" value="tse-schedule-exporter" />';
echo '<div>';
echo '<div style="margin-bottom:16px;">';
echo '<label for="tse-schedule-exporter-export-type"><strong>' . esc_html__( 'Format', 'tonys-sportspress-enhancements' ) . '</strong></label><br />';
echo '<select id="tse-schedule-exporter-export-type" name="export_type">';
foreach ( tse_sp_schedule_exporter_get_export_types() as $type_key => $type_label ) {
printf(
'<option value="%1$s" %2$s>%3$s</option>',
esc_attr( $type_key ),
selected( $export_type, $type_key, false ),
esc_html( $type_label )
);
}
echo '</select>';
echo '<p class="description">' . esc_html__( 'CSV builds a feed URL, iCal Link builds a subscription URL, and Printable opens the printable page.', 'tonys-sportspress-enhancements' ) . '</p>';
echo '</div>';
echo '<div data-subformat-wrap="1" style="margin-bottom:16px;">';
echo '<label for="tse-schedule-exporter-subformat"><strong>' . esc_html__( 'CSV Layout', 'tonys-sportspress-enhancements' ) . '</strong></label><br />';
echo '<select id="tse-schedule-exporter-subformat" name="subformat">';
foreach ( tse_sp_event_export_get_formats() as $format_key => $format_definition ) {
printf(
'<option value="%1$s" %2$s>%3$s</option>',
esc_attr( $format_key ),
selected( $subformat, $format_key, false ),
esc_html( $format_definition['label'] )
);
}
echo '</select>';
echo '<p class="description">' . esc_html__( 'Matchup is away vs home. Team is opponent-based and requires one specific team.', 'tonys-sportspress-enhancements' ) . '</p>';
echo '</div>';
echo '<div style="margin-bottom:16px;">';
echo '<label for="tse-schedule-exporter-league"><strong>' . esc_html__( 'League', 'tonys-sportspress-enhancements' ) . '</strong></label><br />';
echo '<select id="tse-schedule-exporter-league" name="league_id" data-auto-submit="1">';
foreach ( $leagues as $league ) {
printf(
'<option value="%1$s" %2$s>%3$s</option>',
esc_attr( (string) $league->term_id ),
selected( $league_id, (int) $league->term_id, false ),
esc_html( $league->name )
);
}
echo '</select>';
echo '</div>';
echo '<div style="margin-bottom:16px;">';
echo '<label for="tse-schedule-exporter-season"><strong>' . esc_html__( 'Season', 'tonys-sportspress-enhancements' ) . '</strong></label><br />';
echo '<select id="tse-schedule-exporter-season" name="season_id" data-auto-submit="1">';
echo '<option value="0">' . esc_html__( 'Current / All matching events', 'tonys-sportspress-enhancements' ) . '</option>';
foreach ( $seasons as $season ) {
printf(
'<option value="%1$s" %2$s>%3$s</option>',
esc_attr( (string) $season->term_id ),
selected( $season_id, (int) $season->term_id, false ),
esc_html( $season->name )
);
}
echo '</select>';
echo '</div>';
echo '<div style="margin-bottom:16px;">';
echo '<label for="tse-schedule-exporter-team"><strong>' . esc_html__( 'Team', 'tonys-sportspress-enhancements' ) . '</strong></label><br />';
echo '<select id="tse-schedule-exporter-team" name="team_id">';
echo '<option value="0">' . esc_html__( 'All teams', 'tonys-sportspress-enhancements' ) . '</option>';
foreach ( $teams as $team ) {
printf(
'<option value="%1$s" %2$s>%3$s</option>',
esc_attr( (string) $team->ID ),
selected( $team_id, (int) $team->ID, false ),
esc_html( $team->post_title )
);
}
echo '</select>';
echo '<p class="description">' . esc_html__( 'Teams are filtered by the selected league and season.', 'tonys-sportspress-enhancements' ) . '</p>';
echo '</div>';
echo '<div style="margin-bottom:16px;">';
echo '<label for="tse-schedule-exporter-field"><strong>' . esc_html__( 'Field', 'tonys-sportspress-enhancements' ) . '</strong></label><br />';
echo '<select id="tse-schedule-exporter-field" name="field_id">';
echo '<option value="0">' . esc_html__( 'All fields', 'tonys-sportspress-enhancements' ) . '</option>';
foreach ( $fields as $field ) {
printf(
'<option value="%1$s" %2$s>%3$s</option>',
esc_attr( (string) $field->term_id ),
selected( $field_id, (int) $field->term_id, false ),
esc_html( $field->name )
);
}
echo '</select>';
echo '<p class="description">' . esc_html__( 'Use the field filter to narrow the feed to a specific venue.', 'tonys-sportspress-enhancements' ) . '</p>';
echo '</div>';
echo '</div>';
echo '</form>';
if ( empty( $teams ) ) {
echo '<div class="notice notice-warning inline"><p>' . esc_html__( 'No SportsPress teams match the selected league and season.', 'tonys-sportspress-enhancements' ) . '</p></div>';
echo '</div>';
return;
}
echo '<div style="max-width:960px;padding:20px 24px;border:1px solid #dcdcde;background:#fff;">';
echo '<h2 style="margin-top:0;">' . esc_html__( 'Output URL', 'tonys-sportspress-enhancements' ) . '</h2>';
echo '<p>' . esc_html__( 'The generated URL below updates from the shared controls above.', 'tonys-sportspress-enhancements' ) . '</p>';
tse_sp_schedule_exporter_render_column_picker( 'matchup', 'admin', $subformat );
tse_sp_schedule_exporter_render_column_picker( 'team', 'admin', $subformat );
$base_args = array(
'league_id' => $league_id,
'team_id' => $team_id,
'season_id' => $season_id,
'field_id' => $field_id,
'format' => $subformat,
);
$csv_url = tse_sp_event_export_get_feed_url( $base_args, 'csv' );
$ics_url = tse_sp_event_export_get_feed_url(
array(
'league_id' => $league_id,
'team_id' => $team_id,
'season_id' => $season_id,
'field_id' => $field_id,
),
'ics'
);
$print_url = tse_sp_schedule_exporter_get_printable_url( $team_id, $season_id, 'letter', $league_id );
$current_url = tse_sp_schedule_exporter_get_output_url( $export_type, $csv_url, $ics_url, $print_url );
echo '<div style="display:flex;align-items:center;gap:8px;max-width:100%;margin-top:16px;">';
echo '<input type="text" class="large-text code tse-output-url" readonly="readonly" value="' . esc_attr( $current_url ) . '" />';
echo '<button type="button" class="button tse-copy-link" title="' . esc_attr__( 'Copy URL', 'tonys-sportspress-enhancements' ) . '">' . esc_html__( 'Copy URL', 'tonys-sportspress-enhancements' ) . '</button>';
echo '<button type="button" class="button button-primary tse-open-link" data-csv-url="' . esc_url( $csv_url ) . '" data-ics-url="' . esc_url( $ics_url ) . '" data-print-url="' . esc_url( $print_url ) . '" title="' . esc_attr__( 'Open URL in new tab', 'tonys-sportspress-enhancements' ) . '">' . esc_html__( 'Open URL in New Tab', 'tonys-sportspress-enhancements' ) . '</button>';
echo '<button type="button" class="button button-primary tse-ics-ios-link" data-ics-url="' . esc_url( $ics_url ) . '" title="' . esc_attr__( 'Subscribe on iPhone or iPad', 'tonys-sportspress-enhancements' ) . '" style="display:none;">' . esc_html__( 'Subscribe on iPhone/iPad', 'tonys-sportspress-enhancements' ) . '</button>';
echo '<button type="button" class="button tse-ics-android-link" data-ics-url="' . esc_url( $ics_url ) . '" title="' . esc_attr__( 'Subscribe on Android', 'tonys-sportspress-enhancements' ) . '" style="display:none;">' . esc_html__( 'Subscribe on Android', 'tonys-sportspress-enhancements' ) . '</button>';
echo '</div>';
echo '<p class="description tse-output-note">' . esc_html__( 'Use the buttons to copy the generated URL or open the right destination for this export type.', 'tonys-sportspress-enhancements' ) . '</p>';
tse_sp_schedule_exporter_render_link_sync_script( true );
echo '</div>';
echo '</div>';
}
/**
* Render the public shortcode.
*

View File

@@ -160,6 +160,8 @@ function tse_sp_url_builder_render_script() {
}
var baseUrl = <?php echo wp_json_encode( $base_url ); ?>;
var labelOpenIcs = <?php echo wp_json_encode( __( 'Open ICS Feed', 'tonys-sportspress-enhancements' ) ); ?>;
var labelOpenCsv = <?php echo wp_json_encode( __( 'Open Feed URL', 'tonys-sportspress-enhancements' ) ); ?>;
var feedType = root.querySelector('#tse-url-builder-feed-type');
var format = root.querySelector('#tse-url-builder-format');
var output = root.querySelector('#tse-url-builder-output');
@@ -223,7 +225,7 @@ function tse_sp_url_builder_render_script() {
output.value = url.toString();
openLink.href = url.toString();
openLink.textContent = selectedFeedType === 'ics' ? 'Open ICS Feed' : 'Open Feed URL';
openLink.textContent = selectedFeedType === 'ics' ? labelOpenIcs : labelOpenCsv;
}
syncColumnGroups();

1717
includes/sp-webhooks.php Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,83 @@
<?php
/**
* Tests for configurable SportsPress webhooks.
*
* @package Tonys_Sportspress_Enhancements
*/
/**
* Webhook feature tests.
*/
class Test_SP_Webhooks extends WP_UnitTestCase {
/**
* Template placeholders should resolve nested values and JSON serialization.
*/
public function test_render_template_supports_dot_paths_and_tojson() {
$webhooks = Tony_Sportspress_Webhooks::instance();
$template = 'Trigger={{ trigger.key }} Team={{ event.teams.0.name }} Image={{ event.image }} Payload={{ event|tojson }}';
$context = array(
'trigger' => array(
'key' => 'event_results_updated',
),
'event' => array(
'id' => 55,
'image' => 'https://example.com/head-to-head?post=55',
'teams' => array(
array(
'name' => 'Blue Team',
),
),
),
);
$rendered = $webhooks->render_template( $template, $context );
$this->assertStringContainsString( 'Trigger=event_results_updated', $rendered );
$this->assertStringContainsString( 'Team=Blue Team', $rendered );
$this->assertStringContainsString( 'Image=https://example.com/head-to-head?post=55', $rendered );
$this->assertStringContainsString( '"id":55', $rendered );
}
/**
* Sanitization should keep only complete provider-specific webhook rows.
*/
public function test_sanitize_settings_keeps_only_valid_webhooks() {
$webhooks = Tony_Sportspress_Webhooks::instance();
$sanitized = $webhooks->sanitize_settings(
array(
'webhooks' => array(
array(
'name' => 'Results',
'enabled' => '1',
'provider' => 'google_chat',
'url' => 'https://chat.googleapis.com/v1/spaces/AAA/messages?key=test&token=test',
'triggers' => array( 'event_results_updated' ),
'template' => '{"summary":"{{ results.summary }}"}',
),
array(
'name' => 'Invalid',
'enabled' => '1',
'provider' => 'groupme_bot',
'url' => 'invalid bot id',
'triggers' => array( 'event_datetime_changed' ),
'template' => 'ignored',
),
array(
'name' => 'Missing trigger',
'enabled' => '1',
'provider' => 'generic_json',
'url' => 'https://example.com/missing-trigger',
'template' => 'ignored',
),
),
)
);
$this->assertCount( 1, $sanitized['webhooks'] );
$this->assertSame( 'Results', $sanitized['webhooks'][0]['name'] );
$this->assertSame( 'google_chat', $sanitized['webhooks'][0]['provider'] );
$this->assertSame( 'https://chat.googleapis.com/v1/spaces/AAA/messages?key=test&token=test', $sanitized['webhooks'][0]['url'] );
$this->assertSame( array( 'event_results_updated' ), $sanitized['webhooks'][0]['triggers'] );
}
}

View File

@@ -7,13 +7,14 @@
* Author URI: https://github.com/anthonyscorrea/
* Text Domain: tonys-sportspress-enhancements
* Domain Path: /languages
* Version: 0.1.7
* Update URI: https://github.com/anthonyscorrea/tonys-sportspress-enhancements
* Version: 0.1.9
*
* @package Tonys_Sportspress_Enhancements
*/
if ( ! defined( 'TONY_SPORTSPRESS_ENHANCEMENTS_VERSION' ) ) {
define( 'TONY_SPORTSPRESS_ENHANCEMENTS_VERSION', '0.1.7' );
define( 'TONY_SPORTSPRESS_ENHANCEMENTS_VERSION', '0.1.9' );
}
if ( ! defined( 'TONY_SPORTSPRESS_ENHANCEMENTS_FILE' ) ) {
@@ -28,16 +29,24 @@ if ( ! defined( 'TONY_SPORTSPRESS_ENHANCEMENTS_URL' ) ) {
define( 'TONY_SPORTSPRESS_ENHANCEMENTS_URL', plugin_dir_url( __FILE__ ) );
}
// Include other files here
require_once plugin_dir_path(__FILE__) . 'includes/open-graph-tags.php';
require_once plugin_dir_path(__FILE__) . 'includes/featured-image-generator.php';
require_once plugin_dir_path(__FILE__) . 'includes/sp-event-permalink.php';
require_once plugin_dir_path(__FILE__) . 'includes/sp-event-export.php';
require_once plugin_dir_path(__FILE__) . 'includes/sp-event-csv.php';
require_once plugin_dir_path(__FILE__) . 'includes/sp-event-admin-week-filter.php';
require_once plugin_dir_path(__FILE__) . 'includes/sp-event-quick-edit-officials.php';
require_once plugin_dir_path(__FILE__) . 'includes/sp-event-team-ordering.php';
require_once plugin_dir_path(__FILE__) . 'includes/sp-printable-calendars.php';
require_once plugin_dir_path(__FILE__) . 'includes/sp-url-builder.php';
require_once plugin_dir_path(__FILE__) . 'includes/sp-schedule-exporter.php';
require_once plugin_dir_path(__FILE__) . 'includes/sp-venue-meta.php';
if ( ! defined( 'TONY_SPORTSPRESS_ENHANCEMENTS_PLUGIN_BASENAME' ) ) {
define( 'TONY_SPORTSPRESS_ENHANCEMENTS_PLUGIN_BASENAME', plugin_basename( __FILE__ ) );
}
require_once TONY_SPORTSPRESS_ENHANCEMENTS_DIR . 'includes/sp-github-updater.php';
require_once TONY_SPORTSPRESS_ENHANCEMENTS_DIR . 'includes/sp-officials-manager-role.php';
require_once TONY_SPORTSPRESS_ENHANCEMENTS_DIR . 'includes/open-graph-tags.php';
require_once TONY_SPORTSPRESS_ENHANCEMENTS_DIR . 'includes/featured-image-generator.php';
require_once TONY_SPORTSPRESS_ENHANCEMENTS_DIR . 'includes/sp-event-permalink.php';
require_once TONY_SPORTSPRESS_ENHANCEMENTS_DIR . 'includes/sp-event-export.php';
require_once TONY_SPORTSPRESS_ENHANCEMENTS_DIR . 'includes/sp-event-csv.php';
require_once TONY_SPORTSPRESS_ENHANCEMENTS_DIR . 'includes/sp-event-admin-week-filter.php';
require_once TONY_SPORTSPRESS_ENHANCEMENTS_DIR . 'includes/sp-event-quick-edit-officials.php';
require_once TONY_SPORTSPRESS_ENHANCEMENTS_DIR . 'includes/sp-event-team-ordering.php';
require_once TONY_SPORTSPRESS_ENHANCEMENTS_DIR . 'includes/sp-printable-calendars.php';
require_once TONY_SPORTSPRESS_ENHANCEMENTS_DIR . 'includes/sp-url-builder.php';
require_once TONY_SPORTSPRESS_ENHANCEMENTS_DIR . 'includes/sp-webhooks.php';
require_once TONY_SPORTSPRESS_ENHANCEMENTS_DIR . 'includes/sp-schedule-exporter.php';
require_once TONY_SPORTSPRESS_ENHANCEMENTS_DIR . 'includes/sp-venue-meta.php';
register_activation_hook( __FILE__, 'tony_sportspress_sync_officials_manager_roles' );