347 lines
18 KiB
PHP
347 lines
18 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 INTERWEB_MZ_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) INTERWEB_MZ_AI_Settings::get('write_enabled') === 1 && INTERWEB_MZ_AI_Settings::api_key() !== '';
|
|
}
|
|
|
|
public static function post_types()
|
|
{
|
|
$types = array_values(array_filter((array) INTERWEB_MZ_AI_Settings::get('write_post_types'), 'post_type_exists'));
|
|
return apply_filters('interweb_mz_ai_writer_post_types', $types);
|
|
}
|
|
|
|
public static function tones()
|
|
{
|
|
return array(
|
|
'friendly' => __('Friendly and close', 'interweb-mz-ai'),
|
|
'professional' => __('Professional', 'interweb-mz-ai'),
|
|
'simple' => __('Simple and direct', 'interweb-mz-ai'),
|
|
'persuasive' => __('Persuasive, without exaggeration', 'interweb-mz-ai'),
|
|
);
|
|
}
|
|
|
|
public static function languages()
|
|
{
|
|
return array(
|
|
'site' => __('Language of the site', 'interweb-mz-ai'),
|
|
'pt_PT' => __('European Portuguese', 'interweb-mz-ai'),
|
|
'pt_BR' => __('Brazilian Portuguese', 'interweb-mz-ai'),
|
|
'en' => __('English', 'interweb-mz-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', 'interweb-mz-ai'),
|
|
'excerpt' => __('Short description', 'interweb-mz-ai'),
|
|
);
|
|
}
|
|
$out = array('content' => __('Text of the page', 'interweb-mz-ai'));
|
|
if (post_type_supports($post_type, 'excerpt')) {
|
|
$out['excerpt'] = __('Excerpt', 'interweb-mz-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('interweb-mz-ai-writer', __('Write with AI', 'interweb-mz-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('interweb-mz-ai-admin', INTERWEB_MZ_AI_URL . 'assets/admin.css', array(), INTERWEB_MZ_AI_VERSION);
|
|
wp_enqueue_script('interweb-mz-ai-select', INTERWEB_MZ_AI_URL . 'assets/select.js', array(), INTERWEB_MZ_AI_VERSION, true);
|
|
wp_enqueue_script('interweb-mz-ai-writer', INTERWEB_MZ_AI_URL . 'assets/writer.js', array(), INTERWEB_MZ_AI_VERSION, true);
|
|
wp_localize_script('interweb-mz-ai-writer', 'interwebMzAiWriter', array(
|
|
'url' => esc_url_raw(rest_url('interweb-mz-ai/v1/write')),
|
|
'nonce' => wp_create_nonce('wp_rest'),
|
|
'writing' => __('Writing... this can take up to a minute.', 'interweb-mz-ai'),
|
|
'error' => __('The text could not be written. Please try again.', 'interweb-mz-ai'),
|
|
'empty' => __('Say in a few words what the text should cover.', 'interweb-mz-ai'),
|
|
'inserted' => __('Done. Check the text before you publish.', 'interweb-mz-ai'),
|
|
));
|
|
}
|
|
|
|
public static function meta_box_html($post)
|
|
{
|
|
$targets = self::targets($post->post_type);
|
|
echo '<div class="interweb-mz-ai-writer" data-post="' . (int) $post->ID . '">';
|
|
echo '<p><label for="interweb-mz-ai-writer-target">' . esc_html__('What to write', 'interweb-mz-ai') . '</label><br>' . self::select_html('interweb-mz-ai-writer-target', $targets, 'content') . '</p>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- built only from escaped parts (esc_html, esc_attr, esc_url, selected).
|
|
echo '<p><label for="interweb-mz-ai-writer-brief">' . esc_html__('What should it say?', 'interweb-mz-ai') . '</label>';
|
|
echo '<textarea id="interweb-mz-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.', 'interweb-mz-ai') : __('Example: how to choose a domain name, for small businesses, with 3 tips.', 'interweb-mz-ai')) . '"></textarea></p>';
|
|
echo '<p><label for="interweb-mz-ai-writer-tone">' . esc_html__('Tone', 'interweb-mz-ai') . '</label><br>' . self::select_html('interweb-mz-ai-writer-tone', self::tones(), (string) INTERWEB_MZ_AI_Settings::get('write_tone')) . '</p>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- built only from escaped parts (esc_html, esc_attr, esc_url, selected).
|
|
echo '<p><label for="interweb-mz-ai-writer-lang">' . esc_html__('Language', 'interweb-mz-ai') . '</label><br>' . self::select_html('interweb-mz-ai-writer-lang', self::languages(), 'site') . '</p>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- built only from escaped parts (esc_html, esc_attr, esc_url, selected).
|
|
echo '<p><button type="button" class="button button-primary interweb-mz-ai-writer-go">' . esc_html__('Write', 'interweb-mz-ai') . '</button></p>';
|
|
echo '<p class="interweb-mz-ai-writer-msg" role="status" aria-live="polite"></p>';
|
|
echo '<div class="interweb-mz-ai-writer-result" hidden>';
|
|
echo '<label for="interweb-mz-ai-writer-text">' . esc_html__('Suggestion (you can edit it)', 'interweb-mz-ai') . '</label>';
|
|
echo '<textarea id="interweb-mz-ai-writer-text" rows="10"></textarea>';
|
|
echo '<p class="interweb-mz-ai-writer-actions"><button type="button" class="button interweb-mz-ai-writer-insert" data-mode="append">' . esc_html__('Add at the end', 'interweb-mz-ai') . '</button> ';
|
|
echo '<button type="button" class="button interweb-mz-ai-writer-insert" data-mode="replace">' . esc_html__('Replace the text', 'interweb-mz-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.', 'interweb-mz-ai') . '</p>';
|
|
echo '</div>';
|
|
}
|
|
|
|
private static function select_html($id, array $options, $current)
|
|
{
|
|
$html = '<select id="' . esc_attr($id) . '" data-interweb-mz-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('interweb-mz-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.', 'interweb-mz-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.', 'interweb-mz-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.', 'interweb-mz-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);
|
|
}
|
|
INTERWEB_MZ_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) INTERWEB_MZ_AI_Settings::get('write_per_day'));
|
|
$bucket = 'interweb_mz_ai_wr_' . md5($user_id . '|' . gmdate('Ymd'));
|
|
$used = (int) get_transient($bucket);
|
|
if ($used >= $limit) {
|
|
return new WP_Error('interweb_mz_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.', 'interweb-mz-ai'),
|
|
$limit
|
|
));
|
|
}
|
|
set_transient($bucket, $used + 1, DAY_IN_SECONDS);
|
|
|
|
$model = trim((string) INTERWEB_MZ_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) INTERWEB_MZ_AI_Settings::get('write_max_tokens'))),
|
|
);
|
|
if (strpos($body['model'], 'agent/') === 0) {
|
|
$body['messages'] = array_slice($body['messages'], 1);
|
|
}
|
|
$res = INTERWEB_MZ_AI_Api::request('POST', '/v1/chat/completions', $body, array('timeout' => 90, 'idempotency_key' => true));
|
|
if (is_wp_error($res)) {
|
|
INTERWEB_MZ_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 === '') {
|
|
INTERWEB_MZ_AI_Log::add('write', false, __('The model answered without text.', 'interweb-mz-ai'));
|
|
return new WP_Error('interweb_mz_ai_empty', __('The model answered without text. Please try again.', 'interweb-mz-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) INTERWEB_MZ_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('interweb_mz_ai_empty_topic', __('Say in a few words what the text should cover.', 'interweb-mz-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;
|
|
}
|
|
INTERWEB_MZ_AI_Log::add('draft', true, $title, array('post' => $id, 'tokens' => $res['tokens']));
|
|
return $id;
|
|
}
|
|
}
|