Vigiar
1
0
Derivar
Você já tinha feito uma derivação do repositório wordpress-ai-plugin, anteriormente
0
wordpress-ai-plugin/mozout-ai/includes/class-writer.php
2026-12-01 13:25:59 +02:00

347 linhas
17 KiB
PHP

<?php
if (!defined('ABSPATH')) {
exit;
}
/**
* Writing help: a box in the editor of posts, pages and WooCommerce products that drafts texts with
* All in One AI (POST /v1/chat/completions), and new drafts of posts and pages from the settings page.
* The browser talks only to this WordPress; the key stays on the server. Each user has a daily limit.
*/
class MOZOUT_AI_Writer
{
const MAX_BRIEF = 2000;
public static function init()
{
add_action('rest_api_init', array(__CLASS__, 'routes'));
if (is_admin()) {
add_action('add_meta_boxes', array(__CLASS__, 'meta_box'), 20, 2);
add_action('admin_enqueue_scripts', array(__CLASS__, 'assets'));
}
}
public static function enabled()
{
return (int) MOZOUT_AI_Settings::get('write_enabled') === 1 && MOZOUT_AI_Settings::api_key() !== '';
}
public static function post_types()
{
$types = array_values(array_filter((array) MOZOUT_AI_Settings::get('write_post_types'), 'post_type_exists'));
return apply_filters('mozout_ai_writer_post_types', $types);
}
public static function tones()
{
return array(
'friendly' => __('Friendly and close', 'mozout-ai'),
'professional' => __('Professional', 'mozout-ai'),
'simple' => __('Simple and direct', 'mozout-ai'),
'persuasive' => __('Persuasive, without exaggeration', 'mozout-ai'),
);
}
public static function languages()
{
return array(
'site' => __('Language of the site', 'mozout-ai'),
'pt_PT' => __('European Portuguese', 'mozout-ai'),
'pt_BR' => __('Brazilian Portuguese', 'mozout-ai'),
'en' => __('English', 'mozout-ai'),
);
}
/** What can be written for a post type: field => label. */
public static function targets($post_type)
{
if ($post_type === 'product') {
return array(
'content' => __('Product description', 'mozout-ai'),
'excerpt' => __('Short description', 'mozout-ai'),
);
}
$out = array('content' => __('Text of the page', 'mozout-ai'));
if (post_type_supports($post_type, 'excerpt')) {
$out['excerpt'] = __('Excerpt', 'mozout-ai');
}
return $out;
}
/* ---- Editor box ---- */
public static function meta_box($post_type, $post = null)
{
if (!self::enabled() || !in_array($post_type, self::post_types(), true)) {
return;
}
add_meta_box('mozout-ai-writer', __('Write with AI', 'mozout-ai'), array(__CLASS__, 'meta_box_html'), $post_type, 'side', 'high');
}
public static function assets($hook)
{
if (!in_array($hook, array('post.php', 'post-new.php'), true) || !self::enabled()) {
return;
}
$screen = function_exists('get_current_screen') ? get_current_screen() : null;
if (!$screen || !in_array($screen->post_type, self::post_types(), true)) {
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);
wp_enqueue_script('mozout-ai-writer', MOZOUT_AI_URL . 'assets/writer.js', array(), MOZOUT_AI_VERSION, true);
wp_localize_script('mozout-ai-writer', 'mozoutAiWriter', array(
'url' => esc_url_raw(rest_url('mozout-ai/v1/write')),
'nonce' => wp_create_nonce('wp_rest'),
'writing' => __('Writing... this can take up to a minute.', 'mozout-ai'),
'error' => __('The text could not be written. Please try again.', 'mozout-ai'),
'empty' => __('Say in a few words what the text should cover.', 'mozout-ai'),
'inserted' => __('Done. Check the text before you publish.', 'mozout-ai'),
));
}
public static function meta_box_html($post)
{
$targets = self::targets($post->post_type);
echo '<div class="mozout-ai-writer" data-post="' . (int) $post->ID . '">';
echo '<p><label for="mozout-ai-writer-target">' . esc_html__('What to write', 'mozout-ai') . '</label><br>' . self::select_html('mozout-ai-writer-target', $targets, 'content') . '</p>';
echo '<p><label for="mozout-ai-writer-brief">' . esc_html__('What should it say?', 'mozout-ai') . '</label>';
echo '<textarea id="mozout-ai-writer-brief" rows="4" maxlength="' . (int) self::MAX_BRIEF . '" placeholder="' . esc_attr($post->post_type === 'product' ? __('Example: cotton t-shirt, sizes S to XL, washes at 30 degrees.', 'mozout-ai') : __('Example: how to choose a domain name, for small businesses, with 3 tips.', 'mozout-ai')) . '"></textarea></p>';
echo '<p><label for="mozout-ai-writer-tone">' . esc_html__('Tone', 'mozout-ai') . '</label><br>' . self::select_html('mozout-ai-writer-tone', self::tones(), (string) MOZOUT_AI_Settings::get('write_tone')) . '</p>';
echo '<p><label for="mozout-ai-writer-lang">' . esc_html__('Language', 'mozout-ai') . '</label><br>' . self::select_html('mozout-ai-writer-lang', self::languages(), 'site') . '</p>';
echo '<p><button type="button" class="button button-primary mozout-ai-writer-go">' . esc_html__('Write', 'mozout-ai') . '</button></p>';
echo '<p class="mozout-ai-writer-msg" role="status" aria-live="polite"></p>';
echo '<div class="mozout-ai-writer-result" hidden>';
echo '<label for="mozout-ai-writer-text">' . esc_html__('Suggestion (you can edit it)', 'mozout-ai') . '</label>';
echo '<textarea id="mozout-ai-writer-text" rows="10"></textarea>';
echo '<p class="mozout-ai-writer-actions"><button type="button" class="button mozout-ai-writer-insert" data-mode="append">' . esc_html__('Add at the end', 'mozout-ai') . '</button> ';
echo '<button type="button" class="button mozout-ai-writer-insert" data-mode="replace">' . esc_html__('Replace the text', 'mozout-ai') . '</button></p>';
echo '</div>';
echo '<p class="description">' . esc_html__('Texts are written by AI and may have mistakes. Each request spends AI credits.', 'mozout-ai') . '</p>';
echo '</div>';
}
private static function select_html($id, array $options, $current)
{
$html = '<select id="' . esc_attr($id) . '" data-mozout-ai-select>';
foreach ($options as $k => $v) {
$html .= '<option value="' . esc_attr($k) . '" ' . selected($current, $k, false) . '>' . esc_html($v) . '</option>';
}
return $html . '</select>';
}
/* ---- REST ---- */
public static function routes()
{
register_rest_route('mozout-ai/v1', '/write', array(
'methods' => 'POST',
'callback' => array(__CLASS__, 'rest_write'),
'permission_callback' => function (WP_REST_Request $req) {
$id = (int) $req->get_param('post');
return $id > 0 ? current_user_can('edit_post', $id) : current_user_can('edit_posts');
},
));
}
public static function rest_write(WP_REST_Request $req)
{
if (!self::enabled()) {
return new WP_REST_Response(array('ok' => false, 'message' => __('Writing help is turned off in the plugin settings.', 'mozout-ai')), 503);
}
$post = get_post((int) $req->get_param('post'));
if (!$post) {
return new WP_REST_Response(array('ok' => false, 'message' => __('Save the draft once and try again.', 'mozout-ai')), 404);
}
$target = (string) $req->get_param('target');
$targets = self::targets($post->post_type);
if (!isset($targets[$target])) {
$target = 'content';
}
$brief = self::clean_brief($req->get_param('brief'));
if ($brief === '') {
return new WP_REST_Response(array('ok' => false, 'message' => __('Say in a few words what the text should cover.', 'mozout-ai')), 422);
}
$tone = (string) $req->get_param('tone');
$lang = (string) $req->get_param('lang');
$res = self::generate(self::task_for_post($post, $target, $brief), $tone, $lang, $target === 'excerpt' ? 250 : 0);
if (is_wp_error($res)) {
return new WP_REST_Response(array('ok' => false, 'message' => $res->get_error_message()), 502);
}
MOZOUT_AI_Log::add('write', true, $targets[$target] . ': ' . $post->post_title, array('post' => $post->ID, 'tokens' => $res['tokens']));
return new WP_REST_Response(array('ok' => true, 'text' => $res['text'], 'html' => $target === 'content'));
}
private static function clean_brief($text)
{
$text = trim(sanitize_textarea_field((string) $text));
return function_exists('mb_substr') ? mb_substr($text, 0, self::MAX_BRIEF) : substr($text, 0, self::MAX_BRIEF);
}
/** The task for the model, with what the post already has. */
private static function task_for_post($post, $target, $brief)
{
$lines = array();
if ($post->post_type === 'product' && function_exists('wc_get_product')) {
$product = wc_get_product($post->ID);
$lines[] = $target === 'excerpt'
? 'Write the short description of this product: two or three sentences, plain text.'
: 'Write the description of this product for its page: a short opening paragraph, then the details that matter to the buyer.';
if ($product) {
$lines[] = 'Product name: ' . $product->get_name();
$cats = wp_strip_all_tags(wc_get_product_category_list($product->get_id(), ', '));
if ($cats !== '') {
$lines[] = 'Categories: ' . $cats;
}
foreach ($product->get_attributes() as $attr) {
if (is_object($attr) && method_exists($attr, 'get_name')) {
$vals = $attr->is_taxonomy() ? wc_get_product_terms($product->get_id(), $attr->get_name(), array('fields' => 'names')) : $attr->get_options();
$lines[] = wc_attribute_label($attr->get_name()) . ': ' . implode(', ', (array) $vals);
}
}
}
} else {
$lines[] = $target === 'excerpt'
? 'Write the excerpt of this ' . $post->post_type . ': one or two sentences, plain text.'
: 'Write the text of this ' . $post->post_type . ', ready to publish.';
if ($post->post_title !== '') {
$lines[] = 'Title: ' . $post->post_title;
}
}
$lines[] = 'What the author wants: ' . $brief;
return implode("\n", $lines);
}
/**
* Calls the model. $max_chars cuts plain text (excerpts).
*
* @return array|WP_Error text, tokens
*/
public static function generate($task, $tone, $lang, $max_chars = 0, $user_id = 0)
{
$user_id = $user_id ? $user_id : get_current_user_id();
$limit = max(1, (int) MOZOUT_AI_Settings::get('write_per_day'));
$bucket = 'mozout_ai_wr_' . md5($user_id . '|' . gmdate('Ymd'));
$used = (int) get_transient($bucket);
if ($used >= $limit) {
return new WP_Error('mozout_ai_limit', sprintf(
/* translators: %d: requests per day */
__('You reached the limit of %d texts for today. The limit can be changed in the plugin settings.', 'mozout-ai'),
$limit
));
}
set_transient($bucket, $used + 1, DAY_IN_SECONDS);
$model = trim((string) MOZOUT_AI_Settings::get('write_model'));
$body = array(
'model' => $model !== '' ? $model : 'deepseek-ai/deepseek-v4-flash',
'messages' => array(
array('role' => 'system', 'content' => self::system_prompt($tone, $lang, $max_chars > 0)),
array('role' => 'user', 'content' => $task),
),
'max_tokens' => min(4000, max(100, (int) MOZOUT_AI_Settings::get('write_max_tokens'))),
);
if (strpos($body['model'], 'agent/') === 0) {
$body['messages'] = array_slice($body['messages'], 1);
}
$res = MOZOUT_AI_Api::request('POST', '/v1/chat/completions', $body, array('timeout' => 90, 'idempotency_key' => true));
if (is_wp_error($res)) {
MOZOUT_AI_Log::add('write', false, $res->get_error_message());
return $res;
}
$data = $res['raw'];
$text = isset($data['choices'][0]['message']['content']) ? trim((string) $data['choices'][0]['message']['content']) : '';
if ($text === '') {
MOZOUT_AI_Log::add('write', false, __('The model answered without text.', 'mozout-ai'));
return new WP_Error('mozout_ai_empty', __('The model answered without text. Please try again.', 'mozout-ai'));
}
$text = preg_replace('/^```(?:html)?\s*|\s*```$/i', '', $text);
if ($max_chars > 0) {
$text = wp_strip_all_tags($text);
} else {
$text = wp_kses_post($text);
}
$tokens = isset($data['usage']['total_tokens']) ? (int) $data['usage']['total_tokens'] : 0;
return array('text' => trim($text), 'tokens' => $tokens);
}
private static function language_name($lang)
{
if ($lang === 'site' || $lang === '') {
$locale = get_locale();
$lang = strpos($locale, 'pt_BR') === 0 ? 'pt_BR' : (strpos($locale, 'pt') === 0 ? 'pt_PT' : 'en');
}
$names = array(
'pt_PT' => 'European Portuguese (as written in Portugal, Mozambique and Angola)',
'pt_BR' => 'Brazilian Portuguese',
'en' => 'English',
);
return isset($names[$lang]) ? $names[$lang] : $names['en'];
}
public static function system_prompt($tone, $lang, $plain)
{
$tones = array(
'friendly' => 'friendly and close, like a person from the team talking to a customer',
'professional' => 'professional and clear',
'simple' => 'simple and direct, with short sentences',
'persuasive' => 'persuasive but honest, without exaggeration',
);
$tone_text = isset($tones[$tone]) ? $tones[$tone] : $tones['friendly'];
$site = wp_specialchars_decode(get_bloginfo('name'), ENT_QUOTES);
$parts = array(
sprintf('You write texts for the website "%1$s" (%2$s).', $site, home_url('/')),
'Write in ' . self::language_name($lang) . '. Tone: ' . $tone_text . '.',
'Use short sentences. Avoid empty marketing phrases and cliches. Never use the long dash character; use a comma, a colon or a full stop.',
'Do not invent prices, deadlines, technical details, awards or promises that are not in the information given.',
$plain ? 'Answer with the text only, in plain text, without a title and without quotes.' : 'Answer with the text only, in simple HTML (p, h2, h3, ul, li, strong). No title at the top, no html or body tags, no code fences.',
);
$brief = trim((string) MOZOUT_AI_Settings::get('write_brief'));
if ($brief !== '') {
$parts[] = "About the business, from the site owner:\n" . $brief;
}
return implode("\n", $parts);
}
/* ---- New drafts from the settings page ---- */
/**
* Writes a new draft of a post or page. @return int|WP_Error the new post id.
*/
public static function new_draft($type, $topic, $tone, $lang)
{
$type = in_array($type, array('post', 'page'), true) ? $type : 'post';
$topic = self::clean_brief($topic);
if ($topic === '') {
return new WP_Error('mozout_ai_empty_topic', __('Say in a few words what the text should cover.', 'mozout-ai'));
}
$task = 'Write a new ' . $type . " for the website.\nOn the first line write only the title, without quotes or HTML. Then a blank line, then the text.\nWhat the author wants: " . $topic;
$res = self::generate($task, $tone, $lang);
if (is_wp_error($res)) {
return $res;
}
$parts = preg_split('/\r?\n/', $res['text'], 2);
$title = trim(wp_strip_all_tags(isset($parts[0]) ? $parts[0] : ''));
$title = trim(preg_replace('/^#+\s*/', '', $title), " \"'*");
$content = isset($parts[1]) ? trim($parts[1]) : '';
if ($content === '') {
$content = $res['text'];
$title = function_exists('mb_substr') ? mb_substr($topic, 0, 80) : substr($topic, 0, 80);
}
if (strpos($content, '<p') === false && strpos($content, '<h') === false) {
$content = wpautop($content);
}
$id = wp_insert_post(array(
'post_type' => $type,
'post_status' => 'draft',
'post_title' => $title,
'post_content' => $content,
'post_author' => get_current_user_id(),
), true);
if (is_wp_error($id)) {
return $id;
}
MOZOUT_AI_Log::add('draft', true, $title, array('post' => $id, 'tokens' => $res['tokens']));
return $id;
}
}