Save AI settings through component page
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
<?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\BaseController;
|
||||
use Joomla\CMS\Router\Route;
|
||||
use Joomla\CMS\Session\Session;
|
||||
|
||||
class AiController extends BaseController
|
||||
{
|
||||
public function save(): void
|
||||
{
|
||||
if (!Session::checkToken()) {
|
||||
throw new \RuntimeException(Text::_('JINVALID_TOKEN'), 403);
|
||||
}
|
||||
|
||||
$user = Factory::getApplication()->getIdentity();
|
||||
if (!$user->authorise('core.admin', 'com_testquestions') && !$user->authorise('core.options', 'com_testquestions')) {
|
||||
throw new \RuntimeException(Text::_('JERROR_ALERTNOAUTHOR'), 403);
|
||||
}
|
||||
|
||||
$input = Factory::getApplication()->getInput();
|
||||
$provider = strtolower($input->post->getCmd('ai_provider', ''));
|
||||
if (!in_array($provider, ['openai', 'grok'], true)) {
|
||||
throw new \RuntimeException(Text::_('COM_TESTQUESTIONS_AI_PROVIDER_INVALID'));
|
||||
}
|
||||
|
||||
$db = Factory::getContainer()->get('DatabaseDriver');
|
||||
$row = $db->setQuery(
|
||||
$db->getQuery(true)
|
||||
->select([$db->quoteName('extension_id'), $db->quoteName('params')])
|
||||
->from($db->quoteName('#__extensions'))
|
||||
->where($db->quoteName('type') . ' = ' . $db->quote('component'))
|
||||
->where($db->quoteName('element') . ' = ' . $db->quote('com_testquestions'))
|
||||
)->loadObject();
|
||||
|
||||
if (!$row) {
|
||||
throw new \RuntimeException(Text::_('COM_TESTQUESTIONS_AI_SAVE_FAILED'));
|
||||
}
|
||||
|
||||
$settings = json_decode((string) $row->params, true);
|
||||
$settings = is_array($settings) ? $settings : [];
|
||||
$apiKey = trim((string) $input->post->get('ai_api_key', '', 'RAW'));
|
||||
|
||||
$settings['ai_provider'] = $provider;
|
||||
if ($apiKey !== '') {
|
||||
$settings['ai_api_key'] = $apiKey;
|
||||
}
|
||||
|
||||
$extension = (object) [
|
||||
'extension_id' => (int) $row->extension_id,
|
||||
'params' => json_encode($settings, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
|
||||
];
|
||||
|
||||
if (!$db->updateObject('#__extensions', $extension, 'extension_id')) {
|
||||
throw new \RuntimeException(Text::_('COM_TESTQUESTIONS_AI_SAVE_FAILED'));
|
||||
}
|
||||
|
||||
$this->setRedirect(
|
||||
Route::_('index.php?option=com_testquestions&view=ai', false),
|
||||
Text::_('COM_TESTQUESTIONS_AI_SETTINGS_SAVED')
|
||||
);
|
||||
}
|
||||
|
||||
public function cancel(): void
|
||||
{
|
||||
$this->setRedirect(Route::_('index.php?option=com_testquestions&view=questions', false));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user