Repository navigation
Expand file tree
/
Copy pathics-filter-api.php
More file actions
267 lines (228 loc) · 10 KB
/
Copy pathics-filter-api.php
File metadata and controls
267 lines (228 loc) · 10 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
<?php
/**
* Plugin Name: ICS Filter REST API
* Plugin URI: https://github.com/w0yl/ics-filter-wordpress-api-plugin
* Description: Adds a secured, cached custom REST API endpoint to fetch and filter an ICS calendar by keywords.
* Version: 1.0.0
* Requires at least: 5.8
* Requires PHP: 7.4
* Author: SCARC
* License: GPL v2 or later
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
class ICS_Filter_API {
public function __construct() {
add_action( 'rest_api_init', [ $this, 'register_routes' ] );
add_action( 'admin_init', [ $this, 'register_settings' ] );
add_action( 'admin_menu', [ $this, 'register_settings_page' ] );
}
/**
* Register the custom REST API route with API key permission checks.
*/
public function register_routes() {
register_rest_route( 'icsfilter/v1', '/filter', [
'methods' => 'GET',
'callback' => [ $this, 'handle_ics_filter' ],
'permission_callback' => [ $this, 'check_api_permission' ],
'args' => [
'url' => [
'required' => true,
'type' => 'string',
'sanitize_callback' => 'esc_url_raw',
'description' => 'The absolute URL of the ICS calendar.',
],
'keywords' => [
'required' => true,
'type' => 'string',
'sanitize_callback' => 'sanitize_text_field',
'description' => 'Comma-separated list of keywords to filter by.',
],
'api_key' => [
'required' => false,
'type' => 'string',
'sanitize_callback' => 'sanitize_text_field',
'description' => 'API Key (alternative to X-API-Key header).',
],
],
] );
}
/**
* Verify the API key via HTTP Header (X-API-Key) or Query Parameter (api_key).
*/
public function check_api_permission( WP_REST_Request $request ) {
$provided_key = $request->get_header( 'X-API-Key' );
if ( empty( $provided_key ) ) {
$provided_key = $request->get_param( 'api_key' );
}
$stored_key = get_option( 'ics_filter_api_key', 'default_change_me_secret_key' );
if ( empty( $stored_key ) || ! hash_equals( $stored_key, (string) $provided_key ) ) {
return new WP_Error(
'rest_forbidden',
'Invalid or missing API key.',
[ 'status' => 401 ]
);
}
return true;
}
/**
* Handle the API request with caching and raw text calendar output.
*/
public function handle_ics_filter( WP_REST_Request $request ) {
$ics_url = $request->get_param( 'url' );
$keywords_raw = $request->get_param( 'keywords' );
$keywords = array_filter( array_map( 'trim', explode( ',', $keywords_raw ) ) );
if ( empty( $keywords ) ) {
return new WP_Error( 'no_keywords', 'At least one valid keyword must be provided.', [ 'status' => 400 ] );
}
sort( $keywords );
$cache_key = 'ics_filter_' . md5( $ics_url . '_' . implode( '|', $keywords ) );
$filtered_ics = get_transient( $cache_key );
if ( false === $filtered_ics ) {
$response = wp_remote_get( $ics_url, [ 'timeout' => 20 ] );
if ( is_wp_error( $response ) ) {
return new WP_Error( 'fetch_failed', 'Failed to fetch the ICS file: ' . $response->get_error_message(), [ 'status' => 502 ] );
}
$ics_content = wp_remote_retrieve_body( $response );
$status_code = wp_remote_retrieve_response_code( $response );
if ( 200 !== $status_code || empty( $ics_content ) ) {
return new WP_Error( 'invalid_ics_response', 'The remote server returned an invalid response or empty calendar.', [ 'status' => 502 ] );
}
$filtered_ics = $this->filter_ics_events( $ics_content, $keywords );
set_transient( $cache_key, $filtered_ics, HOUR_IN_SECONDS );
}
// Send raw text/calendar headers and output exact string without JSON encoding wrappers
status_header( 200 );
header( 'Content-Type: text/calendar; charset=utf-8' );
header( 'Content-Disposition: attachment; filename="filtered-calendar.ics"' );
echo $filtered_ics;
exit;
}
/**
* Parse raw ICS content and filter VEVENT blocks based on keywords in SUMMARY.
*/
private function filter_ics_events( $ics_content, $keywords ) {
$ics_content = str_replace( [ "\r\n", "\r" ], "\n", $ics_content );
$lines = explode( "\n", $ics_content );
$output_lines = [];
$in_event = false;
$current_event = [];
$current_summary = '';
foreach ( $lines as $line ) {
if ( ! empty( $line ) && ( $line[0] === ' ' || $line[0] === "\t" ) ) {
if ( $in_event ) {
$current_event[] = $line;
if ( 0 === strpos( trim( $line ), 'SUMMARY:' ) || ! empty( $current_summary ) ) {
$current_summary .= trim( substr( $line, 1 ) );
}
} else {
$output_lines[] = $line;
}
continue;
}
if ( trim( $line ) === 'BEGIN:VEVENT' ) {
$in_event = true;
$current_event = [ $line ];
$current_summary = '';
continue;
}
if ( trim( $line ) === 'END:VEVENT' ) {
if ( $in_event ) {
$current_event[] = $line;
if ( $this->summary_matches_all_keywords( $current_summary, $keywords ) ) {
$output_lines = array_merge( $output_lines, $current_event );
}
}
$in_event = false;
$current_event = [];
$current_summary = '';
continue;
}
if ( $in_event ) {
$current_event[] = $line;
if ( 0 === strpos( $line, 'SUMMARY:' ) ) {
$current_summary = substr( $line, 8 );
}
} else {
$output_lines[] = $line;
}
}
return implode( "\r\n", $output_lines );
}
/**
* Check if summary matches all keywords (case-insensitive).
*/
private function summary_matches_all_keywords( $summary, $keywords ) {
$summary_lower = mb_strtolower( $summary );
foreach ( $keywords as $keyword ) {
$keyword_lower = mb_strtolower( $keyword );
if ( false === mb_strpos( $summary_lower, $keyword_lower ) ) {
return false;
}
}
return true;
}
/**
* Register WordPress settings.
*/
public function register_settings() {
register_setting( 'ics_filter_options_group', 'ics_filter_api_key', 'sanitize_text_field' );
}
/**
* Add settings page under Settings menu.
*/
public function register_settings_page() {
add_options_page(
'ICS Filter API Settings',
'ICS Filter API',
'manage_options',
'ics-filter-settings',
[ $this, 'settings_page_html' ]
);
}
/**
* Render settings page HTML including cache clearing functionality.
*/
public function settings_page_html() {
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
// Handle cache clearing action if button was clicked
if ( isset( $_POST['ics_clear_cache_nonce'] ) && wp_verify_nonce( $_POST['ics_clear_cache_nonce'], 'ics_clear_cache_action' ) ) {
global $wpdb;
// Delete all transients matching our ics_filter_ prefix from the database options table
$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_ics_filter_%' OR option_name LIKE '_transient_timeout_ics_filter_%'" );
echo '<div class="notice notice-success is-dismissible"><p><strong>Calendar cache successfully cleared!</strong></p></div>';
}
?>
<div class="wrap">
<h1>ICS Filter API Settings</h1>
<form action="options.php" method="post">
<?php
settings_fields( 'ics_filter_options_group' );
do_settings_sections( 'ics_filter_options_group' );
?>
<table class="form-table">
<tr>
<th scope="row"><label for="ics_filter_api_key">API Key</label></th>
<td>
<input type="text" id="ics_filter_api_key" name="ics_filter_api_key" value="<?php echo esc_attr( get_option( 'ics_filter_api_key', 'default_change_me_secret_key' ) ); ?>" class="regular-text" />
<p class="description">Provide this key in the <code>X-API-Key</code> request header or via the <code>?api_key=</code> parameter.</p>
</td>
</tr>
</table>
<?php submit_button(); ?>
</form>
<hr style="margin: 40px 0 20px 0;">
<h2>Manage Cache</h2>
<p>Filtered calendar files are cached in the database for 1 hour to improve speed. If your source calendar has changed and you want to force an immediate refresh, you can clear the cache below.</p>
<form method="post">
<?php wp_nonce_field( 'ics_clear_cache_action', 'ics_clear_cache_nonce' ); ?>
<?php submit_button( 'Clear Calendar Cache', 'secondary', 'ics_clear_cache_submit', false ); ?>
</form>
</div>
<?php
}
}
new ICS_Filter_API();