Compare commits

..
12 Commits
29 changed files with 342 additions and 60 deletions
+1 -1
View File
@@ -30,6 +30,6 @@ Szkielet komponentu Joomla 6 do gromadzenia pytań testowych.
## Instalacja ## Instalacja
W Joomla wybierz **System → Install → Install from Folder** i wskaż ten katalog. Manifestem instalacyjnym jest `com_testquestions.xml` (wersja 1.43.19). W Joomla wybierz **System → Install → Install from Folder** i wskaż ten katalog. Manifestem instalacyjnym jest `com_testquestions.xml` (wersja 1.43.31).
Po instalacji komponent jest dostępny w panelu administratora jako **Pytania testowe**. Po instalacji komponent jest dostępny w panelu administratora jako **Pytania testowe**.
@@ -5,6 +5,8 @@
<field name="ai_provider" type="list" label="COM_TESTQUESTIONS_AI_PROVIDER"> <field name="ai_provider" type="list" label="COM_TESTQUESTIONS_AI_PROVIDER">
<option value="openai">OpenAI</option> <option value="openai">OpenAI</option>
<option value="grok">Grok</option> <option value="grok">Grok</option>
<option value="groq">Groq</option>
<option value="gemini">Gemini</option>
</field> </field>
<field name="ai_api_key" type="aiapikey" addfieldprefix="Komponent\Component\Testquestions\Administrator\Field" label="COM_TESTQUESTIONS_AI_API_KEY" filter="raw" autocomplete="off" size="120" class="w-100" /> <field name="ai_api_key" type="aiapikey" addfieldprefix="Komponent\Component\Testquestions\Administrator\Field" label="COM_TESTQUESTIONS_AI_API_KEY" filter="raw" autocomplete="off" size="120" class="w-100" />
</fieldset> </fieldset>
@@ -71,8 +71,12 @@ COM_TESTQUESTIONS_AI_PROVIDER="Dostawca AI"
COM_TESTQUESTIONS_AI_API_KEY="Klucz API" COM_TESTQUESTIONS_AI_API_KEY="Klucz API"
COM_TESTQUESTIONS_AI_OPENAI_KEY="Klucz API OpenAI" COM_TESTQUESTIONS_AI_OPENAI_KEY="Klucz API OpenAI"
COM_TESTQUESTIONS_AI_GROK_KEY="Klucz API Grok" COM_TESTQUESTIONS_AI_GROK_KEY="Klucz API Grok"
COM_TESTQUESTIONS_AI_GROQ_KEY="Klucz API Groq"
COM_TESTQUESTIONS_AI_GEMINI_KEY="Klucz API Gemini"
COM_TESTQUESTIONS_AI_OPENAI_MODEL="Model OpenAI" COM_TESTQUESTIONS_AI_OPENAI_MODEL="Model OpenAI"
COM_TESTQUESTIONS_AI_GROK_MODEL="Model Grok" COM_TESTQUESTIONS_AI_GROK_MODEL="Model Grok"
COM_TESTQUESTIONS_AI_GROQ_MODEL="Model Groq API"
COM_TESTQUESTIONS_AI_GEMINI_MODEL="Model Gemini"
COM_TESTQUESTIONS_AI_MODEL_INVALID="Wybierz prawidłowy model dla każdego dostawcy AI." COM_TESTQUESTIONS_AI_MODEL_INVALID="Wybierz prawidłowy model dla każdego dostawcy AI."
COM_TESTQUESTIONS_AI_TOKEN_USAGE="Wykorzystanie tokenów API" COM_TESTQUESTIONS_AI_TOKEN_USAGE="Wykorzystanie tokenów API"
COM_TESTQUESTIONS_AI_TOKEN_USAGE_INFO="Suma użycia zapisanego przy ocenach AI we wszystkich wynikach testów. Powtórne oceny są zliczane, jeśli zostały wykonane po tej aktualizacji." COM_TESTQUESTIONS_AI_TOKEN_USAGE_INFO="Suma użycia zapisanego przy ocenach AI we wszystkich wynikach testów. Powtórne oceny są zliczane, jeśli zostały wykonane po tej aktualizacji."
@@ -139,6 +143,8 @@ COM_TESTQUESTIONS_RESULTS_TEST_NAME="Nazwa testu"
COM_TESTQUESTIONS_RESULTS_ALL_TESTS="Wszystkie zestawy" COM_TESTQUESTIONS_RESULTS_ALL_TESTS="Wszystkie zestawy"
COM_TESTQUESTIONS_RESULTS_DATE_FROM="Data od" COM_TESTQUESTIONS_RESULTS_DATE_FROM="Data od"
COM_TESTQUESTIONS_RESULTS_DATE_TO="Data do" COM_TESTQUESTIONS_RESULTS_DATE_TO="Data do"
COM_TESTQUESTIONS_RESULTS_DELETED="Usunięto %s zapisanych testów."
COM_TESTQUESTIONS_RESULTS_DELETE_NONE="Zaznacz testy, które chcesz usunąć."
COM_TESTQUESTIONS_YOUR_ANSWER="Twoja odpowiedź" COM_TESTQUESTIONS_YOUR_ANSWER="Twoja odpowiedź"
COM_TESTQUESTIONS_SELECTED_ANSWER="Zaznaczona odpowiedź" COM_TESTQUESTIONS_SELECTED_ANSWER="Zaznaczona odpowiedź"
COM_TESTQUESTIONS_ANSWER_CORRECT="Poprawna odpowiedź" COM_TESTQUESTIONS_ANSWER_CORRECT="Poprawna odpowiedź"
@@ -0,0 +1 @@
-- Wydanie 1.43.20: czas testu bez ustawionego limitu zestawu jest sumowany z czasów pytań.
@@ -0,0 +1 @@
-- Wydanie 1.43.21: naprawiono wyświetlanie obrazów w szczegółach rozwiązanego testu.
@@ -0,0 +1 @@
-- Wydanie 1.43.22: kolejność odpowiedzi zamkniętych jest losowana i zapisywana dla podejścia.
@@ -0,0 +1 @@
-- Wydanie 1.43.23: zachowano w wyniku kolejność pytań z wylosowanego testu.
@@ -0,0 +1 @@
-- Wydanie 1.43.24: ukryto ocenę AI i korektę punktów dla pustych odpowiedzi.
@@ -0,0 +1 @@
-- Wydanie 1.43.25: kolor oceny AI odzwierciedla poziom uznanych punktów.
@@ -0,0 +1 @@
-- Wydanie 1.43.26: dodano zbiorcze usuwanie zapisanych testów.
@@ -0,0 +1 @@
-- Wydanie 1.43.27: dodano dostawcę Groq API.
@@ -0,0 +1 @@
-- Wydanie 1.43.28: dodano dostawcę Gemini API.
@@ -0,0 +1 @@
-- Wydanie 1.43.29: ograniczono czas generowania oceny przez Gemini.
@@ -0,0 +1 @@
-- Wydanie 1.43.30: odczyt tokenów Gemini z pola usageMetadata.
@@ -0,0 +1 @@
-- Brak zmian w schemacie bazy danych w wersji 1.43.31.
@@ -36,14 +36,14 @@ class AiController extends BaseController
$input = Factory::getApplication()->getInput(); $input = Factory::getApplication()->getInput();
$provider = strtolower($input->post->getCmd('ai_provider', '')); $provider = strtolower($input->post->getCmd('ai_provider', ''));
if (!in_array($provider, ['openai', 'grok'], true)) { if (!in_array($provider, ['openai', 'grok', 'groq', 'gemini'], true)) {
throw new \RuntimeException(Text::_('COM_TESTQUESTIONS_AI_PROVIDER_INVALID')); throw new \RuntimeException(Text::_('COM_TESTQUESTIONS_AI_PROVIDER_INVALID'));
} }
$models = AiService::availableModels(); $models = AiService::availableModels();
$selectedModels = []; $selectedModels = [];
foreach (['openai', 'grok'] as $modelProvider) { foreach (['openai', 'grok', 'groq', 'gemini'] as $modelProvider) {
$model = $input->post->getCmd('ai_' . $modelProvider . '_model', ''); $model = trim($input->post->getString('ai_' . $modelProvider . '_model', ''));
if (!isset($models[$modelProvider][$model])) { if (!isset($models[$modelProvider][$model])) {
throw new \RuntimeException(Text::_('COM_TESTQUESTIONS_AI_MODEL_INVALID')); throw new \RuntimeException(Text::_('COM_TESTQUESTIONS_AI_MODEL_INVALID'));
} }
@@ -71,7 +71,7 @@ class AiController extends BaseController
$settings['ai_' . $modelProvider . '_model'] = $model; $settings['ai_' . $modelProvider . '_model'] = $model;
} }
foreach (['openai', 'grok'] as $keyProvider) { foreach (['openai', 'grok', 'groq', 'gemini'] as $keyProvider) {
$fieldName = 'ai_' . $keyProvider . '_api_key'; $fieldName = 'ai_' . $keyProvider . '_api_key';
$apiKey = trim((string) $input->post->get($fieldName, '', 'RAW')); $apiKey = trim((string) $input->post->get($fieldName, '', 'RAW'));
if ($apiKey !== '') { if ($apiKey !== '') {
@@ -0,0 +1,54 @@
<?php
namespace Komponent\Component\Testquestions\Administrator\Controller;
defined('_JEXEC') or die;
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\MVC\Controller\AdminController;
use Joomla\CMS\Router\Route;
use Joomla\CMS\Session\Session;
class ResultsController extends AdminController
{
public function delete()
{
if (!Session::checkToken()) {
throw new \RuntimeException(Text::_('JINVALID_TOKEN'), 403);
}
$user = Factory::getApplication()->getIdentity();
if (!$user->authorise('core.delete', 'com_testquestions')) {
throw new \RuntimeException(Text::_('JERROR_ALERTNOAUTHOR'), 403);
}
$ids = array_values(array_unique(array_filter(array_map(
'intval',
(array) $this->input->post->get('cid', [], 'array')
), static function ($id) {
return $id > 0;
})));
if (!$ids) {
$this->setRedirect(
Route::_('index.php?option=com_testquestions&view=results', false),
Text::_('COM_TESTQUESTIONS_RESULTS_DELETE_NONE'),
'warning'
);
return;
}
$db = Factory::getContainer()->get('DatabaseDriver');
$db->setQuery(
$db->getQuery(true)
->delete($db->quoteName('#__testquestions_results'))
->where($db->quoteName('id') . ' IN (' . implode(',', $ids) . ')')
)->execute();
$this->setRedirect(
Route::_('index.php?option=com_testquestions&view=results', false),
Text::sprintf('COM_TESTQUESTIONS_RESULTS_DELETED', $db->getAffectedRows())
);
}
}
@@ -17,7 +17,7 @@ class ResultModel extends BaseDatabaseModel
$db = Factory::getContainer()->get('DatabaseDriver'); $db = Factory::getContainer()->get('DatabaseDriver');
$item = $db->setQuery( $item = $db->setQuery(
$db->getQuery(true) $db->getQuery(true)
->select(['r.*', 's.title AS set_title', 'sub.title AS subject_title']) ->select(['r.*', 's.title AS set_title', 's.image AS set_image', 'sub.title AS subject_title'])
->from($db->quoteName('#__testquestions_results', 'r')) ->from($db->quoteName('#__testquestions_results', 'r'))
->leftJoin($db->quoteName('#__testquestions_sets', 's') . ' ON s.id = r.set_id') ->leftJoin($db->quoteName('#__testquestions_sets', 's') . ' ON s.id = r.set_id')
->leftJoin($db->quoteName('#__testquestions_subjects', 'sub') . ' ON sub.id = s.subject_id') ->leftJoin($db->quoteName('#__testquestions_subjects', 'sub') . ' ON sub.id = s.subject_id')
@@ -35,7 +35,7 @@ class ResultModel extends BaseDatabaseModel
if ($ids) { if ($ids) {
$item->questions = $db->setQuery( $item->questions = $db->setQuery(
$db->getQuery(true) $db->getQuery(true)
->select(['id', 'question_type', 'question', 'answer_a', 'answer_b', 'answer_c', 'answer_d', 'answer_open', 'correct_answer', 'points']) ->select(['id', 'question_type', 'question', 'answer_a', 'answer_b', 'answer_c', 'answer_d', 'answer_open', 'correct_answer', 'points', 'image'])
->from($db->quoteName('#__testquestions_questions')) ->from($db->quoteName('#__testquestions_questions'))
->where('id IN (' . implode(',', $ids) . ')') ->where('id IN (' . implode(',', $ids) . ')')
)->loadObjectList('id'); )->loadObjectList('id');
@@ -96,7 +96,7 @@ class ResultModel extends BaseDatabaseModel
$keyName = 'ai_' . $provider . '_api_key'; $keyName = 'ai_' . $provider . '_api_key';
$apiKey = trim((string) $params->get($keyName, $params->get('ai_api_key', ''))); $apiKey = trim((string) $params->get($keyName, $params->get('ai_api_key', '')));
$componentKeyLength = mb_strlen($apiKey); $componentKeyLength = mb_strlen($apiKey);
$defaultModels = ['openai' => 'gpt-4.1-mini', 'grok' => 'grok-4.7']; $defaultModels = ['openai' => 'gpt-4.1-mini', 'grok' => 'grok-4.7', 'groq' => 'openai/gpt-oss-120b', 'gemini' => 'gemini-3.8-flash'];
$model = trim((string) $params->get('ai_' . $provider . '_model', $defaultModels[$provider] ?? '')); $model = trim((string) $params->get('ai_' . $provider . '_model', $defaultModels[$provider] ?? ''));
// Odczytaj zapisane parametry bezpośrednio z bazy. Dzięki temu nie użyjemy // Odczytaj zapisane parametry bezpośrednio z bazy. Dzięki temu nie użyjemy
@@ -202,7 +202,7 @@ class ResultModel extends BaseDatabaseModel
$questionIds = []; $questionIds = [];
foreach ($item->answers as $questionId => $answer) { foreach ($item->answers as $questionId => $answer) {
$question = $item->questions[(int) $questionId] ?? null; $question = $item->questions[(int) $questionId] ?? null;
if ($question && $question->question_type === 'open' && empty($answer['correct'])) { if ($question && $question->question_type === 'open' && empty($answer['correct']) && trim((string) ($answer['selected'] ?? '')) !== '') {
$questionIds[] = (int) $questionId; $questionIds[] = (int) $questionId;
} }
} }
@@ -18,7 +18,7 @@ class ResultsModel extends ListModel
$item->ai_output_tokens = 0; $item->ai_output_tokens = 0;
$item->ai_total_tokens = 0; $item->ai_total_tokens = 0;
$item->ai_cost_usd = 0.0; $item->ai_cost_usd = 0.0;
$item->ai_tokens_by_provider = ['openai' => 0, 'grok' => 0]; $item->ai_tokens_by_provider = ['openai' => 0, 'grok' => 0, 'groq' => 0, 'gemini' => 0];
$answers = json_decode((string) ($item->answers ?? ''), true); $answers = json_decode((string) ($item->answers ?? ''), true);
if (!is_array($answers)) { if (!is_array($answers)) {
@@ -68,7 +68,7 @@ class ResultsModel extends ListModel
'output_tokens' => 0, 'output_tokens' => 0,
'total_tokens' => 0, 'total_tokens' => 0,
'cost_usd' => 0.0, 'cost_usd' => 0.0,
'providers' => ['openai' => $emptyProviderTotals, 'grok' => $emptyProviderTotals], 'providers' => ['openai' => $emptyProviderTotals, 'grok' => $emptyProviderTotals, 'groq' => $emptyProviderTotals, 'gemini' => $emptyProviderTotals],
]; ];
foreach ($answersRows as $answersJson) { foreach ($answersRows as $answersJson) {
@@ -23,6 +23,15 @@ class AiService
'grok-4.20' => 'Grok 4.20 Reasoning', 'grok-4.20' => 'Grok 4.20 Reasoning',
'grok-4.20-non-reasoning' => 'Grok 4.20 Non-Reasoning', 'grok-4.20-non-reasoning' => 'Grok 4.20 Non-Reasoning',
], ],
'groq' => [
'openai/gpt-oss-120b' => 'GPT OSS 120B',
'openai/gpt-oss-20b' => 'GPT OSS 20B',
'llama-3.3-70b-versatile' => 'Llama 3.3 70B Versatile',
],
'gemini' => [
'gemini-3.8-flash' => 'Gemini 3.8 Flash',
'gemini-3.1-pro-preview' => 'Gemini 3.1 Pro (Preview)',
],
]; ];
} }
@@ -30,15 +39,18 @@ class AiService
{ {
$provider = strtolower(trim($provider)); $provider = strtolower(trim($provider));
$provider = preg_replace('/[^a-z]/', '', $provider); $provider = preg_replace('/[^a-z]/', '', $provider);
$config = $provider === 'grok' $config = match ($provider) {
? ['url' => 'https://api.x.ai/v1/responses'] 'grok' => ['url' => 'https://api.x.ai/v1/responses'],
: ['url' => 'https://api.openai.com/v1/responses']; 'groq' => ['url' => 'https://api.groq.com/openai/v1/chat/completions'],
'gemini' => ['url' => 'https://generativelanguage.googleapis.com/v1beta/models/' . rawurlencode($model) . ':generateContent'],
default => ['url' => 'https://api.openai.com/v1/responses'],
};
if (trim($apiKey) === '') { if (trim($apiKey) === '') {
throw new \RuntimeException('AI_NOT_CONFIGURED'); throw new \RuntimeException('AI_NOT_CONFIGURED');
} }
if (!in_array($provider, ['openai', 'grok'], true)) { if (!in_array($provider, ['openai', 'grok', 'groq', 'gemini'], true)) {
throw new \RuntimeException('Nieprawidłowy dostawca AI: ' . $provider); throw new \RuntimeException('Nieprawidłowy dostawca AI: ' . $provider);
} }
@@ -54,24 +66,45 @@ class AiService
. "Odpowiedź ucznia:\n" . ($answer !== '' ? $answer : 'Brak odpowiedzi') . "\n\n" . "Odpowiedź ucznia:\n" . ($answer !== '' ? $answer : 'Brak odpowiedzi') . "\n\n"
. "Zwróć wyłącznie poprawny obiekt JSON w formacie {\"awarded_points\": liczba_całkowita, \"feedback\": \"krótka ocena po polsku\"}. W ocenie opisz poprawne i brakujące elementy. Nie zmieniaj wzorca odpowiedzi."; . "Zwróć wyłącznie poprawny obiekt JSON w formacie {\"awarded_points\": liczba_całkowita, \"feedback\": \"krótka ocena po polsku\"}. W ocenie opisz poprawne i brakujące elementy. Nie zmieniaj wzorca odpowiedzi.";
$requestData = [ $requestData = match ($provider) {
'groq' => [
'model' => $model,
'messages' => [['role' => 'user', 'content' => $input]],
'temperature' => 0.1,
],
'gemini' => [
'contents' => [['parts' => [['text' => $input]]]],
'generationConfig' => [
'maxOutputTokens' => 256,
'responseMimeType' => 'application/json',
'thinkingConfig' => ['thinkingLevel' => 'low'],
],
],
default => [
'model' => $model, 'model' => $model,
'input' => $input, 'input' => $input,
]; ],
};
// GPT-5.x reasoning models do not accept a custom temperature. // GPT-5.x reasoning models do not accept a custom temperature.
if ($provider === 'grok' || $model === 'gpt-4.1-mini') { if ($provider === 'grok' || ($provider === 'openai' && $model === 'gpt-4.1-mini')) {
$requestData['temperature'] = 0.1; $requestData['temperature'] = 0.1;
} }
$payload = json_encode($requestData, JSON_UNESCAPED_UNICODE); $payload = json_encode($requestData, JSON_UNESCAPED_UNICODE);
$headers = [
'Content-Type' => 'application/json',
];
if ($provider === 'gemini') {
$headers['x-goog-api-key'] = trim($apiKey);
} else {
$headers['Authorization'] = 'Bearer ' . trim($apiKey);
}
$response = HttpFactory::getHttp()->post( $response = HttpFactory::getHttp()->post(
$config['url'], $config['url'],
$payload, $payload,
[ $headers,
'Authorization' => 'Bearer ' . trim($apiKey), $provider === 'gemini' ? 25 : 60
'Content-Type' => 'application/json',
],
60
); );
$body = json_decode((string) $response->body, true); $body = json_decode((string) $response->body, true);
@@ -114,14 +147,22 @@ class AiService
private function getUsage(array $body, string $provider, string $model): ?array private function getUsage(array $body, string $provider, string $model): ?array
{ {
$usage = $body['usage'] ?? null; // Gemini uses camelCase UsageMetadata at the response root; the
if (!is_array($usage) || !isset($usage['input_tokens'], $usage['output_tokens'])) { // OpenAI-compatible providers return their counters in `usage`.
$usage = $body['usageMetadata'] ?? $body['usage'] ?? null;
if (!is_array($usage)) {
return null; return null;
} }
$inputTokens = max(0, (int) $usage['input_tokens']); $inputTokens = max(0, (int) ($usage['input_tokens'] ?? $usage['prompt_tokens'] ?? $usage['promptTokenCount'] ?? 0));
$outputTokens = max(0, (int) $usage['output_tokens']); $outputTokens = max(0, (int) ($usage['output_tokens'] ?? $usage['completion_tokens'] ?? (
$cachedTokens = min($inputTokens, max(0, (int) ($usage['input_tokens_details']['cached_tokens'] ?? 0))); (int) ($usage['candidatesTokenCount'] ?? 0) + (int) ($usage['thoughtsTokenCount'] ?? 0)
)));
if ((!isset($usage['input_tokens']) && !isset($usage['prompt_tokens']) && !isset($usage['promptTokenCount']))
|| (!isset($usage['output_tokens']) && !isset($usage['completion_tokens']) && !isset($usage['candidatesTokenCount']))) {
return null;
}
$cachedTokens = min($inputTokens, max(0, (int) ($usage['input_tokens_details']['cached_tokens'] ?? $usage['cachedContentTokenCount'] ?? 0)));
$cost = null; $cost = null;
$costSource = ''; $costSource = '';
@@ -142,7 +183,7 @@ class AiService
'model' => $model, 'model' => $model,
'input_tokens' => $inputTokens, 'input_tokens' => $inputTokens,
'output_tokens' => $outputTokens, 'output_tokens' => $outputTokens,
'total_tokens' => (int) ($usage['total_tokens'] ?? ($inputTokens + $outputTokens)), 'total_tokens' => (int) ($usage['total_tokens'] ?? $usage['totalTokenCount'] ?? ($inputTokens + $outputTokens)),
'cached_input_tokens' => $cachedTokens, 'cached_input_tokens' => $cachedTokens,
'cost_usd' => $cost, 'cost_usd' => $cost,
'cost_source' => $costSource, 'cost_source' => $costSource,
@@ -162,6 +203,20 @@ class AiService
private function extractText(array $body): string private function extractText(array $body): string
{ {
if (isset($body['candidates'][0]['content']['parts']) && is_array($body['candidates'][0]['content']['parts'])) {
$parts = [];
foreach ($body['candidates'][0]['content']['parts'] as $part) {
if (isset($part['text']) && is_string($part['text'])) {
$parts[] = $part['text'];
}
}
return trim(implode("\n", $parts));
}
if (isset($body['choices'][0]['message']['content']) && is_string($body['choices'][0]['message']['content'])) {
return trim($body['choices'][0]['message']['content']);
}
if (!empty($body['output_text']) && is_string($body['output_text'])) { if (!empty($body['output_text']) && is_string($body['output_text'])) {
return trim($body['output_text']); return trim($body['output_text']);
} }
@@ -28,6 +28,8 @@ class HtmlView extends BaseHtmlView
$this->usageTotals = [ $this->usageTotals = [
'openai' => ['calls' => 0, 'input_tokens' => 0, 'output_tokens' => 0, 'total_tokens' => 0, 'cost_usd' => 0.0, 'cost_calls' => 0], 'openai' => ['calls' => 0, 'input_tokens' => 0, 'output_tokens' => 0, 'total_tokens' => 0, 'cost_usd' => 0.0, 'cost_calls' => 0],
'grok' => ['calls' => 0, 'input_tokens' => 0, 'output_tokens' => 0, 'total_tokens' => 0, 'cost_usd' => 0.0, 'cost_calls' => 0], 'grok' => ['calls' => 0, 'input_tokens' => 0, 'output_tokens' => 0, 'total_tokens' => 0, 'cost_usd' => 0.0, 'cost_calls' => 0],
'groq' => ['calls' => 0, 'input_tokens' => 0, 'output_tokens' => 0, 'total_tokens' => 0, 'cost_usd' => 0.0, 'cost_calls' => 0],
'gemini' => ['calls' => 0, 'input_tokens' => 0, 'output_tokens' => 0, 'total_tokens' => 0, 'cost_usd' => 0.0, 'cost_calls' => 0],
]; ];
$usageRows = $db->setQuery( $usageRows = $db->setQuery(
@@ -8,6 +8,7 @@ use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Language\Text; use Joomla\CMS\Language\Text;
use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView; use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView;
use Joomla\CMS\Toolbar\ToolbarHelper; use Joomla\CMS\Toolbar\ToolbarHelper;
use Joomla\CMS\Factory;
class HtmlView extends BaseHtmlView class HtmlView extends BaseHtmlView
{ {
@@ -25,6 +26,9 @@ class HtmlView extends BaseHtmlView
$this->sets = $this->get('Sets'); $this->sets = $this->get('Sets');
$this->aiUsageTotals = $this->get('AiUsageTotals'); $this->aiUsageTotals = $this->get('AiUsageTotals');
ToolbarHelper::title(Text::_('COM_TESTQUESTIONS_RESULTS')); ToolbarHelper::title(Text::_('COM_TESTQUESTIONS_RESULTS'));
if (Factory::getApplication()->getIdentity()->authorise('core.delete', 'com_testquestions')) {
ToolbarHelper::deleteList('', 'results.delete', 'JTOOLBAR_DELETE');
}
ToolbarHelper::link('index.php?option=com_testquestions&view=sets', 'COM_TESTQUESTIONS_SETS', 'back'); ToolbarHelper::link('index.php?option=com_testquestions&view=sets', 'COM_TESTQUESTIONS_SETS', 'back');
return parent::display($tpl); return parent::display($tpl);
@@ -7,8 +7,12 @@
<?php $legacyKey = (string) ($this->settings['ai_api_key'] ?? ''); ?> <?php $legacyKey = (string) ($this->settings['ai_api_key'] ?? ''); ?>
<?php $openaiKey = (string) ($this->settings['ai_openai_api_key'] ?? ($provider === 'openai' ? $legacyKey : '')); ?> <?php $openaiKey = (string) ($this->settings['ai_openai_api_key'] ?? ($provider === 'openai' ? $legacyKey : '')); ?>
<?php $grokKey = (string) ($this->settings['ai_grok_api_key'] ?? ($provider === 'grok' ? $legacyKey : '')); ?> <?php $grokKey = (string) ($this->settings['ai_grok_api_key'] ?? ($provider === 'grok' ? $legacyKey : '')); ?>
<?php $groqKey = (string) ($this->settings['ai_groq_api_key'] ?? ($provider === 'groq' ? $legacyKey : '')); ?>
<?php $geminiKey = (string) ($this->settings['ai_gemini_api_key'] ?? ($provider === 'gemini' ? $legacyKey : '')); ?>
<?php $openaiModel = (string) ($this->settings['ai_openai_model'] ?? 'gpt-4.1-mini'); ?> <?php $openaiModel = (string) ($this->settings['ai_openai_model'] ?? 'gpt-4.1-mini'); ?>
<?php $grokModel = (string) ($this->settings['ai_grok_model'] ?? 'grok-4.7'); ?> <?php $grokModel = (string) ($this->settings['ai_grok_model'] ?? 'grok-4.7'); ?>
<?php $groqModel = (string) ($this->settings['ai_groq_model'] ?? 'openai/gpt-oss-120b'); ?>
<?php $geminiModel = (string) ($this->settings['ai_gemini_model'] ?? 'gemini-3.8-flash'); ?>
<form action="<?php echo Route::_('index.php?option=com_testquestions&view=ai'); ?>" method="post" name="adminForm" id="adminForm"> <form action="<?php echo Route::_('index.php?option=com_testquestions&view=ai'); ?>" method="post" name="adminForm" id="adminForm">
<div class="card" style="max-width: 900px;"> <div class="card" style="max-width: 900px;">
<div class="card-body"> <div class="card-body">
@@ -17,9 +21,11 @@
<select id="ai-provider" name="ai_provider" class="form-select" required> <select id="ai-provider" name="ai_provider" class="form-select" required>
<option value="openai" <?php echo $provider === 'openai' ? 'selected' : ''; ?>>OpenAI</option> <option value="openai" <?php echo $provider === 'openai' ? 'selected' : ''; ?>>OpenAI</option>
<option value="grok" <?php echo $provider === 'grok' ? 'selected' : ''; ?>>Grok</option> <option value="grok" <?php echo $provider === 'grok' ? 'selected' : ''; ?>>Grok</option>
<option value="groq" <?php echo $provider === 'groq' ? 'selected' : ''; ?>>Groq</option>
<option value="gemini" <?php echo $provider === 'gemini' ? 'selected' : ''; ?>>Gemini</option>
</select> </select>
</div> </div>
<div class="mb-3"> <div class="mb-3" data-ai-provider-section="openai">
<label for="ai-openai-model" class="form-label"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_OPENAI_MODEL'); ?></label> <label for="ai-openai-model" class="form-label"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_OPENAI_MODEL'); ?></label>
<select id="ai-openai-model" name="ai_openai_model" class="form-select" required> <select id="ai-openai-model" name="ai_openai_model" class="form-select" required>
<?php foreach ($availableModels['openai'] as $modelId => $modelLabel) : ?> <?php foreach ($availableModels['openai'] as $modelId => $modelLabel) : ?>
@@ -27,7 +33,7 @@
<?php endforeach; ?> <?php endforeach; ?>
</select> </select>
</div> </div>
<div class="mb-3"> <div class="mb-3" data-ai-provider-section="openai">
<label for="ai-openai-api-key" class="form-label"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_OPENAI_KEY'); ?></label> <label for="ai-openai-api-key" class="form-label"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_OPENAI_KEY'); ?></label>
<div class="input-group"> <div class="input-group">
<input type="password" id="ai-openai-api-key" name="ai_openai_api_key" value="<?php echo htmlspecialchars($openaiKey, ENT_QUOTES, 'UTF-8'); ?>" class="form-control" size="120" maxlength="4096" autocomplete="new-password"> <input type="password" id="ai-openai-api-key" name="ai_openai_api_key" value="<?php echo htmlspecialchars($openaiKey, ENT_QUOTES, 'UTF-8'); ?>" class="form-control" size="120" maxlength="4096" autocomplete="new-password">
@@ -37,7 +43,7 @@
<?php echo $openaiKey !== '' ? 'Zapisany klucz: ' . mb_strlen($openaiKey) . ' znaków. Pozostaw pole bez zmian, aby go zachować.' : 'Nie zapisano klucza OpenAI.'; ?> <?php echo $openaiKey !== '' ? 'Zapisany klucz: ' . mb_strlen($openaiKey) . ' znaków. Pozostaw pole bez zmian, aby go zachować.' : 'Nie zapisano klucza OpenAI.'; ?>
</small> </small>
</div> </div>
<div class="mb-3"> <div class="mb-3" data-ai-provider-section="grok">
<label for="ai-grok-api-key" class="form-label"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_GROK_KEY'); ?></label> <label for="ai-grok-api-key" class="form-label"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_GROK_KEY'); ?></label>
<div class="input-group"> <div class="input-group">
<input type="password" id="ai-grok-api-key" name="ai_grok_api_key" value="<?php echo htmlspecialchars($grokKey, ENT_QUOTES, 'UTF-8'); ?>" class="form-control" size="120" maxlength="4096" autocomplete="new-password"> <input type="password" id="ai-grok-api-key" name="ai_grok_api_key" value="<?php echo htmlspecialchars($grokKey, ENT_QUOTES, 'UTF-8'); ?>" class="form-control" size="120" maxlength="4096" autocomplete="new-password">
@@ -47,7 +53,7 @@
<?php echo $grokKey !== '' ? 'Zapisany klucz: ' . mb_strlen($grokKey) . ' znaków. Pozostaw pole bez zmian, aby go zachować.' : 'Nie zapisano klucza Grok.'; ?> <?php echo $grokKey !== '' ? 'Zapisany klucz: ' . mb_strlen($grokKey) . ' znaków. Pozostaw pole bez zmian, aby go zachować.' : 'Nie zapisano klucza Grok.'; ?>
</small> </small>
</div> </div>
<div class="mb-3"> <div class="mb-3" data-ai-provider-section="grok">
<label for="ai-grok-model" class="form-label"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_GROK_MODEL'); ?></label> <label for="ai-grok-model" class="form-label"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_GROK_MODEL'); ?></label>
<select id="ai-grok-model" name="ai_grok_model" class="form-select" required> <select id="ai-grok-model" name="ai_grok_model" class="form-select" required>
<?php foreach ($availableModels['grok'] as $modelId => $modelLabel) : ?> <?php foreach ($availableModels['grok'] as $modelId => $modelLabel) : ?>
@@ -55,6 +61,42 @@
<?php endforeach; ?> <?php endforeach; ?>
</select> </select>
</div> </div>
<div class="mb-3" data-ai-provider-section="groq">
<label for="ai-groq-api-key" class="form-label"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_GROQ_KEY'); ?></label>
<div class="input-group">
<input type="password" id="ai-groq-api-key" name="ai_groq_api_key" value="<?php echo htmlspecialchars($groqKey, ENT_QUOTES, 'UTF-8'); ?>" class="form-control" size="120" maxlength="4096" autocomplete="new-password">
<button type="button" class="btn btn-outline-secondary" data-ai-key-toggle="ai-groq-api-key">Pokaż</button>
</div>
<small class="form-text text-muted">
<?php echo $groqKey !== '' ? 'Zapisany klucz: ' . mb_strlen($groqKey) . ' znaków. Pozostaw pole bez zmian, aby go zachować.' : 'Nie zapisano klucza Groq.'; ?>
</small>
</div>
<div class="mb-3" data-ai-provider-section="groq">
<label for="ai-groq-model" class="form-label"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_GROQ_MODEL'); ?></label>
<select id="ai-groq-model" name="ai_groq_model" class="form-select" required>
<?php foreach ($availableModels['groq'] as $modelId => $modelLabel) : ?>
<option value="<?php echo htmlspecialchars($modelId, ENT_QUOTES, 'UTF-8'); ?>" <?php echo $groqModel === $modelId ? 'selected' : ''; ?>><?php echo htmlspecialchars($modelLabel, ENT_QUOTES, 'UTF-8'); ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="mb-3" data-ai-provider-section="gemini">
<label for="ai-gemini-api-key" class="form-label"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_GEMINI_KEY'); ?></label>
<div class="input-group">
<input type="password" id="ai-gemini-api-key" name="ai_gemini_api_key" value="<?php echo htmlspecialchars($geminiKey, ENT_QUOTES, 'UTF-8'); ?>" class="form-control" size="120" maxlength="4096" autocomplete="new-password">
<button type="button" class="btn btn-outline-secondary" data-ai-key-toggle="ai-gemini-api-key">Pokaż</button>
</div>
<small class="form-text text-muted">
<?php echo $geminiKey !== '' ? 'Zapisany klucz: ' . mb_strlen($geminiKey) . ' znaków. Pozostaw pole bez zmian, aby go zachować.' : 'Nie zapisano klucza Gemini.'; ?>
</small>
</div>
<div class="mb-3" data-ai-provider-section="gemini">
<label for="ai-gemini-model" class="form-label"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_GEMINI_MODEL'); ?></label>
<select id="ai-gemini-model" name="ai_gemini_model" class="form-select" required>
<?php foreach ($availableModels['gemini'] as $modelId => $modelLabel) : ?>
<option value="<?php echo htmlspecialchars($modelId, ENT_QUOTES, 'UTF-8'); ?>" <?php echo $geminiModel === $modelId ? 'selected' : ''; ?>><?php echo htmlspecialchars($modelLabel, ENT_QUOTES, 'UTF-8'); ?></option>
<?php endforeach; ?>
</select>
</div>
<hr> <hr>
<h3><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_TOKEN_USAGE'); ?></h3> <h3><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_TOKEN_USAGE'); ?></h3>
<p class="text-muted"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_TOKEN_USAGE_INFO'); ?></p> <p class="text-muted"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_TOKEN_USAGE_INFO'); ?></p>
@@ -71,7 +113,7 @@
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<?php foreach (['openai' => 'OpenAI', 'grok' => 'Grok'] as $usageProvider => $usageProviderLabel) : ?> <?php foreach (['openai' => 'OpenAI', 'grok' => 'Grok', 'groq' => 'Groq', 'gemini' => 'Gemini'] as $usageProvider => $usageProviderLabel) : ?>
<?php $providerUsage = $usageTotals[$usageProvider]; ?> <?php $providerUsage = $usageTotals[$usageProvider]; ?>
<tr> <tr>
<th><?php echo $usageProviderLabel; ?></th> <th><?php echo $usageProviderLabel; ?></th>
@@ -106,4 +148,12 @@ document.querySelectorAll('[data-ai-key-toggle]').forEach(function (button) {
this.textContent = visible ? 'Pokaż' : 'Ukryj'; this.textContent = visible ? 'Pokaż' : 'Ukryj';
}); });
}); });
const providerSelect = document.getElementById('ai-provider');
const updateProviderFields = function () {
document.querySelectorAll('[data-ai-provider-section]').forEach(function (section) {
section.hidden = section.dataset.aiProviderSection !== providerSelect.value;
});
};
providerSelect.addEventListener('change', updateProviderFields);
updateProviderFields();
</script> </script>
@@ -1,6 +1,18 @@
<?php defined('_JEXEC') or die; ?> <?php defined('_JEXEC') or die; ?>
<?php use Joomla\CMS\HTML\HTMLHelper; ?> <?php use Joomla\CMS\HTML\HTMLHelper; ?>
<?php use Joomla\CMS\Router\Route; ?> <?php use Joomla\CMS\Router\Route; ?>
<?php use Joomla\CMS\Uri\Uri; ?>
<?php
$resolveImageUrl = static function ($path) {
$path = trim((string) $path);
if ($path === '' || preg_match('#^(https?:)?//#i', $path)) {
return $path;
}
return Uri::root() . ltrim($path, '/');
};
?>
<div class="container-fluid"> <div class="container-fluid">
<dl class="row"> <dl class="row">
<div class="row"<?php echo (int) $this->item->extra_time > 0 ? ' style="background-color: #fff3cd;"' : ''; ?>> <div class="row"<?php echo (int) $this->item->extra_time > 0 ? ' style="background-color: #fff3cd;"' : ''; ?>>
@@ -9,6 +21,7 @@
</div> </div>
<dt class="col-sm-3"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_SET_TITLE'); ?></dt> <dt class="col-sm-3"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_SET_TITLE'); ?></dt>
<dd class="col-sm-9"><?php echo $this->escape(($this->item->subject_title ? $this->item->subject_title . ' — ' : '') . $this->item->set_title); ?></dd> <dd class="col-sm-9"><?php echo $this->escape(($this->item->subject_title ? $this->item->subject_title . ' — ' : '') . $this->item->set_title); ?></dd>
<?php if (!empty($this->item->set_image)) : ?><dt class="col-sm-3"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_SET_IMAGE'); ?></dt><dd class="col-sm-9"><img src="<?php echo htmlspecialchars($resolveImageUrl($this->item->set_image), ENT_QUOTES, 'UTF-8'); ?>" alt="" loading="lazy" style="max-width: 100%; height: auto;"></dd><?php endif; ?>
<dt class="col-sm-3"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_RESULT_SCORE'); ?></dt> <dt class="col-sm-3"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_RESULT_SCORE'); ?></dt>
<dd class="col-sm-9"><?php echo (int) $this->item->correct_count; ?> / <?php echo (int) $this->item->total_count; ?> (<?php echo htmlspecialchars((string) $this->item->percentage, ENT_QUOTES, 'UTF-8'); ?>%)</dd> <dd class="col-sm-9"><?php echo (int) $this->item->correct_count; ?> / <?php echo (int) $this->item->total_count; ?> (<?php echo htmlspecialchars((string) $this->item->percentage, ENT_QUOTES, 'UTF-8'); ?>%)</dd>
<dt class="col-sm-3"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_RESULT_POINTS_BEFORE_AFTER'); ?></dt> <dt class="col-sm-3"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_RESULT_POINTS_BEFORE_AFTER'); ?></dt>
@@ -28,7 +41,7 @@
<?php $pendingAiCount = 0; ?> <?php $pendingAiCount = 0; ?>
<?php foreach ($this->item->answers as $questionId => $answer) : ?> <?php foreach ($this->item->answers as $questionId => $answer) : ?>
<?php $candidate = $this->item->questions[(int) $questionId] ?? null; ?> <?php $candidate = $this->item->questions[(int) $questionId] ?? null; ?>
<?php if ($candidate && $candidate->question_type === 'open' && empty($answer['correct'])) { $pendingAiCount++; } ?> <?php if ($candidate && $candidate->question_type === 'open' && empty($answer['correct']) && trim((string) ($answer['selected'] ?? '')) !== '') { $pendingAiCount++; } ?>
<?php endforeach; ?> <?php endforeach; ?>
<?php if ($pendingAiCount > 0) : ?> <?php if ($pendingAiCount > 0) : ?>
<div class="mb-3"> <div class="mb-3">
@@ -36,22 +49,26 @@
<?php echo \Joomla\CMS\Language\Text::sprintf('COM_TESTQUESTIONS_AI_EVALUATE_ALL', $pendingAiCount); ?> <?php echo \Joomla\CMS\Language\Text::sprintf('COM_TESTQUESTIONS_AI_EVALUATE_ALL', $pendingAiCount); ?>
</button> </button>
<?php <?php
$usageTotals = ['input_tokens' => 0, 'output_tokens' => 0, 'total_tokens' => 0, 'cost_usd' => 0.0, 'providers' => []]; $usageTotals = ['input_tokens' => 0, 'output_tokens' => 0, 'total_tokens' => 0, 'cost_usd' => 0.0, 'cost_calls' => 0, 'providers' => []];
foreach ($this->item->answers as $savedAnswer) { foreach ($this->item->answers as $savedAnswer) {
$usage = $savedAnswer['ai_usage'] ?? null; $usage = $savedAnswer['ai_usage'] ?? null;
if (!is_array($usage)) continue; if (!is_array($usage)) continue;
$usageTotals['input_tokens'] += (int) ($usage['input_tokens'] ?? 0); $usageTotals['input_tokens'] += (int) ($usage['input_tokens'] ?? 0);
$usageTotals['output_tokens'] += (int) ($usage['output_tokens'] ?? 0); $usageTotals['output_tokens'] += (int) ($usage['output_tokens'] ?? 0);
$usageTotals['total_tokens'] += (int) ($usage['total_tokens'] ?? 0); $usageTotals['total_tokens'] += (int) ($usage['total_tokens'] ?? 0);
if (is_numeric($usage['cost_usd'] ?? null)) $usageTotals['cost_usd'] += (float) $usage['cost_usd']; if (is_numeric($usage['cost_usd'] ?? null)) {
$usageTotals['cost_usd'] += (float) $usage['cost_usd'];
$usageTotals['cost_calls']++;
}
if (!empty($usage['provider'])) $usageTotals['providers'][(string) $usage['provider']] = true; if (!empty($usage['provider'])) $usageTotals['providers'][(string) $usage['provider']] = true;
} }
?> ?>
<?php if ($usageTotals['total_tokens'] > 0) : ?> <?php if ($usageTotals['total_tokens'] > 0) : ?>
<?php $usageProviderLabels = array_map(static function ($usageProvider) { return ['openai' => 'OpenAI', 'grok' => 'Grok', 'groq' => 'Groq', 'gemini' => 'Gemini'][$usageProvider] ?? $usageProvider; }, array_keys($usageTotals['providers'])); ?>
<span class="badge text-bg-light border ms-2" title="Suma dotychczasowych ocen AI"> <span class="badge text-bg-light border ms-2" title="Suma dotychczasowych ocen AI">
✦ <?php echo implode(' + ', array_map('htmlspecialchars', array_keys($usageTotals['providers']))); ?>: ✦ <?php echo implode(' + ', array_map('htmlspecialchars', $usageProviderLabels)); ?>:
<?php echo number_format($usageTotals['total_tokens'], 0, ',', ' '); ?> tokenów, <?php echo number_format($usageTotals['total_tokens'], 0, ',', ' '); ?> tokenów,
<?php echo number_format($usageTotals['cost_usd'], 8, ',', ' '); ?> USD <?php echo $usageTotals['cost_calls'] > 0 ? number_format($usageTotals['cost_usd'], 8, ',', ' ') . ' USD' : 'koszt niedostępny'; ?>
</span> </span>
<?php endif; ?> <?php endif; ?>
</div> </div>
@@ -59,8 +76,10 @@
<h2><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_RESULT_ANSWERS'); ?></h2> <h2><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_RESULT_ANSWERS'); ?></h2>
<?php foreach ($this->item->answers as $questionId => $answer) : ?> <?php foreach ($this->item->answers as $questionId => $answer) : ?>
<?php $question = $this->item->questions[(int) $questionId] ?? null; if (!$question) continue; ?> <?php $question = $this->item->questions[(int) $questionId] ?? null; if (!$question) continue; ?>
<?php $hasResponse = trim((string) ($answer['selected'] ?? '')) !== ''; ?>
<article class="mb-4 border rounded p-3"> <article class="mb-4 border rounded p-3">
<div class="mb-2"><?php echo $question->question; ?></div> <div class="mb-2"><?php echo $question->question; ?></div>
<?php if (!empty($question->image)) : ?><div class="mb-3"><img src="<?php echo htmlspecialchars($resolveImageUrl($question->image), ENT_QUOTES, 'UTF-8'); ?>" alt="" loading="lazy" style="max-width: 100%; height: auto;"></div><?php endif; ?>
<?php if ($question->question_type === 'open') : ?> <?php if ($question->question_type === 'open') : ?>
<div><strong><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_YOUR_ANSWER'); ?>:</strong> <?php echo htmlspecialchars($answer['selected'] ?: '—', ENT_QUOTES, 'UTF-8'); ?></div> <div><strong><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_YOUR_ANSWER'); ?>:</strong> <?php echo htmlspecialchars($answer['selected'] ?: '—', ENT_QUOTES, 'UTF-8'); ?></div>
<div><strong><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_CORRECT_PATTERN'); ?>:</strong> <?php echo htmlspecialchars($question->answer_open, ENT_QUOTES, 'UTF-8'); ?></div> <div><strong><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_CORRECT_PATTERN'); ?>:</strong> <?php echo htmlspecialchars($question->answer_open, ENT_QUOTES, 'UTF-8'); ?></div>
@@ -69,7 +88,7 @@
<?php endif; ?> <?php endif; ?>
<div class="mt-2 <?php echo !empty($answer['correct']) ? 'text-success' : 'text-danger'; ?>"><?php echo !empty($answer['correct']) ? '✓ ' . \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_ANSWER_CORRECT') : '✗ ' . \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_ANSWER_INCORRECT'); ?></div> <div class="mt-2 <?php echo !empty($answer['correct']) ? 'text-success' : 'text-danger'; ?>"><?php echo !empty($answer['correct']) ? '✓ ' . \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_ANSWER_CORRECT') : '✗ ' . \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_ANSWER_INCORRECT'); ?></div>
<?php if (empty($answer['correct'])) : ?> <?php if (empty($answer['correct'])) : ?>
<?php if ($question->question_type === 'open') : ?> <?php if ($question->question_type === 'open' && $hasResponse) : ?>
<div class="mt-3"> <div class="mt-3">
<button type="submit" name="ai_question_id" value="<?php echo (int) $questionId; ?>" onclick="this.form.task.value='result.ai';" formaction="<?php echo Route::_('index.php?option=com_testquestions&task=result.ai&id=' . (int) $this->item->id); ?>" class="btn btn-outline-primary"> <button type="submit" name="ai_question_id" value="<?php echo (int) $questionId; ?>" onclick="this.form.task.value='result.ai';" formaction="<?php echo Route::_('index.php?option=com_testquestions&task=result.ai&id=' . (int) $this->item->id); ?>" class="btn btn-outline-primary">
<?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_EVALUATE'); ?> <?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_EVALUATE'); ?>
@@ -77,8 +96,8 @@
<?php if (!empty($answer['ai_usage']) && is_array($answer['ai_usage'])) : ?> <?php if (!empty($answer['ai_usage']) && is_array($answer['ai_usage'])) : ?>
<?php $usage = $answer['ai_usage']; ?> <?php $usage = $answer['ai_usage']; ?>
<?php $usageProvider = (string) ($usage['provider'] ?? ''); ?> <?php $usageProvider = (string) ($usage['provider'] ?? ''); ?>
<span class="badge text-bg-light border ms-2" title="<?php echo $usageProvider === 'grok' ? 'Koszt zwrócony przez dostawcę' : 'Koszt obliczony z faktycznie wykorzystanych tokenów i stawek modelu'; ?>"> <span class="badge text-bg-light border ms-2" title="<?php echo $usageProvider === 'grok' ? 'Koszt zwrócony przez dostawcę' : (in_array($usageProvider, ['groq', 'gemini'], true) ? 'Dostawca zwrócił wykorzystane tokeny; koszt nie jest zwracany przez to API' : 'Koszt obliczony z faktycznie wykorzystanych tokenów i stawek modelu'); ?>">
<?php echo $usageProvider === 'grok' ? '✦ Grok' : '◉ OpenAI'; ?> · <?php echo $usageProvider === 'grok' ? '✦ Grok' : ($usageProvider === 'groq' ? '⚡ Groq' : ($usageProvider === 'gemini' ? '✧ Gemini' : '◉ OpenAI')); ?> ·
<?php echo number_format((int) ($usage['input_tokens'] ?? 0), 0, ',', ' '); ?> in / <?php echo number_format((int) ($usage['input_tokens'] ?? 0), 0, ',', ' '); ?> in /
<?php echo number_format((int) ($usage['output_tokens'] ?? 0), 0, ',', ' '); ?> out · <?php echo number_format((int) ($usage['output_tokens'] ?? 0), 0, ',', ' '); ?> out ·
<?php echo is_numeric($usage['cost_usd'] ?? null) ? number_format((float) $usage['cost_usd'], 8, ',', ' ') . ' USD' : 'koszt niedostępny'; ?> <?php echo is_numeric($usage['cost_usd'] ?? null) ? number_format((float) $usage['cost_usd'], 8, ',', ' ') . ' USD' : 'koszt niedostępny'; ?>
@@ -87,10 +106,15 @@
<?php endif; ?> <?php endif; ?>
</div> </div>
<?php if (!empty($answer['ai_feedback'])) : ?> <?php if (!empty($answer['ai_feedback'])) : ?>
<div class="alert alert-info mt-3"><strong><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_RESULT'); ?>:</strong><br><?php echo nl2br(htmlspecialchars((string) $answer['ai_feedback'], ENT_QUOTES, 'UTF-8')); ?></div> <?php
$aiPoints = (int) ($answer['awarded_points'] ?? 0);
$maxPoints = (int) ($question->points ?? 0);
$aiAlertClass = $aiPoints <= 0 ? 'alert-danger' : ($aiPoints >= $maxPoints ? 'alert-success' : 'alert-info');
?>
<div class="alert <?php echo $aiAlertClass; ?> mt-3"><strong><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_AI_RESULT'); ?>:</strong><br><?php echo nl2br(htmlspecialchars((string) $answer['ai_feedback'], ENT_QUOTES, 'UTF-8')); ?></div>
<?php endif; ?> <?php endif; ?>
<?php endif; ?> <?php endif; ?>
<?php if ($question->question_type === 'open') : ?> <?php if ($question->question_type === 'open' && $hasResponse) : ?>
<div class="row mt-3"> <div class="row mt-3">
<div class="col-md-3"> <div class="col-md-3">
<label for="awarded-points-<?php echo (int) $questionId; ?>" class="form-label"><?php echo \Joomla\CMS\Language\Text::sprintf('COM_TESTQUESTIONS_RESULT_AWARDED_POINTS', (int) ($question->points ?? 0)); ?></label> <label for="awarded-points-<?php echo (int) $questionId; ?>" class="form-label"><?php echo \Joomla\CMS\Language\Text::sprintf('COM_TESTQUESTIONS_RESULT_AWARDED_POINTS', (int) ($question->points ?? 0)); ?></label>
@@ -4,6 +4,7 @@ defined('_JEXEC') or die;
use Joomla\CMS\HTML\HTMLHelper; use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Router\Route; use Joomla\CMS\Router\Route;
HTMLHelper::_('behavior.multiselect');
?> ?>
<form action="<?php echo Route::_('index.php?option=com_testquestions&view=results'); ?>" method="post" name="adminForm" id="adminForm"> <form action="<?php echo Route::_('index.php?option=com_testquestions&view=results'); ?>" method="post" name="adminForm" id="adminForm">
<div class="row mb-3"> <div class="row mb-3">
@@ -49,10 +50,23 @@ use Joomla\CMS\Router\Route;
<?php echo number_format((int) $this->aiUsageTotals['providers']['grok']['output_tokens'], 0, ',', ' '); ?> wyj.) <?php echo number_format((int) $this->aiUsageTotals['providers']['grok']['output_tokens'], 0, ',', ' '); ?> wyj.)
<?php if ($this->aiUsageTotals['providers']['grok']['cost_usd'] > 0) : ?> · <?php echo number_format((float) $this->aiUsageTotals['providers']['grok']['cost_usd'], 8, ',', ' '); ?> USD<?php endif; ?> <?php if ($this->aiUsageTotals['providers']['grok']['cost_usd'] > 0) : ?> · <?php echo number_format((float) $this->aiUsageTotals['providers']['grok']['cost_usd'], 8, ',', ' '); ?> USD<?php endif; ?>
</span> </span>
<span class="d-block">
<strong>Groq:</strong>
<?php echo number_format((int) $this->aiUsageTotals['providers']['groq']['total_tokens'], 0, ',', ' '); ?> tokenów
(<?php echo number_format((int) $this->aiUsageTotals['providers']['groq']['input_tokens'], 0, ',', ' '); ?> wej. /
<?php echo number_format((int) $this->aiUsageTotals['providers']['groq']['output_tokens'], 0, ',', ' '); ?> wyj.)
</span>
<span class="d-block">
<strong>Gemini:</strong>
<?php echo number_format((int) $this->aiUsageTotals['providers']['gemini']['total_tokens'], 0, ',', ' '); ?> tokenów
(<?php echo number_format((int) $this->aiUsageTotals['providers']['gemini']['input_tokens'], 0, ',', ' '); ?> wej. /
<?php echo number_format((int) $this->aiUsageTotals['providers']['gemini']['output_tokens'], 0, ',', ' '); ?> wyj.)
</span>
<span class="d-block"><strong>Łącznie:</strong> <?php echo number_format((int) $this->aiUsageTotals['total_tokens'], 0, ',', ' '); ?> tokenów</span> <span class="d-block"><strong>Łącznie:</strong> <?php echo number_format((int) $this->aiUsageTotals['total_tokens'], 0, ',', ' '); ?> tokenów</span>
</div> </div>
<table class="table table-striped"> <table class="table table-striped">
<thead><tr> <thead><tr>
<th class="w-1"><?php echo HTMLHelper::_('grid.checkall'); ?></th>
<th><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_RESULT_PARTICIPANT'); ?></th> <th><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_RESULT_PARTICIPANT'); ?></th>
<th><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_SET_TITLE'); ?></th> <th><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_SET_TITLE'); ?></th>
<th><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_RESULT_POINTS_BEFORE_AFTER'); ?></th> <th><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_RESULT_POINTS_BEFORE_AFTER'); ?></th>
@@ -62,8 +76,9 @@ use Joomla\CMS\Router\Route;
<th><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_RESULT_AI_TOKENS'); ?></th> <th><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_RESULT_AI_TOKENS'); ?></th>
</tr></thead> </tr></thead>
<tbody> <tbody>
<?php foreach ($this->items as $item) : ?> <?php foreach ($this->items as $i => $item) : ?>
<tr class="<?php echo (int) $item->extra_time > 0 ? 'table-warning' : ''; ?>"> <tr class="<?php echo (int) $item->extra_time > 0 ? 'table-warning' : ''; ?>">
<td><?php echo HTMLHelper::_('grid.id', $i, $item->id); ?></td>
<th><a href="<?php echo Route::_('index.php?option=com_testquestions&view=result&id=' . (int) $item->id); ?>"><?php echo $this->escape($item->participant_name); ?></a></th> <th><a href="<?php echo Route::_('index.php?option=com_testquestions&view=result&id=' . (int) $item->id); ?>"><?php echo $this->escape($item->participant_name); ?></a></th>
<td><?php echo $this->escape(($item->subject_title ? $item->subject_title . ' — ' : '') . $item->set_title); ?></td> <td><?php echo $this->escape(($item->subject_title ? $item->subject_title . ' — ' : '') . $item->set_title); ?></td>
<?php $pointsTotal = (int) $item->points_total ?: (int) $item->total_count; ?> <?php $pointsTotal = (int) $item->points_total ?: (int) $item->total_count; ?>
@@ -81,7 +96,9 @@ use Joomla\CMS\Router\Route;
<?php if ($item->ai_total_tokens > 0) : ?> <?php if ($item->ai_total_tokens > 0) : ?>
<small class="d-block text-muted"> <small class="d-block text-muted">
OpenAI: <?php echo number_format((int) $item->ai_tokens_by_provider['openai'], 0, ',', ' '); ?> · OpenAI: <?php echo number_format((int) $item->ai_tokens_by_provider['openai'], 0, ',', ' '); ?> ·
Grok: <?php echo number_format((int) $item->ai_tokens_by_provider['grok'], 0, ',', ' '); ?> Grok: <?php echo number_format((int) $item->ai_tokens_by_provider['grok'], 0, ',', ' '); ?> ·
Groq: <?php echo number_format((int) $item->ai_tokens_by_provider['groq'], 0, ',', ' '); ?>
· Gemini: <?php echo number_format((int) $item->ai_tokens_by_provider['gemini'], 0, ',', ' '); ?>
</small> </small>
<small class="d-block text-muted"> <small class="d-block text-muted">
<?php echo number_format((int) $item->ai_total_tokens, 0, ',', ' '); ?> łącznie <?php echo number_format((int) $item->ai_total_tokens, 0, ',', ' '); ?> łącznie
@@ -96,6 +113,7 @@ use Joomla\CMS\Router\Route;
</tbody> </tbody>
</table> </table>
<?php echo $this->pagination->getListFooter(); ?> <?php echo $this->pagination->getListFooter(); ?>
<input type="hidden" name="boxchecked" value="0">
<input type="hidden" name="task" value=""> <input type="hidden" name="task" value="">
<?php echo HTMLHelper::_('form.token'); ?> <?php echo HTMLHelper::_('form.token'); ?>
</form> </form>
+1 -1
View File
@@ -4,7 +4,7 @@
<creationDate>2026-10-14</creationDate> <creationDate>2026-10-14</creationDate>
<author>Komponent</author> <author>Komponent</author>
<license>GNU General Public License version 2 or later</license> <license>GNU General Public License version 2 or later</license>
<version>1.43.19</version> <version>1.43.31</version>
<description>COM_TESTQUESTIONS_DESCRIPTION</description> <description>COM_TESTQUESTIONS_DESCRIPTION</description>
<element>com_testquestions</element> <element>com_testquestions</element>
<namespace path="src">Komponent\Component\Testquestions</namespace> <namespace path="src">Komponent\Component\Testquestions</namespace>
@@ -77,7 +77,7 @@ class SetModel extends BaseDatabaseModel
} }
$query = $db->getQuery(true) $query = $db->getQuery(true)
->select(['q.id', 'q.question_type', 'q.question', 'q.answer_a', 'q.answer_b', 'q.answer_c', 'q.answer_d', 'q.answer_open', 'q.correct_answer', 'q.points', 'q.image']) ->select(['q.id', 'q.question_type', 'q.question', 'q.answer_a', 'q.answer_b', 'q.answer_c', 'q.answer_d', 'q.answer_open', 'q.correct_answer', 'q.points', 'q.image', 'q.time_limit'])
->from($db->quoteName('#__testquestions_set_questions', 'sq')) ->from($db->quoteName('#__testquestions_set_questions', 'sq'))
->innerJoin($db->quoteName('#__testquestions_questions', 'q') . ' ON q.id = sq.question_id') ->innerJoin($db->quoteName('#__testquestions_questions', 'q') . ' ON q.id = sq.question_id')
->where('sq.set_id = ' . $setId) ->where('sq.set_id = ' . $setId)
@@ -25,6 +25,26 @@ class HtmlView extends BaseHtmlView
$this->items = $this->get('Items'); $this->items = $this->get('Items');
$this->sets = $this->get('Sets'); $this->sets = $this->get('Sets');
$input = Factory::getApplication()->getInput(); $input = Factory::getApplication()->getInput();
if ($input->getCmd('task') === 'check' && $input->getMethod() === 'POST' && $this->items) {
$submittedQuestionOrder = array_map('intval', (array) $input->post->get('question_order', [], 'array'));
$expectedQuestionIds = array_map(static function ($item) {
return (int) $item->id;
}, $this->items);
$sortedSubmittedOrder = $submittedQuestionOrder;
$sortedExpectedIds = $expectedQuestionIds;
sort($sortedSubmittedOrder);
sort($sortedExpectedIds);
if ($sortedSubmittedOrder === $sortedExpectedIds) {
$itemsById = [];
foreach ($this->items as $item) {
$itemsById[(int) $item->id] = $item;
}
$this->items = array_values(array_map(static function ($questionId) use ($itemsById) {
return $itemsById[$questionId];
}, $submittedQuestionOrder));
}
}
$this->started = $input->getMethod() === 'POST' $this->started = $input->getMethod() === 'POST'
&& $input->post->getString('participant_name', '') !== '' && $input->post->getString('participant_name', '') !== ''
&& $input->post->getInt('set_id', 0) > 0; && $input->post->getInt('set_id', 0) > 0;
@@ -51,6 +71,7 @@ class HtmlView extends BaseHtmlView
} }
$answers = (array) $input->post->get('answers', [], 'array'); $answers = (array) $input->post->get('answers', [], 'array');
$submittedAnswerOrder = (array) $input->post->get('answer_order', [], 'array');
$results = []; $results = [];
$correct = 0; $correct = 0;
@@ -70,6 +91,14 @@ class HtmlView extends BaseHtmlView
$isCorrect = (string) $item->correct_answer === $selected; $isCorrect = (string) $item->correct_answer === $selected;
} }
$answerOrder = array_map('intval', explode(',', (string) ($submittedAnswerOrder[$item->id] ?? '')));
sort($answerOrder);
if ($item->question_type !== 'closed' || $answerOrder !== [1, 2, 3, 4]) {
$answerOrder = [1, 2, 3, 4];
} else {
$answerOrder = array_map('intval', explode(',', (string) $submittedAnswerOrder[$item->id]));
}
if ($isCorrect) { if ($isCorrect) {
$correct++; $correct++;
} }
@@ -78,6 +107,7 @@ class HtmlView extends BaseHtmlView
'selected' => $selected, 'selected' => $selected,
'correct' => $isCorrect, 'correct' => $isCorrect,
'points' => (int) ($item->points ?? 0), 'points' => (int) ($item->points ?? 0),
'answer_order' => $answerOrder,
]; ];
} }
@@ -5,6 +5,8 @@ defined('_JEXEC') or die;
use Joomla\CMS\Factory; use Joomla\CMS\Factory;
use Joomla\CMS\Uri\Uri; use Joomla\CMS\Uri\Uri;
$testDurationSeconds = 0;
$resolveImageUrl = static function ($path) { $resolveImageUrl = static function ($path) {
$path = trim((string) $path); $path = trim((string) $path);
@@ -50,16 +52,26 @@ $resolveImageUrl = static function ($path) {
<?php elseif (!$this->set) : ?> <?php elseif (!$this->set) : ?>
<div class="alert alert-info"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_SET_NOT_FOUND'); ?></div> <div class="alert alert-info"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_SET_NOT_FOUND'); ?></div>
<?php else : ?> <?php else : ?>
<?php
$extraTime = Factory::getApplication()->getInput()->post->getInt('extra_time', 0);
$baseDurationSeconds = (int) $this->set->duration > 0
? (int) $this->set->duration * 60
: array_sum(array_map(static function ($item) {
return max(0, (int) ($item->time_limit ?? 0));
}, $this->items));
$testDurationSeconds = $baseDurationSeconds + ($extraTime * 60);
$durationMinutes = intdiv($testDurationSeconds, 60);
$durationRemainder = $testDurationSeconds % 60;
?>
<header class="test-set-header"> <header class="test-set-header">
<?php if ($this->set->subject_title) : ?><div class="text-muted"><?php echo htmlspecialchars($this->set->subject_title, ENT_QUOTES, 'UTF-8'); ?></div><?php endif; ?> <?php if ($this->set->subject_title) : ?><div class="text-muted"><?php echo htmlspecialchars($this->set->subject_title, ENT_QUOTES, 'UTF-8'); ?></div><?php endif; ?>
<h1><?php echo htmlspecialchars($this->set->title, ENT_QUOTES, 'UTF-8'); ?></h1> <h1><?php echo htmlspecialchars($this->set->title, ENT_QUOTES, 'UTF-8'); ?></h1>
<?php $extraTime = Factory::getApplication()->getInput()->post->getInt('extra_time', 0); ?> <?php if ($testDurationSeconds > 0) : ?><div class="small text-muted"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_SET_DURATION'); ?>: <?php echo $durationMinutes; ?> min<?php if ($durationRemainder > 0) : ?> <?php echo $durationRemainder; ?> s<?php endif; ?></div><?php endif; ?>
<?php if ((int) $this->set->duration > 0) : ?><div class="small text-muted"><?php echo \Joomla\CMS\Language\Text::_('COM_TESTQUESTIONS_SET_DURATION'); ?>: <?php echo (int) $this->set->duration + $extraTime; ?> min</div><?php endif; ?>
<?php if ($this->set->image) : ?><div class="foto_pyt"><img src="<?php echo htmlspecialchars($resolveImageUrl($this->set->image), ENT_QUOTES, 'UTF-8'); ?>" alt="" loading="lazy"></div><?php endif; ?>
<?php if ($this->set->test_content) : ?><div class="test-set-content"><?php echo $this->set->test_content; ?></div><?php endif; ?> <?php if ($this->set->test_content) : ?><div class="test-set-content"><?php echo $this->set->test_content; ?></div><?php endif; ?>
<?php if ($this->set->image) : ?><div class="foto_pyt"><img src="<?php echo htmlspecialchars($resolveImageUrl($this->set->image), ENT_QUOTES, 'UTF-8'); ?>" alt="" loading="lazy"></div><?php endif; ?>
</header> </header>
<?php if (!$this->results && ((int) $this->set->duration + $extraTime) > 0) : ?> <?php if (!$this->results && $testDurationSeconds > 0) : ?>
<div class="timer-container mb-4" id="test-timer-container" data-duration="<?php echo ((int) $this->set->duration + $extraTime) * 60; ?>" aria-live="polite"> <div class="timer-container mb-4" id="test-timer-container" data-duration="<?php echo $testDurationSeconds; ?>" aria-live="polite">
<svg width="120" height="120" viewBox="0 0 120 120" aria-hidden="true"> <svg width="120" height="120" viewBox="0 0 120 120" aria-hidden="true">
<circle cx="60" cy="60" r="54" fill="none" stroke="#dfe3e7" stroke-width="8"></circle> <circle cx="60" cy="60" r="54" fill="none" stroke="#dfe3e7" stroke-width="8"></circle>
<circle id="test-timer-ring" class="progress-ring__circle" cx="60" cy="60" r="54" fill="none" stroke="#4a86cf" stroke-width="8" stroke-linecap="round"></circle> <circle id="test-timer-ring" class="progress-ring__circle" cx="60" cy="60" r="54" fill="none" stroke="#4a86cf" stroke-width="8" stroke-linecap="round"></circle>
@@ -72,7 +84,18 @@ $resolveImageUrl = static function ($path) {
<?php endif; ?> <?php endif; ?>
<?php if ($this->items) : ?> <?php if ($this->items) : ?>
<form action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI'], ENT_QUOTES, 'UTF-8'); ?>" method="post" id="test-form"> <form action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI'], ENT_QUOTES, 'UTF-8'); ?>" method="post" id="test-form">
<?php if (!$this->results) : ?>
<?php foreach ($this->items as $item) : ?><input type="hidden" name="question_order[]" value="<?php echo (int) $item->id; ?>"><?php endforeach; ?>
<?php endif; ?>
<?php foreach ($this->items as $number => $item) : ?> <?php foreach ($this->items as $number => $item) : ?>
<?php
$answerOrder = $this->results && !empty($this->results['items'][$item->id]['answer_order'])
? $this->results['items'][$item->id]['answer_order']
: [1, 2, 3, 4];
if (!$this->results && $item->question_type === 'closed') {
shuffle($answerOrder);
}
?>
<article class="testquestion mb-4"> <article class="testquestion mb-4">
<div class="pyt"><div class="question-header"><span class="question-number"><?php echo ($number + 1) . '.'; ?></span><div class="question-text"><?php echo $item->question; ?></div></div></div> <div class="pyt"><div class="question-header"><span class="question-number"><?php echo ($number + 1) . '.'; ?></span><div class="question-text"><?php echo $item->question; ?></div></div></div>
<?php if ($item->image) : ?><div class="foto_pyt"><img src="<?php echo htmlspecialchars($resolveImageUrl($item->image), ENT_QUOTES, 'UTF-8'); ?>" alt="" loading="lazy"></div><?php endif; ?> <?php if ($item->image) : ?><div class="foto_pyt"><img src="<?php echo htmlspecialchars($resolveImageUrl($item->image), ENT_QUOTES, 'UTF-8'); ?>" alt="" loading="lazy"></div><?php endif; ?>
@@ -87,12 +110,14 @@ $resolveImageUrl = static function ($path) {
<?php endif; ?> <?php endif; ?>
</div> </div>
<?php else : ?> <?php else : ?>
<?php if (!$this->results) : ?><input type="hidden" name="answer_order[<?php echo (int) $item->id; ?>]" value="<?php echo htmlspecialchars(implode(',', $answerOrder), ENT_QUOTES, 'UTF-8'); ?>"><?php endif; ?>
<ol type="A" class="answer-list"> <ol type="A" class="answer-list">
<?php foreach (['answer_a', 'answer_b', 'answer_c', 'answer_d'] as $answerIndex => $answerField) : ?> <?php foreach ($answerOrder as $displayIndex => $optionValue) : ?>
<?php $isSelected = $this->results && $this->results['items'][$item->id]['selected'] === (string) ($answerIndex + 1); ?> <?php $answerField = 'answer_' . chr(96 + (int) $optionValue); ?>
<?php $isCorrectAnswer = $this->results && (string) $item->correct_answer === (string) ($answerIndex + 1); ?> <?php $isSelected = $this->results && $this->results['items'][$item->id]['selected'] === (string) $optionValue; ?>
<?php $isCorrectAnswer = $this->results && (string) $item->correct_answer === (string) $optionValue; ?>
<li class="<?php echo $isSelected && $this->results['items'][$item->id]['correct'] ? 'odpup' : ($isSelected ? 'odpu' : ($isCorrectAnswer ? 'odpp' : 'odp')); ?>"> <li class="<?php echo $isSelected && $this->results['items'][$item->id]['correct'] ? 'odpup' : ($isSelected ? 'odpu' : ($isCorrectAnswer ? 'odpp' : 'odp')); ?>">
<label><input type="radio" name="answers[<?php echo (int) $item->id; ?>]" value="<?php echo $answerIndex + 1; ?>" <?php echo $isSelected ? 'checked' : ''; ?>><strong><?php echo chr(65 + $answerIndex); ?>.</strong> <span class="answer-text"><?php echo $item->$answerField; ?></span></label> <label><input type="radio" name="answers[<?php echo (int) $item->id; ?>]" value="<?php echo (int) $optionValue; ?>" <?php echo $isSelected ? 'checked' : ''; ?>><strong><?php echo chr(65 + $displayIndex); ?>.</strong> <span class="answer-text"><?php echo $item->$answerField; ?></span></label>
</li> </li>
<?php endforeach; ?> <?php endforeach; ?>
</ol> </ol>
@@ -118,7 +143,7 @@ $resolveImageUrl = static function ($path) {
<?php endif; ?> <?php endif; ?>
<?php endif; ?> <?php endif; ?>
</div> </div>
<?php if ($this->started && !$this->results && ((int) $this->set->duration + $extraTime) > 0) : ?> <?php if ($this->started && !$this->results && $testDurationSeconds > 0) : ?>
<script> <script>
document.addEventListener('DOMContentLoaded', function () { document.addEventListener('DOMContentLoaded', function () {
const container = document.getElementById('test-timer-container'); const container = document.getElementById('test-timer-container');