self::usage() + 1 ), false ); } /** * Remaining generations (-1 = unlimited, null = unknown yet). * * Only Fillnova AI has a quota; your own key and WordPress AI are unlimited. * * @return int|null */ public static function remaining() { return 'cloud' === self::source() ? Fillnova_AI_Cloud::remaining() : -1; } /** * Everything the admin UI shows about AI: source, label and quota. * * @param bool $refresh Refresh Fillnova AI usage from the service. * @return array */ public static function status( $refresh = false ) { $source = self::source(); $labels = array( 'cloud' => __( 'Fillnova AI', 'fillnova' ), 'wordpress' => __( 'WordPress AI', 'fillnova' ), 'key' => __( 'Your API key', 'fillnova' ), 'offline' => __( 'Built-in generator', 'fillnova' ), ); $out = array( 'source' => $source, 'label' => $labels[ $source ], 'used' => null, 'limit' => null, 'remaining' => -1, 'plan' => fillnova_is_pro() ? 'pro' : 'free', 'resets' => gmdate( 'Y-m-01', strtotime( 'first day of next month' ) ), ); if ( 'cloud' === $source ) { $u = Fillnova_AI_Cloud::usage( $refresh ); if ( $u ) { $out['used'] = (int) $u['used']; $out['limit'] = (int) $u['limit']; $out['remaining'] = (int) $u['remaining']; $out['plan'] = $u['plan']; $out['resets'] = isset( $u['resets'] ) ? (string) $u['resets'] : $out['resets']; // '' = one-time allowance. } else { $out['remaining'] = null; } } return $out; } /** * Generate a form from a prompt. * * @param string $prompt User description. * @param array $options mode (auto|standard|multistep|conversational), tone, language. * @return array|WP_Error { title, fields, settings, source } */ public static function generate( $prompt, $options = array() ) { $prompt = trim( wp_strip_all_tags( (string) $prompt ) ); if ( strlen( $prompt ) < 3 ) { return new WP_Error( 'fillnova_ai_prompt', __( 'Please describe the form you want to create.', 'fillnova' ) ); } $prompt = function_exists( 'mb_substr' ) ? mb_substr( $prompt, 0, 2000 ) : substr( $prompt, 0, 2000 ); $options = wp_parse_args( $options, array( 'mode' => 'auto', 'language' => '', ) ); $source = self::source(); if ( 'offline' === $source || ! empty( $options['offline'] ) ) { $result = self::offline_generate( $prompt, $options ); $result['source'] = 'offline'; return $result; } if ( 'cloud' === $source ) { $result = Fillnova_AI_Cloud::generate( $prompt, $options ); if ( is_wp_error( $result ) && 'fillnova_cloud_unreachable' === $result->get_error_code() ) { // The service is down or the site is offline: still give the user a form. $fallback = self::offline_generate( $prompt, $options ); $fallback['source'] = 'offline'; $fallback['notice'] = $result->get_error_message(); return $fallback; } if ( ! is_wp_error( $result ) ) { self::track(); } return $result; } $system = self::system_prompt( $options ); $user = "Create a form for this request:\n\n" . $prompt; $raw = self::request( $system, $user ); if ( is_wp_error( $raw ) ) { return $raw; } $parsed = self::parse( $raw ); if ( is_wp_error( $parsed ) ) { return $parsed; } self::track(); $parsed['source'] = 'ai'; return $parsed; } /** * Build the system prompt. * * @param array $options Options. * @return string */ public static function system_prompt( $options = array() ) { $types = array(); $all = Fillnova_Fields::types(); foreach ( self::allowed_types() as $key ) { if ( isset( $all[ $key ] ) ) { $types[] = $key . ' (' . $all[ $key ]['label'] . ')'; } } $mode_rule = 'Choose "mode": "standard" for short forms (<= 7 inputs), "multistep" for long forms (split into logical sections with "pagebreak" fields), "conversational" for lead generation, quizzes or friendly one-question-at-a-time experiences.'; if ( ! empty( $options['mode'] ) && 'auto' !== $options['mode'] ) { $mode_rule = 'Use "mode": "' . sanitize_key( $options['mode'] ) . '".'; } $lang = ! empty( $options['language'] ) ? 'Write all labels in ' . sanitize_text_field( $options['language'] ) . '.' : 'Write labels in the same language as the user request.'; $extra = (string) apply_filters( 'fillnova_ai_system_extra', '' ); return 'You are a senior UX designer and conversion expert who builds professional web forms.' . "\n" . 'Return ONLY a valid JSON object (no markdown, no comments) with this exact shape:' . "\n" . '' . "\n" . '{' . "\n" . ' "title": "Form title",' . "\n" . ' "settings": {' . "\n" . ' "mode": "standard|multistep|conversational",' . "\n" . ' "submit_text": "Action-oriented button text",' . "\n" . ' "success_message": "Friendly thank-you message",' . "\n" . ' "description": "Optional one-sentence intro shown above the form",' . "\n" . ' "welcome_title": "Only for conversational mode",' . "\n" . ' "welcome_text": "Only for conversational mode"' . "\n" . ' },' . "\n" . ' "fields": [' . "\n" . ' {' . "\n" . ' "id": "f_short_snake_case_unique",' . "\n" . ' "type": "one of the allowed types",' . "\n" . ' "label": "Clear question or label",' . "\n" . ' "placeholder": "Helpful example",' . "\n" . ' "help": "Optional short helper text",' . "\n" . ' "required": true,' . "\n" . ' "width": "full|half",' . "\n" . ' "options": [ { "label": "Choice", "value": "Choice" } ],' . "\n" . ' "conditions": { "enabled": true, "action": "show", "match": "all", "rules": [ { "field": "f_other_id", "operator": "is|is_not|contains|gt|lt|empty|not_empty", "value": "x" } ] }' . "\n" . ' }' . "\n" . ' ]' . "\n" . '}' . "\n" . '' . "\n" . 'Allowed field types: {TYPES}' . "\n" . '' . "\n" . 'Rules for a professional result:' . "\n" . '- ' . $mode_rule . "\n" . '- Ask only what is needed; order questions logically (identity → context → details → consent).' . "\n" . '- Use "name" for a person\'s full name, "email" for emails, "phone" for phone numbers, "address" for postal addresses.' . "\n" . '- Put two short related fields side by side with "width": "half" (e.g. email + phone).' . "\n" . '- Use choice fields (radio, select, checkbox) with 3–6 realistic options instead of free text when answers are predictable.' . "\n" . '- Mark essential fields as required; keep optional fields optional.' . "\n" . '- Add conditional logic where it improves the experience (e.g. show "Please specify" when "Other" is chosen; show a follow-up when a rating is low). Conditions must reference ids of fields that appear earlier.' . "\n" . '- When personal data is collected, finish with a "consent" field (required) with "consent_text".' . "\n" . '- For file uploads set "accept" (comma separated extensions) and "max_size" in MB.' . "\n" . '- For "rating" you may set "stars" (3–10). For "range" set "min", "max", "step".' . "\n" . '- For "heading" use it to title sections; for "pagebreak" the label is the next step name.' . "\n" . '- Write in a warm, professional tone. ' . $lang . "\n" . $extra . "\n"; } /** * Send a prompt to the AI. * * The free plugin talks to Fillnova AI through Fillnova_AI_Cloud. Fillnova Pro adds direct * connections (WordPress AI, your own OpenAI / Anthropic / compatible key) through the * "fillnova_ai_request" filter. * * @param string $system System prompt. * @param string $user User prompt. * @return string|WP_Error Raw text. */ public static function request( $system, $user ) { $system = str_replace( '{TYPES}', implode( ', ', self::allowed_types() ), $system ); /** * Answer an AI request directly (Pro: WordPress AI or your own key). Return the raw text or a WP_Error. * * @param null|string|WP_Error $pre Null to continue. * @param string $system System prompt. * @param string $user User prompt. */ $pre = apply_filters( 'fillnova_ai_request', null, $system, $user ); if ( null !== $pre ) { return $pre; } return new WP_Error( 'fillnova_ai_source', __( 'No direct AI connection is available for this request.', 'fillnova' ) ); } /** * Parse the model output into a sanitized schema. * * @param string $raw Raw text. * @return array|WP_Error */ public static function parse( $raw ) { $raw = trim( (string) $raw ); $raw = preg_replace( '/^```(?:json)?\s*|\s*```$/i', '', $raw ); $start = strpos( $raw, '{' ); $end = strrpos( $raw, '}' ); if ( false === $start || false === $end ) { return new WP_Error( 'fillnova_ai_parse', __( 'The AI response could not be read. Please try again.', 'fillnova' ) ); } $data = json_decode( substr( $raw, $start, $end - $start + 1 ), true ); if ( ! is_array( $data ) || empty( $data['fields'] ) ) { return new WP_Error( 'fillnova_ai_parse', __( 'The AI response could not be read. Please try again.', 'fillnova' ) ); } // Fill type defaults the model may have omitted. $types = Fillnova_Fields::types(); foreach ( $data['fields'] as $i => $f ) { if ( isset( $f['type'] ) && isset( $types[ $f['type'] ]['defaults'] ) ) { $data['fields'][ $i ] = array_merge( $types[ $f['type'] ]['defaults'], (array) $f ); } } $settings = wp_parse_args( isset( $data['settings'] ) ? (array) $data['settings'] : array(), Fillnova_Forms::default_settings() ); $schema = Fillnova_Forms::sanitize_schema( array( 'fields' => $data['fields'], 'settings' => $settings, ) ); if ( empty( $schema['fields'] ) ) { return new WP_Error( 'fillnova_ai_parse', __( 'The AI did not return any usable fields. Try rephrasing your request.', 'fillnova' ) ); } return array( 'title' => isset( $data['title'] ) ? sanitize_text_field( $data['title'] ) : __( 'AI generated form', 'fillnova' ), 'fields' => $schema['fields'], 'settings' => $schema['settings'], ); } /** * Offline generator: picks the best template by keywords and adds requested fields. * * @param string $prompt Prompt. * @param array $options Options. * @return array */ public static function offline_generate( $prompt, $options = array() ) { $p = strtolower( $prompt ); $map = array( 'job' => array( 'job', 'career', 'hiring', 'applicant', 'application', 'cv', 'resume', 'recruit', 'vacancy' ), 'lead' => array( 'lead', 'proposal', 'quote', 'sales', 'agency', 'b2b', 'prospect' ), 'feedback' => array( 'feedback', 'review', 'satisfaction', 'rate us', 'testimonial' ), 'survey' => array( 'survey', 'questionnaire', 'research', 'poll' ), 'event' => array( 'event', 'registration', 'register', 'conference', 'webinar', 'workshop', 'ticket' ), 'booking' => array( 'booking', 'appointment', 'reservation', 'schedule', 'book a', 'salon', 'clinic', 'restaurant' ), 'support' => array( 'support', 'ticket', 'bug', 'issue', 'help desk', 'complaint' ), 'newsletter' => array( 'newsletter', 'subscribe', 'mailing list', 'signup', 'sign up' ), 'referral' => array( 'referral', 'refer a friend', 'invite' ), 'quiz' => array( 'quiz', 'trivia', 'test', 'exam' ), 'order' => array( 'order', 'payment', 'paypal', 'purchase', 'buy', 'checkout', 'donation' ), 'contact' => array( 'contact', 'get in touch', 'enquiry', 'inquiry', 'message' ), ); $best = 'contact'; $score = 0; foreach ( $map as $tpl => $words ) { $s = 0; foreach ( $words as $w ) { if ( false !== strpos( $p, $w ) ) { $s += strlen( $w ); } } if ( $s > $score ) { $score = $s; $best = $tpl; } } $tpl = Fillnova_Templates::get( $best ); $fields = $tpl['fields']; $settings = wp_parse_args( isset( $tpl['settings'] ) ? $tpl['settings'] : array(), Fillnova_Forms::default_settings() ); // Requested extras by keyword. $extras = array( 'phone' => array( array( 'phone', 'mobile', 'telephone', 'whatsapp' ), 'phone', __( 'Phone number', 'fillnova' ) ), 'address' => array( array( 'address', 'shipping', 'delivery' ), 'address', __( 'Address', 'fillnova' ) ), 'file' => array( array( 'upload', 'attachment', 'photo', 'image', 'document', 'file' ), 'file', __( 'Upload a file', 'fillnova' ) ), 'date' => array( array( 'date', 'birthday', 'day' ), 'date', __( 'Date', 'fillnova' ) ), 'rating' => array( array( 'rating', 'stars', 'rate' ), 'rating', __( 'Your rating', 'fillnova' ) ), 'url' => array( array( 'website', 'portfolio', 'linkedin', 'url' ), 'url', __( 'Website', 'fillnova' ) ), 'company' => array( array( 'company', 'business name', 'organization', 'organisation' ), 'text', __( 'Company', 'fillnova' ) ), 'budget' => array( array( 'budget' ), 'select', __( 'Budget', 'fillnova' ) ), 'consent' => array( array( 'gdpr', 'consent', 'privacy', 'terms' ), 'consent', __( 'Consent', 'fillnova' ) ), ); $have_types = wp_list_pluck( $fields, 'type' ); $labels = strtolower( implode( ' ', wp_list_pluck( $fields, 'label' ) ) ); foreach ( $extras as $key => $def ) { list( $words, $type, $label ) = $def; $wanted = false; foreach ( $words as $w ) { if ( preg_match( '/\b' . preg_quote( $w, '/' ) . '/', $p ) ) { $wanted = true; break; } } if ( ! $wanted ) { continue; } if ( 'text' === $type || 'select' === $type ? false !== strpos( $labels, strtolower( $label ) ) : in_array( $type, $have_types, true ) ) { continue; } $extra = array(); if ( 'budget' === $key ) { $extra['options'] = Fillnova_Templates::o( array( '< $1,000', '$1,000 – $5,000', '$5,000 – $20,000', '$20,000+' ) ); } $new = Fillnova_Templates::f( $type, $label, $extra ); // Insert before consent if present. $pos = array_search( 'consent', wp_list_pluck( $fields, 'type' ), true ); if ( false !== $pos && 'consent' !== $type ) { array_splice( $fields, $pos, 0, array( $new ) ); } else { $fields[] = $new; } $have_types[] = $type; } if ( ! empty( $options['mode'] ) && 'auto' !== $options['mode'] ) { $settings['mode'] = $options['mode']; } elseif ( false !== strpos( $p, 'conversational' ) || false !== strpos( $p, 'one question' ) || false !== strpos( $p, 'chat' ) ) { $settings['mode'] = 'conversational'; } elseif ( false !== strpos( $p, 'multi-step' ) || false !== strpos( $p, 'multistep' ) || false !== strpos( $p, 'steps' ) ) { $settings['mode'] = 'multistep'; } $schema = Fillnova_Forms::sanitize_schema( array( 'fields' => $fields, 'settings' => $settings, ) ); $title = ucfirst( trim( preg_replace( '/^(create|make|build|i need|i want|generate)\s+(a|an|me a)?\s*/i', '', $prompt ) ) ); $title = strlen( $title ) > 60 ? $tpl['name'] : $title; return array( 'title' => $title ? $title : $tpl['name'], 'fields' => $schema['fields'], 'settings' => $schema['settings'], ); } }