-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdebug.php
More file actions
349 lines (297 loc) · 14.2 KB
/
debug.php
File metadata and controls
349 lines (297 loc) · 14.2 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
<?php
// This file is part of Moodle - http://moodle.org/
/**
* Debugging tool for Chatbot block
*
* @package block_chatbo
* @copyright 2025 Your Name <your.email@example.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
/**
* Diagnostic functions for Chatbo
*/
class block_chatbot_diagnostics {
/** @var string $log_file Path to the log file */
private static $log_file = null;
/**
* Initialize the log file
*/
public static function init_log() {
// Create logs directory if it doesn't exis
$log_dir = __DIR__ . '/logs';
if (!file_exists($log_dir)) {
mkdir($log_dir, 0755, true);
}
// Create or truncate log file
self::$log_file = $log_dir . '/debug_' . date('Y-m-d_H-i-s') . '.log';
file_put_contents(self::$log_file, "=== Chatbot Debug Log ===\n" . date('Y-m-d H:i:s') . "\n\n");
}
/**
* Write a message to the log file
*
* @param string $message Message to log
* @param string $level Log level (INFO, WARNING, ERROR)
*/
public static function log($message, $level = 'INFO') {
if (self::$log_file === null) {
self::init_log();
}
$timestamp = date('Y-m-d H:i:s');
$log_message = "[$timestamp] [$level] $message\n";
// Write to log file
file_put_contents(self::$log_file, $log_message, FILE_APPEND);
// Also log to error_log for redundancy
error_log("CHATBOT_DEBUG [$level]: $message");
}
/**
* Test API connectivity for all providers
*
* @return array Results of the tests
*/
public static function test_api_connectivity() {
global $CFG;
require_once($CFG->dirroot . '/blocks/chatbot/classes/api_client.php');
$results = [
'openai' => ['status' => 'Not tested', 'message' => ''],
'google' => ['status' => 'Not tested', 'message' => ''],
'anthropic' => ['status' => 'Not tested', 'message' => '']
];
// Get configuration
$config = get_config('block_chatbot');
// Test OpenAI connectivity
if (!empty($config->openai_apikey)) {
self::log("Testing OpenAI API connectivity...");
try {
$client = new block_chatbot_openai_client($config->openai_apikey);
$client->set_model('gpt-4o');
$client->set_max_tokens(50);
$messages = [
['role' => 'system', 'content' => 'You are a helpful assistant.'],
['role' => 'user', 'content' => 'Say "Hello, this is a test."']
];
self::log("Sending request to OpenAI API...");
$response = $client->get_completion($messages);
if ($response !== false) {
$results['openai']['status'] = 'Success';
$results['openai']['message'] = "API connection successful. Response: " . substr($response, 0, 100);
self::log("OpenAI API test successful: " . substr($response, 0, 100), 'INFO');
} else {
$results['openai']['status'] = 'Failed';
$results['openai']['message'] = "API request failed. Check Moodle error logs for details.";
self::log("OpenAI API test failed", 'ERROR');
}
} catch (Exception $e) {
$results['openai']['status'] = 'Error';
$results['openai']['message'] = "Exception: " . $e->getMessage();
self::log("OpenAI API test exception: " . $e->getMessage(), 'ERROR');
}
} else {
$results['openai']['status'] = 'Skipped';
$results['openai']['message'] = "No API key configured";
self::log("OpenAI API test skipped - no API key configured", 'WARNING');
}
// Test Google connectivity
if (!empty($config->google_apikey)) {
self::log("Testing Google Gemini API connectivity...");
try {
$client = new block_chatbot_google_client($config->google_apikey);
$client->set_model('gemini-2.5-pro');
$client->set_max_tokens(50);
$messages = [
['role' => 'system', 'content' => 'You are a helpful assistant.'],
['role' => 'user', 'content' => 'Say "Hello, this is a test."']
];
self::log("Sending request to Google Gemini API...");
$response = $client->get_completion($messages);
if ($response !== false) {
$results['google']['status'] = 'Success';
$results['google']['message'] = "API connection successful. Response: " . substr($response, 0, 100);
self::log("Google API test successful: " . substr($response, 0, 100), 'INFO');
} else {
$results['google']['status'] = 'Failed';
$results['google']['message'] = "API request failed. Check Moodle error logs for details.";
self::log("Google API test failed", 'ERROR');
}
} catch (Exception $e) {
$results['google']['status'] = 'Error';
$results['google']['message'] = "Exception: " . $e->getMessage();
self::log("Google API test exception: " . $e->getMessage(), 'ERROR');
}
} else {
$results['google']['status'] = 'Skipped';
$results['google']['message'] = "No API key configured";
self::log("Google API test skipped - no API key configured", 'WARNING');
}
// Anthropic test has been removed
$results['anthropic']['status'] = 'Removed';
$results['anthropic']['message'] = "Anthropic integration has been removed";
self::log("Anthropic API test skipped - integration removed", 'INFO');
return $results;
}
/**
* Get current configuration
*
* @return array Configuration details
*/
public static function get_configuration() {
$config = get_config('block_chatbot');
// Mask API keys for security
$masked_config = clone $config;
if (isset($masked_config->openai_apikey)) {
$key_length = strlen($masked_config->openai_apikey);
$masked_config->openai_apikey = ($key_length > 8) ?
substr($masked_config->openai_apikey, 0, 4) . '...' . substr($masked_config->openai_apikey, -4) :
'********';
}
if (isset($masked_config->google_apikey)) {
$key_length = strlen($masked_config->google_apikey);
$masked_config->google_apikey = ($key_length > 8) ?
substr($masked_config->google_apikey, 0, 4) . '...' . substr($masked_config->google_apikey, -4) :
'********';
}
if (isset($masked_config->anthropic_apikey)) {
$key_length = strlen($masked_config->anthropic_apikey);
$masked_config->anthropic_apikey = ($key_length > 8) ?
substr($masked_config->anthropic_apikey, 0, 4) . '...' . substr($masked_config->anthropic_apikey, -4) :
'********';
}
return [
'default_provider' => isset($config->default_provider) ? $config->default_provider : 'openai',
'default_model' => isset($config->default_model) ? $config->default_model : 'openai:gpt-4o',
'temperature' => isset($config->temperature) ? $config->temperature : '0.7',
'top_p' => isset($config->top_p) ? $config->top_p : '0.9',
'max_tokens' => isset($config->max_tokens) ? $config->max_tokens : '2500',
'timeout' => isset($config->timeout) ? $config->timeout : '30',
'response_format' => isset($config->response_format) ? $config->response_format : 'text',
'openai_apikey_set' => !empty($config->openai_apikey),
'google_apikey_set' => !empty($config->google_apikey),
'anthropic_apikey_set' => !empty($config->anthropic_apikey),
'openai_apikey_masked' => isset($masked_config->openai_apikey) ? $masked_config->openai_apikey : 'not set',
'google_apikey_masked' => isset($masked_config->google_apikey) ? $masked_config->google_apikey : 'not set',
'anthropic_apikey_masked' => isset($masked_config->anthropic_apikey) ? $masked_config->anthropic_apikey : 'not set',
'moodle_version' => $CFG->version,
'php_version' => phpversion(),
'curl_version' => function_exists('curl_version') ? curl_version()['version'] : 'unknown'
];
}
/**
* Check system requirements
*
* @return array Results of system checks
*/
public static function check_system() {
$results = [];
// Check PHP version
$php_version = phpversion();
$results['php_version'] = [
'status' => version_compare($php_version, '8.2') >= 0 ? 'OK' : 'Warning',
'message' => "PHP $php_version" . (version_compare($php_version, '8.2') < 0 ? " (PHP 8.2 or later recommended)" : "")
];
// Check cURL extension
$results['curl'] = [
'status' => function_exists('curl_init') ? 'OK' : 'Error',
'message' => function_exists('curl_init') ?
"cURL extension installed (" . curl_version()['version'] . ")" :
"cURL extension not available"
];
// Check JSON extension
$results['json'] = [
'status' => function_exists('json_encode') ? 'OK' : 'Error',
'message' => function_exists('json_encode') ?
"JSON extension installed" :
"JSON extension not available"
];
// Check logs directory
$log_dir = __DIR__ . '/logs';
$results['logs_dir'] = [
'status' => (file_exists($log_dir) && is_writable($log_dir)) ? 'OK' :
(file_exists($log_dir) ? 'Warning' : 'Not Created'),
'message' => file_exists($log_dir) ?
(is_writable($log_dir) ? "Logs directory is writable" : "Logs directory exists but is not writable") :
"Logs directory does not exist (will be created)"
];
return $results;
}
}
// This script can be run from the command line for testing
if (PHP_SAPI === 'cli') {
// Set up Moodle environmen
define('CLI_SCRIPT', true);
require_once(__DIR__ . '/../../config.php');
// Run diagnostics
echo "Running Chatbot diagnostics...\n";
block_chatbot_diagnostics::init_log();
block_chatbot_diagnostics::log("Starting CLI diagnostics");
echo "\nSystem Checks:\n";
$system_checks = block_chatbot_diagnostics::check_system();
foreach ($system_checks as $check => $result) {
echo "- $check: " . $result['status'] . " - " . $result['message'] . "\n";
}
echo "\nConfiguration:\n";
$config = block_chatbot_diagnostics::get_configuration();
foreach ($config as $key => $value) {
echo "- $key: $value\n";
}
echo "\nAPI Connectivity Tests:\n";
$api_tests = block_chatbot_diagnostics::test_api_connectivity();
foreach ($api_tests as $provider => $result) {
echo "- $provider: " . $result['status'] . " - " . $result['message'] . "\n";
}
echo "\nDiagnostics complete. Log file: " . block_chatbot_diagnostics::$log_file . "\n";
}
// Debug endpoints
if (isset($_GET['action']) && $_GET['action'] === 'debug') {
// Web-based diagnostics
require_once(__DIR__ . '/../../config.php');
require_once($CFG->libdir . '/adminlib.php');
// Check admin privileges
admin_externalpage_setup('blocksettingchatbot');
// Set up page
$PAGE->set_context(context_system::instance());
$PAGE->set_url('/blocks/chatbot/debug.php', ['action' => 'debug']);
$PAGE->set_title('Chatbot Diagnostics');
$PAGE->set_heading('Chatbot Diagnostics');
// Initialize diagnostic logger
block_chatbot_diagnostics::init_log();
block_chatbot_diagnostics::log("Starting web diagnostics");
// Run tests
$system_checks = block_chatbot_diagnostics::check_system();
$config = block_chatbot_diagnostics::get_configuration();
$api_tests = block_chatbot_diagnostics::test_api_connectivity();
// Output page
echo $OUTPUT->header();
echo $OUTPUT->heading('Chatbot Diagnostics');
echo '<div class="alert alert-info">This page runs diagnostic tests on the Chatbot plugin to help identify configuration issues.</div>';
// System checks
echo $OUTPUT->heading('System Checks', 3);
echo '<table class="table"><thead><tr><th>Check</th><th>Status</th><th>Details</th></tr></thead><tbody>';
foreach ($system_checks as $check => $result) {
$status_class = $result['status'] === 'OK' ? 'success' : ($result['status'] === 'Warning' ? 'warning' : 'danger');
echo "<tr><td>$check</td><td><span class='badge badge-$status_class'>{$result['status']}</span></td><td>{$result['message']}</td></tr>";
}
echo '</tbody></table>';
// Configuration
echo $OUTPUT->heading('Configuration', 3);
echo '<table class="table"><thead><tr><th>Setting</th><th>Value</th></tr></thead><tbody>';
foreach ($config as $key => $value) {
echo "<tr><td>$key</td><td>$value</td></tr>";
}
echo '</tbody></table>';
// API connectivity tests
echo $OUTPUT->heading('API Connectivity Tests', 3);
echo '<table class="table"><thead><tr><th>Provider</th><th>Status</th><th>Details</th></tr></thead><tbody>';
foreach ($api_tests as $provider => $result) {
$status_class = $result['status'] === 'Success' ? 'success' :
($result['status'] === 'Skipped' ? 'secondary' : 'danger');
echo "<tr><td>$provider</td><td><span class='badge badge-$status_class'>{$result['status']}</span></td><td>{$result['message']}</td></tr>";
}
echo '</tbody></table>';
// Log file information
$log_file = block_chatbot_diagnostics::$log_file;
$log_contents = file_exists($log_file) ? file_get_contents($log_file) : 'No log file available';
echo $OUTPUT->heading('Debug Log', 3);
echo '<pre style="max-height: 400px; overflow-y: auto;">' . htmlspecialchars($log_contents) . '</pre>';
echo $OUTPUT->footer();
exit;
}