forked from VolkanSah/WP-Claude-Interface
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclaude.php
More file actions
454 lines (403 loc) · 17.1 KB
/
claude.php
File metadata and controls
454 lines (403 loc) · 17.1 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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
<?php
/**
* Plugin Name: Claude 3.x Chat Interface
* Description: Adds a Claude AI chat interface to your WordPress site using a shortcode.
* Version: 1.4
* Author: Volkan Kücükbudak
* Enhancements: TurtleEngr
*/
// Define the available models
define('CLAUDE_MODELS', [
'claude-3-haiku-20240307' => 'Claude 3.0 Haiku',
'claude-3-5-haiku-20241022' => 'Claude 3.5 Haiku',
'claude-haiku-4-5-20251001' => 'Claude 4.5 Haiku',
'claude-3-5-sonnet-20241022' => 'Claude 3.5 Sonnet',
'claude-3-7-sonnet-20250219' => 'Claude 3.7 Sonnet',
'claude-sonnet-4-5-20250929' => 'Claude 4.5 Sonnet',
]);
// Register settings
function claude_chat_register_settings() {
register_setting('claude_chat_options', 'claude_chat_api_key');
register_setting('claude_chat_options', 'claude_chat_model');
register_setting('claude_chat_options', 'claude_chat_temperature');
register_setting('claude_chat_options', 'claude_chat_max_tokens');
register_setting('claude_chat_options', 'claude_chat_prefix_prompt', [
'sanitize_callback' => 'sanitize_textarea_field',
]);
// Additional prompt settings
register_setting('claude_chat_options', 'claude_chat_addon_prompt_enabled');
register_setting('claude_chat_options', 'claude_chat_addon_prompt_label', [
'sanitize_callback' => 'sanitize_text_field',
]);
register_setting('claude_chat_options', 'claude_chat_addon_prompt_text', [
'sanitize_callback' => 'sanitize_textarea_field',
]);
}
add_action('admin_init', 'claude_chat_register_settings');
// Enqueue necessary scripts and styles
function claude_chat_enqueue_scripts() {
wp_enqueue_style('claude-chat-style', plugin_dir_url(__FILE__) . 'css/claude-chat.css');
wp_enqueue_script('claude-chat-script', plugin_dir_url(__FILE__) . 'js/claude-chat.js', array('jquery'), '1.4', true);
wp_localize_script('claude-chat-script', 'claudeChat', array(
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('claude-chat-nonce'),
// FIX: Only expose a boolean flag — never the prompt text itself.
// The actual prompt text is appended server-side in claude_chat_ajax_handler().
'addon_enabled' => get_option('claude_chat_addon_prompt_enabled', '0') === '1',
));
}
add_action('wp_enqueue_scripts', 'claude_chat_enqueue_scripts');
// Shortcode to display the chat interface
function claude_chat_shortcode() {
$addon_enabled = get_option('claude_chat_addon_prompt_enabled', '0');
$addon_label = get_option('claude_chat_addon_prompt_label', '');
ob_start();
?>
<div id="claude-chat-interface">
<div id="claude-chat-messages"></div>
<?php if ( $addon_enabled === '1' ) : ?>
<div id="claude-chat-addon">
<label>
<input type="checkbox" id="claude-chat-addon-checkbox">
<?php echo esc_html( $addon_label ); ?>
</label>
</div>
<?php endif; ?>
<textarea id="claude-chat-input" placeholder="Ask Claude something..." rows="3"></textarea>
<button id="claude-chat-submit">Send</button>
</div>
<?php
return ob_get_clean();
}
add_shortcode('claude_chat', 'claude_chat_shortcode');
// ---------------------------------------------------------------------------
// FIX: Transient-based rate limiter — max 10 requests per minute per IP.
// Returns true when the request is allowed, false when the limit is exceeded.
// ---------------------------------------------------------------------------
function claude_chat_check_rate_limit() {
$ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : 'unknown';
$transient_key = 'claude_chat_rate_' . md5($ip);
$count = get_transient($transient_key);
if ($count === false) {
// First request in this window — start the counter with a 60-second TTL.
set_transient($transient_key, 1, 60);
return true;
}
if (intval($count) >= 10) {
return false; // Rate limit exceeded.
}
// Increment without resetting the existing TTL by reusing the same key.
set_transient($transient_key, intval($count) + 1, 60);
return true;
}
// AJAX handler for chat requests
function claude_chat_ajax_handler() {
check_ajax_referer('claude-chat-nonce', 'nonce');
// FIX: Enforce rate limit before doing any further work.
if ( ! claude_chat_check_rate_limit() ) {
wp_send_json_error('Rate limit exceeded. Please wait a moment before sending another message.');
return;
}
// FIX: Use sanitize_textarea_field so newlines in multi-line messages
// are preserved (sanitize_text_field strips them).
$message = sanitize_textarea_field($_POST['message']);
// FIX: The addon prompt text never travels to the browser.
// The JS sends only a boolean flag; we append the stored prompt server-side.
$addon_checked = ! empty($_POST['addon_enabled']) && $_POST['addon_enabled'] === '1';
if ($addon_checked && get_option('claude_chat_addon_prompt_enabled', '0') === '1') {
$addon_text = get_option('claude_chat_addon_prompt_text', '');
if ($addon_text !== '') {
$message = $message . "\n" . $addon_text;
}
}
$response = claude_chat_api_request($message);
if ($response) {
wp_send_json_success($response);
} else {
wp_send_json_error('Error: No response from API');
}
}
add_action('wp_ajax_claude_chat', 'claude_chat_ajax_handler');
add_action('wp_ajax_nopriv_claude_chat', 'claude_chat_ajax_handler');
// Claude API request function with logging
function claude_chat_api_request($message) {
$api_key = get_option('claude_chat_api_key');
$model = get_option('claude_chat_model');
$temperature = get_option('claude_chat_temperature');
$max_tokens = get_option('claude_chat_max_tokens');
$prefix_prompt = trim(get_option('claude_chat_prefix_prompt', ''));
// Use the correct API-Endpoint.
$url = 'https://api.anthropic.com/v1/messages';
$headers = array(
'Content-Type' => 'application/json',
'x-api-key' => $api_key,
'anthropic-version' => '2023-06-01',
// Required to enable cache_control on system/content blocks.
'anthropic-beta' => 'prompt-caching-2024-07-31',
);
// -----------------------------------------------------------------------
// FIX: Move the prefix prompt to the dedicated `system` parameter.
//
// Placing it in `system` gives it architectural separation from the
// conversation turn — it cannot be overridden by "Ignore previous
// instructions…" style user inputs and benefits from Claude's distinct
// system-prompt handling.
//
// The array form is used (rather than a plain string) so that
// cache_control can be set on the block, preserving the prompt-caching
// benefit of the original implementation.
// -----------------------------------------------------------------------
$body = array(
'model' => $model,
'max_tokens' => intval($max_tokens),
'messages' => array(
array(
'role' => 'user',
'content' => $message, // plain string — no prefix bundled in here
),
),
);
if ($prefix_prompt !== '') {
$body['system'] = array(
array(
'type' => 'text',
'text' => $prefix_prompt,
'cache_control' => array('type' => 'ephemeral'),
),
);
}
// Only include temperature when set (0 is falsy but valid, so check !== '')
if ($temperature !== '') {
$body['temperature'] = floatval($temperature);
}
$response = wp_remote_post($url, array(
'headers' => $headers,
'body' => json_encode($body),
'timeout' => 60,
));
if (is_wp_error($response)) {
claude_chat_log_error('HTTP Error', $response->get_error_message());
return 'Error: ' . $response->get_error_message();
}
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
if (isset($data['content'][0]['text'])) {
return $data['content'][0]['text'];
} elseif (isset($data['error'])) {
claude_chat_log_error('API Error', print_r($data, true));
return 'API Error: ' . $data['error']['message'];
} else {
claude_chat_log_error('Unknown Error', 'Unable to get a response from Claude API. Response: ' . print_r($data, true));
return 'Error: Unable to get a response from Claude API.';
}
}
// Logging function
function claude_chat_log_error($error_type, $error_message) {
$log_message = date('Y-m-d H:i:s') . " - $error_type: $error_message\n";
$log_file = plugin_dir_path(__FILE__) . 'claude-chat-error.log';
error_log($log_message, 3, $log_file);
}
// Add settings page
function claude_chat_settings_page() {
add_options_page(
'Claude Chat Settings',
'Claude Chat',
'manage_options',
'claude-chat-settings',
'claude_chat_settings_page_html'
);
}
add_action('admin_menu', 'claude_chat_settings_page');
// Settings page HTML
function claude_chat_settings_page_html() {
?>
<div class="wrap">
<h1><?php echo esc_html(get_admin_page_title()); ?></h1>
<form action="options.php" method="post">
<?php
settings_fields('claude_chat_options');
do_settings_sections('claude-chat-settings');
submit_button('Save Settings');
?>
</form>
</div>
<?php
}
// Initialize settings
function claude_chat_settings_init() {
add_settings_section(
'claude_chat_settings_section',
'Claude API Settings',
'claude_chat_settings_section_callback',
'claude-chat-settings'
);
add_settings_field(
'claude_chat_api_key',
'API Key',
'claude_chat_api_key_field_callback', // FIX: dedicated callback uses type="password"
'claude-chat-settings',
'claude_chat_settings_section',
array('label_for' => 'claude_chat_api_key')
);
add_settings_field(
'claude_chat_model',
'Model',
'claude_chat_model_dropdown_callback',
'claude-chat-settings',
'claude_chat_settings_section',
array('label_for' => 'claude_chat_model')
);
add_settings_field(
'claude_chat_temperature',
'Temperature',
'claude_chat_number_field_callback',
'claude-chat-settings',
'claude_chat_settings_section',
array(
'label_for' => 'claude_chat_temperature',
'description' => 'Range: 0 to 1',
'min' => 0,
'max' => 1,
'step' => 0.1,
)
);
add_settings_field(
'claude_chat_max_tokens',
'Max Tokens',
'claude_chat_number_field_callback',
'claude-chat-settings',
'claude_chat_settings_section',
array(
'label_for' => 'claude_chat_max_tokens',
'description' => 'Range: 1 to 8096',
'min' => 1,
'max' => 8096,
)
);
add_settings_field(
'claude_chat_prefix_prompt',
'Prefix Prompt',
'claude_chat_textarea_field_callback',
'claude-chat-settings',
'claude_chat_settings_section',
array(
'label_for' => 'claude_chat_prefix_prompt',
'description' => 'Optional. Sent as the <code>system</code> prompt on every request, keeping it architecturally separate from the conversation. Uses <code>cache_control</code> (ephemeral) for prompt-caching eligibility. Leave blank to disable.',
)
);
// -----------------------------------------------------------------------
// Additional prompt field — a single settings row that groups together:
// 1. An enable/disable checkbox
// 2. A text input for the checkbox label shown in the user form
// 3. A textarea for the prompt text that gets appended to the message
// -----------------------------------------------------------------------
add_settings_field(
'claude_chat_addon_prompt',
'Additional Prompt',
'claude_chat_addon_prompt_callback',
'claude-chat-settings',
'claude_chat_settings_section'
);
}
add_action('admin_init', 'claude_chat_settings_init');
// Field render callbacks
function claude_chat_settings_section_callback($args) {
echo '<p>Enter your Claude API settings below:</p>';
}
// FIX: Render the API key as a password field so it is masked in the browser.
function claude_chat_api_key_field_callback($args) {
$option = get_option($args['label_for']);
echo '<input type="password" id="' . esc_attr($args['label_for'])
. '" name="' . esc_attr($args['label_for'])
. '" value="' . esc_attr($option)
. '" class="regular-text"'
. ' autocomplete="new-password">';
if ( ! empty($args['description'])) {
echo '<p class="description">' . wp_kses($args['description'], array('code' => array())) . '</p>';
}
}
function claude_chat_number_field_callback($args) {
$option = get_option($args['label_for']);
echo '<input type="number" id="' . esc_attr($args['label_for'])
. '" name="' . esc_attr($args['label_for'])
. '" value="' . esc_attr($option)
. '" class="regular-text"'
. ' min="' . esc_attr($args['min'])
. '" max="' . esc_attr($args['max'])
. '" step="' . (isset($args['step']) ? esc_attr($args['step']) : '1')
. '">';
if ( ! empty($args['description'])) {
echo '<p class="description">' . wp_kses($args['description'], array('code' => array())) . '</p>';
}
}
function claude_chat_model_dropdown_callback($args) {
$selected_model = get_option($args['label_for']);
echo '<select id="' . esc_attr($args['label_for'])
. '" name="' . esc_attr($args['label_for'])
. '" class="regular-text">';
foreach (CLAUDE_MODELS as $model_key => $model_name) {
$selected = ($selected_model == $model_key) ? 'selected="selected"' : '';
echo '<option value="' . esc_attr($model_key) . '" ' . $selected . '>'
. esc_html($model_name) . '</option>';
}
echo '</select>';
if ( ! empty($args['description'])) {
echo '<p class="description">' . wp_kses($args['description'], array('code' => array())) . '</p>';
}
}
function claude_chat_textarea_field_callback($args) {
$option = get_option($args['label_for'], '');
echo '<textarea id="' . esc_attr($args['label_for'])
. '" name="' . esc_attr($args['label_for'])
. '" rows="6" cols="60" class="large-text code">'
. esc_textarea($option)
. '</textarea>';
if ( ! empty($args['description'])) {
echo '<p class="description">' . wp_kses($args['description'], array('code' => array())) . '</p>';
}
}
// ---------------------------------------------------------------------------
// Callback for the "Additional Prompt" settings row.
//
// Renders three controls in one table row:
// Row 1 — Enable checkbox + label text input (inline)
// Row 2 — Prompt textarea
// ---------------------------------------------------------------------------
function claude_chat_addon_prompt_callback() {
$enabled = get_option('claude_chat_addon_prompt_enabled', '0');
$label = get_option('claude_chat_addon_prompt_label', '');
$text = get_option('claude_chat_addon_prompt_text', '');
// ---- Enable checkbox + label input (same line) ----
echo '<label style="display:inline-flex; align-items:center; gap:6px;">';
echo '<input type="checkbox"'
. ' id="claude_chat_addon_prompt_enabled"'
. ' name="claude_chat_addon_prompt_enabled"'
. ' value="1"'
. checked('1', $enabled, false)
. '>';
echo '<strong>Enable</strong>';
echo '</label>';
echo ' ';
echo '<label for="claude_chat_addon_prompt_label" style="font-weight:normal;">Checkbox label: </label>';
echo '<input type="text"'
. ' id="claude_chat_addon_prompt_label"'
. ' name="claude_chat_addon_prompt_label"'
. ' value="' . esc_attr($label) . '"'
. ' class="regular-text"'
. ' placeholder="e.g. Include extra context">';
// ---- Prompt textarea ----
echo '<br><br>';
echo '<textarea'
. ' id="claude_chat_addon_prompt_text"'
. ' name="claude_chat_addon_prompt_text"'
. ' rows="4" cols="60" class="large-text code">'
. esc_textarea($text)
. '</textarea>';
echo '<p class="description">'
. 'When <strong>Enable</strong> is checked, a checkbox labelled with the text above '
. 'is shown in the user chat form (before the message input). '
. 'If the user ticks that checkbox, a boolean flag is sent to the server and '
. 'the prompt text is appended to their message <strong>server-side</strong> — '
. 'the prompt text is never exposed to the browser.'
. '</p>';
}