604 lines
34 KiB
PHP
604 lines
34 KiB
PHP
<?php
|
|
if (!defined('ABSPATH')) {
|
|
exit;
|
|
}
|
|
|
|
/**
|
|
* Settings page: Settings > MozOut All in One AI, with tabs.
|
|
* The API key is saved encrypted and is never printed back into the page.
|
|
*/
|
|
class MOZOUT_AI_Admin
|
|
{
|
|
const PAGE = 'mozout-ai';
|
|
|
|
public static function init()
|
|
{
|
|
add_action('admin_menu', array(__CLASS__, 'menu'));
|
|
add_action('admin_post_mozout_ai_save', array(__CLASS__, 'save'));
|
|
add_action('admin_post_mozout_ai_test', array(__CLASS__, 'test_connection'));
|
|
add_action('admin_post_mozout_ai_test_ai', array(__CLASS__, 'test_ai'));
|
|
add_action('admin_post_mozout_ai_draft', array(__CLASS__, 'draft'));
|
|
add_action('admin_enqueue_scripts', array(__CLASS__, 'assets'));
|
|
add_filter('plugin_action_links_' . plugin_basename(MOZOUT_AI_FILE), array(__CLASS__, 'action_links'));
|
|
}
|
|
|
|
public static function menu()
|
|
{
|
|
add_options_page(
|
|
__('MozOut All in One AI', 'mozout-ai'),
|
|
__('MozOut All in One AI', 'mozout-ai'),
|
|
'manage_options',
|
|
self::PAGE,
|
|
array(__CLASS__, 'page')
|
|
);
|
|
}
|
|
|
|
public static function action_links($links)
|
|
{
|
|
array_unshift($links, '<a href="' . esc_url(self::url()) . '">' . esc_html__('Settings', 'mozout-ai') . '</a>');
|
|
return $links;
|
|
}
|
|
|
|
public static function assets($hook)
|
|
{
|
|
if ($hook !== 'settings_page_' . self::PAGE) {
|
|
return;
|
|
}
|
|
wp_enqueue_style('mozout-ai-admin', MOZOUT_AI_URL . 'assets/admin.css', array(), MOZOUT_AI_VERSION);
|
|
wp_enqueue_script('mozout-ai-select', MOZOUT_AI_URL . 'assets/select.js', array(), MOZOUT_AI_VERSION, true);
|
|
}
|
|
|
|
public static function url($tab = 'connection', $args = array())
|
|
{
|
|
return add_query_arg(array_merge(array('page' => self::PAGE, 'tab' => $tab), $args), admin_url('options-general.php'));
|
|
}
|
|
|
|
private static function tabs()
|
|
{
|
|
return array(
|
|
'connection' => __('Connection', 'mozout-ai'),
|
|
'assistant' => __('Site assistant', 'mozout-ai'),
|
|
'writing' => __('Writing help', 'mozout-ai'),
|
|
'drafts' => __('New draft', 'mozout-ai'),
|
|
'activity' => __('Activity', 'mozout-ai'),
|
|
);
|
|
}
|
|
|
|
private static function notice_from_query()
|
|
{
|
|
if (empty($_GET['mozout_ai_msg'])) {
|
|
return;
|
|
}
|
|
$key = sanitize_key(wp_unslash($_GET['mozout_ai_msg']));
|
|
$notice = get_transient('mozout_ai_notice_' . get_current_user_id());
|
|
delete_transient('mozout_ai_notice_' . get_current_user_id());
|
|
if (!is_array($notice) || $notice['key'] !== $key) {
|
|
return;
|
|
}
|
|
$class = $notice['ok'] ? 'notice-success' : 'notice-error';
|
|
echo '<div class="notice ' . esc_attr($class) . ' is-dismissible"><p>' . esc_html($notice['text']);
|
|
if (!empty($notice['link'])) {
|
|
echo ' <a class="mozout-ai-draft-link" href="' . esc_url($notice['link']) . '">' . esc_html__('Open the draft', 'mozout-ai') . '</a>';
|
|
}
|
|
echo '</p></div>';
|
|
}
|
|
|
|
private static function redirect($tab, $ok, $text, $link = '')
|
|
{
|
|
$key = strtolower(wp_generate_password(8, false, false));
|
|
set_transient('mozout_ai_notice_' . get_current_user_id(), array('key' => $key, 'ok' => $ok, 'text' => $text, 'link' => $link), 120);
|
|
wp_safe_redirect(self::url($tab, array('mozout_ai_msg' => $key)));
|
|
exit;
|
|
}
|
|
|
|
private static function check($action, $cap = 'manage_options')
|
|
{
|
|
if (!current_user_can($cap)) {
|
|
wp_die(esc_html__('You do not have permission to change these settings.', 'mozout-ai'), 403);
|
|
}
|
|
check_admin_referer($action);
|
|
}
|
|
|
|
/* ------------------------------------------------------------------ */
|
|
/* Page */
|
|
/* ------------------------------------------------------------------ */
|
|
|
|
public static function page()
|
|
{
|
|
if (!current_user_can('manage_options')) {
|
|
return;
|
|
}
|
|
$tabs = self::tabs();
|
|
$tab = isset($_GET['tab']) ? sanitize_key(wp_unslash($_GET['tab'])) : 'connection';
|
|
if (!isset($tabs[$tab])) {
|
|
$tab = 'connection';
|
|
}
|
|
echo '<div class="wrap mozout-ai-wrap">';
|
|
echo '<h1>' . esc_html__('MozOut All in One AI', 'mozout-ai') . ' <span class="mozout-ai-brand">' . esc_html(MOZOUT_AI_Brands::name()) . '</span></h1>';
|
|
self::notice_from_query();
|
|
echo '<nav class="nav-tab-wrapper">';
|
|
foreach ($tabs as $id => $label) {
|
|
printf('<a href="%s" class="nav-tab %s">%s</a>', esc_url(self::url($id)), $id === $tab ? 'nav-tab-active' : '', esc_html($label));
|
|
}
|
|
echo '</nav>';
|
|
call_user_func(array(__CLASS__, 'tab_' . $tab));
|
|
echo '</div>';
|
|
}
|
|
|
|
private static function form_open($tab, $action = 'mozout_ai_save')
|
|
{
|
|
echo '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '" class="mozout-ai-form" autocomplete="off">';
|
|
echo '<input type="hidden" name="action" value="' . esc_attr($action) . '"><input type="hidden" name="tab" value="' . esc_attr($tab) . '">';
|
|
wp_nonce_field($action === 'mozout_ai_save' ? 'mozout_ai_save_' . $tab : $action);
|
|
echo '<table class="form-table" role="presentation">';
|
|
}
|
|
|
|
private static function form_close($button = null)
|
|
{
|
|
echo '</table>';
|
|
submit_button($button === null ? __('Save changes', 'mozout-ai') : $button);
|
|
echo '</form>';
|
|
}
|
|
|
|
private static function row($label, $html, $help = '', $for = '')
|
|
{
|
|
echo '<tr><th scope="row">' . ($for ? '<label for="' . esc_attr($for) . '">' . esc_html($label) . '</label>' : esc_html($label)) . '</th><td>' . $html;
|
|
if ($help !== '') {
|
|
echo '<p class="description">' . wp_kses($help, array('a' => array('href' => array(), 'target' => array(), 'rel' => array()), 'code' => array(), 'strong' => array())) . '</p>';
|
|
}
|
|
echo '</td></tr>';
|
|
}
|
|
|
|
private static function checkbox($name, $label)
|
|
{
|
|
return '<label><input type="checkbox" name="' . esc_attr($name) . '" value="1" ' . checked((int) MOZOUT_AI_Settings::get($name), 1, false) . '> ' . esc_html($label) . '</label>';
|
|
}
|
|
|
|
private static function input($name, $type = 'text', $attrs = '')
|
|
{
|
|
return '<input type="' . esc_attr($type) . '" id="mozout-ai-' . esc_attr($name) . '" name="' . esc_attr($name) . '" value="' . esc_attr((string) MOZOUT_AI_Settings::get($name)) . '" class="regular-text" ' . $attrs . '>';
|
|
}
|
|
|
|
private static function textarea($name, $rows = 3, $value = null, $placeholder = '')
|
|
{
|
|
$v = $value === null ? (string) MOZOUT_AI_Settings::get($name) : $value;
|
|
return '<textarea id="mozout-ai-' . esc_attr($name) . '" name="' . esc_attr($name) . '" rows="' . (int) $rows . '" class="large-text" placeholder="' . esc_attr($placeholder) . '">' . esc_textarea($v) . '</textarea>';
|
|
}
|
|
|
|
/** A select box with the plugin style (select.js turns it into a button with a list). */
|
|
private static function select($name, array $options, $current, $id = '')
|
|
{
|
|
$id = $id !== '' ? $id : 'mozout-ai-' . $name;
|
|
$html = '<select name="' . esc_attr($name) . '" id="' . esc_attr($id) . '" data-mozout-ai-select>';
|
|
foreach ($options as $k => $v) {
|
|
$html .= '<option value="' . esc_attr($k) . '" ' . selected((string) $current, (string) $k, false) . '>' . esc_html($v) . '</option>';
|
|
}
|
|
return $html . '</select>';
|
|
}
|
|
|
|
private static function need_key_notice()
|
|
{
|
|
if (MOZOUT_AI_Settings::api_key() === '') {
|
|
echo '<div class="notice notice-warning inline"><p>' . esc_html__('Save the API key in the Connection tab first.', 'mozout-ai') . '</p></div>';
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* The text models (and the agents, when $agents) of the account, kept for an hour.
|
|
* Falls back to a text field when the list cannot be read.
|
|
*/
|
|
private static function model_field($name, $agents)
|
|
{
|
|
$current = (string) MOZOUT_AI_Settings::get($name);
|
|
$list = self::models();
|
|
if (!is_array($list) || !$list) {
|
|
$help = is_wp_error($list) ? $list->get_error_message() : '';
|
|
return self::input($name, 'text', 'placeholder="deepseek-ai/deepseek-v4-flash"') . ($help !== '' ? '<p class="description">' . esc_html($help) . '</p>' : '');
|
|
}
|
|
$opts = array();
|
|
foreach ($list as $m) {
|
|
if (empty($m['id']) || (!$agents && isset($m['type']) && $m['type'] === 'agent')) {
|
|
continue;
|
|
}
|
|
$label = !empty($m['name']) ? $m['name'] : $m['id'];
|
|
if (isset($m['type']) && $m['type'] === 'agent') {
|
|
/* translators: %s: agent name */
|
|
$label = sprintf(__('Agent: %s', 'mozout-ai'), $label);
|
|
} elseif (isset($m['pricing']['input'], $m['pricing']['output'])) {
|
|
$label = sprintf(
|
|
/* translators: 1: model name, 2: credits per million input tokens, 3: credits per million output tokens */
|
|
__('%1$s (credits per million tokens: %2$s in, %3$s out)', 'mozout-ai'),
|
|
$label,
|
|
number_format_i18n((float) $m['pricing']['input'], 2),
|
|
number_format_i18n((float) $m['pricing']['output'], 2)
|
|
);
|
|
}
|
|
$opts[(string) $m['id']] = $label;
|
|
}
|
|
if ($current !== '' && !isset($opts[$current])) {
|
|
$opts = array($current => $current) + $opts;
|
|
}
|
|
return self::select($name, $opts, $current);
|
|
}
|
|
|
|
/** @return array|WP_Error|null */
|
|
private static function models()
|
|
{
|
|
if (MOZOUT_AI_Settings::api_key() === '') {
|
|
return null;
|
|
}
|
|
$hit = get_transient('mozout_ai_models');
|
|
if (is_array($hit)) {
|
|
return $hit;
|
|
}
|
|
$out = array();
|
|
foreach (array('agent', 'text') as $type) {
|
|
$res = MOZOUT_AI_Api::request('GET', '/v1/models', null, array('query' => array('type' => $type), 'timeout' => 15));
|
|
if (is_wp_error($res)) {
|
|
return $res;
|
|
}
|
|
$rows = isset($res['raw']['data']) && is_array($res['raw']['data']) ? $res['raw']['data'] : array();
|
|
if ($type === 'text') {
|
|
usort($rows, function ($a, $b) {
|
|
return strcasecmp(isset($a['name']) ? $a['name'] : $a['id'], isset($b['name']) ? $b['name'] : $b['id']);
|
|
});
|
|
}
|
|
foreach ($rows as $r) {
|
|
$out[] = array(
|
|
'id' => isset($r['id']) ? (string) $r['id'] : '',
|
|
'name' => isset($r['name']) ? (string) $r['name'] : '',
|
|
'type' => isset($r['type']) ? (string) $r['type'] : $type,
|
|
'pricing' => isset($r['pricing']) && is_array($r['pricing']) ? $r['pricing'] : array(),
|
|
);
|
|
}
|
|
}
|
|
set_transient('mozout_ai_models', $out, HOUR_IN_SECONDS);
|
|
return $out;
|
|
}
|
|
|
|
/* ---- Connection ---- */
|
|
|
|
private static function tab_connection()
|
|
{
|
|
$hint = MOZOUT_AI_Settings::key_hint();
|
|
self::form_open('connection');
|
|
|
|
if (!MOZOUT_AI_Brands::is_fixed()) {
|
|
$opts = array();
|
|
foreach (MOZOUT_AI_Brands::all() as $id => $b) {
|
|
$opts[$id] = MOZOUT_AI_Brands::label($b);
|
|
}
|
|
self::row(__('Brand', 'mozout-ai'), self::select('brand', $opts, MOZOUT_AI_Brands::current_id()), __('The company where you have your account. The API address and links follow this choice.', 'mozout-ai'), 'mozout-ai-brand');
|
|
}
|
|
|
|
if (MOZOUT_AI_Settings::key_from_constant()) {
|
|
$key_html = '<p><strong>' . esc_html__('The key is defined in wp-config.php (MOZOUT_AI_API_KEY) and cannot be changed here.', 'mozout-ai') . '</strong></p>';
|
|
} else {
|
|
$key_html = '<input type="password" name="api_key" id="mozout-ai-api_key" class="regular-text" value="" autocomplete="new-password" spellcheck="false" placeholder="'
|
|
. esc_attr(!empty($hint['suffix']) ? __('Saved. Write a new key only to replace it.', 'mozout-ai') : 'prod_... / sandbox_...') . '">';
|
|
if (!empty($hint['suffix'])) {
|
|
$key_html .= '<p class="mozout-ai-keyhint">' . esc_html(sprintf(
|
|
/* translators: 1: Sandbox or Production, 2: last 4 characters */
|
|
__('Saved key: %1$s, ending in %2$s.', 'mozout-ai'),
|
|
$hint['mode'] === 'sandbox' ? 'Sandbox' : __('Production', 'mozout-ai'),
|
|
$hint['suffix']
|
|
)) . '</p>';
|
|
$key_html .= '<label><input type="checkbox" name="delete_key" value="1"> ' . esc_html__('Delete the saved key', 'mozout-ai') . '</label>';
|
|
}
|
|
if (MOZOUT_AI_Settings::key_unreadable()) {
|
|
$key_html .= '<p class="mozout-ai-error">' . esc_html__('The saved API key can no longer be read (the WordPress security keys changed). Save the key again.', 'mozout-ai') . '</p>';
|
|
}
|
|
}
|
|
$help = sprintf(
|
|
/* translators: 1: link to the API page, 2: name of the customer area */
|
|
__('Create the key in %2$s, on the <a href="%1$s" target="_blank" rel="noopener">API page</a>, with the ai:read and ai:write permissions. It is saved encrypted and is never shown again. With a sandbox_ key the model is not called and nothing is spent: every answer is a fixed test text.', 'mozout-ai'),
|
|
esc_url(MOZOUT_AI_Brands::portal_link('api-center.php')),
|
|
esc_html(MOZOUT_AI_Brands::portal_name())
|
|
);
|
|
self::row(__('API key', 'mozout-ai'), $key_html, $help, 'mozout-ai-api_key');
|
|
|
|
$lang_opts = array('auto' => __('Same as WordPress', 'mozout-ai'), 'pt' => 'Português', 'en' => 'English');
|
|
self::row(__('Language', 'mozout-ai'), self::select('ui_lang', $lang_opts, MOZOUT_AI_Settings::get('ui_lang')), __('Language of this page and of the texts shown to visitors.', 'mozout-ai'), 'mozout-ai-ui_lang');
|
|
self::form_close();
|
|
|
|
echo '<h2>' . esc_html__('Connection test', 'mozout-ai') . '</h2>';
|
|
echo '<div class="mozout-ai-inline">';
|
|
echo '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '">';
|
|
echo '<input type="hidden" name="action" value="mozout_ai_test">';
|
|
wp_nonce_field('mozout_ai_test');
|
|
submit_button(__('Test the connection', 'mozout-ai'), 'secondary', 'submit', false);
|
|
echo '</form>';
|
|
echo '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '">';
|
|
echo '<input type="hidden" name="action" value="mozout_ai_test_ai">';
|
|
wp_nonce_field('mozout_ai_test_ai');
|
|
submit_button(__('Ask the model a short question', 'mozout-ai'), 'secondary', 'submit', false);
|
|
echo '</form></div>';
|
|
echo '<p class="description">' . esc_html__('The question asks for a one-word answer with the writing model, so it costs almost nothing. With a sandbox_ key it costs nothing.', 'mozout-ai') . '</p>';
|
|
$info = get_transient('mozout_ai_token_info');
|
|
if (is_array($info)) {
|
|
echo '<table class="widefat striped mozout-ai-info"><tbody>';
|
|
echo '<tr><th>' . esc_html__('Mode', 'mozout-ai') . '</th><td>' . esc_html($info['mode'] === 'sandbox' ? __('Sandbox (the model is not called)', 'mozout-ai') : __('Production', 'mozout-ai')) . '</td></tr>';
|
|
echo '<tr><th>' . esc_html__('Key name', 'mozout-ai') . '</th><td>' . esc_html($info['name']) . '</td></tr>';
|
|
echo '<tr><th>' . esc_html__('Expires', 'mozout-ai') . '</th><td>' . esc_html($info['expires_at'] ? $info['expires_at'] : __('Never', 'mozout-ai')) . '</td></tr>';
|
|
if (isset($info['credits'])) {
|
|
echo '<tr><th>' . esc_html__('AI credits', 'mozout-ai') . '</th><td>' . esc_html(number_format_i18n((float) $info['credits'], 2)) . '</td></tr>';
|
|
}
|
|
echo '<tr><th>' . esc_html__('Permissions', 'mozout-ai') . '</th><td>';
|
|
foreach (array('ai:write' => __('assistant and writing help', 'mozout-ai'), 'ai:read' => __('models and balance', 'mozout-ai')) as $scope => $what) {
|
|
$has = in_array($scope, $info['permissions'], true) || in_array('*', $info['permissions'], true);
|
|
echo '<span class="mozout-ai-scope ' . ($has ? 'is-ok' : 'is-missing') . '">' . esc_html(($has ? '✓ ' : '✗ ') . $scope) . '</span> <span class="description">' . esc_html($what) . '</span><br>';
|
|
}
|
|
echo '</td></tr></tbody></table>';
|
|
}
|
|
}
|
|
|
|
/* ---- Assistant ---- */
|
|
|
|
private static function tab_assistant()
|
|
{
|
|
self::need_key_notice();
|
|
echo '<p>' . esc_html__('A chat button appears on every page. Visitor questions go to this WordPress, and WordPress asks All in One AI with your key: the key never reaches the browser. Each answer spends AI credits.', 'mozout-ai') . '</p>';
|
|
self::form_open('assistant');
|
|
self::row(__('Assistant', 'mozout-ai'), self::checkbox('ai_enabled', __('Show on the site', 'mozout-ai')));
|
|
self::row(__('Model or agent', 'mozout-ai'), self::model_field('ai_model', true), sprintf(
|
|
/* translators: %s: link to the docs */
|
|
__('An agent you created in All in One AI brings its own instructions. Models and prices: <a href="%s" target="_blank" rel="noopener">documentation</a>.', 'mozout-ai'),
|
|
esc_url(MOZOUT_AI_Brands::docs_link('ai/'))
|
|
), 'mozout-ai-ai_model');
|
|
self::row(__('Instructions', 'mozout-ai'), self::textarea('ai_instructions', 6, null, MOZOUT_AI_Assistant::instructions('en')), __('What the assistant knows and how it answers: products, hours, contacts, what it must not promise. Not used with an agent.', 'mozout-ai'));
|
|
self::row(__('Title (Portuguese)', 'mozout-ai'), self::input('ai_title_pt', 'text', 'placeholder="' . esc_attr(MOZOUT_AI_I18n::in('pt', 'Assistant')) . '"'), '', 'mozout-ai-ai_title_pt');
|
|
self::row(__('Title (English)', 'mozout-ai'), self::input('ai_title_en', 'text', 'placeholder="Assistant"'), '', 'mozout-ai-ai_title_en');
|
|
self::row(__('Welcome (Portuguese)', 'mozout-ai'), self::input('ai_welcome_pt', 'text', 'placeholder="' . esc_attr(MOZOUT_AI_I18n::in('pt', 'Hello! How can I help you?')) . '"'), '', 'mozout-ai-ai_welcome_pt');
|
|
self::row(__('Welcome (English)', 'mozout-ai'), self::input('ai_welcome_en', 'text', 'placeholder="Hello! How can I help you?"'), '', 'mozout-ai-ai_welcome_en');
|
|
self::row(__('Maximum answer length', 'mozout-ai'), self::input('ai_max_tokens', 'number', 'min="50" max="2000" style="width:7em"') . ' tokens', __('Shorter answers spend fewer credits.', 'mozout-ai'), 'mozout-ai-ai_max_tokens');
|
|
self::row(__('Messages per visitor', 'mozout-ai'),
|
|
self::input('ai_per_hour', 'number', 'min="1" max="500" style="width:6em"') . ' ' . esc_html__('per hour', 'mozout-ai') . ' '
|
|
. '<input type="number" name="ai_per_day" min="1" max="5000" style="width:6em" value="' . esc_attr((string) MOZOUT_AI_Settings::get('ai_per_day')) . '" aria-label="' . esc_attr__('per day', 'mozout-ai') . '"> ' . esc_html__('per day', 'mozout-ai'),
|
|
__('Counted by browser and by IP address, whichever reaches the limit first.', 'mozout-ai'), 'mozout-ai-ai_per_hour');
|
|
self::row(__('Messages per day, whole site', 'mozout-ai'), self::input('ai_site_per_day', 'number', 'min="0" max="100000" style="width:7em"'), __('0 means no limit for the site.', 'mozout-ai'), 'mozout-ai-ai_site_per_day');
|
|
self::row(__('Colour', 'mozout-ai'), self::input('ai_color', 'color', 'style="width:5em"'), '', 'mozout-ai-ai_color');
|
|
$pos = array('right' => __('Bottom right', 'mozout-ai'), 'left' => __('Bottom left', 'mozout-ai'));
|
|
self::row(__('Position', 'mozout-ai'), self::select('ai_position', $pos, MOZOUT_AI_Settings::get('ai_position')), '', 'mozout-ai-ai_position');
|
|
self::form_close();
|
|
self::log_table('ai');
|
|
}
|
|
|
|
/* ---- Writing help ---- */
|
|
|
|
private static function tab_writing()
|
|
{
|
|
self::need_key_notice();
|
|
echo '<p>' . esc_html__('A "Write with AI" box appears in the editor. It drafts product descriptions, short descriptions, page texts and excerpts from a few words you write. You check the text and choose where it goes.', 'mozout-ai') . '</p>';
|
|
self::form_open('writing');
|
|
self::row(__('Writing help', 'mozout-ai'), self::checkbox('write_enabled', __('Show the box in the editor', 'mozout-ai')));
|
|
$types = array();
|
|
foreach (array('post', 'page', 'product') as $t) {
|
|
$obj = get_post_type_object($t);
|
|
if ($obj) {
|
|
$types[] = '<label class="mozout-ai-check"><input type="checkbox" name="write_post_types[]" value="' . esc_attr($t) . '" ' . checked(in_array($t, (array) MOZOUT_AI_Settings::get('write_post_types'), true), true, false) . '> ' . esc_html($obj->labels->name) . '</label>';
|
|
}
|
|
}
|
|
self::row(__('Where', 'mozout-ai'), implode(' ', $types));
|
|
self::row(__('Model', 'mozout-ai'), self::model_field('write_model', false), __('A fast and cheap model is enough for short texts.', 'mozout-ai'), 'mozout-ai-write_model');
|
|
self::row(__('Default tone', 'mozout-ai'), self::select('write_tone', MOZOUT_AI_Writer::tones(), MOZOUT_AI_Settings::get('write_tone')), '', 'mozout-ai-write_tone');
|
|
self::row(__('About the business', 'mozout-ai'), self::textarea('write_brief', 5, null, __('Example: we make handmade furniture, delivery in 5 days, payment by bank transfer or mobile money.', 'mozout-ai')), __('Facts the AI may use in every text. It is told not to invent anything else.', 'mozout-ai'));
|
|
self::row(__('Maximum length', 'mozout-ai'), self::input('write_max_tokens', 'number', 'min="100" max="4000" style="width:7em"') . ' tokens', __('About 700 tokens give a text of 400 to 500 words.', 'mozout-ai'), 'mozout-ai-write_max_tokens');
|
|
self::row(__('Texts per user, per day', 'mozout-ai'), self::input('write_per_day', 'number', 'min="1" max="1000" style="width:6em"'), '', 'mozout-ai-write_per_day');
|
|
self::form_close();
|
|
self::log_table('write');
|
|
}
|
|
|
|
/* ---- New draft ---- */
|
|
|
|
private static function tab_drafts()
|
|
{
|
|
if (self::need_key_notice()) {
|
|
return;
|
|
}
|
|
echo '<p>' . esc_html__('Describe the post or page and the AI writes a first draft. It is saved as a draft and nothing is published.', 'mozout-ai') . '</p>';
|
|
self::form_open('drafts', 'mozout_ai_draft');
|
|
$types = array('post' => __('Post', 'mozout-ai'), 'page' => __('Page', 'mozout-ai'));
|
|
self::row(__('Type', 'mozout-ai'), self::select('type', $types, 'post', 'mozout-ai-draft-type'), '', 'mozout-ai-draft-type');
|
|
self::row(__('What should it say?', 'mozout-ai'), self::textarea('topic', 5, '', __('Example: how to choose a domain name, for small businesses, with 3 tips.', 'mozout-ai')), '', 'mozout-ai-topic');
|
|
self::row(__('Tone', 'mozout-ai'), self::select('tone', MOZOUT_AI_Writer::tones(), MOZOUT_AI_Settings::get('write_tone'), 'mozout-ai-draft-tone'), '', 'mozout-ai-draft-tone');
|
|
self::row(__('Language', 'mozout-ai'), self::select('lang', MOZOUT_AI_Writer::languages(), 'site', 'mozout-ai-draft-lang'), '', 'mozout-ai-draft-lang');
|
|
self::form_close(__('Write the draft', 'mozout-ai'));
|
|
self::log_table('draft');
|
|
}
|
|
|
|
/* ---- Activity ---- */
|
|
|
|
private static function tab_activity()
|
|
{
|
|
self::log_table(null, 50);
|
|
}
|
|
|
|
private static function log_table($area, $n = 10)
|
|
{
|
|
$log = array_slice(MOZOUT_AI_Log::all($area), 0, $n);
|
|
if (!$log) {
|
|
if ($area === null) {
|
|
echo '<p>' . esc_html__('No activity yet.', 'mozout-ai') . '</p>';
|
|
}
|
|
return;
|
|
}
|
|
$areas = array(
|
|
'ai' => __('Site assistant', 'mozout-ai'),
|
|
'write' => __('Writing help', 'mozout-ai'),
|
|
'draft' => __('New draft', 'mozout-ai'),
|
|
'test' => __('Test', 'mozout-ai'),
|
|
);
|
|
echo '<h2>' . esc_html__('Recent activity', 'mozout-ai') . '</h2><table class="widefat striped mozout-ai-log"><thead><tr><th>' . esc_html__('Date', 'mozout-ai') . '</th><th>' . esc_html__('Area', 'mozout-ai') . '</th><th>' . esc_html__('Result', 'mozout-ai') . '</th><th>' . esc_html__('Details', 'mozout-ai') . '</th></tr></thead><tbody>';
|
|
foreach ($log as $e) {
|
|
$extra = array();
|
|
foreach ((array) $e['extra'] as $k => $v) {
|
|
$extra[] = $k . ': ' . (is_scalar($v) ? $v : wp_json_encode($v));
|
|
}
|
|
$area_name = isset($areas[$e['area']]) ? $areas[$e['area']] : $e['area'];
|
|
echo '<tr><td>' . esc_html(wp_date('d/m/Y H:i', $e['t'])) . '</td><td>' . esc_html($area_name) . '</td><td class="' . ($e['ok'] ? 'mozout-ai-ok' : 'mozout-ai-error') . '">' . esc_html($e['text']) . '</td><td>' . esc_html(implode(' · ', $extra)) . '</td></tr>';
|
|
}
|
|
echo '</tbody></table>';
|
|
}
|
|
|
|
/* ------------------------------------------------------------------ */
|
|
/* Saving */
|
|
/* ------------------------------------------------------------------ */
|
|
|
|
private static function clean_model($value)
|
|
{
|
|
return substr(preg_replace('/[^A-Za-z0-9._:\/\-]/', '', (string) $value), 0, 200);
|
|
}
|
|
|
|
public static function save()
|
|
{
|
|
$tab = isset($_POST['tab']) ? sanitize_key(wp_unslash($_POST['tab'])) : '';
|
|
self::check('mozout_ai_save_' . $tab);
|
|
$p = wp_unslash($_POST);
|
|
$v = array();
|
|
$msg = __('Settings saved.', 'mozout-ai');
|
|
$ok = true;
|
|
|
|
switch ($tab) {
|
|
case 'connection':
|
|
$brands = MOZOUT_AI_Brands::all();
|
|
$old_brand = MOZOUT_AI_Brands::current_id();
|
|
if (!MOZOUT_AI_Brands::is_fixed() && isset($p['brand'], $brands[$p['brand']])) {
|
|
$v['brand'] = $p['brand'];
|
|
}
|
|
$v['ui_lang'] = in_array(isset($p['ui_lang']) ? $p['ui_lang'] : '', array('auto', 'pt', 'en'), true) ? $p['ui_lang'] : 'auto';
|
|
MOZOUT_AI_Settings::update($v);
|
|
if (!MOZOUT_AI_Settings::key_from_constant()) {
|
|
if (!empty($p['delete_key'])) {
|
|
MOZOUT_AI_Settings::delete_api_key();
|
|
$msg = __('Settings saved. The key was deleted.', 'mozout-ai');
|
|
} elseif (!empty($p['api_key'])) {
|
|
$r = MOZOUT_AI_Settings::save_api_key($p['api_key']);
|
|
if (is_wp_error($r)) {
|
|
$ok = false;
|
|
$msg = $r->get_error_message();
|
|
} else {
|
|
$msg = __('Settings saved. The key is stored encrypted and will not be shown again.', 'mozout-ai');
|
|
}
|
|
}
|
|
}
|
|
if (isset($v['brand']) && $v['brand'] !== $old_brand) {
|
|
delete_transient('mozout_ai_token_info');
|
|
}
|
|
delete_transient('mozout_ai_models');
|
|
break;
|
|
|
|
case 'assistant':
|
|
$v['ai_enabled'] = empty($p['ai_enabled']) ? 0 : 1;
|
|
$v['ai_model'] = self::clean_model(isset($p['ai_model']) ? $p['ai_model'] : '');
|
|
$v['ai_instructions'] = sanitize_textarea_field(isset($p['ai_instructions']) ? $p['ai_instructions'] : '');
|
|
foreach (array('ai_title_pt', 'ai_title_en', 'ai_welcome_pt', 'ai_welcome_en') as $f) {
|
|
$v[$f] = sanitize_text_field(isset($p[$f]) ? $p[$f] : '');
|
|
}
|
|
$v['ai_max_tokens'] = min(2000, max(50, (int) (isset($p['ai_max_tokens']) ? $p['ai_max_tokens'] : 400)));
|
|
$v['ai_per_hour'] = min(500, max(1, (int) (isset($p['ai_per_hour']) ? $p['ai_per_hour'] : 10)));
|
|
$v['ai_per_day'] = min(5000, max(1, (int) (isset($p['ai_per_day']) ? $p['ai_per_day'] : 30)));
|
|
$v['ai_site_per_day'] = min(100000, max(0, (int) (isset($p['ai_site_per_day']) ? $p['ai_site_per_day'] : 500)));
|
|
$color = sanitize_hex_color(isset($p['ai_color']) ? $p['ai_color'] : '');
|
|
$v['ai_color'] = $color ? $color : '#d60037';
|
|
$v['ai_position'] = (isset($p['ai_position']) && $p['ai_position'] === 'left') ? 'left' : 'right';
|
|
if ($v['ai_enabled'] && $v['ai_model'] === '') {
|
|
$ok = false;
|
|
$msg = __('Saved, but the assistant stays hidden until you choose a model or agent.', 'mozout-ai');
|
|
}
|
|
MOZOUT_AI_Settings::update($v);
|
|
break;
|
|
|
|
case 'writing':
|
|
$v['write_enabled'] = empty($p['write_enabled']) ? 0 : 1;
|
|
$v['write_post_types'] = array_values(array_intersect(array('post', 'page', 'product'), array_map('sanitize_key', (array) (isset($p['write_post_types']) ? $p['write_post_types'] : array()))));
|
|
$v['write_model'] = self::clean_model(isset($p['write_model']) ? $p['write_model'] : '');
|
|
$v['write_tone'] = isset($p['write_tone']) && array_key_exists($p['write_tone'], MOZOUT_AI_Writer::tones()) ? $p['write_tone'] : 'friendly';
|
|
$v['write_brief'] = sanitize_textarea_field(isset($p['write_brief']) ? $p['write_brief'] : '');
|
|
$v['write_max_tokens'] = min(4000, max(100, (int) (isset($p['write_max_tokens']) ? $p['write_max_tokens'] : 700)));
|
|
$v['write_per_day'] = min(1000, max(1, (int) (isset($p['write_per_day']) ? $p['write_per_day'] : 50)));
|
|
MOZOUT_AI_Settings::update($v);
|
|
break;
|
|
|
|
default:
|
|
wp_die('bad tab', 400);
|
|
}
|
|
self::redirect($tab, $ok, $msg);
|
|
}
|
|
|
|
public static function test_connection()
|
|
{
|
|
self::check('mozout_ai_test');
|
|
delete_transient('mozout_ai_token_info');
|
|
delete_transient('mozout_ai_models');
|
|
$res = MOZOUT_AI_Api::request('GET', '/v1/token', null, array('timeout' => 10));
|
|
if (is_wp_error($res)) {
|
|
self::redirect('connection', false, $res->get_error_message());
|
|
}
|
|
$d = is_array($res['data']) ? $res['data'] : array();
|
|
$info = array(
|
|
'mode' => isset($d['mode']) ? $d['mode'] : (isset($d['type']) ? $d['type'] : ''),
|
|
'name' => isset($d['name']) ? (string) $d['name'] : '',
|
|
'expires_at' => isset($d['expires_at']) ? (string) $d['expires_at'] : '',
|
|
'permissions' => isset($d['permissions']) && is_array($d['permissions']) ? $d['permissions'] : array(),
|
|
);
|
|
$bal = MOZOUT_AI_Api::request('GET', '/v1/ai/balance', null, array('timeout' => 10));
|
|
if (!is_wp_error($bal) && is_array($bal['data']) && isset($bal['data']['credits'])) {
|
|
$info['credits'] = $bal['data']['credits'];
|
|
}
|
|
set_transient('mozout_ai_token_info', $info, HOUR_IN_SECONDS);
|
|
self::redirect('connection', true, sprintf(
|
|
/* translators: %s: brand name */
|
|
__('Connection to %s working.', 'mozout-ai'),
|
|
MOZOUT_AI_Brands::name()
|
|
));
|
|
}
|
|
|
|
/** A minimal request: one short question, at most 16 tokens of answer. */
|
|
public static function test_ai()
|
|
{
|
|
self::check('mozout_ai_test_ai');
|
|
$model = trim((string) MOZOUT_AI_Settings::get('write_model'));
|
|
$body = array(
|
|
'model' => $model !== '' ? $model : 'deepseek-ai/deepseek-v4-flash',
|
|
'messages' => array(array('role' => 'user', 'content' => 'Reply with one word: ok')),
|
|
'max_tokens' => 16,
|
|
);
|
|
$res = MOZOUT_AI_Api::request('POST', '/v1/chat/completions', $body, array('timeout' => 45, 'idempotency_key' => true));
|
|
if (is_wp_error($res)) {
|
|
MOZOUT_AI_Log::add('test', false, $res->get_error_message());
|
|
self::redirect('connection', false, $res->get_error_message());
|
|
}
|
|
$answer = isset($res['raw']['choices'][0]['message']['content']) ? trim((string) $res['raw']['choices'][0]['message']['content']) : '';
|
|
$tokens = isset($res['raw']['usage']['total_tokens']) ? (int) $res['raw']['usage']['total_tokens'] : 0;
|
|
MOZOUT_AI_Log::add('test', $answer !== '', $answer !== '' ? $answer : __('The model answered without text.', 'mozout-ai'), array('model' => $body['model'], 'tokens' => $tokens));
|
|
self::redirect('connection', $answer !== '', sprintf(
|
|
/* translators: 1: answer of the model, 2: tokens used */
|
|
__('The model answered: "%1$s" (%2$s tokens).', 'mozout-ai'),
|
|
function_exists('mb_substr') ? mb_substr($answer, 0, 80) : substr($answer, 0, 80),
|
|
number_format_i18n($tokens)
|
|
));
|
|
}
|
|
|
|
public static function draft()
|
|
{
|
|
self::check('mozout_ai_draft', 'edit_posts');
|
|
$p = wp_unslash($_POST);
|
|
$type = isset($p['type']) && $p['type'] === 'page' ? 'page' : 'post';
|
|
if ($type === 'page' && !current_user_can('edit_pages')) {
|
|
self::redirect('drafts', false, __('You do not have permission to do this.', 'mozout-ai'));
|
|
}
|
|
$tone = isset($p['tone']) ? (string) $p['tone'] : 'friendly';
|
|
$lang = isset($p['lang']) && array_key_exists($p['lang'], MOZOUT_AI_Writer::languages()) ? $p['lang'] : 'site';
|
|
$id = MOZOUT_AI_Writer::new_draft($type, isset($p['topic']) ? $p['topic'] : '', $tone, $lang);
|
|
if (is_wp_error($id)) {
|
|
self::redirect('drafts', false, $id->get_error_message());
|
|
}
|
|
self::redirect('drafts', true, sprintf(
|
|
/* translators: %s: title of the draft */
|
|
__('Draft saved: %s.', 'mozout-ai'),
|
|
get_the_title($id)
|
|
), get_edit_post_link($id, 'raw'));
|
|
}
|
|
}
|