'forbidden'], 403); } $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : ''; if (!wp_verify_nonce($nonce, 'aiomatic_live_feed')) { wp_send_json_error(['message' => 'bad_nonce'], 400); } if (empty($GLOBALS['aiomatic_stats']) || !is_object($GLOBALS['aiomatic_stats'])) { wp_send_json_error(['message' => 'stats_unavailable'], 500); } $last_id = isset($_POST['last_id']) ? intval($_POST['last_id']) : 0; $limit = isset($_POST['limit']) ? intval($_POST['limit']) : 30; if ($limit < 1) $limit = 30; if ($limit > 100) $limit = 100; $filters = []; $sort = ['accessor' => 'id', 'by' => 'desc']; $res = $GLOBALS['aiomatic_stats']->logs_query([], 0, $limit, $filters, $sort); $rows = isset($res['rows']) && is_array($res['rows']) ? $res['rows'] : []; $new = []; foreach ($rows as $r) { if (!isset($r['id'])) { continue; } if (intval($r['id']) > $last_id) { $new[] = $r; } } usort($new, function($a, $b){ return intval($a['id']) <=> intval($b['id']); }); $out = []; $max_id = $last_id; foreach ($new as $r) { $id = intval($r['id']); if ($id > $max_id) $max_id = $id; $price = ''; if (isset($r['apiRef']) && function_exists('aiomatic_is_aiomaticapi_key') && aiomatic_is_aiomaticapi_key($r['apiRef'])) { $price = 'N/A'; } else { $price = isset($r['price']) ? (string)$r['price'] . '$' : ''; } $out[] = [ 'id' => $id, 'time' => isset($r['time']) ? (string)$r['time'] : '', 'env' => isset($r['env']) ? (string)$r['env'] : '', 'mode' => isset($r['mode']) ? (string)$r['mode'] : '', 'model' => isset($r['model']) ? (string)$r['model'] : '', 'assistant_id' => isset($r['assistant_id']) ? (string)$r['assistant_id'] : '', 'units' => isset($r['units']) ? (int)$r['units'] : 0, 'type' => isset($r['type']) ? (string)$r['type'] : '', 'price' => $price, 'session' => isset($r['session']) ? (string)$r['session'] : '', 'userId' => isset($r['userId']) ? (int)$r['userId'] : 0, 'ip' => isset($r['ip']) ? (string)$r['ip'] : '', ]; } wp_send_json_success([ 'last_id' => $max_id, 'items' => $out, ]); }); add_action('wp_ajax_aimogen_dismiss_notice', 'aimogen_dismiss_notice'); function aimogen_dismiss_notice() { check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('edit_posts') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } if ( isset($_POST['notice_id']) ) { $user_id = get_current_user_id(); $notice_id = sanitize_text_field( wp_unslash($_POST['notice_id']) ); update_user_meta( $user_id, $notice_id . '_dismissed', true ); wp_send_json_success(); } else { wp_send_json_error(); } die(); } add_action( 'wp_ajax_aimogen_refresh_ollama_models', 'aimogen_refresh_ollama_models' ); function aimogen_refresh_ollama_models() { check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('edit_posts') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } $aimogen_Main_Settings = get_option('aimogen_Main_Settings', false); if (!isset($aimogen_Main_Settings['ollama_url']) || trim($aimogen_Main_Settings['ollama_url']) == '') { wp_send_json_error(array( 'message' => 'You need to enter an Ollama API URl for this to work!')); exit; } aimogen_get_ollama_embedding_models(true); $llama_models = aimogen_get_ollama_models(true); if($llama_models !== false) { wp_send_json_success( array('data' => $llama_models) ); die(); } else { wp_send_json_error(array( 'message' => 'Failed to get Ollama models list.')); die(); } } add_action( 'wp_ajax_aimogen_refresh_openrouter_models', 'aimogen_refresh_openrouter_models' ); function aimogen_refresh_openrouter_models() { check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('edit_posts') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } $aimogen_Main_Settings = get_option('aimogen_Main_Settings', false); if (!isset($aimogen_Main_Settings['app_id_openrouter']) || trim($aimogen_Main_Settings['app_id_openrouter']) == '') { wp_send_json_error(array( 'message' => 'You need to enter an OpenRouter API URl for this to work!')); exit; } delete_option('aimogen_openrouter_model_list'); wp_send_json_success( array('data' => 'ok') ); die(); } add_action( 'wp_ajax_aimogen_refresh_replicate_models', 'aimogen_refresh_replicate_models' ); function aimogen_refresh_replicate_models() { check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('edit_posts') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } $aimogen_Main_Settings = get_option('aimogen_Main_Settings', false); if (!isset($aimogen_Main_Settings['replicate_app_id']) || trim($aimogen_Main_Settings['replicate_app_id']) == '') { wp_send_json_error(array( 'message' => 'You need to enter an Replicate API URl for this to work!')); exit; } $api_key = trim($aimogen_Main_Settings['replicate_app_id']); $url = 'https://api.replicate.com/v1/collections/text-to-image'; $response = wp_remote_get($url, array( 'headers' => array( 'Authorization' => 'Bearer ' . $api_key ) )); if (is_wp_error($response)) { aimogen_log_to_file('Failed to fetch models'); } else { $body = wp_remote_retrieve_body($response); $data = json_decode($body); if (isset($data->models)) { usort($data->models, function($a, $b) { return $b->run_count - $a->run_count; }); $return_data = array(); foreach ($data->models as $model) { $model_name = $model->name ?? ''; $model_version = $model->latest_version->id ?? ''; $return_data[$model_version] = $model_name; } if(count($return_data) == 0) { aimogen_log_to_file('No returned models found'); } else { aimogen_update_option('aimogen_replicate_model_list', $return_data); wp_send_json_success( array('data' => 'ok') ); } } else { aimogen_log_to_file('No models found'); } } wp_send_json_error(array( 'message' => 'Failed to get Replicate models list.')); die(); } add_action('wp_ajax_aimogen_check_process_status', 'aimogen_check_process_status'); function aimogen_check_process_status() { check_ajax_referer('openai-bulk-nonce', 'nonce'); if ( ! current_user_can('edit_posts') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with status polling'); $poll = get_transient('aimogen_log_history'); if($poll !== false) { $aimogen_result['msg'] = esc_html($poll); $aimogen_result['status'] = 'success'; } else { $aimogen_result['msg'] = 'Running status not found'; } wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_load_chat_conversation_data', 'aimogen_load_chat_conversation_data'); add_action('wp_ajax_nopriv_aimogen_load_chat_conversation_data', 'aimogen_load_chat_conversation_data'); function aimogen_load_chat_conversation_data() { check_ajax_referer('openai-ajax-nonce', 'nonce'); $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong'); if ( isset( $_POST['dataid'] ) && sanitize_text_field( wp_unslash( $_POST['dataid'] ) ) !== '' ) { $dataid = sanitize_text_field( wp_unslash($_POST['dataid'])); } else { $aimogen_result['msg'] = 'Insuficient parameters for call!'; wp_send_json($aimogen_result); } if(isset($_POST['persistent_guests']) && sanitize_text_field( wp_unslash($_POST['persistent_guests'])) !== '') { $persistent_guests = sanitize_text_field( wp_unslash($_POST['persistent_guests'])); } else { $aimogen_result['msg'] = 'Insuficient parameters for call!'; wp_send_json($aimogen_result); } if(isset($_POST['persistent']) && sanitize_text_field( wp_unslash($_POST['persistent'])) !== '') { $persistent = sanitize_text_field( wp_unslash($_POST['persistent'])); } else { $aimogen_result['msg'] = 'Insuficient parameters for call!'; wp_send_json($aimogen_result); } $user_id = get_current_user_id(); if($user_id == 0 && ($persistent_guests == 'on' || $persistent_guests == '1')) { $user_id = aimogen_get_guest_id(); } if($user_id == 0) { $aimogen_result['msg'] = 'You are not allowed to do this action'; wp_send_json($aimogen_result); } if($dataid === 'new-chat') { if(isset($_POST['init_message']) && sanitize_text_field( wp_unslash($_POST['init_message'])) !== '') { $init_message = sanitize_text_field( wp_unslash($_POST['init_message'])); } else { $init_message = ''; } $aimogen_result['status'] = 'success'; $aimogen_result['data'] = array('data' => wp_unslash($init_message)); wp_send_json($aimogen_result); } if(is_numeric($user_id)) { $conversation_data = get_user_meta($user_id, 'aimogen_chat_history_' . $persistent, true); if(!is_array($conversation_data)) { $conversation_data = array(); } } else { $conversation_data = get_transient('aimogen_chat_history_' . $persistent . '_' . $user_id); if(!is_array($conversation_data)) { $conversation_data = array(); } } if(!isset($conversation_data[$dataid])) { $aimogen_result['msg'] = 'Conversation not found in database'; wp_send_json($aimogen_result); } else { $aimogen_result['status'] = 'success'; $aimogen_result['data'] = $conversation_data[$dataid]; wp_send_json($aimogen_result); } } add_action('wp_ajax_aimogen_remove_chat_logs', 'aimogen_remove_chat_logs'); add_action('wp_ajax_nopriv_aimogen_remove_chat_logs', 'aimogen_remove_chat_logs'); function aimogen_remove_chat_logs() { check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('manage_options') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong'); if(isset($_POST['dataid']) && sanitize_text_field( wp_unslash($_POST['dataid'])) !== '') { $dataid = sanitize_text_field( wp_unslash($_POST['dataid'])); } else { $aimogen_result['msg'] = 'Insuficient parameters for call!'; wp_send_json($aimogen_result); } if(isset($_POST['persistent_guests']) && sanitize_text_field( wp_unslash($_POST['persistent_guests'])) !== '') { $persistent_guests = sanitize_text_field( wp_unslash($_POST['persistent_guests'])); } else { $aimogen_result['msg'] = 'Insuficient parameters for call!'; wp_send_json($aimogen_result); } if(isset($_POST['persistent']) && sanitize_text_field( wp_unslash($_POST['persistent'])) !== '') { $persistent = sanitize_text_field( wp_unslash($_POST['persistent'])); } else { $aimogen_result['msg'] = 'Insuficient parameters for call!'; wp_send_json($aimogen_result); } $user_id = get_current_user_id(); if($user_id == 0 && ($persistent_guests == 'on' || $persistent_guests == '1')) { $user_id = aimogen_get_guest_id(); } if($user_id == 0) { $aimogen_result['msg'] = 'You are not allowed to do this action'; wp_send_json($aimogen_result); } if($dataid === 'new-chat') { $aimogen_result['msg'] = 'This is not allowed'; wp_send_json($aimogen_result); } if(is_numeric($user_id)) { $conversation_data = get_user_meta($user_id, 'aimogen_chat_history_' . $persistent, true); if(!is_array($conversation_data)) { $conversation_data = array(); } } else { $conversation_data = get_transient('aimogen_chat_history_' . $persistent . '_' . $user_id); if(!is_array($conversation_data)) { $conversation_data = array(); } } if(isset($conversation_data[$dataid])) { unset($conversation_data[$dataid]); if(is_numeric($user_id)) { update_user_meta($user_id, 'aimogen_chat_history_' . $persistent, $conversation_data); } else { $aimogen_Chatbot_Settings = get_option('aimogen_Chatbot_Settings', false); if(isset($aimogen_Chatbot_Settings['remember_chat_transient']) && $aimogen_Chatbot_Settings['remember_chat_transient'] !== '' && is_numeric($aimogen_Chatbot_Settings['remember_chat_transient'])) { $remember_time = intval($aimogen_Chatbot_Settings['remember_chat_transient']); } else { $remember_time = 0; } set_transient('aimogen_chat_history_' . $persistent . '_' . $user_id, $conversation_data, $remember_time); } $aimogen_result['status'] = 'success'; $aimogen_result['msg'] = 'ok'; wp_send_json($aimogen_result); } else { $aimogen_result['data'] = 'Conversation not found'; wp_send_json($aimogen_result); } } add_action('wp_ajax_aimogen_persona_upload', 'aimogen_persona_upload'); function aimogen_persona_upload() { check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('edit_posts') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with persona upload'); if(isset($_FILES['file']) && empty($_FILES['file']['error'])) { $file = isset( $_FILES['file'] ) && is_array( $_FILES['file'] ) ? [ 'name' => isset( $_FILES['file']['name'] ) ? sanitize_file_name( wp_unslash( $_FILES['file']['name'] ) ) : '', 'type' => isset( $_FILES['file']['type'] ) ? sanitize_text_field( wp_unslash( $_FILES['file']['type'] ) ) : '', 'tmp_name' => isset( $_FILES['file']['tmp_name'] ) ? sanitize_text_field( wp_unslash( $_FILES['file']['tmp_name'] ) ) : '', 'error' => isset( $_FILES['file']['error'] ) ? absint( wp_unslash($_FILES['file']['error'] )) : 0, 'size' => isset( $_FILES['file']['size'] ) ? absint( wp_unslash($_FILES['file']['size'] )) : 0, ] : null; $tmp = isset($file['tmp_name']) ? wp_unslash($file['tmp_name']) : ''; $rawname = isset($file['name']) ? wp_unslash($file['name']) : ''; $file_name = sanitize_file_name( basename( $rawname ) ); $filetype = wp_check_filetype( $file_name ); if ( $filetype['ext'] !== 'json' && ! aimogen_endsWith( $file_name, '.json' ) ) { $aimogen_result['msg'] = 'Only files with the json extension are supported, you sent: ' . $file_name; wp_send_json( $aimogen_result ); } $fc = file_get_contents( $tmp ); if ( empty( $fc ) ) { $aimogen_result['msg'] = 'Failed to read file: ' . $tmp; wp_send_json( $aimogen_result ); } $fc_dec = json_decode( $fc, true ); if ( $fc_dec === null ) { $aimogen_result['msg'] = 'Failed to decode json file: ' . $file_name; wp_send_json( $aimogen_result ); } $overwrite = isset( $_POST['overwrite'] ) ? sanitize_text_field( wp_unslash( $_POST['overwrite'] ) ) : '0'; foreach($fc_dec as $jsonf) { $address_post_id = 0; $query = new WP_Query( array( 'post_type' => 'aimogen_personas', 'title' => $jsonf['name'], 'post_status' => 'any', 'posts_per_page' => 1, 'no_found_rows' => true, 'ignore_sticky_posts' => true, 'update_post_term_cache' => false, 'update_post_meta_cache' => false, 'orderby' => 'post_date ID', 'order' => 'ASC', ) ); if ( ! empty( $query->post ) ) { if($overwrite != '1') { //persona already exists, skipping it continue; } else { while ( $query->have_posts() ) { $query->the_post(); $address_post_id = get_the_ID(); break; } } } $name = isset( $jsonf['name'] ) ? sanitize_text_field( $jsonf['name'] ) : ''; $role = isset( $jsonf['role'] ) ? sanitize_text_field( $jsonf['role'] ) : ''; $prompt = isset( $jsonf['prompt'] ) ? wp_kses_post( $jsonf['prompt'] ) : ''; $message = isset( $jsonf['message'] ) ? wp_kses_post( $jsonf['message'] ) : ''; $model = isset( $jsonf['model'] ) ? sanitize_text_field( $jsonf['model'] ) : ''; if ( $name === '' ) { continue; } $personas_data = array( 'post_type' => 'aimogen_personas', 'post_title' => $name, 'post_excerpt' => $role, 'post_content' => $prompt, 'post_status' => 'publish' ); $personas_data['ID'] = $address_post_id; if($overwrite != '1') { $personas_id = wp_insert_post($personas_data); } else { if(isset($personas_data['ID']) && $personas_data['ID'] != '0') { $personas_id = wp_update_post($personas_data); } else { $personas_id = wp_insert_post($personas_data); } } if(is_wp_error($personas_id)) { aimogen_log_to_file('Failed to import persona: ' . $personas_id->get_error_message()); } elseif($personas_id === 0) { aimogen_log_to_file('Failed to insert persona to database: ' . json_encode($personas_data)); } else { if(is_numeric($jsonf['avatar'])) { if($jsonf['avatar'] > 0) { if(!function_exists('set_post_thumbnail')) { require_once(ABSPATH . 'wp-admin/includes/image.php'); require_once(ABSPATH . 'wp-admin/includes/media.php'); } set_post_thumbnail( $personas_id, $jsonf['avatar'] ); } } elseif(filter_var($jsonf['avatar'], FILTER_VALIDATE_URL)) { if (!aimogen_generate_featured_image($jsonf['avatar'], $personas_id)) { if (isset($aimogen_Main_Settings['enable_detailed_logging'])) { aimogen_log_to_file('aimogen_generate_featured_image failed for ' . $jsonf['avatar']); } } } if(isset($jsonf['message']) && !empty($jsonf['message'])) { update_post_meta($personas_id, '_persona_first_message', $message); } if(isset($jsonf['model']) && !empty($jsonf['model'])) { update_post_meta($personas_id, '_persona_model', $model); } } } $aimogen_result['status'] = 'success'; } wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_assistant_upload', 'aimogen_assistant_upload'); function aimogen_assistant_upload() { check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('edit_posts') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with assistant upload'); if(isset($_FILES['file']) && empty($_FILES['file']['error'])) { $aimogen_Main_Settings = get_option('aimogen_Main_Settings', false); if (!isset($aimogen_Main_Settings['app_id']) || trim($aimogen_Main_Settings['app_id']) == '') { $aimogen_result['msg'] = 'You need to add an API key in plugin settings for this shortcode to work.'; wp_send_json($aimogen_result); } else { $appids = preg_split('/\r\n|\r|\n/', trim($aimogen_Main_Settings['app_id'])); $appids = array_filter($appids); $token = $appids[array_rand($appids)]; $token = apply_filters('aimogen_openai_api_key', $token); if(empty($token)) { $aimogen_result['msg'] = 'Invalid API key submitted'; wp_send_json($aimogen_result); } if(aimogen_is_aimogen_key($token)) { $aimogen_result['msg'] = 'Currently only OpenAI API is supported for text moderation.'; wp_send_json($aimogen_result); } } $raw_name = ''; if ( isset( $_FILES['file']['name'] ) ) { $raw_name = sanitize_file_name(wp_unslash( $_FILES['file']['name'] )); } $file_name = basename( $raw_name ); $filetype = wp_check_filetype($file_name); if($filetype['ext'] !== 'json' && !aimogen_endsWith($file_name, '.json')){ $aimogen_result['msg'] = 'Only files with the json extension are supported, you sent: ' . $file_name; wp_send_json($aimogen_result); } global $wp_filesystem; if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){ require_once ABSPATH . 'wp-admin/includes/file.php'; $creds = request_filesystem_credentials( site_url() ); wp_filesystem($creds); } $raw_tmp = ''; if ( isset( $_FILES['file']['tmp_name'] ) ) { $raw_tmp = sanitize_text_field(wp_unslash( $_FILES['file']['tmp_name'] )); } $tmp = $raw_tmp; $fc = file_get_contents( $tmp ); if ( $fc === false || $fc === '' ) { $aimogen_result['msg'] = 'Failed to read file.'; wp_send_json( $aimogen_result ); } $fc_dec = json_decode( $fc, true ); if ( json_last_error() !== JSON_ERROR_NONE ) { $aimogen_result['msg'] = 'Failed to decode JSON file.'; wp_send_json( $aimogen_result ); } if(isset($_POST['overwrite'])) { $overwrite = sanitize_text_field( wp_unslash($_POST['overwrite'])); } else { $overwrite = '0'; } require_once (dirname(__FILE__) . "/res/aimogen-assistants-api.php"); foreach($fc_dec as $jsonf) { $vector_store_id = ''; if(empty($jsonf['role'])) { $jsonf['role'] = ''; } if(empty($jsonf['prompt'])) { $jsonf['prompt'] = ''; } if(empty($jsonf['message'])) { $jsonf['message'] = ''; } $existing_openai = false; $address_post_id = 0; $assistant_id = ''; $temperature = ''; $topp = ''; if(isset($jsonf['temperature'])) { $temperature = $jsonf['temperature']; } if(isset($jsonf['topp'])) { $topp = $jsonf['topp']; } if(isset($jsonf['id']) && !empty($jsonf['id'])) { $query = new WP_Query( array( 'post_type' => 'aimogen_assistants', 'meta_query' => array( array( 'key' => '_assistant_id', 'value' => $jsonf['id'], 'compare' => 'EXISTS' ), ), 'post_status' => 'any', 'posts_per_page' => 1, 'no_found_rows' => true, 'ignore_sticky_posts' => true, 'update_post_term_cache' => false, 'update_post_meta_cache' => false, 'orderby' => 'post_date ID', 'order' => 'ASC', ) ); if ( ! empty( $query->post ) ) { if($overwrite != '1') { //assistant already exists, skipping it continue; } else { while ( $query->have_posts() ) { $query->the_post(); $address_post_id = get_the_ID(); $assistant_id = get_post_meta($address_post_id, '_assistant_id', true); break; } } } if(!empty($assistant_id)) { try { $ex_assistant = aimogen_openai_retrieve_assistant($token, $assistant_id); if(isset($ex_assistant['id']) && $ex_assistant['id'] == $assistant_id) { $existing_openai = true; } } catch(Exception $e) { $aimogen_result['msg'] = 'Failed to retrieve assistant using the API ' . $e->getMessage(); wp_send_json($aimogen_result); } } } if($existing_openai == true) { $tools = []; if($jsonf['code_interpreter'] == 'on') { $tools[] = ['type' => 'code_interpreter']; } if($jsonf['file_search'] == 'on') { $tools[] = ['type' => 'file_search']; } $functions_json = $jsonf['functions']; if($functions_json === false) { $functions = array(); } else { if(is_array($functions_json) && !isset($functions_json['name'])) { $functions = $functions_json; } elseif(isset($functions_json['name'])) { $functions = array($functions_json); } else { $functions = array(); } } foreach($functions as $func) { $tools[] = ['type' => 'function', 'function' => $func]; } try { if($address_post_id != '' && $address_post_id != 0) { $vector_store_id = get_post_meta($address_post_id, '_assistant_vector_store_id', true); } $metadata = ''; $assistantData = aimogen_openai_modify_assistant($token, $assistant_id, $jsonf['model'], $jsonf['name'], $jsonf['role'], $jsonf['prompt'], $temperature, $topp, $tools, $jsonf['files'], $metadata, $vector_store_id, $address_post_id); if($assistantData === false) { $aimogen_result['msg'] = 'Failed to update assistant using the API'; wp_send_json($aimogen_result); } } catch(Exception $e) { $aimogen_result['msg'] = 'Failed to retrieve assistant using the API ' . $e->getMessage(); wp_send_json($aimogen_result); } } else { $tools = []; if($jsonf['code_interpreter'] == 'on') { $tools[] = ['type' => 'code_interpreter']; } if($jsonf['file_search'] == 'on') { $tools[] = ['type' => 'file_search']; } $functions_json = $jsonf['functions']; if($functions_json === false) { $functions = array(); } else { if(is_array($functions_json) && !isset($functions_json['name'])) { $functions = $functions_json; } elseif(isset($functions_json['name'])) { $functions = array($functions_json); } else { $functions = array(); } } foreach($functions as $func) { $tools[] = ['type' => 'function', 'function' => $func]; } try { $metadata = ''; $assistantData = aimogen_openai_save_assistant( $token, $jsonf['model'], $jsonf['name'], $jsonf['role'], $temperature, $topp, $jsonf['prompt'], $tools, $jsonf['files'], $metadata, $vector_store_id ); if($assistantData === false) { $aimogen_result['msg'] = 'Failed to save assistant using the API'; wp_send_json($aimogen_result); } else { $assistant_id = $assistantData['id']; } } catch(Exception $e) { $aimogen_result['msg'] = 'Failed to retrieve assistant using the API ' . $e->getMessage(); wp_send_json($aimogen_result); } } $assistants_data = array( 'post_type' => 'aimogen_assistants', 'post_title' => $jsonf['name'], 'post_excerpt' => $jsonf['role'], 'post_content' => $jsonf['prompt'], 'post_status' => 'publish' ); $assistants_data['ID'] = $address_post_id; remove_filter('content_save_pre', 'wp_filter_post_kses'); remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');remove_filter('title_save_pre', 'wp_filter_kses'); if($overwrite != '1') { $assistants_id_local = wp_insert_post($assistants_data); } else { if(isset($assistants_data['ID']) && $assistants_data['ID'] != '0') { $assistants_id_local = wp_update_post($assistants_data); } else { $assistants_id_local = wp_insert_post($assistants_data); } } add_filter('content_save_pre', 'wp_filter_post_kses'); add_filter('content_filtered_save_pre', 'wp_filter_post_kses');add_filter('title_save_pre', 'wp_filter_kses'); if(is_wp_error($assistants_id_local)) { aimogen_log_to_file('Failed to import assistant: ' . $assistants_id_local->get_error_message()); } elseif($assistants_id_local === 0) { aimogen_log_to_file('Failed to insert assistant to database: ' . json_encode($assistants_data)); } else { if(is_numeric($jsonf['avatar'])) { if($jsonf['avatar'] > 0) { if(!function_exists('set_post_thumbnail')) { require_once(ABSPATH . 'wp-admin/includes/image.php'); require_once(ABSPATH . 'wp-admin/includes/media.php'); } set_post_thumbnail( $assistants_id_local, $jsonf['avatar'] ); } } elseif(filter_var($jsonf['avatar'], FILTER_VALIDATE_URL)) { if (!aimogen_generate_featured_image($jsonf['avatar'], $assistants_id_local)) { if (isset($aimogen_Main_Settings['enable_detailed_logging'])) { aimogen_log_to_file('aimogen_generate_featured_image failed for ' . $jsonf['avatar']); } } } if(isset($jsonf['message']) && !empty($jsonf['message'])) { update_post_meta($assistants_id_local, '_assistant_first_message', $jsonf['message']); } else { update_post_meta($assistants_id_local, '_assistant_first_message', ''); } update_post_meta($assistants_id_local, '_assistant_id', $assistant_id); if(!empty($jsonf['model'])) { update_post_meta($assistants_id_local, '_assistant_model', $jsonf['model']); } $tools = []; if($jsonf['code_interpreter'] == 'on') { $tools[] = ['type' => 'code_interpreter']; } if($jsonf['file_search'] == 'on') { $tools[] = ['type' => 'file_search']; } $functions_json = $jsonf['functions']; if($functions_json === false) { $functions = array(); } else { if(is_array($functions_json) && !isset($functions_json['name'])) { $functions = $functions_json; } elseif(isset($functions_json['name'])) { $functions = array($functions_json); } else { $functions = array(); } } foreach($functions as $func) { $tools[] = ['type' => 'function', 'function' => $func]; } if(!empty($tools)) { update_post_meta($assistants_id_local, '_assistant_tools', $tools); } else { update_post_meta($assistants_id_local, '_assistant_tools', array()); } if(!empty($temperature)) { update_post_meta($assistants_id_local, '_assistant_temperature', $temperature); } if(!empty($topp)) { update_post_meta($assistants_id_local, '_assistant_topp', $topp); } if(!empty($vector_store_id)) { update_post_meta($assistants_id_local, '_assistant_vector_store_id', $vector_store_id); } if(!empty($jsonf['files'])) { update_post_meta($assistants_id_local, '_assistant_files', $jsonf['files']); } else { update_post_meta($assistants_id_local, '_assistant_files', array()); } } } $aimogen_result['status'] = 'success'; } wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_default_assistant', 'aimogen_default_assistant'); function aimogen_default_assistant() { check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('edit_posts') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with default assistants'); global $wp_filesystem; if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){ require_once ABSPATH . 'wp-admin/includes/file.php'; $creds = request_filesystem_credentials( site_url() ); wp_filesystem($creds); } $aimogen_Main_Settings = get_option('aimogen_Main_Settings', false); if (!isset($aimogen_Main_Settings['app_id']) || trim($aimogen_Main_Settings['app_id']) == '') { $aimogen_result['msg'] = 'You need to add an API key in plugin settings for this shortcode to work.'; wp_send_json($aimogen_result); } else { $appids = preg_split('/\r\n|\r|\n/', trim($aimogen_Main_Settings['app_id'])); $appids = array_filter($appids); $token = $appids[array_rand($appids)]; $token = apply_filters('aimogen_openai_api_key', $token); if(empty($token)) { $aimogen_result['msg'] = 'Invalid API key submitted'; wp_send_json($aimogen_result); } if(aimogen_is_aimogen_key($token)) { $aimogen_result['msg'] = 'Currently only OpenAI API is supported for text moderation.'; wp_send_json($aimogen_result); } } $default_file = dirname(__FILE__) . "/defaults/assistant-defaults.json"; if(!$wp_filesystem->exists($default_file)) { $aimogen_result['msg'] = 'Default assistant json file not found: ' . $default_file; wp_send_json($aimogen_result); } $fc = $wp_filesystem->get_contents($default_file); if(empty($fc)) { $aimogen_result['msg'] = 'Failed to read file: ' . $default_file; wp_send_json($aimogen_result); } $fc_dec = json_decode($fc, true); if($fc_dec === false || $fc_dec === null) { $aimogen_result['msg'] = 'Failed to decode json file: ' . $default_file; wp_send_json($aimogen_result); } $overwrite = '0'; require_once (dirname(__FILE__) . "/res/aimogen-assistants-api.php"); foreach($fc_dec as $jsonf) { $vector_store_id = ''; if(empty($jsonf['role'])) { $jsonf['role'] = ''; } if(empty($jsonf['prompt'])) { $jsonf['prompt'] = ''; } if(empty($jsonf['message'])) { $jsonf['message'] = ''; } $existing_openai = false; $address_post_id = 0; $assistant_id = ''; $temperature = ''; $topp = ''; if(isset($jsonf['temperature'])) { $temperature = $jsonf['temperature']; } if(isset($jsonf['topp'])) { $topp = $jsonf['topp']; } if(isset($jsonf['id']) && !empty($jsonf['id'])) { $query = new WP_Query( array( 'post_type' => 'aimogen_assistants', 'meta_query' => array( array( 'key' => '_assistant_id', 'value' => $jsonf['id'], 'compare' => 'EXISTS' ), ), 'post_status' => 'any', 'posts_per_page' => 1, 'no_found_rows' => true, 'ignore_sticky_posts' => true, 'update_post_term_cache' => false, 'update_post_meta_cache' => false, 'orderby' => 'post_date ID', 'order' => 'ASC', ) ); if ( ! empty( $query->post ) ) { if($overwrite != '1') { //assistant already exists, skipping it continue; } else { while ( $query->have_posts() ) { $query->the_post(); $address_post_id = get_the_ID(); $assistant_id = get_post_meta($address_post_id, '_assistant_id', true); break; } } } if(!empty($assistant_id)) { try { $ex_assistant = aimogen_openai_retrieve_assistant($token, $assistant_id); if(isset($ex_assistant['id']) && $ex_assistant['id'] == $assistant_id) { $existing_openai = true; } } catch(Exception $e) { $aimogen_result['msg'] = 'Failed to retrieve assistant using the API ' . $e->getMessage(); wp_send_json($aimogen_result); } } } if($existing_openai == true) { $tools = []; if($jsonf['code_interpreter'] == 'on') { $tools[] = ['type' => 'code_interpreter']; } if($jsonf['file_search'] == 'on') { $tools[] = ['type' => 'file_search']; } $functions_json = $jsonf['functions']; if($functions_json === false) { $functions = array(); } else { if(is_array($functions_json) && !isset($functions_json['name'])) { $functions = $functions_json; } elseif(isset($functions_json['name'])) { $functions = array($functions_json); } else { $functions = array(); } } foreach($functions as $func) { $tools[] = ['type' => 'function', 'function' => $func]; } try { if($address_post_id != '' && $address_post_id != 0) { $vector_store_id = get_post_meta($address_post_id, '_assistant_vector_store_id', true); } $metadata = ''; $assistantData = aimogen_openai_modify_assistant($token, $assistant_id, $jsonf['model'], $jsonf['name'], $jsonf['role'], $jsonf['prompt'], $temperature, $topp, $tools, $jsonf['files'], $metadata, $vector_store_id, $address_post_id); if($assistantData === false) { $aimogen_result['msg'] = 'Failed to update assistant using the API'; wp_send_json($aimogen_result); } } catch(Exception $e) { $aimogen_result['msg'] = 'Failed to retrieve assistant using the API ' . $e->getMessage(); wp_send_json($aimogen_result); } } else { $tools = []; if($jsonf['code_interpreter'] == 'on') { $tools[] = ['type' => 'code_interpreter']; } if($jsonf['file_search'] == 'on') { $tools[] = ['type' => 'file_search']; } $functions_json = $jsonf['functions']; if($functions_json === false) { $functions = array(); } else { if(is_array($functions_json) && !isset($functions_json['name'])) { $functions = $functions_json; } elseif(isset($functions_json['name'])) { $functions = array($functions_json); } else { $functions = array(); } } foreach($functions as $func) { $tools[] = ['type' => 'function', 'function' => $func]; } try { $metadata = ''; $assistantData = aimogen_openai_save_assistant( $token, $jsonf['model'], $jsonf['name'], $jsonf['role'], $temperature, $topp, $jsonf['prompt'], $tools, $jsonf['files'], $metadata, $vector_store_id ); if($assistantData === false) { $aimogen_result['msg'] = 'Failed to save assistant using the API'; wp_send_json($aimogen_result); } else { $assistant_id = $assistantData['id']; } } catch(Exception $e) { $aimogen_result['msg'] = 'Failed to retrieve assistant using the API ' . $e->getMessage(); wp_send_json($aimogen_result); } } $assistants_data = array( 'post_type' => 'aimogen_assistants', 'post_title' => $jsonf['name'], 'post_excerpt' => $jsonf['role'], 'post_content' => $jsonf['prompt'], 'post_status' => 'publish' ); $assistants_data['ID'] = $address_post_id; remove_filter('content_save_pre', 'wp_filter_post_kses'); remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');remove_filter('title_save_pre', 'wp_filter_kses'); if($overwrite != '1') { $assistants_id_local = wp_insert_post($assistants_data); } else { if(isset($assistants_data['ID']) && $assistants_data['ID'] != '0') { $assistants_id_local = wp_update_post($assistants_data); } else { $assistants_id_local = wp_insert_post($assistants_data); } } add_filter('content_save_pre', 'wp_filter_post_kses'); add_filter('content_filtered_save_pre', 'wp_filter_post_kses');add_filter('title_save_pre', 'wp_filter_kses'); if(is_wp_error($assistants_id_local)) { aimogen_log_to_file('Failed to import assistant: ' . $assistants_id_local->get_error_message()); } elseif($assistants_id_local === 0) { aimogen_log_to_file('Failed to insert assistant to database: ' . json_encode($assistants_data)); } else { if(is_numeric($jsonf['avatar'])) { if($jsonf['avatar'] > 0) { if(!function_exists('set_post_thumbnail')) { require_once(ABSPATH . 'wp-admin/includes/image.php'); require_once(ABSPATH . 'wp-admin/includes/media.php'); } set_post_thumbnail( $assistants_id_local, $jsonf['avatar'] ); } } elseif(filter_var($jsonf['avatar'], FILTER_VALIDATE_URL)) { if (!aimogen_generate_featured_image($jsonf['avatar'], $assistants_id_local)) { if (isset($aimogen_Main_Settings['enable_detailed_logging'])) { aimogen_log_to_file('aimogen_generate_featured_image failed for ' . $jsonf['avatar']); } } } if(isset($jsonf['message']) && !empty($jsonf['message'])) { update_post_meta($assistants_id_local, '_assistant_first_message', $jsonf['message']); } else { update_post_meta($assistants_id_local, '_assistant_first_message', ''); } update_post_meta($assistants_id_local, '_assistant_id', $assistant_id); if(!empty($jsonf['model'])) { update_post_meta($assistants_id_local, '_assistant_model', $jsonf['model']); } $tools = []; if($jsonf['code_interpreter'] == 'on') { $tools[] = ['type' => 'code_interpreter']; } if($jsonf['file_search'] == 'on') { $tools[] = ['type' => 'file_search']; } $functions_json = $jsonf['functions']; if($functions_json === false) { $functions = array(); } else { if(is_array($functions_json) && !isset($functions_json['name'])) { $functions = $functions_json; } elseif(isset($functions_json['name'])) { $functions = array($functions_json); } else { $functions = array(); } } foreach($functions as $func) { $tools[] = ['type' => 'function', 'function' => $func]; } if(!empty($tools)) { update_post_meta($assistants_id_local, '_assistant_tools', $tools); } else { update_post_meta($assistants_id_local, '_assistant_tools', array()); } if(!empty($vector_store_id)) { update_post_meta($assistants_id_local, '_assistant_vector_store_id', $vector_store_id); } if(!empty($temperature)) { update_post_meta($assistants_id_local, '_assistant_temperature', $temperature); } if(!empty($topp)) { update_post_meta($assistants_id_local, '_assistant_topp', $topp); } if(!empty($jsonf['files'])) { update_post_meta($assistants_id_local, '_assistant_files', $jsonf['files']); } else { update_post_meta($assistants_id_local, '_assistant_files', array()); } } } $aimogen_result['status'] = 'success'; wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_default_persona', 'aimogen_default_persona'); function aimogen_default_persona() { check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('edit_posts') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with default personas'); global $wp_filesystem; if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){ require_once ABSPATH . 'wp-admin/includes/file.php'; $creds = request_filesystem_credentials( site_url() ); wp_filesystem($creds); } $default_file = dirname(__FILE__) . "/defaults/persona-defaults.json"; if(!$wp_filesystem->exists($default_file)) { $aimogen_result['msg'] = 'Default persona json file not found: ' . $default_file; wp_send_json($aimogen_result); } $fc = $wp_filesystem->get_contents($default_file); if(empty($fc)) { $aimogen_result['msg'] = 'Failed to read file: ' . $default_file; wp_send_json($aimogen_result); } $fc_dec = json_decode($fc, true); if($fc_dec === false || $fc_dec === null) { $aimogen_result['msg'] = 'Failed to decode json file: ' . $default_file; wp_send_json($aimogen_result); } $overwrite = '0'; foreach($fc_dec as $jsonf) { $address_post_id = 0; $query = new WP_Query( array( 'post_type' => 'aimogen_personas', 'title' => $jsonf['name'], 'post_status' => 'any', 'posts_per_page' => 1, 'no_found_rows' => true, 'ignore_sticky_posts' => true, 'update_post_term_cache' => false, 'update_post_meta_cache' => false, 'orderby' => 'post_date ID', 'order' => 'ASC', ) ); if ( ! empty( $query->post ) ) { if($overwrite != '1') { //persona already exists, skipping it continue; } else { while ( $query->have_posts() ) { $query->the_post(); $address_post_id = get_the_ID(); break; } } } $personas_data = array( 'post_type' => 'aimogen_personas', 'post_title' => $jsonf['name'], 'post_excerpt' => $jsonf['role'], 'post_content' => $jsonf['prompt'], 'post_status' => 'publish' ); $personas_data['ID'] = $address_post_id; remove_filter('content_save_pre', 'wp_filter_post_kses'); remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');remove_filter('title_save_pre', 'wp_filter_kses'); if($overwrite != '1') { $personas_id = wp_insert_post($personas_data); } else { if(isset($personas_data['ID']) && $personas_data['ID'] != '0') { $personas_id = wp_update_post($personas_data); } else { $personas_id = wp_insert_post($personas_data); } } add_filter('content_save_pre', 'wp_filter_post_kses'); add_filter('content_filtered_save_pre', 'wp_filter_post_kses');add_filter('title_save_pre', 'wp_filter_kses'); if(is_wp_error($personas_id)) { aimogen_log_to_file('Failed to import persona: ' . $personas_id->get_error_message()); } elseif($personas_id === 0) { aimogen_log_to_file('Failed to insert persona to database: ' . json_encode($personas_data)); } else { if(isset($jsonf['avatar'])) { if(is_numeric($jsonf['avatar'])) { if($jsonf['avatar'] > 0) { if(!function_exists('set_post_thumbnail')) { require_once(ABSPATH . 'wp-admin/includes/image.php'); require_once(ABSPATH . 'wp-admin/includes/media.php'); } set_post_thumbnail( $personas_id, $jsonf['avatar'] ); } } elseif(filter_var($jsonf['avatar'], FILTER_VALIDATE_URL)) { if (!aimogen_generate_featured_image($jsonf['avatar'], $personas_id)) { if (isset($aimogen_Main_Settings['enable_detailed_logging'])) { aimogen_log_to_file('aimogen_generate_featured_image failed for ' . $jsonf['avatar']); } } } } if(isset($jsonf['message']) && !empty($jsonf['message'])) { update_post_meta($personas_id, '_persona_first_message', $jsonf['message']); } if(isset($jsonf['model']) && !empty($jsonf['model'])) { update_post_meta($personas_id, '_persona_model', $jsonf['model']); } } } $aimogen_result['status'] = 'success'; wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_run_my_bulk_action', 'aimogen_run_my_bulk_action'); function aimogen_run_my_bulk_action() { check_ajax_referer('openai-bulk-nonce', 'nonce'); if ( ! current_user_can('edit_posts') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } echo wp_kses_post(aimogen_do_bulk_post()); die(); } add_action('wp_ajax_aimogen_run_my_bulk_action_test', 'aimogen_run_my_bulk_action_test'); function aimogen_run_my_bulk_action_test() { check_ajax_referer('openai-bulk-nonce', 'nonce'); if ( ! current_user_can('edit_posts') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } echo wp_kses_post(aimogen_do_bulk_post_test()); die(); } add_action( 'wp_ajax_aimogen_get_image', 'aimogen_get_image' ); add_action( 'wp_ajax_nopriv_aimogen_get_image', 'aimogen_get_image' ); function aimogen_get_image() { check_ajax_referer( 'openai-single-nonce', 'nonce' ); if ( isset( $_GET['id'] ) ) { $id = absint( wp_unslash( $_GET['id'] ) ); if ( ! $id ) { wp_send_json_success( [ 'image' => '' ] ); } $image = wp_get_attachment_image( $id, 'thumbnail', false, [ 'id' => 'aimogen-preview-image' ] ); wp_send_json_success( [ 'image' => $image ] ); } wp_send_json_error(); die(); } add_action( 'wp_ajax_aimogen_create_post', 'aimogen_create_post' ); function aimogen_create_post() { check_ajax_referer( 'create_post', 'nonce' ); if ( ! current_user_can('edit_posts') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } if(isset($_POST['metaFieldsArray'])) { $metaFieldsArray = array(); if ( isset( $_POST['metaFieldsArray'] ) && is_array( $_POST['metaFieldsArray'] ) ) { $metaFieldsArray = array_map( static function( $item ) { return is_array( $item ) ? array_map( 'sanitize_text_field', $item ) : sanitize_text_field( $item ); }, wp_unslash( $_POST['metaFieldsArray'] ) // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized ); } } else { $metaFieldsArray = array(); } $raw_title = ''; if ( isset( $_POST['title'] ) ) { $raw_title = wp_unslash( $_POST['title'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized } $post_title = sanitize_text_field( $raw_title ); $raw_content = ''; if ( isset( $_POST['content'] ) ) { $raw_content = wp_unslash( $_POST['content'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized } $post_content = wp_kses_post( $raw_content ); $raw_excerpt = ''; if ( isset( $_POST['excerpt'] ) ) { $raw_excerpt = wp_unslash( $_POST['excerpt'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized } $post_excerpt = wp_kses_post( $raw_excerpt ); $raw_submit_status = ''; if ( isset( $_POST['submit_status'] ) ) { $raw_submit_status = wp_unslash( $_POST['submit_status'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized } $submit_status = sanitize_text_field( $raw_submit_status ); $raw_submit_type = ''; if ( isset( $_POST['submit_type'] ) ) { $raw_submit_type = wp_unslash( $_POST['submit_type'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized } $submit_type = $raw_submit_type !== '' ? sanitize_text_field( $raw_submit_type ) : 'post'; $raw_sticky = ''; if ( isset( $_POST['post_sticky'] ) ) { $raw_sticky = wp_unslash( $_POST['post_sticky'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized } $post_sticky = sanitize_text_field( $raw_sticky ); $raw_author = ''; if ( isset( $_POST['post_author'] ) ) { $raw_author = wp_unslash( $_POST['post_author'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized } $post_author = sanitize_text_field( $raw_author ); $raw_image_id = ''; if ( isset( $_POST['aimogen_image_id'] ) ) { $raw_image_id = wp_unslash( $_POST['aimogen_image_id'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized } $aimogen_image_id = sanitize_text_field( $raw_image_id ); $raw_post_date = ''; if ( isset( $_POST['post_date'] ) ) { $raw_post_date = wp_unslash( $_POST['post_date'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized } $post_date = sanitize_text_field( $raw_post_date ); $raw_tags = ''; if ( isset( $_POST['post_tags'] ) ) { $raw_tags = wp_unslash( $_POST['post_tags'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized } $post_tags = sanitize_text_field( $raw_tags ); $raw_post_category = ''; if ( isset( $_POST['post_category'] ) ) { $raw_post_category = wp_unslash( $_POST['post_category'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized } $post_category = sanitize_text_field( $raw_post_category ); $post_category = json_decode($post_category, true); if ( empty( $post_title ) || empty( $post_content ) ) { wp_send_json_error( array( 'message' => 'Title and Content are required fields' ) ); } if(empty($submit_type)) { $submit_type = 'post'; } if(!in_array($submit_type, get_post_types( '', 'names' ))) { $submit_type = 'post'; } $statuses = get_post_statuses(); $statuses['trash'] = 'Trash'; if(!array_key_exists($submit_status, $statuses)) { wp_send_json_error( array( 'message' => 'Invalid post status submitted: ' . $submit_status . ' - ' . json_encode($statuses) ) ); } $author_obj = get_user_by('id', $post_author); if($author_obj === false) { wp_send_json_error( array( 'message' => 'Invalid post author submitted' ) ); } $post_args = array( 'post_title' => $post_title, 'post_content' => $post_content, 'post_excerpt' => $post_excerpt, 'post_status' => $submit_status, 'post_type' => $submit_type, 'post_author' => $post_author, 'post_date' => $post_date ); if(!empty($post_tags)) { $post_args['tags_input'] = $post_tags; } if(!empty($metaFieldsArray)) { $post_args['meta_input'] = $metaFieldsArray; } remove_filter('content_save_pre', 'wp_filter_post_kses'); remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');remove_filter('title_save_pre', 'wp_filter_kses'); $post_id = wp_insert_post( $post_args ); add_filter('content_save_pre', 'wp_filter_post_kses'); add_filter('content_filtered_save_pre', 'wp_filter_post_kses');add_filter('title_save_pre', 'wp_filter_kses'); if ( is_wp_error( $post_id ) ) { wp_send_json_error( array( 'message' => $post_id->get_error_message() ) ); } elseif ( $post_id === 0 ) { wp_send_json_error( array( 'message' => 'Failed to insert post: ' . $post_title ) ); } if ($post_sticky == 'on') { stick_post($post_id); } if(is_array($post_category)) { $default_category = get_option('default_category'); $target_cat = 'category'; if($submit_type == 'product') { $target_cat = 'product_cat'; } wp_set_object_terms($post_id, array_map( 'intval', $post_category), $target_cat, true); if(is_numeric($default_category)) { if(!in_array($default_category, $post_category)) { $deftrerm = get_term_by('id', $default_category, $target_cat); if($deftrerm !== false) { wp_remove_object_terms( $post_id, $deftrerm->slug, $target_cat ); } } } } if($aimogen_image_id != '' && is_numeric($aimogen_image_id)) { $aimogen_image_id = intval($aimogen_image_id); if(!function_exists('set_post_thumbnail')) { require_once(ABSPATH . 'wp-admin/includes/image.php'); require_once(ABSPATH . 'wp-admin/includes/media.php'); } set_post_thumbnail($post_id, $aimogen_image_id); } wp_send_json_success( array( 'post_id' => $post_id ) ); die(); } add_action( 'wp_ajax_aimogen_write_text', 'aimogen_write_text' ); add_action( 'wp_ajax_nopriv_aimogen_write_text', 'aimogen_write_text' ); function aimogen_write_text() { check_ajax_referer( 'openai-single-nonce', 'nonce' ); require_once(dirname(__FILE__) . "/res/aimogen-chars.php"); if(!isset($_POST['prompt'])) { wp_send_json_error( array( 'message' => 'Incorrect query sent (prompt)' ) ); } $prompt = sanitize_text_field( wp_unslash( $_POST['prompt'] )); if(!isset($_POST['model'])) { wp_send_json_error( array( 'message' => 'Incorrect query sent (model)' ) ); } $model = sanitize_text_field( wp_unslash( $_POST['model'] )); if(!isset($_POST['assistant_id'])) { wp_send_json_error( array( 'message' => 'Incorrect query sent (assistant_id)' ) ); } $assistant_id = sanitize_text_field( wp_unslash( $_POST['assistant_id'] )); if(!isset($_POST['max_tokens'])) { wp_send_json_error( array( 'message' => 'Incorrect query sent (max_tokens)' ) ); } $max_tokens = sanitize_text_field( wp_unslash( $_POST['max_tokens'] )); if(!isset($_POST['temperature'])) { wp_send_json_error( array( 'message' => 'Incorrect query sent (temperature)' ) ); } $temperature = sanitize_text_field( wp_unslash( $_POST['temperature'] )); if(!isset($_POST['title'])) { wp_send_json_error( array( 'message' => 'Incorrect query sent (title)' ) ); } $title = sanitize_text_field( wp_unslash( $_POST['title'] )); if(!isset($_POST['language'])) { wp_send_json_error( array( 'message' => 'Incorrect query sent (language)' ) ); } $language = sanitize_text_field( wp_unslash( $_POST['language'] )); if(!isset($_POST['writing_style'])) { wp_send_json_error( array( 'message' => 'Incorrect query sent (writing_style)' ) ); } $writing_style = sanitize_text_field( wp_unslash( $_POST['writing_style'] )); if(!isset($_POST['writing_tone'])) { wp_send_json_error( array( 'message' => 'Incorrect query sent (writing_tone)' ) ); } $writing_tone = sanitize_text_field( wp_unslash( $_POST['writing_tone'] )); if(!isset($_POST['topics'])) { wp_send_json_error( array( 'message' => 'Incorrect query sent (topics)' ) ); } $topics = sanitize_text_field( wp_unslash( $_POST['topics'] )); if(!isset($_POST['sections'])) { wp_send_json_error( array( 'message' => 'Incorrect query sent (sections)' ) ); } $sections = sanitize_text_field( wp_unslash( $_POST['sections'] )); if(!isset($_POST['sections_count'])) { wp_send_json_error( array( 'message' => 'Incorrect query sent (sections_count)' ) ); } $sections_count = sanitize_text_field( wp_unslash( $_POST['sections_count'] )); if(!isset($_POST['paragraph_count'])) { wp_send_json_error( array( 'message' => 'Incorrect query sent (paragraph_count)' ) ); } $paragraph_count = sanitize_text_field( wp_unslash( $_POST['paragraph_count'] )); if(!isset($_POST['content_gen_type'])) { wp_send_json_error( array( 'message' => 'Incorrect query sent (content_gen_type)' ) ); } if(isset($_POST['metakeyinput'])) { $metakeyinput = sanitize_text_field( wp_unslash( $_POST['metakeyinput'] )); } else { $metakeyinput = ''; } $content_gen_type = sanitize_text_field( wp_unslash( $_POST['content_gen_type'] )); $temperature = floatval($temperature); $max_tokens = intval($max_tokens); if($max_tokens > 2048) { $big_model = false; if(!aimogen_is_trained_model($model)) { $big_model = true; } elseif(strstr($model, 'turbo') !== false && !aimogen_is_trained_model($model)) { $big_model = true; } elseif(strstr($model, 'gpt-4') !== false && !aimogen_is_trained_model($model)) { $big_model = true; } if($big_model == false) { $max_tokens = 2048; } } $aimogen_Main_Settings = get_option('aimogen_Main_Settings', false); $all_models = aimogen_get_all_models(true); if(!in_array($model, $all_models)) { $model = aimogen_get_default_model_name($aimogen_Main_Settings); } if (!isset($aimogen_Main_Settings['app_id']) || trim($aimogen_Main_Settings['app_id']) == '') { wp_send_json_error( array( 'message' => 'You need to enter an OpenAI API key in plugin settings!' ) ); } $new_post_content = ''; $appids = preg_split('/\r\n|\r|\n/', trim($aimogen_Main_Settings['app_id'])); $appids = array_filter($appids); $token = $appids[array_rand($appids)]; $token = apply_filters('aimogen_openai_api_key', $token); if($content_gen_type == 'yes') { $main_prompt = $prompt; if($sections != '') { $post_sections_arr = preg_split('/\r\n|\r|\n/', $sections); } else { $post_sections_arr = array(); } foreach($post_sections_arr as $current_section) { $prompt = str_replace('%%title%%', $title, $main_prompt); $prompt = str_replace('%%current_section%%', $current_section, $main_prompt); $prompt = str_replace('%%language%%', $language, $prompt); $prompt = str_replace('%%writing_style%%', $writing_style, $prompt); $prompt = str_replace('%%writing_tone%%', $writing_tone, $prompt); $prompt = str_replace('%%topic%%', $topics, $prompt); $prompt = str_replace('%%sections%%', $sections, $prompt); $prompt = str_replace('%%sections_count%%', $sections_count, $prompt); $prompt = str_replace('%%paragraphs_per_section%%', $paragraph_count, $prompt); $prompt = str_replace('%%meta_title%%', $metakeyinput, $prompt); $query_token_count = count(aimogen_encode($prompt)); $available_tokens = aimogen_compute_available_tokens($model, $max_tokens, $prompt, $query_token_count); if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS) { $string_len = strlen($prompt); $string_len = $string_len / 2; $string_len = intval(0 - $string_len); $aicontent = aimogen_substr($prompt, 0, $string_len); $aicontent = trim($aicontent); if(empty($aicontent)) { wp_send_json_error( array( 'message' => 'Incorrect prompt provided!' ) ); } $query_token_count = count(aimogen_encode($aicontent)); $available_tokens = $max_tokens - $query_token_count; } $thread_id = ''; $aierror = ''; $finish_reason = ''; $generated_text = aimogen_generate_text($token, $model, $prompt, $available_tokens, $temperature, 1, 0, 0, false, 'singlePostWriter', 0, $finish_reason, $aierror, false, false, false, '', '', 'user', $assistant_id, $thread_id, '', 'disabled', '', false, false, array(), ''); if($generated_text === false) { wp_send_json_error( array( 'message' => 'Failed to generate AI content: ' . $aierror) ); } else { $new_post_content .= '

' . $current_section . '

'; $new_post_content .= aimogen_sanitize_ai_result($generated_text) . ' '; } } } else { $prompt = str_replace('%%title%%', $title, $prompt); $prompt = str_replace('%%language%%', $language, $prompt); $prompt = str_replace('%%writing_style%%', $writing_style, $prompt); $prompt = str_replace('%%writing_tone%%', $writing_tone, $prompt); $prompt = str_replace('%%topic%%', $topics, $prompt); $prompt = str_replace('%%sections%%', $sections, $prompt); $prompt = str_replace('%%sections_count%%', $sections_count, $prompt); $prompt = str_replace('%%paragraphs_per_section%%', $paragraph_count, $prompt); $prompt = str_replace('%%meta_title%%', $metakeyinput, $prompt); $query_token_count = count(aimogen_encode($prompt)); $available_tokens = aimogen_compute_available_tokens($model, $max_tokens, $prompt, $query_token_count); if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS) { $string_len = strlen($prompt); $string_len = $string_len / 2; $string_len = intval(0 - $string_len); $aicontent = aimogen_substr($prompt, 0, $string_len); $aicontent = trim($aicontent); if(empty($aicontent)) { wp_send_json_error( array( 'message' => 'Incorrect prompt provided!' ) ); } $query_token_count = count(aimogen_encode($aicontent)); $available_tokens = $max_tokens - $query_token_count; } $thread_id = ''; $aierror = ''; $finish_reason = ''; $generated_text = aimogen_generate_text($token, $model, $prompt, $available_tokens, $temperature, 1, 0, 0, false, 'singlePostWriter', 0, $finish_reason, $aierror, false, false, false, '', '', 'user', $assistant_id, $thread_id, '', 'disabled', '', false, false, array(), ''); if($generated_text === false) { wp_send_json_error( array( 'message' => 'Failed to generate AI content: ' . $aierror) ); } else { $new_post_content = aimogen_sanitize_ai_result($generated_text); } } if (!isset($aimogen_Main_Settings['no_undetectibility']) || $aimogen_Main_Settings['no_undetectibility'] != 'on') { if (!isset($aimogen_Main_Settings['no_undetectibility_single']) || $aimogen_Main_Settings['no_undetectibility_single'] != 'on') { if(!isset($aimogen_xchars)) { $aimogen_xchars = array(); } $rand_percentage = wp_rand(10, 20); $new_post_content = aimogen_make_unique($new_post_content, $aimogen_xchars, $rand_percentage); } } do_action('aimogen_text_writer_reply', $new_post_content); wp_send_json_success( array( 'content' => $new_post_content ) ); die(); } add_action( 'wp_ajax_aimogen_delete_template', 'aimogen_delete_template' ); function aimogen_delete_template() { check_ajax_referer( 'openai-single-nonce', 'nonce' ); if ( ! current_user_can('manage_options') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } if(!isset($_POST['template_name'])) { wp_send_json_error( array( 'message' => 'Template name is required!' ) ); } $template_name = sanitize_text_field( wp_unslash($_POST['template_name']) ); if(empty($template_name)) { wp_send_json_error( array( 'message' => 'You need to enter a valid template name!' ) ); } $user_id = get_current_user_id(); if($user_id == 0) { wp_send_json_error( array( 'message' => 'No user logged in, cannot find templates!' ) ); } else { $key = 'aimogen_templates'; $single = true; $aimogen_templates = get_user_meta( $user_id, $key, $single ); if(!is_array($aimogen_templates)) { $aimogen_templates = array(); } if(!isset($aimogen_templates[$template_name])) { wp_send_json_error( array( 'message' => 'Template name not found in database, please refresh this page to update template listing' ) ); } else { unset($aimogen_templates[$template_name]); update_user_meta( $user_id, $key, $aimogen_templates ); } } wp_send_json_success( array( 'content' => 'saved' ) ); die(); } add_action( 'wp_ajax_aimogen_delete_template_advanced', 'aimogen_delete_template_advanced' ); function aimogen_delete_template_advanced() { check_ajax_referer( 'openai-single-nonce', 'nonce' ); if ( ! current_user_can('manage_options') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } if(!isset($_POST['template_name'])) { wp_send_json_error( array( 'message' => 'Template name is required!' ) ); } $template_name = sanitize_text_field( wp_unslash($_POST['template_name']) ); if(empty($template_name)) { wp_send_json_error( array( 'message' => 'You need to enter a valid template name!' ) ); } $user_id = get_current_user_id(); if($user_id == 0) { wp_send_json_error( array( 'message' => 'No user logged in, cannot find templates!' ) ); } else { $key = 'aimogen_templates_advanced'; $single = true; $aimogen_templates = get_user_meta( $user_id, $key, $single ); if(!is_array($aimogen_templates)) { $aimogen_templates = array(); } if(!isset($aimogen_templates[$template_name])) { wp_send_json_error( array( 'message' => 'Template name not found in database, please refresh this page to update template listing' ) ); } else { unset($aimogen_templates[$template_name]); update_user_meta( $user_id, $key, $aimogen_templates ); } } wp_send_json_success( array( 'content' => 'saved' ) ); die(); } add_action( 'wp_ajax_aimogen_save_template', 'aimogen_save_template' ); function aimogen_save_template() { check_ajax_referer( 'openai-single-nonce', 'nonce' ); if ( ! current_user_can('manage_options') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } if(!isset($_POST['template_name'])) { wp_send_json_error( array( 'message' => 'Template name is required!' ) ); } $template_name = sanitize_text_field( wp_unslash($_POST['template_name']) ); if(empty($template_name)) { wp_send_json_error( array( 'message' => 'You need to enter a valid template name!' ) ); } if(!isset($_POST['template_options'])) { wp_send_json_error( array( 'message' => 'Template settings are required!' ) ); } $raw = wp_unslash( $_POST['template_options'] );// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized if ( is_array( $raw ) ) { $template_options = array_map( static function( $item ) { return is_array( $item ) ? array_map( 'sanitize_text_field', $item ) : sanitize_text_field( $item ); }, $raw ); } else { wp_send_json_error( array( 'message' => 'Incorrect format' ) ); } $user_id = get_current_user_id(); if($user_id == 0) { wp_send_json_error( array( 'message' => 'No user logged in, cannot find templates!' ) ); } else { $key = 'aimogen_templates'; $single = true; $aimogen_templates = get_user_meta( $user_id, $key, $single ); if(!is_array($aimogen_templates)) { $aimogen_templates = array(); } $aimogen_templates[$template_name] = $template_options; update_user_meta( $user_id, $key, $aimogen_templates ); } wp_send_json_success( array( 'content' => 'saved' ) ); die(); } add_action( 'wp_ajax_aimogen_save_template_advanced', 'aimogen_save_template_advanced' ); function aimogen_save_template_advanced() { check_ajax_referer( 'openai-single-nonce', 'nonce' ); if ( ! current_user_can('manage_options') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } if(!isset($_POST['template_name'])) { wp_send_json_error( array( 'message' => 'Template name is required!' ) ); } $template_name = sanitize_text_field( wp_unslash($_POST['template_name']) ); if(empty($template_name)) { wp_send_json_error( array( 'message' => 'You need to enter a valid template name!' ) ); } if(!isset($_POST['template_options'])) { wp_send_json_error( array( 'message' => 'Template settings are required!' ) ); } $raw = wp_unslash( $_POST['template_options'] );// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized if ( is_array( $raw ) ) { $template_options = array_map( static function( $item ) { return is_array( $item ) ? array_map( 'sanitize_text_field', $item ) : sanitize_text_field( $item ); }, $raw ); } else { wp_send_json_error( array( 'message' => 'Incorrect format' ) ); } $user_id = get_current_user_id(); if($user_id == 0) { wp_send_json_error( array( 'message' => 'No user logged in, cannot find templates!' ) ); } else { $key = 'aimogen_templates_advanced'; $single = true; $aimogen_templates = get_user_meta( $user_id, $key, $single ); if(!is_array($aimogen_templates)) { $aimogen_templates = array(); } $aimogen_templates[$template_name] = $template_options; update_user_meta( $user_id, $key, $aimogen_templates ); } wp_send_json_success( array( 'content' => 'saved' ) ); die(); } add_action( 'wp_ajax_aimogen_load_template', 'aimogen_load_template' ); function aimogen_load_template() { check_ajax_referer( 'openai-single-nonce', 'nonce' ); if ( ! current_user_can('manage_options') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } if(!isset($_POST['template_name'])) { wp_send_json_error( array( 'message' => 'Template name is required!' ) ); } $template_name = sanitize_text_field( wp_unslash($_POST['template_name']) ); if(empty($template_name)) { wp_send_json_error( array( 'message' => 'You need to enter a valid template name!' ) ); } $aimogen_templates = array(); $user_id = get_current_user_id(); if($user_id == 0) { wp_send_json_error( array( 'message' => 'No user logged in, cannot find templates!' ) ); } else { if($template_name == 'Default Template') { $author_obj = get_user_by('id', $user_id); if($author_obj !== false) { $user_login = $author_obj->ID; } else { aimogen_log_to_file('Failed to detect current user name: ' . $user_id); $user_login = 1; } $dt = new DateTime(); $datef = $dt->format('Y-m-d H:i:s'); $default_category = get_option('default_category'); $aimogen_templates = array ( 'title' => '', 'topics' => '', 'submit_status' => 'draft', 'submit_type' => 'post', 'post_sticky' => 'no', 'post_author' => $user_login, 'post_date' => $datef, 'post_category' => array($default_category), 'post_tags' => '', 'language' => 'English', 'writing_style' => 'Creative', 'writing_tone' => 'Neutral', 'sections_count' => 2, 'paragraph_count' => 3, 'model' => AIMOGEN_DEFAULT_MODEL, 'max_tokens' => 4000, 'temperature' => 1, 'prompt_title' => 'Write a title for an article about "%%topic%%" in %%language%%. Style: %%writing_style%%. Tone: %%writing_tone%%. Must be between 40 and 60 characters.', 'prompt_sections' => 'Write %%sections_count%% consecutive headings for an article about "%%title%%", in %%language%%. Style: %%writing_style%%. Tone: %%writing_tone%%.', 'prompt_content' => 'Write an article about "%%title%%" in %%language%%. The article is organized by the following headings: %%sections%% Write %%paragraphs_per_section%% paragraphs per heading. Use HTML for formatting, include h2 tags, h3 tags, lists and bold. Add an introduction and a conclusion. Style: %%writing_style%%. Tone: %%writing_tone%%.', 'prompt_excerpt' => 'Write an excerpt for an article about "%%title%%" in %%language%%. Style: %%writing_style%%. Tone: %%writing_tone%%. Must be between 150 and 250 characters.' ); } else { $key = 'aimogen_templates'; $single = true; $aimogen_templates = get_user_meta( $user_id, $key, $single ); if(!is_array($aimogen_templates)) { $aimogen_templates = array(); } if(!isset($aimogen_templates[$template_name])) { wp_send_json_error( array( 'message' => 'Template name not found in the database' ) ); } $aimogen_templates = $aimogen_templates[$template_name]; } } wp_send_json_success( array( 'content' => $aimogen_templates ) ); die(); } add_action( 'wp_ajax_aimogen_import_templates_advanced', 'aimogen_import_templates_advanced' ); function aimogen_import_templates_advanced() { check_ajax_referer( 'openai-single-nonce', 'nonce' ); if ( ! current_user_can('manage_options') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } if(!isset($_POST['templates'])) { wp_send_json_error( array( 'message' => 'Template json is required!' ) ); } $templates = wp_unslash( $_POST['templates'] );// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized if(!is_array($templates)) { wp_send_json_error(['message' => 'Invalid JSON data']); } $templates = array_map( function( $item ) { if ( is_array( $item ) ) { return array_map( 'sanitize_text_field', $item ); } return sanitize_text_field( $item ); }, $templates ); $user_id = get_current_user_id(); if($user_id == 0) { wp_send_json_error( array( 'message' => 'No user logged in, cannot find templates!' ) ); } else { $key = 'aimogen_templates_advanced'; $single = true; $aimogen_templates = get_user_meta( $user_id, $key, $single ); if(!is_array($aimogen_templates)) { $aimogen_templates = array(); } $templates = array_merge($templates, $aimogen_templates); update_user_meta( $user_id, $key, $templates ); } wp_send_json_success( array( 'status' => 'ok' ) ); die(); } add_action( 'wp_ajax_aimogen_import_templates', 'aimogen_import_templates' ); function aimogen_import_templates() { check_ajax_referer( 'openai-single-nonce', 'nonce' ); if ( ! current_user_can('manage_options') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } if(!isset($_POST['templates'])) { wp_send_json_error( array( 'message' => 'Template json is required!' ) ); } $templates = wp_unslash( $_POST['templates'] );// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized if(!is_array($templates)) { wp_send_json_error(['message' => 'Invalid JSON data']); } $templates = array_map( function( $item ) { if ( is_array( $item ) ) { return array_map( 'sanitize_text_field', $item ); } return sanitize_text_field( $item ); }, $templates ); $user_id = get_current_user_id(); if($user_id == 0) { wp_send_json_error( array( 'message' => 'No user logged in, cannot find templates!' ) ); } else { $key = 'aimogen_templates'; $single = true; $aimogen_templates = get_user_meta( $user_id, $key, $single ); if(!is_array($aimogen_templates)) { $aimogen_templates = array(); } $templates = array_merge($templates, $aimogen_templates); update_user_meta( $user_id, $key, $templates ); } wp_send_json_success( array( 'status' => 'ok' ) ); die(); } add_action( 'wp_ajax_aimogen_export_templates', 'aimogen_export_templates' ); function aimogen_export_templates() { check_ajax_referer( 'openai-single-nonce', 'nonce' ); if ( ! current_user_can('manage_options') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } $aimogen_templates = array(); $user_id = get_current_user_id(); if($user_id == 0) { wp_send_json_error( array( 'message' => 'No user logged in, cannot find templates!' ) ); } else { $key = 'aimogen_templates'; $single = true; $aimogen_templates = get_user_meta( $user_id, $key, $single ); if(!is_array($aimogen_templates)) { $aimogen_templates = array(); } } wp_send_json_success( array( 'content' => $aimogen_templates ) ); die(); } add_action( 'wp_ajax_aimogen_export_templates_advanced', 'aimogen_export_templates_advanced' ); function aimogen_export_templates_advanced() { check_ajax_referer( 'openai-single-nonce', 'nonce' ); if ( ! current_user_can('manage_options') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } $aimogen_templates = array(); $user_id = get_current_user_id(); if($user_id == 0) { wp_send_json_error( array( 'message' => 'No user logged in, cannot find templates!' ) ); } else { $key = 'aimogen_templates_advanced'; $single = true; $aimogen_templates = get_user_meta( $user_id, $key, $single ); if(!is_array($aimogen_templates)) { $aimogen_templates = array(); } } wp_send_json_success( array( 'content' => $aimogen_templates ) ); die(); } add_action( 'wp_ajax_aimogen_load_template_advanced', 'aimogen_load_template_advanced' ); function aimogen_load_template_advanced() { check_ajax_referer( 'openai-single-nonce', 'nonce' ); if ( ! current_user_can('manage_options') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } if(!isset($_POST['template_name'])) { wp_send_json_error( array( 'message' => 'Template name is required!' ) ); } $template_name = sanitize_text_field( wp_unslash($_POST['template_name']) ); if(empty($template_name)) { wp_send_json_error( array( 'message' => 'You need to enter a valid template name!' ) ); } $aimogen_templates = array(); $user_id = get_current_user_id(); if($user_id == 0) { wp_send_json_error( array( 'message' => 'No user logged in, cannot find templates!' ) ); } else { if($template_name == 'Default Template') { $author_obj = get_user_by('id', $user_id); if($author_obj !== false) { $user_login = $author_obj->ID; } else { aimogen_log_to_file('Failed to detect current user name: ' . $user_id); $user_login = 1; } $dt = new DateTime(); $datef = $dt->format('Y-m-d H:i:s'); $default_category = get_option('default_category'); $aimogen_templates = array( 'title_advanced' => '', 'posting_mode_changer' => '1a', 'aimogen_topics_list' => '', 'aimogen_listicle_list' => '', 'aimogen_titles' => '', 'aimogen_youtube' => '', 'aimogen_roundup' => '', 'aimogen_review' => '', 'csv_title' => '', 'submit_status_advanced' => 'draft', 'submit_type_advanced' => 'post', 'post_sticky_advanced' => 'no', 'post_author_advanced' => $user_login, 'post_date_advanced' => $datef, 'post_category_advanced' => array($default_category), 'post_tags_advanced' => '', 'title_generator_method1a' => 'ai', 'assistant_id1a' => '', 'title_generator_method6' => 'ai', 'assistant_id6' => '', 'assistant_id1b' => '', 'assistant_id2' => '', 'assistant_id3' => '', 'assistant_id4' => '', 'post_sections_list1a' => '', 'section_count1a' => '3-4', 'sections_role1a' => 'h2', 'paragraph_count1a' => 2, 'topic_images1a' => '', 'img_all_headings1a' => 1, 'heading_img_location1a' => 'top', 'topic_videos1a' => '', 'title_outro1a' => '{In Conclusion|To Conclude|In Summary|To Wrap It Up|Key Takeaways|Future Outlook|Closing Remarks|The Conclusion|Final Thoughts|In Retrospect|The Way Forward|Wrapping Up|Concluding Remarks|Insights and Conclusions}', 'enable_toc1a' => 0, 'title_toc1a' => 'Table of Contents', 'enable_qa1a' => 0, 'title_qa1a' => 'Q&A', 'content_language1a' => 'English', 'writing_style1a' => 'Creative', 'writing_tone1a' => 'Neutral', 'title_prompt1a' => 'Write a title for an article about "%%topic%%" in %%language%%. Style: %%writing_style%%. Tone: %%writing_tone%%. Must be between 40 and 60 characters.', 'topic_title_model1a' => AIMOGEN_DEFAULT_MODEL, 'intro_prompt1a' => 'Craft an introduction for an article about "%%title%%", in %%language%%. Style: %%writing_style%%. Tone: %%writing_tone%%.', 'topic_intro_model1a' => AIMOGEN_DEFAULT_MODEL, 'sections_prompt1a' => 'Write %%sections_count%% consecutive headings for an article about "%%title%%" that highlight specific aspects, provide detailed insights and specific recommendations. The headings must be written in %%language%%, following a %%writing_style%% style and a %%writing_tone%% tone. Don\'t add numbers to the headings, hyphens or any types of quotes. Return only the headings list, nothing else.', 'topic_sections_model1a' => AIMOGEN_DEFAULT_MODEL, 'content_prompt1a' => 'Write the content of a post section for the heading "%%current_section%%" in %%language%%. The title of the post is: "%%title%%". Don\'t add the title at the beginning of the created content. Be creative and unique. Don\'t repeat the heading in the created content. Don\'t add an intro or outro. Write %%paragraphs_per_section%% paragraphs in the section. Use HTML for formatting, include unnumbered lists and bold. If needed, you can use WordPress related CSS styling for the article. When applicable, add also HTML tables with WordPress styling (you can use WordPress table classes). If added, table data must be relevant, creative, short and simple. Writing Style: %%writing_style%%. Tone: %%writing_tone%%.', 'topic_content_model1a' => AIMOGEN_DEFAULT_MODEL, 'single_content_call-11a' => 0, 'qa_prompt1a' => 'Write a Q&A for an article about "%%title%%", in %%language%%. Style: %%writing_style%%. Tone: %%writing_tone%%.', 'topic_qa_model1a' => AIMOGEN_DEFAULT_MODEL, 'outro_prompt1a' => 'Write an outro for an article about "%%title%%", in %%language%%. Style: %%writing_style%%. Tone: %%writing_tone%%.', 'topic_outro_model1a' => AIMOGEN_DEFAULT_MODEL, 'excerpt_prompt1a' => 'Write a short excerpt for an article about "%%title%%" in %%language%%. Style: %%writing_style%%. Tone: %%writing_tone%%. Must be between 150 and 250 characters.', 'topic_excerpt_model1a' => AIMOGEN_DEFAULT_MODEL, 'strip_by_regex_prompts1a' => '', 'replace_regex_prompts1a' => '', 'run_regex_on1a' => 'content', 'global_prepend1a' => '', 'global_append1a' => '', 'link_type1a' => 'disabled', 'max_links1a' => '', 'link_list1a' => '', 'link_nofollow1a' => 0, 'link_post_types1a' => '', 'max_tokens1a' => '', 'max_seed_tokens1a' => '', 'temperature1a' => '', 'top_p1a' => '', 'presence_penalty1a' => '', 'frequency_penalty1a' => '', 'search_query_repetition1a' => 0, 'enable_ai_images1a' => 0, 'ai_command_image1a' => 'Generate a high-resolution, visually compelling image that creatively interprets the theme encapsulated by this post title: "%%post_title%%". The image should be versatile enough to fit various niches, from technology and lifestyle to nature and science. It should feature a central, eye-catching element that abstractly represents the topic, surrounded by relevant, subtler motifs that provide context and depth. The composition should be balanced and aesthetically pleasing, with a harmonious color palette that complements the mood of the title. The artwork should be suitable for use as a captivating header image for a blog post.', 'model1a' => '1024x1024', 'post_prepend1a' => '', 'post_append1a' => '', 'custom_shortcodes1a' => '', 'strip_title1a' => 0, 'skip_spin1a' => 0, 'skip_translate1a' => 0, 'strip_by_regex1a' => '', 'replace_regex1a' => '', 'post_sections_list6' => '', 'section_count6' => '3-4', 'sections_role6' => 'h2', 'paragraph_count6' => 2, 'topic_images6' => '', 'img_all_headings6' => 1, 'heading_img_location6' => 'top', 'topic_videos6' => '', 'title_outro6' => '{In Conclusion|To Conclude|In Summary|To Wrap It Up|Key Takeaways|Future Outlook|Closing Remarks|The Conclusion|Final Thoughts|In Retrospect|The Way Forward|Wrapping Up|Concluding Remarks|Insights and Conclusions}', 'enable_toc6' => 0, 'title_toc6' => 'Table of Contents', 'enable_qa6' => 0, 'title_qa6' => 'Q&A', 'content_language6' => 'English', 'writing_style6' => 'Creative', 'writing_tone6' => 'Neutral', 'title_prompt6' => 'Write a title for a listicle about "%%topic%%" in %%language%%. The listicle will include %%sections_count%% items. Style: %%writing_style%%. Tone: %%writing_tone%%. Include a specific number in the title to indicate a list. Must be between 40 and 60 characters.', 'topic_title_model6' => AIMOGEN_DEFAULT_MODEL, 'intro_prompt6' => 'Craft an introduction for a listicle about "%%title%%", in %%language%%. Style: %%writing_style%%. Tone: %%writing_tone%%. Highlight the number of items in the list and what the reader can expect to learn or gain from the listicle.', 'topic_intro_model6' => AIMOGEN_DEFAULT_MODEL, 'sections_prompt6' => 'Write %%sections_count%% consecutive entries for a listicle about "%%title%%". The entries must be written in %%language%%, following a %%writing_style%% style and a %%writing_tone%% tone. Don\'t use HTML in your response, write only plain text entries, one on each line, as I will use these entries to further create content for each of them. Return only the entries, nothing else.', 'topic_sections_model6' => AIMOGEN_DEFAULT_MODEL, 'content_prompt6' => 'Write the content of a listicle section for the heading "%%current_section%%" in %%language%%. The title of the post is: "%%title%%". Don\'t add the title at the beginning of the created content. Be creative and unique. Don\'t repeat the heading in the created content. Don\'t add an intro or outro. Write %%paragraphs_per_section%% paragraphs in the section. Use HTML for formatting, include unnumbered lists and bold. If needed, you can use WordPress related CSS styling for the article. When applicable, add also HTML tables with WordPress styling (you can use WordPress table classes). If added, table data must be relevant, creative, short and simple. Act as a Content Writer, not as a Virtual Assistant. Return only the content requested, without any additional comments or text. Writing Style: %%writing_style%%. Tone: %%writing_tone%%.', 'topic_content_model6' => AIMOGEN_DEFAULT_MODEL, 'single_content_call-16' => 0, 'qa_prompt6' => 'Write a Q&A listicle for an article about "%%title%%", in %%language%%. Style: %%writing_style%%. Tone: %%writing_tone%%. Each question should be clear and engaging, followed by a detailed and informative answer. Use HTML for formatting, include unnumbered lists and bold where applicable. Return only the Q&A content, nothing else.', 'topic_qa_model6' => AIMOGEN_DEFAULT_MODEL, 'outro_prompt6' => 'Write an outro for a listicle about "%%title%%", in %%language%%. Style: %%writing_style%%. Tone: %%writing_tone%%.', 'topic_outro_model6' => AIMOGEN_DEFAULT_MODEL, 'excerpt_prompt6' => 'Write a short excerpt for a listicle about "%%title%%" in %%language%%. Style: %%writing_style%%. Tone: %%writing_tone%%. Must be between 150 and 250 characters. Highlight the listicle nature of the article and what readers can expect to find.', 'topic_excerpt_model6' => AIMOGEN_DEFAULT_MODEL, 'strip_by_regex_prompts6' => '', 'replace_regex_prompts6' => '', 'run_regex_on6' => 'content', 'global_prepend6' => '', 'global_append6' => '', 'link_type6' => 'disabled', 'max_links6' => '', 'link_list6' => '', 'link_nofollow6' => 0, 'link_post_types6' => '', 'max_tokens6' => '', 'max_seed_tokens6' => '', 'temperature6' => '', 'top_p6' => '', 'presence_penalty6' => '', 'frequency_penalty6' => '', 'search_query_repetition6' => 0, 'enable_ai_images6' => 0, 'ai_command_image6' => 'Generate a high-resolution, visually compelling image that creatively interprets the theme encapsulated by this post title: "%%post_title%%". The image should be versatile enough to fit various niches, from technology and lifestyle to nature and science. It should feature a central, eye-catching element that abstractly represents the topic, surrounded by relevant, subtler motifs that provide context and depth. The composition should be balanced and aesthetically pleasing, with a harmonious color palette that complements the mood of the title. The artwork should be suitable for use as a captivating header image for a blog post.', 'model6' => '1024x1024', 'post_prepend6' => '', 'post_append6' => '', 'custom_shortcodes6' => '', 'strip_title6' => 0, 'skip_spin6' => 0, 'skip_translate6' => 0, 'strip_by_regex6' => '', 'replace_regex6' => '', 'model1b' => '1024x1024', 'ai_command1b' => 'Write a comprehensive and SEO-optimized article on the topic of "%%post_title%%". Incorporate relevant keywords naturally throughout the article to enhance search engine visibility. This article must provide valuable information to readers and be well-structured with proper headings, bullet points, and HTML formatting. If needed, you can use WordPress related CSS styling for the article. When applicable, add also HTML tables with WordPress styling (you can use WordPress table classes). If added, table data must be relevant, creative, short and simple. Add an introductory and a conclusion section to the article. You can add also some other sections, when they fit the article\'s subject, like: benefits and practical tips, case studies, first had experience. Please ensure that the article is at least 1200 words in length and adheres to best SEO practices, including proper header tags (H1, H2, H3). The article will be automatically published on my WordPress site, as a post. Feel free to use a friendly, conversational tone and make the article as informative and engaging as possible while ensuring it remains factually accurate and well-researched.', 'min_char1b' => 500, 'title_model1b' => AIMOGEN_DEFAULT_MODEL, 'title_ai_command1b' => 'Craft an attention-grabbing and SEO-optimized article title for a dental health blog. This title must be concise, informative, and designed to pique the interest of readers while clearly conveying the topic of the article.', 'title_source1b' => 'keyword', 'headings1b' => '', 'headings_model1b' => AIMOGEN_DEFAULT_MODEL, 'headings_ai_command1b' => 'Generate %%needed_heading_count%% People Also Ask (PAA) related questions, each on a new line, that are relevant to the topic of the post title: "%%post_title%%".', 'images1b' => '', 'videos1b' => 0, 'headings_list1b' => '', 'images_list1b' => '', 'global_prepend1b' => '', 'global_append1b' => '', 'link_type1b' => 'disabled', 'max_links1b' => '', 'link_list1b' => '', 'link_nofollow1b' => 0, 'link_post_types1b' => '', 'max_tokens1b' => '', 'max_seed_tokens1b' => '', 'max_continue_tokens1b' => '', 'temperature1b' => '', 'top_p1b' => '', 'presence_penalty1b' => '', 'frequency_penalty1b' => '', 'search_query_repetition1b' => 0, 'enable_ai_images1b' => 0, 'ai_command_image1b' => 'Generate a high-resolution, visually compelling image that creatively interprets the theme encapsulated by this post title: "%%post_title%%". The image should be versatile enough to fit various niches, from technology and lifestyle to nature and science. It should feature a central, eye-catching element that abstractly represents the topic, surrounded by relevant, subtler motifs that provide context and depth. The composition should be balanced and aesthetically pleasing, with a harmonious color palette that complements the mood of the title. The artwork should be suitable for use as a captivating header image for a blog post.', 'post_prepend1b' => '', 'post_append1b' => '', 'custom_shortcodes1b' => '', 'strip_title1b' => 0, 'skip_spin1b' => 0, 'skip_translate1b' => 0, 'strip_by_regex1b' => '', 'replace_regex1b' => '', 'default_lang2' => '', 'max_caption2' => 3000, 'ai_titles2' => 0, 'post_sections_list2' => '', 'section_count2' => '3-4', 'sections_role2' => 'h2', 'paragraph_count2' => 2, 'topic_images2' => '', 'img_all_headings2' => 1, 'heading_img_location2' => 'heading', 'topic_videos2' => 0, 'title_outro2' => '{In Conclusion|To Conclude|In Summary|To Wrap It Up|Key Takeaways|Future Outlook|Closing Remarks|The Conclusion|Final Thoughts|In Retrospect|The Way Forward|Wrapping Up|Concluding Remarks|Insights and Conclusions}', 'enable_toc2' => 0, 'title_toc2' => 'Table of Contents', 'enable_qa2' => 0, 'title_qa2' => 'Q&A', 'content_language2' => 'English', 'writing_style2' => 'Creative', 'writing_tone2' => 'Neutral', 'title_prompt2' => 'Generate a title for a blog post discussing the topics covered in the YouTube video titled: "%%video_title%%", in %%language%% language. Style: %%writing_style%%. Tone: %%writing_tone%%. Must be between 40 and 60 characters.', 'topic_title_model2' => AIMOGEN_DEFAULT_MODEL, 'intro_prompt2' => 'Write an introduction for a blog post which talks about the topics discussed in the YouTube video with the following title: "%%video_title%%", in %%language%%. Style: %%writing_style%%. Tone: %%writing_tone%%. The YouTube video has the following transcript: "%%video_captions%%"', 'topic_intro_model2' => AIMOGEN_DEFAULT_MODEL, 'sections_prompt2' => 'Write %%sections_count%% consecutive headings that highlight specific aspects, provide detailed insights and specific recommendations for a blog post which talks about the topics discussed in the YouTube video with the following title: "%%video_title%%", in %%language%%. Style: %%writing_style%%. Tone: %%writing_tone%%. Don\'t add numbers to the headings, hyphens or any types of quotes. Return only the headings list, nothing else. Extract ideas from the following video transcript: "%%video_captions%%"', 'topic_sections_model2' => AIMOGEN_DEFAULT_MODEL, 'content_prompt2' => 'Write the content of a post section for the heading "%%current_section%%" in %%language%%. The title of the post is: "%%video_title%%". Don\'t repeat the heading in the created content. Don\'t add an intro or outro. Be creative and unique. Write %%paragraphs_per_section%% paragraphs in the section. Use HTML for formatting, include unnumbered lists and bold. If needed, you can use WordPress related CSS styling for the article. When applicable, add also HTML tables with WordPress styling (you can use WordPress table classes). If added, table data must be relevant, creative, short and simple. Writing Style: %%writing_style%%. Tone: %%writing_tone%%. Extract content from the following video transcript: "%%video_captions%%"', 'topic_content_model2' => AIMOGEN_DEFAULT_MODEL, 'single_content_call-12' => 0, 'qa_prompt2' => 'Write a Q&A for a blog post which talks about the topics discussed in the YouTube video with the following title: "%%video_title%%", in %%language%%. Style: %%writing_style%%. Tone: %%writing_tone%%. The YouTube video has the following transcript: "%%video_captions%%"', 'topic_qa_model2' => AIMOGEN_DEFAULT_MODEL, 'outro_prompt2' => 'Write an outro for a blog post which talks about the topics discussed in the YouTube video with the following title: "%%video_title%%", in %%language%%. Style: %%writing_style%%. Tone: %%writing_tone%%. The YouTube video has the following transcript: "%%video_captions%%"', 'topic_outro_model2' => AIMOGEN_DEFAULT_MODEL, 'excerpt_prompt2' => 'Write a short excerpt for a blog post which talks about the topics discussed in the YouTube video with the following title: "%%video_title%%" in %%language%%. Style: %%writing_style%%. Tone: %%writing_tone%%. Must be between 150 and 250 characters. The YouTube video has the following transcript: "%%video_captions%%"', 'topic_excerpt_model2' => AIMOGEN_DEFAULT_MODEL, 'strip_by_regex_prompts2' => '', 'replace_regex_prompts2' => '', 'run_regex_on2' => 'content', 'global_prepend2' => '', 'global_append2' => '', 'link_type2' => 'disabled', 'max_links2' => '', 'link_list2' => '', 'link_nofollow2' => 0, 'link_post_types2' => '', 'max_tokens2' => '', 'max_seed_tokens2' => '', 'max_continue_tokens2' => '', 'temperature2' => '', 'top_p2' => '', 'presence_penalty2' => '', 'frequency_penalty2' => '', 'search_query_repetition2' => 0, 'enable_ai_images2' => 0, 'ai_command_image2' => 'Generate a high-resolution, visually compelling image that creatively interprets the theme encapsulated by this post title: "%%post_title%%". The image should be versatile enough to fit various niches, from technology and lifestyle to nature and science. It should feature a central, eye-catching element that abstractly represents the topic, surrounded by relevant, subtler motifs that provide context and depth. The composition should be balanced and aesthetically pleasing, with a harmonious color palette that complements the mood of the title. The artwork should be suitable for use as a captivating header image for a blog post.', 'model2' => '1024x1024', 'post_prepend2' => '', 'post_append2' => '', 'custom_shortcodes2' => '', 'strip_title2' => 0, 'skip_spin2' => 0, 'skip_translate2' => 0, 'no_random2' => 0, 'strip_by_regex2' => '', 'replace_regex2' => '', 'affiliate_id3' => '', 'source3' => 'com', 'min_price3' => '', 'max_price3' => '', 'max_products3' => '3-4', 'sort_results3' => 'none', 'shuffle_products3' => 1, 'first_hand3' => 0, 'sections_role3' => 'h2', 'paragraph_count3' => 2, 'topic_images3' => 1, 'no_headlink3' => 0, 'topic_videos3' => 0, 'title_outro3' => '{Experience the Difference|Unlock Your Potential|Elevate Your Lifestyle|Embrace a New Era|Seize the Opportunity|Discover the Power|Transform Your World|Unleash Your True Potential|Embody Excellence|Achieve New Heights|Experience Innovation|Ignite Your Passion|Reveal the Extraordinary}', 'enable_toc3' => 0, 'title_toc3' => 'Table of Contents', 'enable_qa3' => 0, 'title_qa3' => 'Q&A', 'enable_table3' => 0, 'content_language3' => 'English', 'writing_style3' => 'Creative', 'writing_tone3' => 'Neutral', 'title_prompt3' => 'Write a title for a product roundup blog post which talks about the following products: %%all_product_titles%%, %%all_product_info%%, in %%language%% language. Style: %%writing_style%%. Tone: %%writing_tone%%. Must be between 40 and 60 characters.', 'topic_title_model3' => AIMOGEN_DEFAULT_MODEL, 'intro_prompt3' => 'Write an intro for a blog post which talks about the following products: %%all_product_titles%%, %%all_product_info%%, in %%language%%. The title of the post is "%%post_title%%". Style: %%writing_style%%. Tone: %%writing_tone%%.', 'topic_intro_model3' => AIMOGEN_DEFAULT_MODEL, 'content_prompt3' => 'Write the content of a post section describing the product "%%product_title%%" in %%language%%. Include pros and cons of the product. Don\'t repeat the product title in the created content. Don\'t add an intro or outro. Write %%paragraphs_per_section%% paragraphs in the section. Use HTML for formatting, include unnumbered lists and bold. When applicable, add also HTML tables with WordPress styling (you can use WordPress table classes). If added, table data must be relevant, creative, short and simple. Writing Style: %%writing_style%%. Tone: %%writing_tone%%. %%first_hand_experience_prompt%% Extract content from the following product description: "%%product_description%%"', 'topic_content_model3' => AIMOGEN_DEFAULT_MODEL, 'qa_prompt3' => 'Write a Q&A for a blog post with the following title: "%%post_title%%", in %%language%%. Style: %%writing_style%%. Tone: %%writing_tone%%. The blog post describes and compares multiple products: %%all_product_titles%%', 'topic_qa_model3' => AIMOGEN_DEFAULT_MODEL, 'outro_prompt3' => 'Write an outro for a blog post with the following title: "%%post_title%%", in %%language%%. Style: %%writing_style%%. Tone: %%writing_tone%%. The blog post describes and compares multiple products: %%all_product_titles%%', 'topic_outro_model3' => AIMOGEN_DEFAULT_MODEL, 'excerpt_prompt3' => 'Write a short excerpt for a blog post with the following title: "%%post_title%%", in %%language%%. Style: %%writing_style%%. Tone: %%writing_tone%%. The blog post describes and compares multiple products: %%all_product_titles%%', 'topic_excerpt_model3' => AIMOGEN_DEFAULT_MODEL, 'table_prompt3' => 'Generate a HTML product comparison table, for a product review blog post. The post has the following title: "%%post_title%%", in %%language%%. Style: %%writing_style%%. Tone: %%writing_tone%%. Point Of View: %%point_of_view%%. Don\'t add the entire description as a table entry, but instead, extract data from it, make matches between multiple products, be creative and also short and simple. The table must be in a WordPress friendly format and have modern styling (you can use WordPress table classes). Detail product information: %%all_product_info%%', 'topic_table_model3' => AIMOGEN_DEFAULT_MODEL, 'strip_by_regex_prompts3' => '', 'replace_regex_prompts3' => '', 'run_regex_on3' => 'content', 'global_prepend3' => '', 'global_append3' => '', 'link_type3' => 'disabled', 'max_links3' => '', 'link_list3' => '', 'link_nofollow3' => 0, 'link_post_types3' => '', 'max_tokens3' => '', 'max_seed_tokens3' => '', 'max_continue_tokens3' => '', 'temperature3' => '', 'top_p3' => '', 'presence_penalty3' => '', 'frequency_penalty3' => '', 'search_query_repetition3' => 0, 'enable_ai_images3' => 0, 'ai_command_image3' => 'A high detail image with no text of: "%%post_title%%"', 'model3' => '1024x1024', 'post_prepend3' => '', 'post_append3' => '', 'custom_shortcodes3' => '', 'strip_title3' => 0, 'skip_spin3' => 0, 'skip_translate3' => 0, 'strip_by_regex3' => '', 'replace_regex3' => '', 'affiliate_id4' => '', 'source4' => 'com', 'post_sections_list4' => '', 'section_count4' => '3-4', 'sections_role4' => 'h2', 'paragraph_count4' => 2, 'topic_images4' => 1, 'no_headlink4' => 0, 'topic_videos4' => 0, 'title_outro4' => '{Experience the Difference|Unlock Your Potential|Elevate Your Lifestyle|Embrace a New Era|Seize the Opportunity|Discover the Power|Transform Your World|Unleash Your True Potential|Embody Excellence|Achieve New Heights|Experience Innovation|Ignite Your Passion|Reveal the Extraordinary}', 'enable_toc4' => 0, 'title_toc4' => 'Table of Contents', 'enable_reviews4' => 0, 'title_reviews4' => 'Customer Reviews Analysis', 'enable_proscons4' => 0, 'title_proscons4' => 'Pros & Cons', 'enable_qa4' => 0, 'title_qa4' => 'Q&A', 'content_language4' => 'English', 'writing_style4' => 'Creative', 'writing_tone4' => 'Neutral', 'title_prompt4' => 'Write a title for a product review blog post of the following product: "%%product_title%%", in %%language%% language. Style: %%writing_style%%. Tone: %%writing_tone%%. Point of View: %%point_of_view%%. The title must be between 40 and 60 characters. The description of the product is: "%%product_description%%".', 'topic_title_model4' => AIMOGEN_DEFAULT_MODEL, 'intro_prompt4' => 'Write an introduction for a product review blog post of the following product: "%%product_title%%". The post is reviewing the product "%%product_title%%", in %%language%% language. Style: %%writing_style%%. Tone: %%writing_tone%%. Point of View: %%point_of_view%%. Write as if you had first-hand experience with the product you are describing. The description of the product is: "%%product_description%%".', 'topic_intro_model4' => AIMOGEN_DEFAULT_MODEL, 'sections_prompt4' => 'Write %%sections_count%% consecutive headings for a product review article of the "%%product_title%%" product, that starts with an overview, highlights specific features and aspects of the product, provides detailed insights and specific recommendations. The headings should be written in %%language%%, following a %%writing_style%% style and a %%writing_tone%% tone. Point of view: %%point_of_view%%. Don\'t add numbers to the headings, hyphens or any types of quotes. Write as if you had first-hand experience with the product you are describing. Return only the headings list, nothing else.', 'topic_sections_model4' => AIMOGEN_DEFAULT_MODEL, 'content_prompt4' => 'Write the content of a product review post, for the following section heading: "%%current_section%%". The post is reviewing the product "%%product_title%%" in %%language%%. Don\'t repeat the product title in the created content, also don\'t be repetitive in general. Don\'t add an intro or outro. Write %%paragraphs_per_section%% paragraphs in the section. Use HTML for formatting, include unnumbered lists and bold. When applicable, add also HTML tables with WordPress styling (you can use WordPress table classes). If added, table data must be relevant, creative, short and simple. Writing Style: %%writing_style%%. Tone: %%writing_tone%%. Point Of View: %%point_of_view%%. Extract content from the following product description: "%%product_description%%".', 'topic_content_model4' => AIMOGEN_DEFAULT_MODEL, 'reviews_prompt4' => 'Write the content of a "Customer Reviews Analysis" section for a product review blog post for the following product: "%%product_title%%". The title of the blog post is: "%%post_title%%", in %%language%%. Style: %%writing_style%%. Tone: %%writing_tone%%. Point Of View: %%point_of_view%%. Use HTML for formatting. When applicable, add also HTML tables with WordPress styling (you can use WordPress table classes). If added, table data must be relevant, creative, short and simple. List of customer reviews: "%%product_reviews%%".', 'topic_reviews_model4' => AIMOGEN_DEFAULT_MODEL, 'proscons_prompt4' => 'Write the content of a "Pros & Cons" section for a product review blog post for the following product: "%%product_title%%". The title of the blog post is: "%%post_title%%", in %%language%%. Style: %%writing_style%%. Tone: %%writing_tone%%. Point Of View: %%point_of_view%%.Use HTML for formatting. When applicable, add also HTML tables with WordPress styling (you can use WordPress table classes). If added, table data must be relevant, creative, short and simple. Product description: "%%product_description%%".', 'topic_proscons_model4' => AIMOGEN_DEFAULT_MODEL, 'qa_prompt4' => 'Write the content of a Q&A section for a product review blog post for the following product: "%%product_title%%". The title of the blog post is: "%%post_title%%", in %%language%%. Style: %%writing_style%%. Tone: %%writing_tone%%. Point Of View: %%point_of_view%%. Product description: "%%product_description%%".', 'topic_qa_model4' => AIMOGEN_DEFAULT_MODEL, 'outro_prompt4' => 'Write an outro for a product review blog post, for the product: "%%product_title%%". The post has the following title: "%%post_title%%", in %%language%%. Style: %%writing_style%%. Tone: %%writing_tone%%. Point Of View: %%point_of_view%%. Product description: "%%product_description%%". Add also an engaging final call to action link, in a clickable HTML format (don\'t use markdown language), leading to the link of the product: "%%aff_url%%".', 'topic_outro_model4' => AIMOGEN_DEFAULT_MODEL, 'excerpt_prompt4' => 'Write a short excerpt for a product review blog post, for the product: "%%product_title%%". The post has the following title: "%%post_title%%", in %%language%%. Style: %%writing_style%%. Tone: %%writing_tone%%. Point Of View: %%point_of_view%%. The excerpt must be between 100 and 150 words.', 'topic_excerpt_model4' => AIMOGEN_DEFAULT_MODEL, 'strip_by_regex_prompts4' => '', 'replace_regex_prompts4' => '', 'run_regex_on4' => 'content', 'global_prepend4' => '', 'global_append4' => '', 'link_type4' => 'disabled', 'max_links4' => '', 'link_list4' => '', 'link_nofollow4' => 0, 'link_post_types4' => '', 'max_tokens4' => '', 'max_seed_tokens4' => '', 'max_continue_tokens4' => '', 'temperature4' => '', 'top_p4' => '', 'presence_penalty4' => '', 'frequency_penalty4' => '', 'search_query_repetition4' => 0, 'enable_ai_images4' => 0, 'ai_command_image4' => 'A high detail image with no text of: "%%post_title%%"', 'model4' => '1024x1024', 'post_prepend4' => '', 'post_append4' => '', 'custom_shortcodes4' => '', 'skip_spin4' => 0, 'skip_translate4' => 0, 'strip_by_regex4' => '', 'replace_regex4' => '', 'csv_separator5' => '', 'strip_title5' => 0, 'skip_spin5' => 0, 'skip_translate5' => 0, 'random_order5' => 0, 'strip_by_regex5' => '', 'replace_regex5' => '', 'link_type5' => 'disabled', 'max_links5' => '', 'link_list5' => '', 'link_nofollow5' => 0, 'link_post_types5' => '', 'image_model1a' => 'gpt-image-1', 'image_model1b' => 'gpt-image-1', 'image_model2' => 'gpt-image-1', 'image_model3' => 'gpt-image-1', 'image_model4' => 'gpt-image-1', 'image_model6' => 'gpt-image-1', ); } else { $key = 'aimogen_templates_advanced'; $single = true; $aimogen_templates = get_user_meta( $user_id, $key, $single ); if(!is_array($aimogen_templates)) { $aimogen_templates = array(); } if(!isset($aimogen_templates[$template_name])) { wp_send_json_error( array( 'message' => 'Advanced template name not found in the database' ) ); } $aimogen_templates = $aimogen_templates[$template_name]; } } wp_send_json_success( array( 'content' => $aimogen_templates ) ); die(); } add_action('wp_ajax_aimogen_handle_vision_image_upload', 'aimogen_handle_vision_image_upload'); add_action('wp_ajax_nopriv_aimogen_handle_vision_image_upload', 'aimogen_handle_vision_image_upload'); function aimogen_handle_vision_image_upload() { $aimogen_result = array('status' => 'error', 'msg' => 'Image uploaded successfully'); if ( !isset($_POST['nonce']) || !wp_verify_nonce( sanitize_text_field( wp_unslash ($_POST['nonce'])), 'openai-persistent-nonce')) { $aimogen_result['msg'] = esc_html__('You are not allowed to do this.', 'aimogen'); wp_send_json($aimogen_result); die(); } $allowed_file_types = ['image/jpeg', 'image/png', 'image/gif']; if(!isset($_FILES['image'])) { $aimogen_result['msg'] = esc_html__('No file sent for upload.', 'aimogen'); wp_send_json($aimogen_result); die(); } $file = isset( $_FILES['image'] ) ? sanitize_text_field(wp_unslash( $_FILES['image'] )) : null; if ($file['size'] > 10000000) { $aimogen_result['msg'] = esc_html__('File size exceeds maximum limit.', 'aimogen'); wp_send_json($aimogen_result); die(); } if (!in_array($file['type'], $allowed_file_types)) { $aimogen_result['msg'] = esc_html__('Invalid file type submitted.', 'aimogen'); wp_send_json($aimogen_result); die(); } add_filter('upload_dir', 'aimogen_custom_vision_upload_dir'); $upload = wp_handle_upload($file, ['test_form' => false]); remove_filter('upload_dir', 'aimogen_custom_vision_upload_dir'); if (!empty($upload['error'])) { $aimogen_result['msg'] = esc_html__('Upload error: ', 'aimogen') . esc_html($upload['error']); wp_send_json($aimogen_result); die(); } else { $attachment_data = [ 'post_mime_type' => $upload['type'], 'post_title' => sanitize_file_name($upload['file']), 'post_content' => '', 'post_status' => 'inherit' ]; $attachment_id = wp_insert_attachment($attachment_data, $upload['file']); if(!function_exists('wp_generate_attachment_metadata')) { require_once(ABSPATH . 'wp-admin/includes/image.php'); require_once(ABSPATH . 'wp-admin/includes/media.php'); } $attach_data = wp_generate_attachment_metadata($attachment_id, $upload['file']); wp_update_attachment_metadata($attachment_id, $attach_data); $aimogen_Chatbot_Settings = get_option('aimogen_Chatbot_Settings', false); if (isset($aimogen_Chatbot_Settings['file_expiration']) && trim($aimogen_Chatbot_Settings['file_expiration']) != '') { $mytime = strtotime(trim($aimogen_Chatbot_Settings['file_expiration'])); if($mytime !== false) { $tdate = gmdate('Y-m-d', $mytime); update_post_meta($attachment_id, 'expiry_check', '1'); update_post_meta($attachment_id, 'expiry_date', $tdate); } } $image_url = wp_get_attachment_url($attachment_id); $aimogen_result['status'] = 'success'; $aimogen_result['image_url'] = $image_url; wp_send_json($aimogen_result); } wp_die(); } add_action('wp_ajax_aimogen_handle_chat_file_upload', 'aimogen_handle_chat_file_upload'); add_action('wp_ajax_nopriv_aimogen_handle_chat_file_upload', 'aimogen_handle_chat_file_upload'); function aimogen_handle_chat_file_upload() { if ( !isset($_POST['nonce']) || !wp_verify_nonce( sanitize_text_field( wp_unslash ($_POST['nonce'])), 'openai-persistent-nonce')) { $aimogen_result['msg'] = esc_html__('You are not allowed to do this.', 'aimogen'); wp_send_json($aimogen_result); die(); } $thread_id = ''; if ( isset($_POST['thread_id']) && $_POST['thread_id'] != '') { $thread_id = sanitize_text_field( wp_unslash($_POST['thread_id'])); } $aimogen_result = array('status' => 'error', 'msg' => 'File uploaded successfully'); $aimogen_Main_Settings = get_option('aimogen_Main_Settings', false); if (!aimogen_check_if_azure($aimogen_Main_Settings) && aimogen_check_if_azure_or_others($aimogen_Main_Settings)) { $aimogen_result['msg'] = 'Azure/Claude API is not currently supported for uploads.'; wp_send_json($aimogen_result); die(); } if (!isset($aimogen_Main_Settings['app_id']) || trim($aimogen_Main_Settings['app_id']) == '') { $aimogen_result['msg'] = esc_html__("You need to enter an OpenAI API key for this feature to work.", 'aimogen'); wp_send_json($aimogen_result); die(); } if(!isset($_FILES['image'])) { $aimogen_result['msg'] = esc_html__('No file sent for upload.', 'aimogen'); wp_send_json($aimogen_result); die(); } $file = isset( $_FILES['image'] ) ? sanitize_text_field(wp_unslash( $_FILES['image'] )) : null; if ($file['size'] > 50000000) { $aimogen_result['msg'] = esc_html__('File size exceeds maximum limit.', 'aimogen'); wp_send_json($aimogen_result); die(); } $appids = preg_split('/\r\n|\r|\n/', trim($aimogen_Main_Settings['app_id'])); $appids = array_filter($appids); $token = $appids[array_rand($appids)]; $token = apply_filters('aimogen_openai_api_key', $token); $open_ai = new OpenAi($token); if(!$open_ai){ $aimogen_result['msg'] = 'Missing API Setting'; wp_send_json($aimogen_result); die(); } if (isset($aimogen_Main_Settings['api_selector']) && trim($aimogen_Main_Settings['api_selector']) == 'custom' && isset($aimogen_Main_Settings['custom_endpoint']) && trim($aimogen_Main_Settings['custom_endpoint'], ' /') != '') { $open_ai->setCustomURL(trim($aimogen_Main_Settings['custom_endpoint'], ' /')); } if (isset($aimogen_Main_Settings['openai_organization']) && $aimogen_Main_Settings['openai_organization'] != '') { $open_ai->setORG($aimogen_Main_Settings['openai_organization']); } $file['name'] = 'chatbot-' . $file['name']; $file_name = sanitize_file_name( basename( $file['name'] ) ); $tmp_file = $file['tmp_name']; $detected = wp_check_filetype( $file_name ); $mime = $detected['type'] ?: 'application/octet-stream'; //curl file required for assistants file upload $c_file = curl_file_create( $tmp_file, $mime, $file_name );// phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_file_create -- Required by OpenAI SDK $delay = ''; if (isset($aimogen_Main_Settings['request_delay']) && $aimogen_Main_Settings['request_delay'] != '') { if(stristr($aimogen_Main_Settings['request_delay'], ',') !== false) { $tempo = explode(',', $aimogen_Main_Settings['request_delay']); if(isset($tempo[1]) && is_numeric(trim($tempo[1])) && is_numeric(trim($tempo[0]))) { $delay = wp_rand(trim($tempo[0]), trim($tempo[1])); } } else { if(is_numeric(trim($aimogen_Main_Settings['request_delay']))) { $delay = intval(trim($aimogen_Main_Settings['request_delay'])); } } } if($delay != '' && is_numeric($delay)) { usleep($delay); } $purpose = 'assistants'; $result = $open_ai->uploadFile(array( 'purpose' => $purpose, 'file' => $c_file, )); $result = json_decode($result); if(isset($result->error)){ $aimogen_result['msg'] = $result->error->message; } else { require_once (dirname(__FILE__) . "/res/aimogen-assistants-api.php"); try { $vs = aimogen_openai_create_vector_store($token, 'New Vector Store', array($result->id)); if(isset($vs['id'])) { if(!empty($thread_id)) { $thread = aimogen_openai_modify_thread($token, $thread_id, $vs['id']); if(!isset($thread['id'])) { $aimogen_result['msg'] = 'Invalid thread format when modifying thread: ' . json_encode($thread); wp_send_json($aimogen_result); wp_die(); } } $aimogen_result['msg'] = $vs['id']; $aimogen_result['fid'] = $result->id; $aimogen_result['status'] = 'success'; } } catch(Exception $e) { $aimogen_result['msg'] = 'Exception in vector store creation: ' . $e->getMessage(); } } wp_send_json($aimogen_result); wp_die(); } add_action('wp_ajax_aimogen_save_chat_data', 'aimogen_save_chat_data'); add_action('wp_ajax_nopriv_aimogen_save_chat_data', 'aimogen_save_chat_data'); function aimogen_save_chat_data() { if ( !isset($_POST['nonce']) || !wp_verify_nonce( sanitize_text_field( wp_unslash ($_POST['nonce'])), 'openai-persistent-nonce')) { $aimogen_result['msg'] = esc_html__('You are not allowed to do this.', 'aimogen'); wp_send_json($aimogen_result); die(); } if ( !isset($_POST['uniqid']) || empty($_POST['uniqid'])) { $aimogen_result['msg'] = esc_html__('Missing parameter (uniqid)', 'aimogen'); wp_send_json($aimogen_result); die(); } if ( !isset($_POST['input_text'])) { $aimogen_result['msg'] = esc_html__('Missing parameter (input_text)', 'aimogen'); wp_send_json($aimogen_result); die(); } if ( !isset($_POST['remember_string'])) { $aimogen_result['msg'] = esc_html__('Missing parameter (remember_string)', 'aimogen'); wp_send_json($aimogen_result); die(); } if ( !isset($_POST['user_question'])) { $aimogen_result['msg'] = esc_html__('Missing parameter (user_question)', 'aimogen'); wp_send_json($aimogen_result); die(); } $setarr = array(sanitize_text_field( wp_unslash($_POST['input_text'])), sanitize_text_field( wp_unslash($_POST['remember_string'])), sanitize_text_field( wp_unslash($_POST['user_question']))); if (isset($_POST['function_result']) && !empty($_POST['function_result'])) { $setarr[] = sanitize_text_field( wp_unslash($_POST['function_result'])); } set_transient('aimogen_ai_data_' . sanitize_text_field( wp_unslash($_POST['uniqid'])), $setarr, 900); $aimogen_result = array('status' => 'success', 'msg' => 'OK'); wp_send_json($aimogen_result); wp_die(); } add_action('wp_ajax_aimogen_chat_submit', 'aimogen_chat_submit'); add_action('wp_ajax_nopriv_aimogen_chat_submit', 'aimogen_chat_submit'); function aimogen_chat_submit() { check_ajax_referer('openai-ajax-nonce', 'nonce'); $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with chat'); if(!isset($_POST['input_text']) || !isset($_POST['model']) || !isset($_POST['temp']) || !isset($_POST['presence']) || !isset($_POST['frequency']) || !isset($_POST['remember_string'])) { $aimogen_result['msg'] = esc_html__('Incomplete POST request for chat', 'aimogen'); wp_send_json($aimogen_result); } $is_modern_gpt = '0'; if(isset($_POST['is_modern_gpt'])) { $is_modern_gpt = sanitize_text_field( wp_unslash($_POST['is_modern_gpt'])); } $no_internet = false; if(isset($_POST['internet_access']) && ($_POST['internet_access'] === 'no' || $_POST['internet_access'] === '0' || $_POST['internet_access'] == 'off' || $_POST['internet_access'] == 'disabled' || $_POST['internet_access'] == 'Disabled' || $_POST['internet_access'] == 'disable' || $_POST['internet_access'] == "false")) { $no_internet = true; } $no_embeddings = false; if(isset($_POST['embeddings']) && ($_POST['embeddings'] === 'no' || $_POST['embeddings'] === '0' || $_POST['embeddings'] == 'off' || $_POST['embeddings'] == 'disabled' || $_POST['embeddings'] == 'disable' || $_POST['embeddings'] == 'Disabled' || $_POST['embeddings'] == "false")) { $no_embeddings = true; } $raw_user_cap = ''; if ( isset( $_POST['user_token_cap_per_day'] ) ) { $raw_user_cap = wp_unslash( $_POST['user_token_cap_per_day'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized } $user_token_cap_per_day = sanitize_text_field( $raw_user_cap ); if(!empty($user_token_cap_per_day)) { $user_token_cap_per_day = intval($user_token_cap_per_day); } $aimogen_Chatbot_Settings = get_option('aimogen_Chatbot_Settings', false); if(isset($_POST['file_data'])) { $file_data = sanitize_text_field( wp_unslash($_POST['file_data'])); } else { $file_data = ''; } if(isset($_POST['ai_thread_id'])) { $thread_id = sanitize_text_field( wp_unslash($_POST['ai_thread_id'])); } else { $thread_id = ''; } if(isset($_POST['mcp_servers'])) { $mcp_servers = sanitize_text_field( wp_unslash($_POST['mcp_servers'])); } else { $mcp_servers = ''; } if(isset($_POST['store_data'])) { $store_data = sanitize_text_field( wp_unslash($_POST['store_data'])); } else { $store_data = 'off'; } if(isset($_POST['user_id'])) { $user_id = sanitize_text_field( wp_unslash($_POST['user_id'])); } else { $user_id = ''; } if(isset($_POST['pdf_data'])) { $embedding_namespace = sanitize_text_field( wp_unslash($_POST['pdf_data'])); } else { $embedding_namespace = ''; } if(empty($embedding_namespace)) { if (isset($aimogen_Chatbot_Settings['persistent']) && $aimogen_Chatbot_Settings['persistent'] == 'vector') { $embedding_namespace = 'persistentchat_' . $user_id . '_' . $thread_id; } else { if(isset($_POST['embeddings_namespace']) && !empty($_POST['embeddings_namespace'])) { $embedding_namespace = sanitize_text_field( wp_unslash($_POST['embeddings_namespace'])); } } } $input_text = sanitize_text_field( wp_unslash($_POST['input_text'])); if (isset($aimogen_Chatbot_Settings['max_input_length']) && $aimogen_Chatbot_Settings['max_input_length'] != '' && is_numeric($aimogen_Chatbot_Settings['max_input_length'])) { if(strlen($input_text) > intval($aimogen_Chatbot_Settings['max_input_length'])) { $input_text = aimogen_substr($input_text, 0, intval($aimogen_Chatbot_Settings['max_input_length'])); } } if(isset($_POST['remember_string'])) { $remember_string = sanitize_text_field( wp_unslash($_POST['remember_string'])); } else { $remember_string = ''; } if(isset($_POST['user_question'])) { $user_question = sanitize_text_field( wp_unslash($_POST['user_question'])); } else { $user_question = ''; } if(isset($_POST['ai_assistant_id'])) { $assistant_id = sanitize_text_field( wp_unslash($_POST['ai_assistant_id'])); } else { $assistant_id = ''; } if(isset($_POST['model'])) { $model = sanitize_text_field( wp_unslash($_POST['model'])); } else { $model = 'default'; } if($model == 'default') { $model = AIMOGEN_DEFAULT_MODEL; } if(isset($_POST['temp'])) { $temperature = sanitize_text_field( wp_unslash($_POST['temp'])); } else { $temperature = '1'; } if(isset($_POST['top_p'])) { $top_p = sanitize_text_field( wp_unslash($_POST['top_p'])); } else { $top_p = '1'; } if(isset($_POST['presence'])) { $presence_penalty = sanitize_text_field( wp_unslash($_POST['presence'])); } else { $presence_penalty = '0'; } if(isset($_POST['frequency'])) { $frequency_penalty = sanitize_text_field( wp_unslash($_POST['frequency'])); } else { $frequency_penalty = '0'; } if($is_modern_gpt == '1') { if(!empty($remember_string)) { $remember_string = json_decode($remember_string, true); if($remember_string === null) { $aimogen_result['msg'] = esc_html__('Failed to decode conversation data in request!', 'aimogen'); wp_send_json($aimogen_result); } if(!is_array($remember_string)) { $remember_string = []; } } else { $remember_string = []; } if (isset($aimogen_Chatbot_Settings['chatbot_prepend']) && trim($aimogen_Chatbot_Settings['chatbot_prepend']) != '') { array_unshift($remember_string, array ('role' => 'user', 'content' => trim($aimogen_Chatbot_Settings['chatbot_prepend']))); } if (isset($aimogen_Chatbot_Settings['chatbot_append']) && trim($aimogen_Chatbot_Settings['chatbot_append']) != '') { $remember_string[] = array ('role' => 'user', 'content' => trim($aimogen_Chatbot_Settings['chatbot_append'])); } $remember_string[] = array ('role' => 'user', 'content' => $input_text); $input_text = $remember_string; } else { if (isset($aimogen_Chatbot_Settings['chatbot_prepend']) && trim($aimogen_Chatbot_Settings['chatbot_prepend']) != '') { $remember_string = trim($aimogen_Chatbot_Settings['chatbot_prepend']) . ' ' . $remember_string; } if (isset($aimogen_Chatbot_Settings['chatbot_append']) && trim($aimogen_Chatbot_Settings['chatbot_append']) != '') { $remember_string = $remember_string . ' ' . trim($aimogen_Chatbot_Settings['chatbot_append']); } if(!empty(trim($remember_string))) { $input_text = trim($remember_string) . PHP_EOL . $input_text; } } $all_models = aimogen_get_all_models(); $models = $all_models; if(!in_array($model, $models)) { $aimogen_result['msg'] = esc_html__('Invalid model provided: ', 'aimogen') . $model; wp_send_json($aimogen_result); } $vision_file = ''; if(isset($_REQUEST['vision_file'])) { if(aimogen_is_vision_model($model, $assistant_id)) { $vision_file = sanitize_text_field( wp_unslash($_REQUEST['vision_file'])); } } $temperature = floatval($temperature); $top_p = floatval($top_p); $presence_penalty = floatval($presence_penalty); $frequency_penalty = floatval($frequency_penalty); if (isset($aimogen_Chatbot_Settings['restriction_time']) && $aimogen_Chatbot_Settings['restriction_time'] != '' && is_numeric($aimogen_Chatbot_Settings['restriction_time']) && isset($aimogen_Chatbot_Settings['restriction_count']) && $aimogen_Chatbot_Settings['restriction_count'] != '' && is_numeric($aimogen_Chatbot_Settings['restriction_count'])) { $user_ip = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : ''; $restriction_time = esc_attr( $aimogen_Chatbot_Settings['restriction_time'] ); $user_hash = 'ai' . md5( $user_ip ); $user_requests = get_transient( $user_hash ); if($user_requests === false) { $user_requests = 0; } $user_max_requests = esc_attr( $aimogen_Chatbot_Settings['restriction_count'] ); if ( (int)$user_requests >= (int)$user_max_requests ) { $restriction_message = ''; if (isset($aimogen_Chatbot_Settings['restriction_message']) && $aimogen_Chatbot_Settings['restriction_message'] != '') { $restriction_message = $aimogen_Chatbot_Settings['restriction_message']; } $aimogen_result['msg'] = $restriction_message; wp_send_json($aimogen_result); } set_transient( $user_hash, (int)$user_requests + 1, (int)$restriction_time ); } if($temperature < 0 || $temperature > 2) { $aimogen_result['msg'] = esc_html__('Invalid temperature provided: ', 'aimogen') . $temperature; wp_send_json($aimogen_result); } if($top_p < 0 || $top_p > 1) { $aimogen_result['msg'] = esc_html__('Invalid top_p provided: ', 'aimogen') . $top_p; wp_send_json($aimogen_result); } if($presence_penalty < -2 || $presence_penalty > 2) { $aimogen_result['msg'] = esc_html__('Invalid presence_penalty provided: ', 'aimogen') . $presence_penalty; wp_send_json($aimogen_result); } if($frequency_penalty < -2 || $frequency_penalty > 2) { $aimogen_result['msg'] = esc_html__('Invalid frequency_penalty provided: ', 'aimogen') . $frequency_penalty; wp_send_json($aimogen_result); } $aimogen_Main_Settings = get_option('aimogen_Main_Settings', false); if (!isset($aimogen_Main_Settings['app_id']) || trim($aimogen_Main_Settings['app_id']) == '') { $aimogen_result['msg'] = esc_html__('You need to insert a valid OpenAI/AimogenAPI API Key for this to work!', 'aimogen'); wp_send_json($aimogen_result); } $used_token_count = 0; if(!empty($user_token_cap_per_day) && is_numeric($user_token_cap_per_day)) { if(empty($user_id) || $user_id == 0 || !is_numeric($user_id)) { /* translators: %s: URL */ $aimogen_result['msg'] = sprintf( wp_kses( __( 'You are not allowed to access this form if you are not logged in. Please log in to continue.', 'aimogen'), array( 'a' => array( 'href' => array(), 'target' => array() ) ) ), wp_login_url(get_permalink()) ); wp_send_json($aimogen_result); } $used_token_count = get_user_meta($user_id, 'aimogen_used_chat_tokens', true); if($used_token_count !== '' && $used_token_count !== false && is_numeric($used_token_count)) { $used_token_count = intval($used_token_count); if($used_token_count > $user_token_cap_per_day) { $aimogen_result['msg'] = esc_html__('Daily token count of your user account was exceeded! Please try again tomorrow.', 'aimogen'); wp_send_json($aimogen_result); } } else { $used_token_count = 0; } } $appids = preg_split('/\r\n|\r|\n/', trim($aimogen_Main_Settings['app_id'])); $appids = array_filter($appids); $token = $appids[array_rand($appids)]; $token = apply_filters('aimogen_openai_api_key', $token); $max_tokens = aimogen_get_max_tokens($model); if (isset($aimogen_Chatbot_Settings['max_tokens']) && $aimogen_Chatbot_Settings['max_tokens'] !== '' && is_numeric($aimogen_Chatbot_Settings['max_tokens'])) { $max_tokens_chatbot = intval($aimogen_Chatbot_Settings['max_tokens']); if(intval($max_tokens_chatbot) < $max_tokens) { $max_tokens = intval($max_tokens_chatbot); if($max_tokens <= 0) { $max_tokens = 1000; } } } if($is_modern_gpt == '1') { $aitext = ''; foreach($input_text as $aimess) { if(isset($aimess['content'])) { if(!is_array($aimess['content'])) { $aitext .= $aimess['content'] . '\n'; } else { foreach($aimess['content'] as $internalmess) { if($internalmess['type'] == 'text') { $aitext .= $internalmess['text'] . '\n'; } } } } } $query_token_count = count(aimogen_encode($aitext)); $available_tokens = aimogen_compute_available_tokens($model, $max_tokens, $aitext, $query_token_count); if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS) { $startIndex = intdiv(count($input_text), 2); $input_text = array_slice($input_text, $startIndex); $lastindex = end(array_keys($input_text)); $string_len = strlen($input_text[$lastindex]['content']); $string_len = $string_len / 2; $string_len = intval(0 - $string_len); $input_text[$lastindex]['content'] = aimogen_substr($input_text[$lastindex]['content'], 0, $string_len); $input_text[$lastindex]['content'] = trim($input_text[$lastindex]['content']); $aitext = ''; foreach($input_text as $aimess) { if(isset($aimess['content'])) { if(!is_array($aimess['content'])) { $aitext .= $aimess['content'] . '\n'; } else { foreach($aimess['content'] as $internalmess) { if($internalmess['type'] == 'text') { $aitext .= $internalmess['text'] . '\n'; } } } } } $query_token_count = count(aimogen_encode($aitext)); $available_tokens = $max_tokens - $query_token_count; } } else { $query_token_count = count(aimogen_encode($input_text)); $available_tokens = aimogen_compute_available_tokens($model, $max_tokens, $input_text, $query_token_count); if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS) { $string_len = strlen($input_text); $string_len = $string_len / 2; $string_len = intval(0 - $string_len); $input_text = aimogen_substr($input_text, 0, $string_len); $input_text = trim($input_text); if(empty($input_text)) { aimogen_log_to_file('Empty API seed expression provided (after processing)'); $aimogen_result['msg'] = esc_html__('An internal error occurred, please try again later!', 'aimogen'); wp_send_json($aimogen_result); } $query_token_count = count(aimogen_encode($input_text)); $available_tokens = $max_tokens - $query_token_count; } } $function_result = 'disabled'; $forced_functions = array(); if(isset($_POST['enable_god_mode'])) { if($_POST['enable_god_mode'] === 'disabled' || $_POST['enable_god_mode'] === 'off') { $_POST['enable_god_mode'] = ''; } if($_POST['enable_god_mode'] === 'on' || $_POST['enable_god_mode'] === 'yes' || $_POST['enable_god_mode'] === 'true' || $_POST['enable_god_mode'] === '1' || $_POST['enable_god_mode'] === 'enable' || $_POST['enable_god_mode'] === 'enabled') { $function_result = ''; } elseif(is_string($_POST['enable_god_mode']) && !empty($_POST['enable_god_mode'])) { $forced_functions = explode(',', sanitize_text_field( wp_unslash($_POST['enable_god_mode']))); $function_result = ''; } } $error = ''; $finish_reason = ''; do_action('aimogen_calling_chatbot', $input_text, $model); $response_text = aimogen_generate_text($token, $model, $input_text, $available_tokens, $temperature, $top_p, $presence_penalty, $frequency_penalty, true, 'shortcodeChat', 0, $finish_reason, $error, $no_internet, $no_embeddings, false, $vision_file, $user_question, 'user', $assistant_id, $thread_id, $embedding_namespace, $function_result, $file_data, false, $store_data, $forced_functions, $mcp_servers); if($response_text === false) { $aimogen_result['msg'] = $error; wp_send_json($aimogen_result); } else { if($is_modern_gpt == '1') { $aitext = ''; foreach($input_text as $aimess) { if(isset($aimess['content'])) { if(!is_array($aimess['content'])) { $aitext .= $aimess['content'] . '\n'; } else { foreach($aimess['content'] as $internalmess) { if($internalmess['type'] == 'text') { $aitext .= $internalmess['text'] . '\n'; } } } } } $inp_count = count(aimogen_encode($aitext)); } else { $inp_count = count(aimogen_encode($input_text)); } $resp_count = count(aimogen_encode($response_text)); if(!empty($user_token_cap_per_day) && is_numeric($user_token_cap_per_day)) { $used_token_count = intval($used_token_count) + $inp_count + $resp_count; update_user_meta($user_id, 'aimogen_used_chat_tokens', $used_token_count); } } $aimogen_result['status'] = 'success'; if (isset($aimogen_Chatbot_Settings['enable_html'])) { if(trim($aimogen_Chatbot_Settings['enable_html']) == 'on') { if (isset($aimogen_Chatbot_Settings['strip_js']) && trim($aimogen_Chatbot_Settings['strip_js']) == 'on') { $response_text = preg_replace('//is', "", $response_text); $response_text = preg_replace('/on[a-zA-Z]*="([^"]*?)"/is', "", $response_text); } $aimogen_result['data'] = trim($response_text); } else { $aimogen_result['data'] = trim(esc_html($response_text)); } } else { $aimogen_result['data'] = trim(esc_html($response_text)); } if ((isset($aimogen_Main_Settings['markdown_parse']) && $aimogen_Main_Settings['markdown_parse'] == 'on') || (isset($aimogen_Chatbot_Settings['markdown_parse']) && $aimogen_Chatbot_Settings['markdown_parse'] == 'on')) { if(aimogen_containsMarkdown($aimogen_result['data'])) { $aimogen_result['data'] = aimogen_parse_markdown($aimogen_result['data']); } } $aimogen_result['thread_id'] = $thread_id; do_action('aimogen_chat_reply', $aimogen_result); wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_post_now', 'aimogen_aimogen_submit_post_callback'); function aimogen_aimogen_submit_post_callback() { check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('edit_posts') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } $raw_run_id = ''; if ( isset( $_POST['id'] ) ) { $raw_run_id = wp_unslash( $_POST['id'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized } $run_id = sanitize_text_field( $raw_run_id ); $wp_post = get_post($run_id); if($wp_post != null) { $template = 'skip'; aimogen_do_post($wp_post, true, $template, false); } die(); } add_action('wp_ajax_aimogen_toggle_status', 'aimogen_toggle_status'); function aimogen_toggle_status() { check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('manage_options') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } $raw_run_id = ''; if ( isset( $_POST['id'] ) ) { $raw_run_id = wp_unslash( $_POST['id'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized } $run_id = sanitize_text_field( $raw_run_id ); $wp_post = get_post($run_id); if($wp_post != null) { $aimogen_Spinner_Settings = get_option('aimogen_Spinner_Settings', false); if (isset($aimogen_Spinner_Settings['custom_name']) && trim($aimogen_Spinner_Settings['custom_name']) != '') { $custom_name = trim($aimogen_Spinner_Settings['custom_name']); $custom_name = str_replace('%%current_date%%', gmdate("Y-m-d"), $custom_name); } else { $custom_name = 'aimogen_published'; } $metavalue = get_post_meta($run_id, $custom_name, true); if($metavalue == 'pub') { delete_post_meta($run_id, $custom_name); } else { update_post_meta($run_id, $custom_name, 'pub'); } } die(); } add_action('wp_ajax_aimogen_delete_logs', 'aimogen_delete_logs'); function aimogen_delete_logs() { $aimogen_result = array('status' => 'success', 'msg' => 'Data deleted successfully'); check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('manage_options') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_delete_user_logs', 'aimogen_delete_user_logs'); function aimogen_delete_user_logs() { $aimogen_result = array('status' => 'success', 'msg' => 'Data deleted successfully'); check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('manage_options') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } if(!isset($_POST['delfor']) || empty($_POST['delfor'])) { $aimogen_result['status'] = 'fail'; $aimogen_result['msg'] = 'Empty username added in the request!'; wp_send_json($aimogen_result); } $userId = null; $raw_delfor = ''; if ( isset( $_POST['delfor'] ) ) { $raw_delfor = wp_unslash( $_POST['delfor'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized } $delfor = sanitize_text_field( $raw_delfor ); $user = get_user_by( 'login', $delfor ); if($user) { $userId = $user->ID; } else { $aimogen_result['status'] = 'fail'; $aimogen_result['msg'] = 'Failed to get user ID for username: ' . sanitize_text_field( wp_unslash($_POST['delfor'])); wp_send_json($aimogen_result); } wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_personas', 'aimogen_personas'); function aimogen_personas() { $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with AI Personas'); check_ajax_referer('aimogen_personas', 'nonce'); if ( ! current_user_can('edit_posts') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } if(!isset($_POST['aimogen-persona-title']) || empty($_POST['aimogen-persona-title'])) { $aimogen_result['msg'] = 'Empty persona title added!'; wp_send_json($aimogen_result); } $title = sanitize_text_field( wp_unslash($_POST['aimogen-persona-title'])); if(!isset($_POST['aimogen-persona-prompt']) || empty($_POST['aimogen-persona-prompt'])) { $aimogen_result['msg'] = 'Empty persona prompt added!'; wp_send_json($aimogen_result); } $prompt = sanitize_text_field( wp_unslash($_POST['aimogen-persona-prompt'])); $description = ''; if(isset($_POST['aimogen-persona-description']) && !empty($_POST['aimogen-persona-description'])) { $description = sanitize_text_field( wp_unslash($_POST['aimogen-persona-description'])); } $first_message = ''; if(isset($_POST['aimogen-persona-first-message']) && !empty($_POST['aimogen-persona-first-message'])) { $first_message = sanitize_text_field( wp_unslash($_POST['aimogen-persona-first-message'])); } $avatar = ''; if(isset($_POST['aimogen-persona-avatar']) && !empty($_POST['aimogen-persona-avatar'])) { $avatar = sanitize_text_field( wp_unslash($_POST['aimogen-persona-avatar'])); } $model = ''; if(isset($_POST['aimogen-persona-model']) && !empty($_POST['aimogen-persona-model'])) { $model = sanitize_text_field( wp_unslash($_POST['aimogen-persona-model'])); } $aimogen_result = aimogen_save_persona($title, $prompt, $description, $first_message, $avatar, $model); wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_list_assistant_files', 'aimogen_list_assistant_files'); function aimogen_list_assistant_files() { check_ajax_referer('openai-ajax-nonce', 'nonce'); require_once (dirname(__FILE__) . "/res/openai/Url.php"); require_once (dirname(__FILE__) . "/res/openai/OpenAi.php"); if ( ! current_user_can('manage_options') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with finetuning files'); $aimogen_Main_Settings = get_option('aimogen_Main_Settings', false); if (!aimogen_check_if_azure($aimogen_Main_Settings) && aimogen_check_if_azure_or_others($aimogen_Main_Settings)) { $aimogen_result['msg'] = 'Claude API is not currently supported for assistants.'; wp_send_json($aimogen_result); } //assistant file listing is currently not supported for Azure if(aimogen_check_if_azure($aimogen_Main_Settings)) { $aimogen_result['status'] = 'success'; $aimogen_result['data'] = array(); wp_send_json($aimogen_result); die(); } else { $appids = preg_split('/\r\n|\r|\n/', trim($aimogen_Main_Settings['app_id'])); $appids = array_filter($appids); $token = $appids[array_rand($appids)]; $token = apply_filters('aimogen_openai_api_key', $token); $open_ai = new OpenAi($token); if(!$open_ai){ $aimogen_result['msg'] = 'Missing API Setting'; wp_send_json($aimogen_result); } if (isset($aimogen_Main_Settings['api_selector']) && trim($aimogen_Main_Settings['api_selector']) == 'custom' && isset($aimogen_Main_Settings['custom_endpoint']) && trim($aimogen_Main_Settings['custom_endpoint'], ' /') != '') { $open_ai->setCustomURL(trim($aimogen_Main_Settings['custom_endpoint'], ' /')); } if (isset($aimogen_Main_Settings['openai_organization']) && $aimogen_Main_Settings['openai_organization'] != '') { $open_ai->setORG($aimogen_Main_Settings['openai_organization']); } $delay = ''; if (isset($aimogen_Main_Settings['request_delay']) && $aimogen_Main_Settings['request_delay'] != '') { if(stristr($aimogen_Main_Settings['request_delay'], ',') !== false) { $tempo = explode(',', $aimogen_Main_Settings['request_delay']); if(isset($tempo[1]) && is_numeric(trim($tempo[1])) && is_numeric(trim($tempo[0]))) { $delay = wp_rand(trim($tempo[0]), trim($tempo[1])); } } else { if(is_numeric(trim($aimogen_Main_Settings['request_delay']))) { $delay = intval(trim($aimogen_Main_Settings['request_delay'])); } } } if($delay != '' && is_numeric($delay)) { usleep($delay); } $result = $open_ai->listFiles(array( 'purpose' => 'assistants' )); $result = json_decode($result); if(isset($result->error)){ $aimogen_result['msg'] = $result->error->message; } else{ if(isset($result->data) && is_array($result->data) && count($result->data)) { foreach($result->data as $ind => $rd) { if($rd->purpose != 'assistants') { unset($result->data[$ind]); } } $aimogen_result['status'] = 'success'; $aimogen_result['data'] = $result->data; } else{ $aimogen_result['status'] = 'success'; $aimogen_result['data'] = array(); } } wp_send_json($aimogen_result); die(); } } add_action('wp_ajax_aimogen_download_file', 'aimogen_download_file'); function aimogen_download_file() { $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with file downloading'); check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('edit_posts') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } $aimogen_Main_Settings = get_option('aimogen_Main_Settings', false); if (!aimogen_check_if_azure($aimogen_Main_Settings) && aimogen_check_if_azure_or_others($aimogen_Main_Settings)) { $aimogen_result['msg'] = 'Claude API is not currently supported for this feature.'; wp_send_json($aimogen_result); die(); } $appids = preg_split('/\r\n|\r|\n/', trim($aimogen_Main_Settings['app_id'])); $appids = array_filter($appids); $token = $appids[array_rand($appids)]; $token = apply_filters('aimogen_openai_api_key', $token); if(aimogen_check_if_azure($aimogen_Main_Settings)) { $azure_endpoint = !empty($aimogen_Main_Settings['azure_endpoint']) ? trim($aimogen_Main_Settings['azure_endpoint'], '/') : ''; if (!empty($aimogen_Main_Settings['azure_api_selector_batch']) && $aimogen_Main_Settings['azure_api_selector_batch'] !== 'default') { $api_ver = '?api-version=' . $aimogen_Main_Settings['azure_api_selector_batch']; } else { $api_ver = AIMOGEN_AZURE_BATCHES_API_VERSION; } if (!$azure_endpoint) { $aimogen_result['msg'] = 'Azure endpoint is missing in settings.'; wp_send_json($aimogen_result); } if (isset($_REQUEST['id']) && !empty($_REQUEST['id'])) { $file_id = sanitize_text_field( wp_unslash($_REQUEST['id'])); $url = $azure_endpoint . "/openai/files/{$file_id}/content{$api_ver}"; $args = [ 'method' => 'GET', 'timeout' => 60, 'sslverify' => false, 'headers' => [ 'api-key' => $token ] ]; $response = wp_remote_get($url, $args); if (is_wp_error($response)) { $aimogen_result['msg'] = $response->get_error_message(); wp_send_json($aimogen_result); } $http_code = wp_remote_retrieve_response_code($response); $body = wp_remote_retrieve_body($response); if ($http_code === 200) { $aimogen_result['status'] = 'success'; $aimogen_result['data'] = $body; $aimogen_result['filename'] = "{$file_id}.txt"; } else { $decoded = json_decode($body, true); $err = isset($decoded['error']['message']) ? $decoded['error']['message'] : 'Unknown error'; $aimogen_result['msg'] = "HTTP request failed with code $http_code: $err"; } } else { $aimogen_result['msg'] = 'File ID is required.'; } } else { $open_ai = new OpenAi($token); if(isset($_REQUEST['id']) && !empty($_REQUEST['id'])) { $id = sanitize_text_field( wp_unslash($_REQUEST['id'])); if (!$open_ai) { $aimogen_result['msg'] = 'Missing API Setting'; wp_send_json($aimogen_result); die(); } else { if (isset($aimogen_Main_Settings['api_selector']) && trim($aimogen_Main_Settings['api_selector']) == 'custom' && isset($aimogen_Main_Settings['custom_endpoint']) && trim($aimogen_Main_Settings['custom_endpoint'], ' /') != '') { $open_ai->setCustomURL(trim($aimogen_Main_Settings['custom_endpoint'], ' /')); } if (isset($aimogen_Main_Settings['openai_organization']) && $aimogen_Main_Settings['openai_organization'] != '') { $open_ai->setORG($aimogen_Main_Settings['openai_organization']); } $delay = ''; if (isset($aimogen_Main_Settings['request_delay']) && $aimogen_Main_Settings['request_delay'] != '') { if(stristr($aimogen_Main_Settings['request_delay'], ',') !== false) { $tempo = explode(',', $aimogen_Main_Settings['request_delay']); if(isset($tempo[1]) && is_numeric(trim($tempo[1])) && is_numeric(trim($tempo[0]))) { $delay = wp_rand(trim($tempo[0]), trim($tempo[1])); } } else { if(is_numeric(trim($aimogen_Main_Settings['request_delay']))) { $delay = intval(trim($aimogen_Main_Settings['request_delay'])); } } } if($delay != '' && is_numeric($delay)) { usleep($delay); } $result = $open_ai->retrieveFileContent($id); $json_parse = json_decode($result); if(isset($json_parse->error)){ $aimogen_result['msg'] = 'Error: ' . $json_parse->error->message; wp_send_json($aimogen_result); die(); } else { $file_info = $open_ai->retrieveFile($id); $json_info_parse = json_decode($file_info); if(!isset($json_info_parse->filename)) { $aimogen_result['msg'] = 'Error in file downloading: ' . json_encode($json_info_parse); wp_send_json($aimogen_result); die(); } else { $filename = $json_info_parse->filename; $aimogen_result['status'] = 'success'; $aimogen_result['data'] = $result; $aimogen_result['filename'] = $filename; wp_send_json($aimogen_result); die(); } } } } } wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_delete_assistant_vector_store', 'aimogen_delete_assistant_vector_store'); add_action('wp_ajax_nopriv_aimogen_delete_assistant_vector_store', 'aimogen_delete_assistant_vector_store'); function aimogen_delete_assistant_vector_store() { check_ajax_referer('openai-ajax-nonce', 'nonce'); $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with finetuning deletion'); if(isset($_POST['id']) && !empty($_POST['id'])){ $aimogen_Main_Settings = get_option('aimogen_Main_Settings', false); if (!aimogen_check_if_azure($aimogen_Main_Settings) && aimogen_check_if_azure_or_others($aimogen_Main_Settings)) { $aimogen_result['msg'] = 'Claude API is not currently supported for assistants.'; wp_send_json($aimogen_result); } $appids = preg_split('/\r\n|\r|\n/', trim($aimogen_Main_Settings['app_id'])); $appids = array_filter($appids); $token = $appids[array_rand($appids)]; $token = apply_filters('aimogen_openai_api_key', $token); require_once (dirname(__FILE__) . "/res/aimogen-assistants-api.php"); $raw_storeid = ''; if ( isset( $_POST['storeid'] ) ) { $raw_storeid = wp_unslash( $_POST['storeid'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized } $storeid = sanitize_text_field( $raw_storeid ); try { $store_del = aimogen_openai_delete_vector_store($token, $storeid); if(isset($store_del->error)) { $aimogen_result['msg'] = $result->error->message; wp_send_json($aimogen_result); } } catch(Exception $e) { aimogen_log_to_file('Failed to delete vector store ID: ' . $storeid . ', exception: ' . $e->getMessage()); } $open_ai = new OpenAi($token); if(!$open_ai){ $aimogen_result['msg'] = 'Missing API Setting'; wp_send_json($aimogen_result); } if (isset($aimogen_Main_Settings['api_selector']) && trim($aimogen_Main_Settings['api_selector']) == 'custom' && isset($aimogen_Main_Settings['custom_endpoint']) && trim($aimogen_Main_Settings['custom_endpoint'], ' /') != '') { $open_ai->setCustomURL(trim($aimogen_Main_Settings['custom_endpoint'], ' /')); } if (isset($aimogen_Main_Settings['openai_organization']) && $aimogen_Main_Settings['openai_organization'] != '') { $open_ai->setORG($aimogen_Main_Settings['openai_organization']); } $delay = ''; if (isset($aimogen_Main_Settings['request_delay']) && $aimogen_Main_Settings['request_delay'] != '') { if(stristr($aimogen_Main_Settings['request_delay'], ',') !== false) { $tempo = explode(',', $aimogen_Main_Settings['request_delay']); if(isset($tempo[1]) && is_numeric(trim($tempo[1])) && is_numeric(trim($tempo[0]))) { $delay = wp_rand(trim($tempo[0]), trim($tempo[1])); } } else { if(is_numeric(trim($aimogen_Main_Settings['request_delay']))) { $delay = intval(trim($aimogen_Main_Settings['request_delay'])); } } } if($delay != '' && is_numeric($delay)) { usleep($delay); } $result = $open_ai->deleteFile(sanitize_text_field( wp_unslash($_POST['id']))); $result = json_decode($result); if(isset($result->error)) { $aimogen_result['msg'] = $result->error->message; } else { $aimogen_result['status'] = 'success'; } } wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_delete_assistant_file', 'aimogen_delete_assistant_file'); function aimogen_delete_assistant_file() { check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('edit_posts') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with finetuning deletion'); if(isset($_POST['id']) && !empty($_POST['id'])){ $aimogen_Main_Settings = get_option('aimogen_Main_Settings', false); if (!aimogen_check_if_azure($aimogen_Main_Settings) && aimogen_check_if_azure_or_others($aimogen_Main_Settings)) { $aimogen_result['msg'] = 'Claude API is not currently supported for assistant files.'; wp_send_json($aimogen_result); } $appids = preg_split('/\r\n|\r|\n/', trim($aimogen_Main_Settings['app_id'])); $appids = array_filter($appids); $token = $appids[array_rand($appids)]; $token = apply_filters('aimogen_openai_api_key', $token); if(aimogen_check_if_azure($aimogen_Main_Settings)) { $azure_endpoint = !empty($aimogen_Main_Settings['azure_endpoint']) ? trim($aimogen_Main_Settings['azure_endpoint'], '/') : ''; if (!empty($aimogen_Main_Settings['azure_api_selector_batch']) && $aimogen_Main_Settings['azure_api_selector_batch'] !== 'default') { $api_ver = '?api-version=' . $aimogen_Main_Settings['azure_api_selector_batch']; } else { $api_ver = AIMOGEN_AZURE_BATCHES_API_VERSION; } if (!$azure_endpoint) { $aimogen_result['msg'] = 'Azure endpoint is missing in settings.'; wp_send_json($aimogen_result); } $file_id = sanitize_text_field(sanitize_text_field( wp_unslash($_POST['id']))); $url = $azure_endpoint . "/openai/files/{$file_id}{$api_ver}"; $args = [ 'method' => 'DELETE', 'timeout' => 60, 'sslverify' => false, 'headers' => [ 'Content-Type' => 'application/json', 'api-key' => $token ] ]; $response = wp_remote_request($url, $args); if (is_wp_error($response)) { $aimogen_result['msg'] = $response->get_error_message(); wp_send_json($aimogen_result); } $http_code = wp_remote_retrieve_response_code($response); $body = wp_remote_retrieve_body($response); if ($http_code === 200 || $http_code === 204) { $aimogen_result['status'] = 'success'; $aimogen_result['msg'] = 'File deleted successfully.'; } else { $decoded = json_decode($body, true); $err = isset($decoded['error']['message']) ? $decoded['error']['message'] : 'Unknown error'; $aimogen_result['msg'] = "HTTP request failed with code $http_code: $err"; } } else { $open_ai = new OpenAi($token); if(!$open_ai){ $aimogen_result['msg'] = 'Missing API Setting'; wp_send_json($aimogen_result); } if (isset($aimogen_Main_Settings['api_selector']) && trim($aimogen_Main_Settings['api_selector']) == 'custom' && isset($aimogen_Main_Settings['custom_endpoint']) && trim($aimogen_Main_Settings['custom_endpoint'], ' /') != '') { $open_ai->setCustomURL(trim($aimogen_Main_Settings['custom_endpoint'], ' /')); } if (isset($aimogen_Main_Settings['openai_organization']) && $aimogen_Main_Settings['openai_organization'] != '') { $open_ai->setORG($aimogen_Main_Settings['openai_organization']); } $delay = ''; if (isset($aimogen_Main_Settings['request_delay']) && $aimogen_Main_Settings['request_delay'] != '') { if(stristr($aimogen_Main_Settings['request_delay'], ',') !== false) { $tempo = explode(',', $aimogen_Main_Settings['request_delay']); if(isset($tempo[1]) && is_numeric(trim($tempo[1])) && is_numeric(trim($tempo[0]))) { $delay = wp_rand(trim($tempo[0]), trim($tempo[1])); } } else { if(is_numeric(trim($aimogen_Main_Settings['request_delay']))) { $delay = intval(trim($aimogen_Main_Settings['request_delay'])); } } } if($delay != '' && is_numeric($delay)) { usleep($delay); } $result = $open_ai->deleteFile(sanitize_text_field( wp_unslash($_POST['id']))); $result = json_decode($result); if(isset($result->error)) { $aimogen_result['msg'] = $result->error->message; } else { $aimogen_result['status'] = 'success'; } } } wp_send_json($aimogen_result); } add_action('wp_ajax_aimogen_assistant_file_upload', 'aimogen_assistant_file_upload'); function aimogen_assistant_file_upload() { check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('edit_posts') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with file uploading'); if(isset($_FILES['file']) && empty($_FILES['file']['error'])){ $aimogen_Main_Settings = get_option('aimogen_Main_Settings', false); if (!aimogen_check_if_azure($aimogen_Main_Settings) && aimogen_check_if_azure_or_others($aimogen_Main_Settings)) { $aimogen_result['msg'] = 'Claude API is not currently supported for assistants.'; wp_send_json($aimogen_result); } $appids = preg_split('/\r\n|\r|\n/', trim($aimogen_Main_Settings['app_id'])); $appids = array_filter($appids); $token = $appids[array_rand($appids)]; $token = apply_filters('aimogen_openai_api_key', $token); $open_ai = new OpenAi($token); if(!$open_ai){ $aimogen_result['msg'] = 'Missing API Setting'; wp_send_json($aimogen_result); } if (isset($aimogen_Main_Settings['api_selector']) && trim($aimogen_Main_Settings['api_selector']) == 'custom' && isset($aimogen_Main_Settings['custom_endpoint']) && trim($aimogen_Main_Settings['custom_endpoint'], ' /') != '') { $open_ai->setCustomURL(trim($aimogen_Main_Settings['custom_endpoint'], ' /')); } if (isset($aimogen_Main_Settings['openai_organization']) && $aimogen_Main_Settings['openai_organization'] != '') { $open_ai->setORG($aimogen_Main_Settings['openai_organization']); } $raw_file_name = ''; if ( isset( $_FILES['file']['name'] ) ) { $raw_file_name = wp_unslash( $_FILES['file']['name'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized } $file_name = sanitize_file_name( basename( $raw_file_name ) ); $tmp_file = isset( $_FILES['file']['tmp_name'] ) ? sanitize_text_field(wp_unslash( $_FILES['file']['tmp_name'] )) : ''; $real_type = wp_check_filetype( $file_name ); $mime = empty( $real_type['type'] ) ? 'application/octet-stream' : $real_type['type']; //curl file required for assistants file upload $c_file = curl_file_create( $tmp_file, $mime, $file_name );// phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_file_create -- Required by OpenAI SDK $delay = ''; if (isset($aimogen_Main_Settings['request_delay']) && $aimogen_Main_Settings['request_delay'] != '') { if(stristr($aimogen_Main_Settings['request_delay'], ',') !== false) { $tempo = explode(',', $aimogen_Main_Settings['request_delay']); if(isset($tempo[1]) && is_numeric(trim($tempo[1])) && is_numeric(trim($tempo[0]))) { $delay = wp_rand(trim($tempo[0]), trim($tempo[1])); } } else { if(is_numeric(trim($aimogen_Main_Settings['request_delay']))) { $delay = intval(trim($aimogen_Main_Settings['request_delay'])); } } } if($delay != '' && is_numeric($delay)) { usleep($delay); } $purpose = 'assistants'; $result = $open_ai->uploadFile(array( 'purpose' => $purpose, 'file' => $c_file, )); $result = json_decode($result); if(isset($result->error)){ $aimogen_result['msg'] = $result->error->message; } else { $aimogen_result['msg'] = $result->id; $aimogen_result['status'] = 'success'; } } wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_assistants', 'aimogen_assistants'); function aimogen_assistants() { $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with AI Assistants'); check_ajax_referer('aimogen_assistants', 'nonce'); if ( ! current_user_can('edit_posts') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } if(defined('AIMOGEN_ASSISTANTS_API_RETIRED') && AIMOGEN_ASSISTANTS_API_RETIRED) { $aimogen_result['msg'] = 'New AI Assistant creation is disabled because OpenAI retired the Assistants API. Existing Assistant selections automatically use the default model.'; wp_send_json($aimogen_result); } $token = ''; $aimogen_Main_Settings = get_option('aimogen_Main_Settings', false); if (isset($aimogen_Main_Settings['app_id']) && trim($aimogen_Main_Settings['app_id']) != '') { $appids = preg_split('/\r\n|\r|\n/', trim($aimogen_Main_Settings['app_id'])); $appids = array_filter($appids); $token = $appids[array_rand($appids)]; $token = apply_filters('aimogen_openai_api_key', $token); } else { $aimogen_result['msg'] = 'Please set up your API key in the plugin\' settings.'; wp_send_json($aimogen_result); } if(!isset($_POST['aimogen-assistant-title']) || empty($_POST['aimogen-assistant-title'])) { $aimogen_result['msg'] = 'Empty assistant title added!'; wp_send_json($aimogen_result); } $title = sanitize_text_field( wp_unslash($_POST['aimogen-assistant-title'])); if(!isset($_POST['aimogen-assistant-prompt']) || empty($_POST['aimogen-assistant-prompt'])) { $prompt = ''; } else { $prompt = sanitize_text_field( wp_unslash($_POST['aimogen-assistant-prompt'])); } if(!isset($_POST['aimogen-assistant-model']) || empty($_POST['aimogen-assistant-model'])) { $aimogen_result['msg'] = 'Empty assistant model added!'; wp_send_json($aimogen_result); } $code_interpreter = false; if(isset($_POST['aimogen-assistant-code-interpreter']) && $_POST['aimogen-assistant-code-interpreter'] == 'on') { $code_interpreter = true; } $file_search = false; if(isset($_POST['aimogen-assistant-file_search']) && $_POST['aimogen-assistant-file_search'] == 'on') { $file_search = true; } $model = sanitize_textarea_field( wp_unslash($_POST['aimogen-assistant-model'])); $description = ''; if(isset($_POST['aimogen-assistant-description']) && !empty($_POST['aimogen-assistant-description'])) { $description = sanitize_text_field( wp_unslash($_POST['aimogen-assistant-description'])); } $topp = ''; if(isset($_POST['aimogen-assistant-topp']) && !empty($_POST['aimogen-assistant-topp'])) { $topp = sanitize_textarea_field( wp_unslash($_POST['aimogen-assistant-topp'])); } $temperature = ''; if(isset($_POST['aimogen-assistant-temperature']) && !empty($_POST['aimogen-assistant-temperature'])) { $temperature = sanitize_textarea_field( wp_unslash($_POST['aimogen-assistant-temperature'])); } $assistant_first_message = ''; if(isset($_POST['aimogen-assistant-first-message']) && !empty($_POST['aimogen-assistant-first-message'])) { $assistant_first_message = sanitize_textarea_field( wp_unslash($_POST['aimogen-assistant-first-message'])); } $avatar = ''; if(isset($_POST['aimogen-assistant-avatar'])) { $avatar = sanitize_textarea_field( wp_unslash($_POST['aimogen-assistant-avatar'])); } $functions = ''; if(isset($_POST['aimogen-assistant-functions']) && !empty($_POST['aimogen-assistant-functions'])) { $functions = sanitize_textarea_field( wp_unslash($_POST['aimogen-assistant-functions'])); } $assistant_files = []; if(isset($_POST['aimogen-assistant-files']) && !empty($_POST['aimogen-assistant-files'])) { $raw = null; if ( isset( $_POST['aimogen-assistant-files'] ) ) { $raw = wp_unslash( $_POST['aimogen-assistant-files'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized } if ( is_array( $raw ) ) { $assistant_files = array_map( static function( $item ) { return is_array( $item ) ? array_map( 'sanitize_text_field', $item ) : sanitize_text_field( $item ); }, $raw ); } if(is_array($assistant_files) && $code_interpreter === true && count($assistant_files) > 20) { $assistant_files = array_slice($assistant_files, 0, 20); } } $aimogen_result = aimogen_save_assistant($token, $title, $model, $prompt, $description, $temperature, $topp, $assistant_first_message, $avatar, $code_interpreter, $file_search, $assistant_files, $functions); wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_assistants_edit', 'aimogen_assistants_edit'); function aimogen_assistants_edit() { $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with AI Assistants editing'); check_ajax_referer('aimogen_assistants', 'nonce'); if ( ! current_user_can('edit_posts') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } $token = ''; $aimogen_Main_Settings = get_option('aimogen_Main_Settings', false); if (isset($aimogen_Main_Settings['app_id']) && trim($aimogen_Main_Settings['app_id']) != '') { $appids = preg_split('/\r\n|\r|\n/', trim($aimogen_Main_Settings['app_id'])); $appids = array_filter($appids); $token = $appids[array_rand($appids)]; $token = apply_filters('aimogen_openai_api_key', $token); } else { $aimogen_result['msg'] = 'Please set up your API key in the plugin\' settings.'; wp_send_json($aimogen_result); } if(!isset($_POST['aimogen-assistant-title']) || empty($_POST['aimogen-assistant-title'])) { $aimogen_result['msg'] = 'Empty assistant title added!'; wp_send_json($aimogen_result); } $title = sanitize_textarea_field( wp_unslash($_POST['aimogen-assistant-title'])); if(!isset($_POST['assistant_id']) || empty($_POST['assistant_id'])) { $aimogen_result['msg'] = 'Incorrect request provided!'; wp_send_json($aimogen_result); } $assistant_id_local = sanitize_textarea_field( wp_unslash($_POST['assistant_id'])); $assistant_id = get_post_meta($assistant_id_local, '_assistant_id', true); if(empty($assistant_id)) { $aimogen_result['msg'] = 'Assistant ID was not found in the database!'; wp_send_json($aimogen_result); } if(!isset($_POST['aimogen-assistant-prompt']) || empty($_POST['aimogen-assistant-prompt'])) { $prompt = ''; } else { $prompt = sanitize_textarea_field( wp_unslash($_POST['aimogen-assistant-prompt'])); } if(!isset($_POST['aimogen-assistant-model']) || empty($_POST['aimogen-assistant-model'])) { $aimogen_result['msg'] = 'Empty assistant model added!'; wp_send_json($aimogen_result); } $code_interpreter = false; if(isset($_POST['aimogen-assistant-code-interpreter']) && $_POST['aimogen-assistant-code-interpreter'] == 'on') { $code_interpreter = true; } $file_search = false; if(isset($_POST['aimogen-assistant-file_search']) && $_POST['aimogen-assistant-file_search'] == 'on') { $file_search = true; } $model = sanitize_textarea_field( wp_unslash($_POST['aimogen-assistant-model'])); $description = ''; if(isset($_POST['aimogen-assistant-description']) && !empty($_POST['aimogen-assistant-description'])) { $description = sanitize_textarea_field( wp_unslash($_POST['aimogen-assistant-description'])); } $topp = ''; if(isset($_POST['aimogen-assistant-topp']) && !empty($_POST['aimogen-assistant-topp'])) { $topp = sanitize_textarea_field( wp_unslash($_POST['aimogen-assistant-topp'])); } $temperature = ''; if(isset($_POST['aimogen-assistant-temperature']) && !empty($_POST['aimogen-assistant-temperature'])) { $temperature = sanitize_textarea_field( wp_unslash($_POST['aimogen-assistant-temperature'])); } $assistant_first_message = ''; if(isset($_POST['aimogen-assistant-first-message']) && !empty($_POST['aimogen-assistant-first-message'])) { $assistant_first_message = sanitize_textarea_field( wp_unslash($_POST['aimogen-assistant-first-message'])); } $avatar = ''; if(isset($_POST['aimogen-assistant-avatar'])) { $avatar = sanitize_textarea_field( wp_unslash($_POST['aimogen-assistant-avatar'])); } $functions = ''; if(isset($_POST['aimogen-assistant-functions']) && !empty($_POST['aimogen-assistant-functions'])) { $functions = sanitize_textarea_field( wp_unslash($_POST['aimogen-assistant-functions'])); } $assistant_files = []; if(isset($_POST['aimogen-assistant-files']) && !empty($_POST['aimogen-assistant-files'])) { $raw = null; if ( isset( $_POST['aimogen-assistant-files'] ) ) { $raw = wp_unslash( $_POST['aimogen-assistant-files'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized } if ( is_array( $raw ) ) { $assistant_files = array_map( static function( $item ) { return is_array( $item ) ? array_map( 'sanitize_text_field', $item ) : sanitize_text_field( $item ); }, $raw ); } if(is_array($assistant_files) && $code_interpreter === true && count($assistant_files) > 20) { $assistant_files = array_slice($assistant_files, 0, 20); } } $aimogen_result = aimogen_update_assistant($token, $assistant_id, $assistant_id_local, $title, $model, $prompt, $description, $temperature, $topp, $assistant_first_message, $avatar, $code_interpreter, $file_search, $assistant_files, $functions); wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_deleteall_personas', 'aimogen_deleteall_personas'); function aimogen_deleteall_personas() { $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with general persona deletion'); check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('manage_options') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } $allposts = get_posts( array('post_type'=>'aimogen_personas','numberposts'=>-1) ); foreach ($allposts as $eachpost) { wp_delete_post( $eachpost->ID, true ); } $aimogen_result['msg'] = 'Successfully deleted all personas!'; $aimogen_result['status'] = 'success'; wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_save_theme', 'aimogen_save_theme'); function aimogen_save_theme() { $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with theme saving'); check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('manage_options') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } if(!isset($_POST['post_title']) || empty($_POST['post_title'])) { $aimogen_result['msg'] = 'Empty form post_title added!'; wp_send_json($aimogen_result); } $post_title = sanitize_text_field( wp_unslash($_POST['post_title'] )); if(!isset($_POST['general_background']) || empty($_POST['general_background'])) { $aimogen_result['msg'] = 'Empty form general_background added!'; wp_send_json($aimogen_result); } $general_background = sanitize_text_field( wp_unslash($_POST['general_background'])); if(!isset($_POST['background']) || empty($_POST['background'])) { $aimogen_result['msg'] = 'Empty form background added!'; wp_send_json($aimogen_result); } $background = sanitize_text_field( wp_unslash($_POST['background'])); if(!isset($_POST['input_border_color']) || empty($_POST['input_border_color'])) { $aimogen_result['msg'] = 'Empty form input_border_color added!'; wp_send_json($aimogen_result); } $input_border_color = sanitize_text_field( wp_unslash($_POST['input_border_color'])); if(!isset($_POST['input_text_color']) || empty($_POST['input_text_color'])) { $aimogen_result['msg'] = 'Empty form input_text_color added!'; wp_send_json($aimogen_result); } $input_text_color = sanitize_text_field( wp_unslash($_POST['input_text_color'])); if(!isset($_POST['persona_name_color']) || empty($_POST['persona_name_color'])) { $aimogen_result['msg'] = 'Empty form persona_name_color added!'; wp_send_json($aimogen_result); } $persona_name_color = sanitize_text_field( wp_unslash($_POST['persona_name_color'])); if(!isset($_POST['persona_role_color']) || empty($_POST['persona_role_color'])) { $aimogen_result['msg'] = 'Empty form persona_role_color added!'; wp_send_json($aimogen_result); } $persona_role_color = sanitize_text_field( wp_unslash($_POST['persona_role_color'])); if(!isset($_POST['input_placeholder_color']) || empty($_POST['input_placeholder_color'])) { $aimogen_result['msg'] = 'Empty form input_placeholder_color added!'; wp_send_json($aimogen_result); } $input_placeholder_color = sanitize_text_field( wp_unslash($_POST['input_placeholder_color'])); if(!isset($_POST['user_background_color']) || empty($_POST['user_background_color'])) { $aimogen_result['msg'] = 'Empty form user_background_color added!'; wp_send_json($aimogen_result); } $user_background_color = sanitize_text_field( wp_unslash($_POST['user_background_color'])); if(!isset($_POST['ai_background_color']) || empty($_POST['ai_background_color'])) { $aimogen_result['msg'] = 'Empty form ai_background_color added!'; wp_send_json($aimogen_result); } $ai_background_color = sanitize_text_field( wp_unslash($_POST['ai_background_color'])); if(!isset($_POST['ai_font_color']) || empty($_POST['ai_font_color'])) { $aimogen_result['msg'] = 'Empty form ai_font_color added!'; wp_send_json($aimogen_result); } $ai_font_color = sanitize_text_field( wp_unslash($_POST['ai_font_color'])); if(!isset($_POST['user_font_color']) || empty($_POST['user_font_color'])) { $aimogen_result['msg'] = 'Empty form user_font_color added!'; wp_send_json($aimogen_result); } $user_font_color = sanitize_text_field( wp_unslash($_POST['user_font_color'])); if(!isset($_POST['submit_color']) || empty($_POST['submit_color'])) { $aimogen_result['msg'] = 'Empty form submit_color added!'; wp_send_json($aimogen_result); } $submit_color = sanitize_text_field( wp_unslash($_POST['submit_color'])); if(!isset($_POST['voice_color']) || empty($_POST['voice_color'])) { $aimogen_result['msg'] = 'Empty form voice_color added!'; wp_send_json($aimogen_result); } $voice_color = sanitize_text_field( wp_unslash($_POST['voice_color'])); if(!isset($_POST['voice_color_activated']) || empty($_POST['voice_color_activated'])) { $aimogen_result['msg'] = 'Empty form voice_color_activated added!'; wp_send_json($aimogen_result); } $voice_color_activated = sanitize_text_field( wp_unslash($_POST['voice_color_activated'])); if(!isset($_POST['submit_text_color']) || empty($_POST['submit_text_color'])) { $aimogen_result['msg'] = 'Empty form submit_text_color added!'; wp_send_json($aimogen_result); } $submit_text_color = sanitize_text_field( wp_unslash($_POST['submit_text_color'])); $encode_arr = array( 'general_background' => $general_background, 'background' => $background, 'input_border_color' => $input_border_color, 'input_text_color' => $input_text_color, 'persona_name_color' => $persona_name_color, 'persona_role_color' => $persona_role_color, 'input_placeholder_color' => $input_placeholder_color, 'user_background_color' => $user_background_color, 'ai_background_color' => $ai_background_color, 'ai_font_color' => $ai_font_color, 'user_font_color' => $user_font_color, 'submit_color' => $submit_color, 'voice_color' => $voice_color, 'voice_color_activated' => $voice_color_activated, 'submit_text_color' => $submit_text_color, ); $json_save = json_encode($encode_arr); $themes_data = array( 'post_type' => 'aimogen_themes', 'post_title' => $post_title, 'post_content' => $json_save, 'post_status' => 'publish' ); remove_filter('content_save_pre', 'wp_filter_post_kses'); remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');remove_filter('title_save_pre', 'wp_filter_kses'); $themes_id = wp_insert_post($themes_data); add_filter('content_save_pre', 'wp_filter_post_kses'); add_filter('content_filtered_save_pre', 'wp_filter_post_kses');add_filter('title_save_pre', 'wp_filter_kses'); if(is_wp_error($themes_id)) { $aimogen_result['msg'] = 'Failed to import form: ' . $themes_id->get_error_message(); wp_send_json($aimogen_result); } elseif($themes_id === 0) { $aimogen_result['msg'] = 'Failed to insert form to database: ' . json_encode($themes_data); wp_send_json($aimogen_result); } else { $aimogen_result['msg'] = 'Successfully deleted all personas!'; $aimogen_result['status'] = 'success'; wp_send_json($aimogen_result); } die(); } add_action('wp_ajax_aimogen_get_theme', 'aimogen_get_theme'); function aimogen_get_theme() { $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with theme getting'); check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('manage_options') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } if(!isset($_POST['themeid']) || empty($_POST['themeid'])) { $aimogen_result['msg'] = 'Empty form themeid added!'; wp_send_json($aimogen_result); } $themeid = sanitize_text_field( wp_unslash($_POST['themeid'])); $aimogen_theme = get_post(sanitize_text_field($themeid)); if($aimogen_theme === null || $aimogen_theme === 0) { $aimogen_result['msg'] = 'Failed to get theme ID: ' . $themeid; wp_send_json($aimogen_result); } else { $aimogen_result['msg'] = $aimogen_theme->post_content; $aimogen_result['status'] = 'success'; wp_send_json($aimogen_result); } die(); } add_action('wp_ajax_aimogen_delete_theme', 'aimogen_delete_theme'); function aimogen_delete_theme() { $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with theme deletion'); check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('manage_options') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } if(!isset($_POST['themeid'])) { $aimogen_result['msg'] = 'Incorrect AJAX call'; } else { wp_delete_post(sanitize_text_field( wp_unslash($_POST['themeid']))); $aimogen_result['status'] = 'success'; $aimogen_result['msg'] = 'Theme deleted successfully'; } wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_delete_selected_personas', 'aimogen_delete_selected_personas'); function aimogen_delete_selected_personas() { $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with persona deletion'); check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('manage_options') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } if(!isset($_POST['ids'])) { $aimogen_result['msg'] = 'Incorrect AJAX call'; } else { $deleted = false; $delids = []; $raw_ids = null; if ( isset( $_POST['ids'] ) ) { $raw_ids = wp_unslash( $_POST['ids'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized } if ( is_array( $raw_ids ) && count( $raw_ids ) ) { $delids = array_map( static function( $item ) { return is_array( $item ) ? array_map( 'sanitize_text_field', $item ) : sanitize_text_field( $item ); }, $raw_ids ); foreach ( $delids as $id ) { wp_delete_post( $id ); $deleted = true; } } if($deleted === true) { $aimogen_result['status'] = 'success'; $aimogen_result['msg'] = 'Personas deleted successfully'; } } wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_delete_selected_assistants', 'aimogen_delete_selected_assistants'); function aimogen_delete_selected_assistants() { $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with assistant deletion'); check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('manage_options') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } if(!isset($_POST['ids'])) { $aimogen_result['msg'] = 'Incorrect AJAX call'; } else { $token = ''; $aimogen_Main_Settings = get_option('aimogen_Main_Settings', false); if (isset($aimogen_Main_Settings['app_id']) && trim($aimogen_Main_Settings['app_id']) != '') { $appids = preg_split('/\r\n|\r|\n/', trim($aimogen_Main_Settings['app_id'])); $appids = array_filter($appids); $token = $appids[array_rand($appids)]; $token = apply_filters('aimogen_openai_api_key', $token); } else { $aimogen_result['msg'] = 'Please set up your API key in the plugin\' settings.'; wp_send_json($aimogen_result); } require_once (dirname(__FILE__) . "/res/aimogen-assistants-api.php"); $deleted = false; $errors = ''; if(count($_POST['ids'])) { $delids = []; $raw_ids = null; if ( isset( $_POST['ids'] ) ) { $raw_ids = wp_unslash( $_POST['ids'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized } if ( is_array( $raw_ids ) ) { $delids = array_map( static function( $item ) { return is_array( $item ) ? array_map( 'sanitize_text_field', $item ) : sanitize_text_field( $item ); }, $raw_ids ); } foreach ($delids as $id) { $assistant_id = get_post_meta($id, '_assistant_id', true); if(!empty($assistant_id)) { try { aimogen_openai_delete_assistant($token, $assistant_id); } catch(Exception $e) { $errors .= 'Failed to delete assistant ID: ' . $assistant_id . ', exception: ' . $e->getMessage() . '\n'; } } $vector_store_id = get_post_meta($id, '_assistant_vector_store_id', true); if(!empty($vector_store_id)) { try { aimogen_openai_delete_vector_store($token, $vector_store_id); } catch(Exception $e) { aimogen_log_to_file('Failed to delete vector store ID: ' . $vector_store_id . ', exception: ' . $e->getMessage()); } } wp_delete_post($id); $deleted = true; } } if(!empty($errors)) { $aimogen_result['msg'] = 'Assistant failed to be deleted: ' . $errors; wp_send_json($aimogen_result); } if($deleted === true) { $aimogen_result['status'] = 'success'; $aimogen_result['msg'] = 'Assistant deleted successfully'; } } wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_delete_selected_templates', 'aimogen_delete_selected_templates'); function aimogen_delete_selected_templates() { $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with OmniBlock template deletion'); check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('manage_options') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } if(!isset($_POST['ids'])) { $aimogen_result['msg'] = 'Incorrect AJAX call'; } else { $deleted = false; $delids = []; $raw_ids = null; if ( isset( $_POST['ids'] ) ) { $raw_ids = wp_unslash( $_POST['ids'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized } if ( is_array( $raw_ids ) ) { $delids = array_map( static function( $item ) { return is_array( $item ) ? array_map( 'sanitize_text_field', $item ) : sanitize_text_field( $item ); }, $raw_ids ); } if(count($delids)) { foreach ($delids as $id) { wp_delete_post($id); $deleted = true; } } if($deleted === true) { $aimogen_result['status'] = 'success'; $aimogen_result['msg'] = 'OmniBlock templates deleted successfully'; } } wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_delete_all_templates', 'aimogen_delete_all_templates'); function aimogen_delete_all_templates() { $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with OmniBlock template deletion'); check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('manage_options') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } $deleted = false; $allposts = get_posts(array('post_type'=>'aimogen_omni_temp','numberposts'=>-1)); foreach ($allposts as $eachpost) { wp_delete_post($eachpost->ID, true); $deleted = true; } if($deleted === true) { $aimogen_result['status'] = 'success'; $aimogen_result['msg'] = 'OmniBlock templates deleted successfully'; } else { $aimogen_result['msg'] = 'No OmniBlock templates found to be deleted'; } wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_delete_selected_files', 'aimogen_delete_selected_files'); function aimogen_delete_selected_files() { $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with OmniBlock file deletion'); check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('manage_options') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } if(!isset($_POST['ids'])) { $aimogen_result['msg'] = 'Incorrect AJAX call'; } else { $deleted = false; $delids = []; $raw_ids = null; if ( isset( $_POST['ids'] ) ) { $raw_ids = wp_unslash( $_POST['ids'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized } if ( is_array( $raw_ids ) ) { $delids = array_map( static function ( $item ) { return is_array( $item ) ? array_map( 'sanitize_text_field', $item ) : sanitize_text_field( $item ); }, $raw_ids ); } if(count($delids)) { foreach ($delids as $id) { $this_post = get_post($id); if($this_post === null) { $aimogen_result['msg'] = 'Incorrect post_id sent'; wp_send_json($aimogen_result); } $local_id = get_post_meta($id, 'local_id', true); if(empty($local_id)) { $aimogen_result['msg'] = 'Local file path not found'; wp_send_json($aimogen_result); } $file_type = ''; $terms = wp_get_object_terms( $id, 'aimogen_file_type' ); if(!is_wp_error($terms)) { foreach($terms as $tm) { $file_type = $tm->slug; break; } } if($file_type == 'local') { global $wp_filesystem; if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){ require_once ABSPATH . 'wp-admin/includes/file.php'; $creds = request_filesystem_credentials( site_url() ); wp_filesystem($creds); } $wp_filesystem->delete($local_id); } wp_delete_post($id); $deleted = true; } } if($deleted === true) { $aimogen_result['status'] = 'success'; $aimogen_result['msg'] = 'OmniBlock files deleted successfully'; } } wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_save_editor_template', 'aimogen_save_editor_template'); function aimogen_save_editor_template() { $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with AI Content Editor template creation'); check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('manage_options') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } if(!isset($_POST['editor_template_new']) || empty($_POST['editor_template_new']) || !isset($_POST['extractedData']) || empty($_POST['extractedData'])) { $aimogen_result['msg'] = 'Incorrect AJAX call'; } else { $raw_extracted = ''; if ( isset( $_POST['extractedData'] ) ) { $raw_extracted = wp_unslash( $_POST['extractedData'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized } $decoded = json_decode( $raw_extracted, true ); if ( json_last_error() !== JSON_ERROR_NONE || ! is_array( $decoded ) ) { $aimogen_result['msg'] = 'Invalid JSON data received.'; wp_send_json( $aimogen_result ); } $sanitized = array_map( static function ( $value ) { return is_array( $value ) ? array_map( 'sanitize_text_field', $value ) : sanitize_text_field( $value ); }, $decoded ); $safe_json = wp_json_encode( $sanitized ); $ai_data = array( 'post_type' => 'aimogen_editor_temp', 'post_title' => sanitize_text_field( wp_unslash($_POST['editor_template_new'])), 'post_content' => '', 'post_status' => 'publish' ); remove_filter('content_save_pre', 'wp_filter_post_kses'); remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');remove_filter('title_save_pre', 'wp_filter_kses'); $omni_id = wp_insert_post($ai_data); add_filter('content_save_pre', 'wp_filter_post_kses'); add_filter('content_filtered_save_pre', 'wp_filter_post_kses');add_filter('title_save_pre', 'wp_filter_kses'); if(is_wp_error($omni_id)) { aimogen_log_to_file('Failed to insert AI Content Editor template: ' . $omni_id->get_error_message()); } elseif($omni_id === 0) { aimogen_log_to_file('Failed to insert AI Content Editor template: ' . json_encode($ai_data)); } else { update_post_meta($omni_id, 'aimogen_json', $safe_json); $aimogen_result['status'] = 'success'; $aimogen_result['msg'] = 'AI Content Editor template inserted successfully'; } } wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_rename_editor_template', 'aimogen_rename_editor_template'); function aimogen_rename_editor_template() { $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with AI Content Editor template creation'); check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('manage_options') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } if(!isset($_POST['editor_template_new']) || empty($_POST['editor_template_new']) || !isset($_POST['selected']) || empty($_POST['selected'])) { $aimogen_result['msg'] = 'Incorrect AJAX call'; } else { $template_name = sanitize_text_field( wp_unslash($_POST['editor_template_new']) ); $selected = sanitize_text_field( wp_unslash($_POST['selected'])); if ( get_post_status( $selected ) ) { $ai_data = array( 'ID' => $selected, 'post_title' => $template_name, ); remove_filter('content_save_pre', 'wp_filter_post_kses'); remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');remove_filter('title_save_pre', 'wp_filter_kses'); $za_id = wp_update_post($ai_data); add_filter('content_save_pre', 'wp_filter_post_kses'); add_filter('content_filtered_save_pre', 'wp_filter_post_kses');add_filter('title_save_pre', 'wp_filter_kses'); if(is_wp_error($za_id)) { aimogen_log_to_file('Failed to insert AI Content Editor template: ' . $za_id->get_error_message()); } elseif($za_id === 0) { aimogen_log_to_file('Failed to insert AI Content Editor template: ' . json_encode($ai_data)); } else { $aimogen_result['status'] = 'success'; $aimogen_result['msg'] = 'AI Content Editor template updated successfully'; } } else { $aimogen_result['msg'] = 'AI Content Editor template ID not found: ' . $selected; } } wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_overwrite_editor_template', 'aimogen_overwrite_editor_template'); function aimogen_overwrite_editor_template() { $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with AI Content Editor template overwriting'); check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('manage_options') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } if(!isset($_POST['selected']) || empty($_POST['selected']) || !isset($_POST['extractedData']) || empty($_POST['extractedData'])) { $aimogen_result['msg'] = 'Incorrect AJAX call'; } else { $raw_extracted = ''; if ( isset( $_POST['extractedData'] ) ) { $raw_extracted = wp_unslash( $_POST['extractedData'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized } $decoded = json_decode( $raw_extracted, true ); if ( json_last_error() !== JSON_ERROR_NONE || ! is_array( $decoded ) ) { $aimogen_result['msg'] = 'Invalid JSON data received.'; wp_send_json( $aimogen_result ); } $sanitized = array_map( static function ( $value ) { return is_array( $value ) ? array_map( 'sanitize_text_field', $value ) : sanitize_text_field( $value ); }, $decoded ); $safe_json = wp_json_encode( $sanitized ); $selected = sanitize_text_field( wp_unslash($_POST['selected'])); if ( get_post_status( $selected ) ) { update_post_meta($selected, 'aimogen_json', $safe_json); $aimogen_result['status'] = 'success'; $aimogen_result['msg'] = 'AI Content Editor template overwritten successfully'; } else { $aimogen_result['msg'] = 'AI Content Editor template ID not found: ' . $selected; } } wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_delete_editor_template', 'aimogen_delete_editor_template'); function aimogen_delete_editor_template() { $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with AI Content Editor template deletion'); check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('manage_options') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } if(!isset($_POST['selected']) || empty($_POST['selected'])) { $aimogen_result['msg'] = 'Incorrect AJAX call'; } else { $selected = sanitize_text_field( wp_unslash($_POST['selected'])); if ( get_post_status( $selected ) ) { wp_delete_post($selected, true); $aimogen_result['status'] = 'success'; $aimogen_result['msg'] = 'AI Content Editor template deleted successfully'; } else { $aimogen_result['msg'] = 'AI Content Editor template ID not found: ' . $selected; } } wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_load_editor_template', 'aimogen_load_editor_template'); function aimogen_load_editor_template() { $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with AI Content Editor template loading'); check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('edit_posts') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } if(!isset($_POST['selected']) || empty($_POST['selected'])) { $aimogen_result['msg'] = 'Incorrect AJAX call'; } else { $selected = sanitize_text_field( wp_unslash($_POST['selected'])); if ( get_post_status( $selected ) ) { $json_back = get_post_meta($selected, 'aimogen_json', true); if(empty($json_back)) { $aimogen_result['msg'] = 'Incorrect template structure found for ID: ' . $selected; wp_send_json($aimogen_result); } if(is_string($json_back)) { $json_back = str_replace("\\'", "'", $json_back); $json_back = str_replace("'", "\\\\'", $json_back); $saved_tmp = json_decode($json_back, true); } else { $saved_tmp = $json_back; } if($saved_tmp === null) { if (json_last_error() !== JSON_ERROR_NONE) { aimogen_log_to_file("Failed to decode templaet json: " . json_last_error_msg()); } $aimogen_result['msg'] = 'AI Content Editor edit template failed to be decoded: ' . $selected; wp_send_json($aimogen_result); } $aimogen_Spinner_Settings = get_option('aimogen_Spinner_Settings', array()); foreach($saved_tmp as $theindex => $thevalue) { $aimogen_Spinner_Settings[$theindex] = $thevalue; } aimogen_update_option('aimogen_Spinner_Settings', $aimogen_Spinner_Settings); aimogen_update_option('aimogen_loaded_template', $selected); $aimogen_result['status'] = 'success'; $aimogen_result['msg'] = 'AI Content Editor template loaded successfully'; } else { $aimogen_result['msg'] = 'AI Content Editor template ID not found: ' . $selected; } } wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_sync_assistants', 'aimogen_sync_assistants'); function aimogen_sync_assistants() { $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with assistant importing'); check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('edit_posts') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } $token = ''; $imported = false; $aimogen_Main_Settings = get_option('aimogen_Main_Settings', false); if (isset($aimogen_Main_Settings['app_id']) && trim($aimogen_Main_Settings['app_id']) != '') { $appids = preg_split('/\r\n|\r|\n/', trim($aimogen_Main_Settings['app_id'])); $appids = array_filter($appids); $token = $appids[array_rand($appids)]; $token = apply_filters('aimogen_openai_api_key', $token); } else { $aimogen_result['msg'] = 'Please set up your API key in the plugin\' settings.'; wp_send_json($aimogen_result); } require_once (dirname(__FILE__) . "/res/aimogen-assistants-api.php"); try { $all_assistants = aimogen_openai_list_assistants($token); if(empty($all_assistants)) { $aimogen_result['msg'] = 'No assistants to import.'; wp_send_json($aimogen_result); } foreach($all_assistants as $my_assistant) { $vector_store_id = ''; if(isset($my_assistant['tool_resources']['file_search']['vector_store_ids'][0])) { $vector_store_id = $my_assistant['tool_resources']['file_search']['vector_store_ids'][0]; } $file_ids = array(); if(isset($my_assistant['tool_resources']['code_interpreter']['file_ids'][0])) { $file_ids = $my_assistant['tool_resources']['code_interpreter']['file_ids']; } $result = aimogen_save_assistant_only_local($token, $my_assistant['name'], $my_assistant['model'], $my_assistant['instructions'], $my_assistant['description'], $my_assistant['temperature'], $my_assistant['top_p'], '', '', $file_ids, $my_assistant['id'], $my_assistant['created_at'], $my_assistant['tools'], $vector_store_id); if(!isset($result['id'])) { $aimogen_result['msg'] = 'Failed to import assistant: ' . json_encode($result); } else { $imported = true; } } } catch(Exception $e) { $aimogen_result['msg'] = 'Exception while importing assistants: ' . $e->getMessage(); } if($imported === true) { $aimogen_result['status'] = 'success'; $aimogen_result['msg'] = 'Assistant imported successfully'; } wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_get_persona', 'aimogen_get_persona'); function aimogen_get_persona() { $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with persona query'); check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('edit_posts') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } if(!isset($_POST['ids'])) { $aimogen_result['msg'] = 'Incorrect AJAX call'; } else { $persona = false; $aimogen_persona = get_post(sanitize_text_field( wp_unslash($_POST['ids'])), ARRAY_A); if ($aimogen_persona) { $avatar = get_the_post_thumbnail_url($aimogen_persona['ID'], 'thumbnail'); $avatarid = get_post_thumbnail_id($aimogen_persona['ID']); $message = get_post_meta($aimogen_persona['ID'], '_persona_first_message', true); $model = get_post_meta($aimogen_persona['ID'], '_persona_model', true); $onlyKeys = ['ID', 'post_content','post_title', 'post_excerpt']; $aimogen_persona = array_filter($aimogen_persona, function($v) use ($onlyKeys) { return in_array($v, $onlyKeys); }, ARRAY_FILTER_USE_KEY); $aimogen_persona['avatar'] = $avatar; $aimogen_persona['avatarid'] = $avatarid; $aimogen_persona['message'] = $message; $aimogen_persona['model'] = $model; $persona = json_encode($aimogen_persona); } if($persona !== false) { $aimogen_result['status'] = 'success'; $aimogen_result['msg'] = $persona; } } wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_duplicate_persona', 'aimogen_duplicate_persona'); function aimogen_duplicate_persona() { $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with persona duplication'); if(!isset($_POST['personaid'])) { $aimogen_result['msg'] = 'Incorrect AJAX call'; } else { check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('edit_posts') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } $personaid = sanitize_text_field( wp_unslash($_POST['personaid'])); $original_persona = get_post($personaid); if($original_persona == null) { $aimogen_result['msg'] = 'Persona id was not found!'; wp_send_json($aimogen_result); } $first_message = get_post_meta($personaid, '_persona_first_message', true); $model = get_post_meta($personaid, '_persona_model', true); $original_persona->post_date = wp_date('Y-m-d H:i:s'); $avatar = get_post_thumbnail_id($original_persona->ID); unset($original_persona->ID); remove_filter('content_save_pre', 'wp_filter_post_kses'); remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');remove_filter('title_save_pre', 'wp_filter_kses'); $persona_id = wp_insert_post($original_persona); add_filter('content_save_pre', 'wp_filter_post_kses'); add_filter('content_filtered_save_pre', 'wp_filter_post_kses');add_filter('title_save_pre', 'wp_filter_kses'); if(is_wp_error($persona_id)) { $aimogen_result['msg'] = 'Failed to save duplicated persona!'; wp_send_json($aimogen_result); } if($avatar > 0) { if(!function_exists('set_post_thumbnail')) { require_once(ABSPATH . 'wp-admin/includes/image.php'); require_once(ABSPATH . 'wp-admin/includes/media.php'); } set_post_thumbnail( $persona_id, $avatar ); } if(!empty($first_message)) { update_post_meta($persona_id, '_persona_first_message', $first_message); } if(!empty($model)) { update_post_meta($persona_id, '_persona_model', $model); } $aimogen_result['status'] = 'success'; $aimogen_result['id'] = $persona_id; $aimogen_result['msg'] = 'Success'; } wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_convert_persona', 'aimogen_convert_persona'); function aimogen_convert_persona() { $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with persona duplication'); if(!isset($_POST['personaid'])) { $aimogen_result['msg'] = 'Incorrect AJAX call'; } else { check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('edit_posts') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } $aimogen_Main_Settings = get_option('aimogen_Main_Settings', false); if (!isset($aimogen_Main_Settings['app_id']) || trim($aimogen_Main_Settings['app_id']) == '') { $aimogen_result['msg'] = 'You need to add an API key in plugin settings for this shortcode to work.'; wp_send_json($aimogen_result); } else { $appids = preg_split('/\r\n|\r|\n/', trim($aimogen_Main_Settings['app_id'])); $appids = array_filter($appids); $token = $appids[array_rand($appids)]; $token = apply_filters('aimogen_openai_api_key', $token); if(empty($token)) { $aimogen_result['msg'] = 'Invalid API key submitted'; wp_send_json($aimogen_result); } } $personaid = sanitize_text_field( wp_unslash($_POST['personaid'])); $original_persona = get_post($personaid); if($original_persona == null) { $aimogen_result['msg'] = 'Persona id was not found!'; wp_send_json($aimogen_result); } $assistant_first_message = get_post_meta($personaid, '_persona_first_message', true); $xmodel = get_post_meta($personaid, '_persona_model', true); if(empty($xmodel)) { $xmodel = AIMOGEN_DEFAULT_MODEL; } $featured_image = get_post_thumbnail_id($personaid); $vector_store_id = ''; $metadata = ''; require_once (dirname(__FILE__) . "/res/aimogen-assistants-api.php"); $assistantData = aimogen_openai_save_assistant( $token, AIMOGEN_DEFAULT_MODEL, $original_persona->post_title, $original_persona->post_excerpt, 0, 0, $original_persona->post_content, [], [], $metadata, $vector_store_id ); if($assistantData === false) { $aimogen_result['msg'] = 'Failed to save assistant using the API'; wp_send_json($aimogen_result); } else { if(isset($assistantData['id'])) { $assistant_id = $assistantData['id']; } else { $aimogen_result['msg'] = 'Failed to save assistant using the API!'; wp_send_json($aimogen_result); } } $errors = ''; try { $file_ids = array(); $result = aimogen_save_assistant_only_local($token, $original_persona->post_title, $xmodel, $original_persona->post_content, $original_persona->post_excerpt, 0, 0, $assistant_first_message, $featured_image, $file_ids, $assistant_id, time(), [], $vector_store_id); if(!isset($result['id'])) { $aimogen_result['msg'] = 'Failed to import assistant: ' . json_encode($result); } } catch(Exception $e) { $errors .= 'Failed to duplicate assistant ID locally: ' . $assistant_id . ', exception: ' . $e->getMessage() . '\n'; } if(!empty($errors)) { $aimogen_result['msg'] = 'Assistant failed to be duplicated: ' . $errors; wp_send_json($aimogen_result); } $aimogen_result['status'] = 'success'; $aimogen_result['id'] = $assistant_id; $aimogen_result['msg'] = 'Success'; } wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_delete_assistant', 'aimogen_delete_assistant'); function aimogen_delete_assistant() { $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with singular assistant deletion'); if(!isset($_POST['assistantid'])) { $aimogen_result['msg'] = 'Incorrect AJAX call'; } else { check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('manage_options') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } $aimogen_Main_Settings = get_option('aimogen_Main_Settings', false); if (!isset($aimogen_Main_Settings['app_id']) || trim($aimogen_Main_Settings['app_id']) == '') { $aimogen_result['msg'] = 'You need to add an API key in plugin settings for this shortcode to work.'; wp_send_json($aimogen_result); } else { $appids = preg_split('/\r\n|\r|\n/', trim($aimogen_Main_Settings['app_id'])); $appids = array_filter($appids); $token = $appids[array_rand($appids)]; $token = apply_filters('aimogen_openai_api_key', $token); if(empty($token)) { $aimogen_result['msg'] = 'Invalid API key submitted'; wp_send_json($aimogen_result); } } require_once (dirname(__FILE__) . "/res/aimogen-assistants-api.php"); $errors = ''; $assistant_id = get_post_meta(sanitize_text_field( wp_unslash($_POST['assistantid'])), '_assistant_id', true); if(!empty($assistant_id)) { try { aimogen_openai_delete_assistant($token, $assistant_id); } catch(Exception $e) { $errors .= 'Failed to delete assistant ID: ' . $assistant_id . ', exception: ' . $e->getMessage() . '\n'; } } $vector_store_id = get_post_meta(sanitize_text_field( wp_unslash($_POST['assistantid'])), '_assistant_vector_store_id', true); if(!empty($vector_store_id)) { try { aimogen_openai_delete_vector_store($token, $vector_store_id); } catch(Exception $e) { aimogen_log_to_file('Failed to delete vector store ID: ' . $vector_store_id . ', exception: ' . $e->getMessage()); } } wp_delete_post(sanitize_text_field( wp_unslash($_POST['assistantid']))); if(!empty($errors)) { $aimogen_result['msg'] = 'Assistant failed to be deleted: ' . $errors; wp_send_json($aimogen_result); } $aimogen_result['status'] = 'success'; $aimogen_result['id'] = sanitize_text_field( wp_unslash($_POST['assistantid'])); $aimogen_result['msg'] = 'Success'; } wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_convert_assistant', 'aimogen_convert_assistant'); function aimogen_convert_assistant() { $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with singular assistant convertion'); if(!isset($_POST['assistantid'])) { $aimogen_result['msg'] = 'Incorrect AJAX call'; } else { $assitant_id = sanitize_text_field( wp_unslash($_POST['assistantid'])); if ( ! current_user_can('edit_posts') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } check_ajax_referer('openai-ajax-nonce', 'nonce'); $this_post = get_post($assitant_id); if($this_post === null) { $aimogen_result['msg'] = 'Incorrect post_id sent'; wp_send_json($aimogen_result); } $personas_data = array( 'post_type' => 'aimogen_personas', 'post_title' => $this_post->post_title, 'post_excerpt' => $this_post->post_excerpt, 'post_content' => $this_post->post_content, 'post_status' => 'publish' ); remove_filter('content_save_pre', 'wp_filter_post_kses'); remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');remove_filter('title_save_pre', 'wp_filter_kses'); $personas_id = wp_insert_post($personas_data); if(is_wp_error($personas_id)) { $aimogen_result['msg'] = 'Failed to save persona!'; wp_send_json($aimogen_result); } add_filter('content_save_pre', 'wp_filter_post_kses'); add_filter('content_filtered_save_pre', 'wp_filter_post_kses');add_filter('title_save_pre', 'wp_filter_kses'); $assistant_first_message = get_post_meta($assitant_id, '_assistant_first_message', true); $model = get_post_meta($assitant_id, '_assistant_model', true); $featured_image = get_post_thumbnail_id($assitant_id); if(is_numeric($featured_image)) { if($featured_image > 0) { if(!function_exists('set_post_thumbnail')) { require_once(ABSPATH . 'wp-admin/includes/image.php'); require_once(ABSPATH . 'wp-admin/includes/media.php'); } set_post_thumbnail( $personas_id, $featured_image ); } } update_post_meta($personas_id, '_persona_first_message', $assistant_first_message); update_post_meta($personas_id, '_persona_model', $model); $aimogen_result['status'] = 'success'; $aimogen_result['id'] = $personas_id; $aimogen_result['msg'] = 'Success'; } wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_duplicate_assistant', 'aimogen_duplicate_assistant'); function aimogen_duplicate_assistant() { $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with singular assistant duplication'); if(!isset($_POST['assistantid'])) { $aimogen_result['msg'] = 'Incorrect AJAX call'; } else { check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('edit_posts') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } $vector_store_id = ''; $aimogen_Main_Settings = get_option('aimogen_Main_Settings', false); if (!isset($aimogen_Main_Settings['app_id']) || trim($aimogen_Main_Settings['app_id']) == '') { $aimogen_result['msg'] = 'You need to add an API key in plugin settings for this shortcode to work.'; wp_send_json($aimogen_result); } else { $appids = preg_split('/\r\n|\r|\n/', trim($aimogen_Main_Settings['app_id'])); $appids = array_filter($appids); $token = $appids[array_rand($appids)]; $token = apply_filters('aimogen_openai_api_key', $token); if(empty($token)) { $aimogen_result['msg'] = 'Invalid API key submitted'; wp_send_json($aimogen_result); } } $original_assistant = get_post(sanitize_text_field( wp_unslash($_POST['assistantid'])), ARRAY_A); if($original_assistant == null) { $aimogen_result['msg'] = 'Assistant id was not found!'; wp_send_json($aimogen_result); } require_once (dirname(__FILE__) . "/res/aimogen-assistants-api.php"); $errors = ''; $assistant_id = get_post_meta(sanitize_text_field( wp_unslash($_POST['assistantid'])), '_assistant_id', true); $assistant_first_message = get_post_meta(sanitize_text_field( wp_unslash($_POST['assistantid'])), '_assistant_first_message', true); $featured_image = get_post_thumbnail_id(sanitize_text_field( wp_unslash($_POST['assistantid']))); $new_id = false; if(!empty($assistant_id)) { try { $new_id = aimogen_openai_duplicate_assistant($token, $assistant_id, $vector_store_id); } catch(Exception $e) { $errors .= 'Failed to duplicate assistant ID: ' . $assistant_id . ', exception: ' . $e->getMessage() . '\n'; } } if($new_id !== false) { try { $file_ids = array(); if(isset($new_id['tool_resources']['code_interpreter']['file_ids'][0])) { $file_ids = $new_id['tool_resources']['code_interpreter']['file_ids']; } $result = aimogen_save_assistant_only_local($token, $new_id['name'], $new_id['model'], $new_id['instructions'], $new_id['description'], $new_id['temperature'], $new_id['top_p'], $assistant_first_message, $featured_image, $file_ids, $new_id['id'], $new_id['created_at'], $new_id['tools'], $vector_store_id); if(!isset($result['id'])) { $aimogen_result['msg'] = 'Failed to import assistant: ' . json_encode($result); } } catch(Exception $e) { $errors .= 'Failed to duplicate assistant ID locally: ' . $assistant_id . ', exception: ' . $e->getMessage() . '\n'; } if(!empty($errors)) { $aimogen_result['msg'] = 'Assistant failed to be duplicated: ' . $errors; wp_send_json($aimogen_result); } $aimogen_result['status'] = 'success'; $aimogen_result['id'] = sanitize_text_field( wp_unslash($_POST['assistantid'])); $aimogen_result['msg'] = 'Success'; } } wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_get_assistant', 'aimogen_get_assistant_ajax'); function aimogen_get_assistant_ajax() { $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with singular assistant getting'); if(!isset($_POST['assistantid'])) { $aimogen_result['msg'] = 'Incorrect AJAX call'; } else { check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('edit_posts') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } $original_assistant = get_post(sanitize_text_field( wp_unslash($_POST['assistantid'])), ARRAY_A); if($original_assistant == null) { $aimogen_result['msg'] = 'Assistant id was not found!'; wp_send_json($aimogen_result); } $code_interpreter = false; $file_search = false; $functions = []; $tools = get_post_meta($original_assistant['ID'], '_assistant_tools', true); if(!empty($tools)) { foreach($tools as $tool) { if($tool['type'] == 'code_interpreter') { $code_interpreter = true; } elseif($tool['type'] == 'file_search') { $file_search = true; } elseif($tool['type'] == 'function') { $functions[] = $tool['function']; } } } $assistant_first_message = get_post_meta($original_assistant['ID'], '_assistant_first_message', true); $assistant_model = get_post_meta($original_assistant['ID'], '_assistant_model', true); $assistant_files = get_post_meta($original_assistant['ID'], '_assistant_files', true); $assistant_id = get_post_meta($original_assistant['ID'], '_assistant_id', true); $temperature = get_post_meta($original_assistant['ID'], '_assistant_temperature', true); $topp = get_post_meta($original_assistant['ID'], '_assistant_topp', true); $vector_store_id = get_post_meta($original_assistant['ID'], '_assistant_vector_store_id', true); $original_assistant['code_interpreter'] = $code_interpreter; $original_assistant['file_search'] = $file_search; $original_assistant['functions'] = $functions; $original_assistant['assistant_first_message'] = $assistant_first_message; $original_assistant['assistant_model'] = $assistant_model; $original_assistant['assistant_files'] = $assistant_files; $original_assistant['assistant_id'] = $assistant_id; $original_assistant['temperature'] = $temperature; $original_assistant['topp'] = $topp; $original_assistant['vector_store_id'] = $vector_store_id; $original_assistant['featured_image'] = get_post_thumbnail_id($original_assistant['ID']); if($original_assistant['featured_image'] === false) { $original_assistant['featured_image'] = 0; } $aimogen_result['status'] = 'success'; $aimogen_result['data'] = $original_assistant; } wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_sync_assistant', 'aimogen_sync_assistant_ajax'); function aimogen_sync_assistant_ajax() { $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with singular assistant sync'); if(!isset($_POST['assistantid'])) { $aimogen_result['msg'] = 'Incorrect AJAX call'; } else { check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('edit_posts') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } $original_assistant = get_post(sanitize_text_field( wp_unslash($_POST['assistantid'])), ARRAY_A); if($original_assistant == null) { $aimogen_result['msg'] = 'Assistant id was not found!'; wp_send_json($aimogen_result); } $ass_id = get_post_meta($original_assistant['ID'], '_assistant_id', true); if(empty($ass_id)) { $aimogen_result['msg'] = 'OpenAI assistant id was not found!'; wp_send_json($aimogen_result); } $aimogen_Main_Settings = get_option('aimogen_Main_Settings', false); if (!isset($aimogen_Main_Settings['app_id']) || trim($aimogen_Main_Settings['app_id']) == '') { $aimogen_result['msg'] = 'You need to add an API key in plugin settings for this shortcode to work.'; wp_send_json($aimogen_result); } else { $appids = preg_split('/\r\n|\r|\n/', trim($aimogen_Main_Settings['app_id'])); $appids = array_filter($appids); $token = $appids[array_rand($appids)]; $token = apply_filters('aimogen_openai_api_key', $token); if(empty($token)) { $aimogen_result['msg'] = 'Invalid API key submitted'; wp_send_json($aimogen_result); } } require_once (dirname(__FILE__) . "/res/aimogen-assistants-api.php"); try { $assistant = aimogen_openai_retrieve_assistant($token, $ass_id); if(!isset($assistant['id'])) { throw new Exception('Incorrect response from assistant grabbing: ' . json_encode($assistant)); } } catch(Exception $e) { $aimogen_result['msg'] = 'Exception in assistant grabbing: ' . $e->getMessage(); wp_send_json($aimogen_result); } if(empty($assistant['name'])) { $assistant['name'] = 'Untitled Assistant'; } if(empty($assistant['instructions'])) { $assistant['instructions'] = ''; } if(empty($assistant['description'])) { $assistant['description'] = ''; } $assistant_data = array( 'post_type' => 'aimogen_assistants', 'post_title' => $assistant['name'], 'post_content' => $assistant['instructions'], 'post_excerpt' => $assistant['description'], 'post_status' => 'publish', 'ID' => $original_assistant['ID'] ); remove_filter('content_save_pre', 'wp_filter_post_kses'); remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');remove_filter('title_save_pre', 'wp_filter_kses'); $local_assistant_id = wp_update_post($assistant_data); add_filter('content_save_pre', 'wp_filter_post_kses'); add_filter('content_filtered_save_pre', 'wp_filter_post_kses');add_filter('title_save_pre', 'wp_filter_kses'); if(is_wp_error($local_assistant_id)) { $aimogen_result['msg'] = $local_assistant_id->get_error_message(); } elseif($local_assistant_id === 0) { $aimogen_result['msg'] = 'Failed to update assistant to database: ' . $assistant['name']; } else { update_post_meta($local_assistant_id, '_assistant_model', $assistant['model']); update_post_meta($local_assistant_id, '_assistant_tools', (array) $assistant['tools']); $file_ids = array(); if(isset($assistant['tool_resources']['code_interpreter']['file_ids'][0])) { $file_ids = $assistant['tool_resources']['code_interpreter']['file_ids']; } update_post_meta($local_assistant_id, '_assistant_files', $file_ids); $aimogen_result['status'] = 'success'; $aimogen_result['id'] = $local_assistant_id; } } wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_delete_persona', 'aimogen_delete_persona'); function aimogen_delete_persona() { $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with singular persona deletion'); if(!isset($_POST['personaid'])) { $aimogen_result['msg'] = 'Incorrect AJAX call'; } else { check_ajax_referer('openai-ajax-nonce', 'nonce'); if ( ! current_user_can('manage_options') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } $aimogen_result['status'] = 'success'; $aimogen_result['id'] = sanitize_text_field( wp_unslash($_POST['personaid'])); $aimogen_result['msg'] = 'Success'; wp_delete_post(sanitize_text_field( wp_unslash($_POST['personaid']))); } wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_erase_action', 'aimogen_erase_action'); function aimogen_erase_action() { check_ajax_referer('openai-run-nonce', 'nonce'); if ( ! current_user_can('manage_options') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } $param = ''; if(isset($_POST['id'])) { $param = sanitize_text_field( wp_unslash($_POST['id'])); } else { aimogen_log_to_file('Incorrect POST request sent'); echo 'fail'; die(); } $rules = get_option('aimogen_omni_list', array()); if (!empty($rules)) { $found = 0; $cont = 0; $main_keywords = ''; foreach ($rules as $request => $bundle[]) { if ($cont == $param) { $bundle_values = array_values($bundle); $myValues = $bundle_values[$cont]; $array_my_values = array_values($myValues);for($iji=0;$iji esc_html__("You need to log in to perform this action!", 'aimogen') ) ); } } if(!isset($_POST['prompt'])) { wp_send_json_error( array( 'message' => 'Incorrect query sent (prompt)' ) ); } $prompt = sanitize_text_field( wp_unslash($_POST['prompt']) ); if (isset($aimogen_Main_Settings['assistant_disable']) && $aimogen_Main_Settings['assistant_disable'] == 'on') { wp_send_json_error( array( 'message' => 'Assistant disabled in plugin settings' ) ); } if(isset($aimogen_Main_Settings['assistant_model']) && $aimogen_Main_Settings['assistant_model'] != '') { $model = $aimogen_Main_Settings['assistant_model']; } else { $model = aimogen_get_default_model_name($aimogen_Main_Settings); } if(isset($aimogen_Main_Settings['wizard_assistant_id']) && $aimogen_Main_Settings['wizard_assistant_id'] != '') { $wizard_assistant_id = $aimogen_Main_Settings['wizard_assistant_id']; } else { $wizard_assistant_id = ''; } $temperature = 1; if(isset($aimogen_Main_Settings['assistant_temperature']) && $aimogen_Main_Settings['assistant_temperature'] != '') { $temperature = intval($aimogen_Main_Settings['assistant_temperature']); } $top_p = 1; if(isset($aimogen_Main_Settings['assistant_top_p']) && $aimogen_Main_Settings['assistant_top_p'] != '') { $top_p = intval($aimogen_Main_Settings['assistant_top_p']); } $fpenalty = 0; if(isset($aimogen_Main_Settings['assistant_fpenalty']) && $aimogen_Main_Settings['assistant_fpenalty'] != '') { $fpenalty = intval($aimogen_Main_Settings['assistant_fpenalty']); } $ppenalty = 0; if(isset($aimogen_Main_Settings['assistant_ppenalty']) && $aimogen_Main_Settings['assistant_ppenalty'] != '') { $ppenalty = intval($aimogen_Main_Settings['assistant_ppenalty']); } $max_tokens = aimogen_get_max_tokens($model); $all_models = aimogen_get_all_models(true); if(!in_array($model, $all_models)) { $model = aimogen_get_default_model_name($aimogen_Main_Settings); } if (!isset($aimogen_Main_Settings['app_id']) || trim($aimogen_Main_Settings['app_id']) == '') { wp_send_json_error( array( 'message' => 'You need to enter an OpenAI API key in plugin settings!' ) ); } $new_post_content = ''; $appids = preg_split('/\r\n|\r|\n/', trim($aimogen_Main_Settings['app_id'])); $appids = array_filter($appids); $token = $appids[array_rand($appids)]; $token = apply_filters('aimogen_openai_api_key', $token); $query_token_count = count(aimogen_encode($prompt)); $available_tokens = aimogen_compute_available_tokens($model, $max_tokens, $prompt, $query_token_count); if($available_tokens <= AIMOGEN_MINIMUM_TOKENS_FOR_COMPLETIONS) { $string_len = strlen($prompt); $string_len = $string_len / 2; $string_len = intval(0 - $string_len); $aicontent = aimogen_substr($prompt, 0, $string_len); $aicontent = trim($aicontent); if(empty($aicontent)) { wp_send_json_error( array( 'message' => 'Incorrect prompt provided!' ) ); } $query_token_count = count(aimogen_encode($aicontent)); $available_tokens = $max_tokens - $query_token_count; } $thread_id = ''; $aierror = ''; $finish_reason = ''; $generated_text = aimogen_generate_text($token, $model, $prompt, $available_tokens, $temperature, $top_p, $ppenalty, $fpenalty, false, 'aiAssistantWriter', 0, $finish_reason, $aierror, false, false, false, '', '', 'user', $wizard_assistant_id, $thread_id, '', 'disabled', '', false, false, array(), ''); if($generated_text === false) { wp_send_json_error( array( 'message' => 'Failed to generate AI content: ' . $aierror) ); } else { $new_post_content = aimogen_sanitize_ai_result($generated_text); } do_action('aimogen_assistant_text_reply', $new_post_content); wp_send_json_success( array( 'content' => $new_post_content ) ); die(); } add_action('wp_ajax_nopriv_aimogen_shortcode_replacer', 'aimogen_shortcode_replacer'); add_action('wp_ajax_aimogen_shortcode_replacer', 'aimogen_shortcode_replacer'); function aimogen_shortcode_replacer() { check_ajax_referer('wp_rest', 'nonce'); if(!isset($_POST['postId']) || !isset($_POST['send_prompt'])) { wp_send_json_error( array( 'message' => 'Incorrect query sent (postId or send_prompt)' ) ); } $postId = sanitize_text_field( wp_unslash($_POST['postId'] )); $send_prompt = sanitize_text_field( wp_unslash( $_POST['send_prompt'] )); $post = get_post($postId); if($post === null) { wp_send_json_error( array( 'message' => 'Incorrect postId sent' ) ); exit; } $blog_title = html_entity_decode(get_bloginfo('title')); $post_link = get_permalink($postId); $post_title = $post->post_title; $post_excerpt = $post->post_excerpt; $post_content = $post->post_content; $author_obj = get_user_by('id', $post->post_author); if($author_obj !== false && isset($author_obj->user_nicename)) { $user_name = $author_obj->user_nicename; } else { $user_name = ''; } $featured_image = ''; wp_suspend_cache_addition(true); $metas = get_post_custom($post->ID); wp_suspend_cache_addition(false); if(is_array($metas)) { $rez_meta = aimogen_preg_grep_keys('#.+?_featured_ima?ge?#i', $metas); } else { $rez_meta = array(); } if(count($rez_meta) > 0) { foreach($rez_meta as $rm) { if(isset($rm[0]) && filter_var($rm[0], FILTER_VALIDATE_URL)) { $featured_image = $rm[0]; break; } } } if($featured_image == '') { $featured_image = aimogen_generate_thumbmail($post->ID); } if($featured_image == '' && $post_content != '') { $dom = new DOMDocument(); $internalErrors = libxml_use_internal_errors(true); $dom->loadHTML($post_content); libxml_use_internal_errors($internalErrors); $tags = $dom->getElementsByTagName('img'); foreach ($tags as $tag) { $temp_get_img = $tag->getAttribute('src'); if ($temp_get_img != '') { $temp_get_img = strtok($temp_get_img, '?'); $featured_image = rtrim($temp_get_img, '/'); } } } $post_cats = ''; $post_categories = wp_get_post_categories( $post->ID ); foreach($post_categories as $c){ $cat = get_category( $c ); $post_cats .= $cat->name . ','; } $post_cats = trim($post_cats, ','); if($post_cats != '') { $post_categories = explode(',', $post_cats); } else { $post_categories = array(); } if(count($post_categories) == 0) { $terms = get_the_terms( $post->ID, 'product_cat' ); if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){ foreach ( $terms as $term ) { $post_categories[] = $term->slug; } $post_cats = implode(',', $post_categories); } } $post_tagz = ''; $post_tags = wp_get_post_tags( $post->ID ); foreach($post_tags as $t){ $post_tagz .= $t->name . ','; } $post_tagz = trim($post_tagz, ','); if($post_tagz != '') { $post_tags = explode(',', $post_tagz); } else { $post_tags = array(); } if(count($post_tags) == 0) { $terms = get_the_terms( $post->ID, 'product_tag' ); if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){ foreach ( $terms as $term ) { $post_tags[] = $term->slug; } $post_tagz = implode(',', $post_tags); } } $send_prompt = aimogen_replaceAIPostShortcodes($send_prompt, $post_link, $post_title, $blog_title, $post_excerpt, $post_content, $user_name, $featured_image, $post_cats, $post_tagz, $postId, '', '', '', '', '', ''); wp_send_json_success( array( 'content' => $send_prompt ) ); die(); } add_action('wp_ajax_aimogen_imager', 'aimogen_imager'); function aimogen_imager() { check_ajax_referer('wp_rest', 'nonce'); if ( ! current_user_can('edit_posts') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } if(!isset($_POST['prompt'])) { wp_send_json_error( array( 'message' => 'Incorrect query sent (prompt)' ) ); } $prompt = sanitize_text_field( wp_unslash($_POST['prompt'] )); $aimogen_Main_Settings = get_option('aimogen_Main_Settings', false); if (isset($aimogen_Main_Settings['assistant_disable']) && $aimogen_Main_Settings['assistant_disable'] == 'on') { wp_send_json_error( array( 'message' => 'Assistant disabled in plugin settings' ) ); } if (!isset($aimogen_Main_Settings['app_id']) || trim($aimogen_Main_Settings['app_id']) == '') { wp_send_json_error( array( 'message' => 'You need to enter an OpenAI API key in plugin settings!' ) ); } $appids = preg_split('/\r\n|\r|\n/', trim($aimogen_Main_Settings['app_id'])); $appids = array_filter($appids); $token = $appids[array_rand($appids)]; $token = apply_filters('aimogen_openai_api_key', $token); $image_size = '512x512'; if (isset($aimogen_Main_Settings['assistant_image_size']) && trim($aimogen_Main_Settings['assistant_image_size']) != '') { $image_size = $aimogen_Main_Settings['assistant_image_size']; } $image_model = 'gpt-image-2'; if (isset($aimogen_Main_Settings['assistant_image_model']) && trim($aimogen_Main_Settings['assistant_image_model']) != '') { $image_model = $aimogen_Main_Settings['assistant_image_model']; } if($image_model == 'stability') { $echo_ok = false; $height = '512'; $width = '512'; if ($image_size == '1024x1024') { $height = '1024'; $width = '1024'; } $ierror = ''; $arr_response_text = aimogen_generate_stability_image($prompt, $height, $width, 'aiAssistantStableImage', 0, false, $ierror, false, false, '', 0); if($arr_response_text === false) { wp_send_json_error( array( 'message' => 'Error occurred when calling Stability.ai API in image assistant: ' . $ierror) ); } else { if(!isset($arr_response_text[1])) { wp_send_json_error( array( 'message' => 'Error occurred when calling Stability.ai API in image assistant, incorrect reply!') ); } $image = ''; $echo_ok = true; } if($echo_ok === false) { wp_send_json_error( array( 'message' => 'No image returned from Stability.ai API call: ' . $prompt) ); } } elseif($image_model == 'google') { $echo_ok = false; if (isset($aimogen_Main_Settings['google_ai_image_model']) && trim($aimogen_Main_Settings['google_ai_image_model']) != '') { $model = trim($aimogen_Main_Settings['google_ai_image_model']); } else { $model = AIMOGEN_GOOGLE_IMAGE_DEFAULT_MODEL; } $ierror = ''; $arr_response_text = aimogen_generate_image_google($prompt, $model, 'aiAssistantGoogleImage', false, $ierror, false); if($arr_response_text === false) { wp_send_json_error( array( 'message' => 'Error occurred when calling Stability.ai API in image assistant: ' . $ierror) ); } else { if(!isset($arr_response_text[1])) { wp_send_json_error( array( 'message' => 'Error occurred when calling Stability.ai API in image assistant, incorrect reply!') ); } $image = ''; $echo_ok = true; } if($echo_ok === false) { wp_send_json_error( array( 'message' => 'No image returned from Stability.ai API call: ' . $prompt) ); } } elseif($image_model == 'midjourney') { $echo_ok = false; $height = '512'; $width = '512'; if ($image_size == '1024x1024') { $height = '1024'; $width = '1024'; } elseif ($image_size == '1024x1792') { $height = '1792'; $width = '1024'; } elseif ($image_size == '1792x1024') { $height = '1024'; $width = '1792'; } $ierror = ''; $arr_response_text = aimogen_generate_ai_image_midjourney($prompt, $width, $height, 'aiAssistantMidjourneyImage', false, $ierror); if($arr_response_text === false) { wp_send_json_error( array( 'message' => 'Error occurred when calling GoAPI (Midjourney) API in image assistant: ' . $ierror) ); } else { if(!isset($arr_response_text)) { wp_send_json_error( array( 'message' => 'Error occurred when calling GoAPI (Midjourney) in image assistant, incorrect reply!') ); } $image = ''; $echo_ok = true; } if($echo_ok === false) { wp_send_json_error( array( 'message' => 'No image returned from GoAPI (Midjourney) API call: ' . $prompt) ); } } elseif($image_model == 'replicate') { $echo_ok = false; $height = '512'; $width = '512'; if ($image_size == '1024x1024') { $height = '1024'; $width = '1024'; } elseif ($image_size == '1024x1792') { $height = '1792'; $width = '1024'; } elseif ($image_size == '1792x1024') { $height = '1024'; $width = '1792'; } $ierror = ''; $arr_response_text = aimogen_generate_replicate_image($prompt, $width, $height, 'aiAssistantReplicateImage', false, $ierror); if($arr_response_text === false) { wp_send_json_error( array( 'message' => 'Error occurred when calling Replicate API in image assistant: ' . $ierror) ); } else { if(!isset($arr_response_text)) { wp_send_json_error( array( 'message' => 'Error occurred when calling Replicate in image assistant, incorrect reply!') ); } $image = ''; $echo_ok = true; } if($echo_ok === false) { wp_send_json_error( array( 'message' => 'No image returned from Replicate API call: ' . $prompt) ); } } elseif($image_model == 'ideogram') { $echo_ok = false; $height = '512'; $width = '512'; if ($image_size == '1024x1024') { $height = '1024'; $width = '1024'; } elseif ($image_size == '1024x1792') { $height = '1792'; $width = '1024'; } elseif ($image_size == '1792x1024') { $height = '1024'; $width = '1792'; } $ierror = ''; $arr_response_text = aimogen_generate_ideogram_image($prompt, $width, $height, 'aiAssistantIdeogramImage', false, $ierror); if($arr_response_text === false) { wp_send_json_error( array( 'message' => 'Error occurred when calling Ideogram API in image assistant: ' . $ierror) ); } else { if(!isset($arr_response_text)) { wp_send_json_error( array( 'message' => 'Error occurred when calling Ideogram in image assistant, incorrect reply!') ); } $image = ''; $echo_ok = true; } if($echo_ok === false) { wp_send_json_error( array( 'message' => 'No image returned from Ideogram API call: ' . $prompt) ); } } else { $error = ''; $image = ''; $echo_ok = false; $response_text = aimogen_generate_ai_image($token, 1, $prompt, $image_size, 'aiAssistantImage', true, 0, $error, $image_model, $prompt); if($response_text === false) { wp_send_json_error( array( 'message' => 'Error occurred when calling API in image assistant: ' . $error) ); } else { foreach($response_text as $tmpimg) { $attached_id = ''; $localpath = aimogen_copy_image_locally($tmpimg, $attached_id, '', false, $prompt); if($localpath !== false) { $image = ''; $echo_ok = true; break; } else { wp_send_json_error( array( 'message' => 'Failed to copy image file locally: ' . $tmpimg) ); } } } if($echo_ok === false) { wp_send_json_error( array( 'message' => 'No image returned from API call: ' . $prompt) ); } } if($image === false) { wp_send_json_error( array( 'message' => 'Failed to generate AI image: ' . $error) ); } do_action('aimogen_assistant_image_reply', $image); wp_send_json_success( array( 'content' => $image ) ); die(); } add_action('wp_ajax_aimogen_image_chat_submit', 'aimogen_image_chat_submit'); add_action('wp_ajax_nopriv_aimogen_image_chat_submit', 'aimogen_image_chat_submit'); function aimogen_image_chat_submit() { $echo_ok = false; check_ajax_referer('openai-ajax-images-nonce', 'nonce'); $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with chat submission'); if(!isset($_POST['input_text'])) { $aimogen_result['msg'] = 'Incomplete POST request for image chat'; wp_send_json($aimogen_result); } $raw_user_token_cap_per_day = ''; if ( isset( $_POST['user_token_cap_per_day'] ) ) { $raw_user_token_cap_per_day = wp_unslash( $_POST['user_token_cap_per_day'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized } $user_token_cap_per_day = sanitize_text_field( $raw_user_token_cap_per_day ); if(!empty($user_token_cap_per_day)) { $user_token_cap_per_day = intval($user_token_cap_per_day); } $raw_user_id = ''; if ( isset( $_POST['user_id'] ) ) { $raw_user_id = wp_unslash( $_POST['user_id'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized } $user_id = sanitize_text_field( $raw_user_id ); $input_text = sanitize_text_field( wp_unslash($_POST['input_text'])); $aimogen_Main_Settings = get_option('aimogen_Main_Settings', false); if (!isset($aimogen_Main_Settings['app_id']) || trim($aimogen_Main_Settings['app_id']) == '') { $aimogen_result['msg'] = esc_html__('You need to insert a valid OpenAI/AimogenAPI API Key for this to work!', 'aimogen'); wp_send_json($aimogen_result); } $aimogen_Chatbot_Settings = get_option('aimogen_Chatbot_Settings', false); $used_token_count = 0; if(!empty($user_token_cap_per_day) && is_numeric($user_token_cap_per_day)) { if(empty($user_id) || $user_id == 0 || !is_numeric($user_id)) { /* translators: %s: URL */ $aimogen_result['msg'] = sprintf( wp_kses( __( 'You are not allowed to access this form if you are not logged in. Please log in to continue.', 'aimogen'), array( 'a' => array( 'href' => array(), 'target' => array() ) ) ), wp_login_url(get_permalink()) ); wp_send_json($aimogen_result); } $used_token_count = get_user_meta($user_id, 'aimogen_used_image_chat_tokens', true); if($used_token_count !== '' && $used_token_count !== false && is_numeric($used_token_count)) { $used_token_count = intval($used_token_count); if($used_token_count > $user_token_cap_per_day) { $aimogen_result['msg'] = esc_html__('Daily token limit for your user account was exceeded! Please try again tomorrow.', 'aimogen'); wp_send_json($aimogen_result); } } else { $used_token_count = 0; } } $appids = preg_split('/\r\n|\r|\n/', trim($aimogen_Main_Settings['app_id'])); $appids = array_filter($appids); $token = $appids[array_rand($appids)]; $token = apply_filters('aimogen_openai_api_key', $token); $error = ''; $image_size = '512x512'; if (isset($aimogen_Chatbot_Settings['image_chat_size']) && trim($aimogen_Chatbot_Settings['image_chat_size']) != '') { $image_size = $aimogen_Chatbot_Settings['image_chat_size']; } $image_chat_model = 'gpt-image-2'; if (isset($aimogen_Chatbot_Settings['image_chat_model']) && trim($aimogen_Chatbot_Settings['image_chat_model']) != '') { $image_chat_model = $aimogen_Chatbot_Settings['image_chat_model']; } $response_text = aimogen_generate_ai_image($token, 1, $input_text, $image_size, 'shortcodeImageChat', false, 0, $error, $image_chat_model, $input_text); if($response_text === false) { $aimogen_result['msg'] = $error; wp_send_json($aimogen_result); } else { foreach($response_text as $tmpimg) { $aimogen_result['status'] = 'success'; if(isset($aimogen_result['data'])) { $aimogen_result['data'] .= ''; } else { $aimogen_result['data'] = ''; } $echo_ok = true; } if(!empty($user_token_cap_per_day) && is_numeric($user_token_cap_per_day)) { $used_token_count = intval($used_token_count) + 1000; update_user_meta($user_id, 'aimogen_used_image_chat_tokens', $used_token_count); } } if($echo_ok === false) { $aimogen_result['msg'] = esc_html__('No image returned from API call: ', 'aimogen') . $input_text; wp_send_json($aimogen_result); } do_action('aimogen_image_chat_reply', $aimogen_result); wp_send_json($aimogen_result); die(); } add_action('wp_ajax_aimogen_user_meta_save', 'aimogen_user_meta_save'); add_action('wp_ajax_nopriv_aimogen_user_meta_save', 'aimogen_user_meta_save'); function aimogen_user_meta_save() { $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong'); check_ajax_referer('openai-persistent-nonce', 'nonce'); if(!isset($_POST['x_input_text'])) { $aimogen_result = array('status' => 'error', 'msg' => 'Failed to save persistent conversation, no x_input_text'); wp_send_json($aimogen_result); wp_die(); } if(!isset($_POST['user_id'])) { $aimogen_result = array('status' => 'error', 'msg' => 'Failed to save persistent conversation, no user_id'); wp_send_json($aimogen_result); wp_die(); } $user_id = sanitize_text_field( wp_unslash($_POST['user_id'])); if(!isset($_POST['persistent'])) { $aimogen_result = array('status' => 'error', 'msg' => 'Failed to save persistent conversation, no persistentid'); wp_send_json($aimogen_result); wp_die(); } $persistent = sanitize_text_field( wp_unslash($_POST['persistent'])); if(empty($user_id) || $user_id == 0) { $aimogen_result = array('status' => 'error', 'msg' => 'Failed to save persistent conversation, user_id is not valid'); wp_send_json($aimogen_result); wp_die(); } if(isset($_POST['thread_id'])) { $thread_id = sanitize_text_field( wp_unslash($_POST['thread_id'])); } else { $thread_id = ''; } if($persistent == 'history') { if(empty($thread_id)) { if(isset($_POST['saving_index'])) { $saving_index = sanitize_text_field( wp_unslash($_POST['saving_index'])); } if(empty($saving_index)) { $aimogen_result = array('status' => 'error', 'msg' => 'Failed to save persistent conversation, saving_index is not valid'); wp_send_json($aimogen_result); wp_die(); } if(isset($_POST['main_index'])) { $main_index = sanitize_text_field( wp_unslash($_POST['main_index'])); } if(empty($main_index)) { $aimogen_result = array('status' => 'error', 'msg' => 'Failed to save persistent conversation, main_index is not valid'); wp_send_json($aimogen_result); wp_die(); } $x_input_text = sanitize_text_field( wp_unslash($_POST['x_input_text'])); if(!empty($x_input_text)) { if(is_numeric($user_id)) { $pmeta = get_user_meta($user_id, 'aimogen_chat_history_' . $persistent, true); if(!is_array($pmeta)) { $pmeta = array(); } $is_existing = false; if(isset($pmeta[$saving_index])) { $is_existing = true; } $aimogen_Chatbot_Settings = get_option('aimogen_Chatbot_Settings', false); if(isset($aimogen_Chatbot_Settings['max_chat_log_login']) && $aimogen_Chatbot_Settings['max_chat_log_login'] !== '' && is_numeric($aimogen_Chatbot_Settings['max_chat_log_login'])) { $xmax = intval($aimogen_Chatbot_Settings['max_chat_log_login']) - 1; if($xmax < 0) { $xmax = 0; } if(count($pmeta) >= $xmax) { uasort($pmeta, function ($a, $b) { return $b['time'] <=> $a['time']; }); $pmeta = array_slice($pmeta, 0, $xmax); } } $name = aimogen_generate_conversation_title($x_input_text); $pmeta[$saving_index]['name'] = $name; $pmeta[$saving_index]['main_index'] = $main_index; $pmeta[$saving_index]['time'] = time(); $pmeta[$saving_index]['data'] = $x_input_text; update_user_meta($user_id, 'aimogen_chat_history_' . $persistent, $pmeta); if(!$is_existing) { $aimogen_result = array('status' => 'success', 'name' => $name, 'msg' => 'true'); wp_send_json($aimogen_result); wp_die(); } $aimogen_result = array('status' => 'success', 'msg' => 'ok'); wp_send_json($aimogen_result); wp_die(); } else { $pmeta = get_transient('aimogen_chat_history_' . $persistent . '_' . $user_id); if(!is_array($pmeta)) { $pmeta = array(); } $is_existing = false; if(isset($pmeta[$saving_index])) { $is_existing = true; } $aimogen_Chatbot_Settings = get_option('aimogen_Chatbot_Settings', false); if(isset($aimogen_Chatbot_Settings['max_chat_log_not_login']) && $aimogen_Chatbot_Settings['max_chat_log_not_login'] !== '' && is_numeric($aimogen_Chatbot_Settings['max_chat_log_not_login'])) { $xmax = intval($aimogen_Chatbot_Settings['max_chat_log_not_login']) - 1; if($xmax < 0) { $xmax = 0; } if(count($pmeta) >= $xmax) { uasort($pmeta, function ($a, $b) { return $b['time'] <=> $a['time']; }); $pmeta = array_slice($pmeta, 0, $xmax); } } $name = aimogen_generate_conversation_title($x_input_text); $pmeta[$saving_index]['name'] = $name; $pmeta[$saving_index]['main_index'] = $main_index; $pmeta[$saving_index]['time'] = time(); $pmeta[$saving_index]['data'] = $x_input_text; if(isset($aimogen_Chatbot_Settings['remember_chat_transient']) && $aimogen_Chatbot_Settings['remember_chat_transient'] !== '' && is_numeric($aimogen_Chatbot_Settings['remember_chat_transient'])) { $remember_time = intval($aimogen_Chatbot_Settings['remember_chat_transient']); } else { $remember_time = 0; } set_transient('aimogen_chat_history_' . $persistent . '_' . $user_id, $pmeta, $remember_time); if(!$is_existing) { $aimogen_result = array('status' => 'success', 'name' => $name, 'msg' => 'true'); wp_send_json($aimogen_result); wp_die(); } $aimogen_result = array('status' => 'success', 'msg' => 'ok'); wp_send_json($aimogen_result); wp_die(); } } } } else { if(empty($thread_id)) { $x_input_text = sanitize_text_field( wp_unslash($_POST['x_input_text'])); if(!empty($x_input_text)) { if(is_numeric($user_id)) { update_user_meta($user_id, 'aimogen_chat_history_' . $persistent, $x_input_text); } else { $aimogen_Chatbot_Settings = get_option('aimogen_Chatbot_Settings', false); if(isset($aimogen_Chatbot_Settings['remember_chat_transient']) && $aimogen_Chatbot_Settings['remember_chat_transient'] !== '' && is_numeric($aimogen_Chatbot_Settings['remember_chat_transient'])) { $remember_time = intval($aimogen_Chatbot_Settings['remember_chat_transient']); } else { $remember_time = 0; } set_transient('aimogen_chat_history_' . $persistent . '_' . $user_id, $x_input_text, $remember_time); } } } else { if(is_numeric($user_id)) { update_user_meta($user_id, 'aimogen_assistant_history_thread', $thread_id); } else { $aimogen_Chatbot_Settings = get_option('aimogen_Chatbot_Settings', false); if(isset($aimogen_Chatbot_Settings['remember_chat_transient']) && $aimogen_Chatbot_Settings['remember_chat_transient'] !== '' && is_numeric($aimogen_Chatbot_Settings['remember_chat_transient'])) { $remember_time = intval($aimogen_Chatbot_Settings['remember_chat_transient']); } else { $remember_time = 0; } set_transient('aimogen_assistant_history_thread_' . $user_id, $thread_id, $remember_time); } } } $aimogen_result = array('status' => 'success', 'msg' => 'ok'); wp_send_json($aimogen_result); wp_die(); } add_action('wp_ajax_aimogen_record_user_usage', 'aimogen_record_user_usage'); add_action('wp_ajax_nopriv_aimogen_record_user_usage', 'aimogen_record_user_usage'); function aimogen_record_user_usage() { $aimogen_Main_Settings = get_option('aimogen_Main_Settings', false); check_ajax_referer('openai-persistent-nonce', 'nonce'); if(!isset($_POST['input_text'])) { $aimogen_result = array('status' => 'error', 'msg' => 'Failed to save persistent conversation, no input_text'); wp_send_json($aimogen_result); wp_die(); } $input_text = sanitize_text_field( wp_unslash($_POST['input_text'])); if(!isset($_POST['user_id'])) { $aimogen_result = array('status' => 'error', 'msg' => 'Failed to save persistent conversation, no user_id'); wp_send_json($aimogen_result); wp_die(); } $user_id = sanitize_text_field( wp_unslash($_POST['user_id'])); if(!isset($_POST['user_token_cap_per_day'])) { $aimogen_result = array('status' => 'error', 'msg' => 'Failed to save persistent conversation, no user_token_cap_per_day'); wp_send_json($aimogen_result); wp_die(); } $user_token_cap_per_day = sanitize_text_field( wp_unslash($_POST['user_token_cap_per_day'])); if(!isset($_POST['response_text'])) { $aimogen_result = array('status' => 'error', 'msg' => 'Failed to save persistent conversation, no response_text'); wp_send_json($aimogen_result); wp_die(); } $response_text = sanitize_text_field( wp_unslash($_POST['response_text'])); if(!isset($_POST['model'])) { $aimogen_result = array('status' => 'error', 'msg' => 'Failed to save persistent conversation, no model'); wp_send_json($aimogen_result); wp_die(); } $model = sanitize_text_field( wp_unslash($_POST['model'])); if(!isset($_POST['temp'])) { $aimogen_result = array('status' => 'error', 'msg' => 'Failed to save persistent conversation, no temp'); wp_send_json($aimogen_result); wp_die(); } $vision_file = ''; if(isset($_POST['vision_file'])) { $vision_file = sanitize_text_field( wp_unslash($_POST['vision_file'])); } $source = 'chat'; if(isset($_POST['source'])) { $source = sanitize_text_field( wp_unslash($_POST['source'])); } if($source === 'forms') { $source = 'shortcodeForms'; } else { $source = 'shortcodeChat'; } $temperature = sanitize_text_field( wp_unslash($_POST['temp'])); $inp_count = count(aimogen_encode($input_text)); $resp_count = count(aimogen_encode($response_text)); if($user_token_cap_per_day != '' && is_numeric($user_token_cap_per_day)) { if(empty($user_id) || $user_id == 0) { aimogen_log_to_file('Failed to save persistent conversation, invalid user ID sent'); } else { $used_token_count = 0; $used_token_count = get_user_meta($user_id, 'aimogen_used_chat_tokens', true); if($used_token_count !== '' && $used_token_count !== false && is_numeric($used_token_count)) { $used_token_count = intval($used_token_count); } else { $used_token_count = 0; } $used_token_count = intval($used_token_count) + $inp_count + $resp_count; update_user_meta($user_id, 'aimogen_used_chat_tokens', $used_token_count); } } $session = aimogen_get_session_id(); $appids = preg_split('/\r\n|\r|\n/', trim($aimogen_Main_Settings['app_id'])); $appids = array_filter($appids); $token = $appids[array_rand($appids)]; $token = apply_filters('aimogen_openai_api_key', $token); $query = new Aimogen_lite_Query($input_text, 0, $model, $temperature, null, $source, 'text', $token, $session, 1, '', ''); apply_filters( 'aimogen_ai_reply', $response_text, $query ); $aimogen_result = array('status' => 'success', 'msg' => 'ok'); wp_send_json($aimogen_result); wp_die(); } add_action('wp_ajax_aimogen_call_google_ai_function', 'aimogen_call_google_ai_function'); add_action('wp_ajax_nopriv_aimogen_call_google_ai_function', 'aimogen_call_google_ai_function'); function aimogen_call_google_ai_function() { check_ajax_referer('openai-persistent-nonce', 'nonce'); if(!isset($_POST['func_call'])) { aimogen_log_to_file('Failed to call google function, no func_call'); wp_send_json(array('scope' => 'fail', 'data' => 'fail')); wp_die(); } require_once(dirname(__FILE__) . "/aimogen-god-mode-parser.php"); if ( ! isset( $_POST['func_call'] ) ) { aimogen_log_to_file('Failed to call google function, no func_call'); wp_send_json( [ 'scope' => 'fail', 'data' => 'fail' ] ); wp_die(); } // Unslash and decode properly // Isolate raw POST access $raw_func_call = null; if ( isset( $_POST['func_call'] ) ) { $raw_func_call = wp_unslash( $_POST['func_call'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized } // Validate format (string or array) if ( is_string( $raw_func_call ) ) { $decoded = json_decode( $raw_func_call, true ); if ( json_last_error() !== JSON_ERROR_NONE ) { wp_send_json( [ 'scope' => 'fail', 'data' => 'invalid_json' ] ); wp_die(); } $current_data = $decoded; } elseif ( is_array( $raw_func_call ) ) { $current_data = $raw_func_call; } else { wp_send_json( [ 'scope' => 'fail', 'data' => 'invalid_format' ] ); wp_die(); } // Validate required keys if ( empty( $current_data['name'] ) || empty( $current_data['args'] ) ) { wp_send_json( [ 'scope' => 'fail', 'data' => 'missing_keys' ] ); wp_die(); } // Sanitize function name $function_name = sanitize_key( $current_data['name'] ); // Sanitize all arguments (deep) $function_args = array_map( static function( $value ) { return is_array( $value ) ? array_map( 'sanitize_text_field', $value ) : sanitize_text_field( $value ); }, $current_data['args'] ); $filter_tool_object = new stdClass(); $filter_tool_object->tool_calls = array(); $tool_oarr = new stdClass(); $tool_oarr->type = 'function'; $tool_oarr->id = uniqid(); $tool_oarr->function = new stdClass(); $tool_oarr->function->name = $function_name; $tool_oarr->function->arguments = (object) $function_args; $filter_tool_object->tool_calls[] = $tool_oarr; $filter_tool_object = apply_filters('aimogen_google_tools_ai_reply_raw', $filter_tool_object); if(isset($filter_tool_object->aimogen_tool_direct_message) && isset($filter_tool_object->aimogen_tool_direct_message[0]) && isset($filter_tool_object->aimogen_tool_direct_message[0]['content']) && !empty($filter_tool_object->aimogen_tool_direct_message[0]['content'])) { wp_send_json(array( 'scope' => 'user_message', 'data' => $filter_tool_object->aimogen_tool_direct_message[0]['content'] )); wp_die(); } if(isset($filter_tool_object->aimogen_tool_end_conversation) && isset($filter_tool_object->aimogen_tool_end_conversation[0]) && isset($filter_tool_object->aimogen_tool_end_conversation[0]['content']) && !empty($filter_tool_object->aimogen_tool_end_conversation[0]['content'])) { wp_send_json(array( 'scope' => 'end_message', 'data' => $filter_tool_object->aimogen_tool_end_conversation[0]['content'] )); wp_die(); } if(isset($filter_tool_object->aimogen_tool_results) && isset($filter_tool_object->aimogen_tool_results[0]) && isset($filter_tool_object->aimogen_tool_results[0]['content']) && !empty($filter_tool_object->aimogen_tool_results[0]['content'])) { remove_filter('aimogen_ai_functions', 'aimogen_add_god_mode', 999); wp_send_json(array( 'scope' => 'response', 'data' => $filter_tool_object->aimogen_tool_results[0]['content'] )); wp_die(); } wp_send_json(array('scope' => 'fail', 'data' => 'fail')); wp_die(); } add_action('wp_ajax_aimogen_create_thread', 'aimogen_create_thread'); add_action('wp_ajax_nopriv_aimogen_create_thread', 'aimogen_create_thread'); function aimogen_create_thread() { $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with assistant thread creation'); check_ajax_referer('openai-ajax-nonce', 'nonce'); if(defined('AIMOGEN_ASSISTANTS_API_RETIRED') && AIMOGEN_ASSISTANTS_API_RETIRED) { $aimogen_result['status'] = 'success'; $aimogen_result['data'] = ''; $aimogen_result['msg'] = 'Assistants API thread creation skipped; the default model will be used.'; wp_send_json($aimogen_result); wp_die(); } $assistant_id = isset($_POST['assistantid']) ? sanitize_text_field( wp_unslash($_POST['assistantid'])) : ''; $file_data = isset($_POST['file_data']) ? sanitize_text_field( wp_unslash($_POST['file_data'])) : ''; if(empty($assistant_id)) { $aimogen_result['msg'] = 'No assistant ID passed'; wp_send_json($aimogen_result); wp_die(); } $aimogen_Main_Settings = get_option('aimogen_Main_Settings', false); if (!isset($aimogen_Main_Settings['app_id']) || trim($aimogen_Main_Settings['app_id']) == '') { $aimogen_result['msg'] = 'You need to add an API key in plugin settings for this shortcode to work.'; wp_send_json($aimogen_result); wp_die(); } else { $appids = preg_split('/\r\n|\r|\n/', trim($aimogen_Main_Settings['app_id'])); $appids = array_filter($appids); $token = $appids[array_rand($appids)]; $token = apply_filters('aimogen_openai_api_key', $token); if(empty($token)) { $aimogen_result['msg'] = 'Invalid API key submitted'; wp_send_json($aimogen_result); wp_die(); } if(aimogen_is_aimogen_key($token)) { $aimogen_result['msg'] = 'Currently only OpenAI API is supported for audio processing.'; wp_send_json($aimogen_result); wp_die(); } } $assistant_first_message = ''; require_once (dirname(__FILE__) . "/res/aimogen-assistants-api.php"); try { $local_assistant_id = aimogen_find_local_assistant_id($assistant_id); if($local_assistant_id === false) { $aimogen_result['msg'] = 'Failed to find local assistant ID for: ' . $assistant_id; wp_send_json($aimogen_result); wp_die(); } $assistant_first_message = get_post_meta($local_assistant_id, '_assistant_first_message', true); if(!empty($assistant_first_message)) { $simulate_conv = array(); $simulate_conv[] = array("role" => 'assistant', "content" => $assistant_first_message); } else { $simulate_conv = []; } $thread = aimogen_openai_create_thread($token, $simulate_conv, $file_data); if(!isset($thread['id'])) { $aimogen_result['msg'] = 'Invalid thread format: ' . json_encode($thread); wp_send_json($aimogen_result); wp_die(); } $thread_id = $thread['id']; $aimogen_result['status'] = 'success'; $aimogen_result['data'] = $thread_id; } catch(Exception $e) { $aimogen_result['msg'] = 'Exception in thread creation: ' . $e->getMessage(); } wp_send_json($aimogen_result); wp_die(); } add_action( 'wp_ajax_aimogen_moderate_text', 'aimogen_moderate_text' ); add_action( 'wp_ajax_nopriv_aimogen_moderate_text', 'aimogen_moderate_text' ); function aimogen_moderate_text() { check_ajax_referer('openai-moderation-nonce', 'nonce'); $aimogen_result = array('status' => 'error', 'msg' => 'Something went wrong with text moderation'); $text = isset($_REQUEST['text']) && !empty($_REQUEST['text']) ? sanitize_text_field( wp_unslash($_REQUEST['text'])) : ''; if(empty($text)) { $aimogen_result['msg'] = 'You need to enter a text to moderate!'; wp_send_json($aimogen_result); } $aimogen_Main_Settings = get_option('aimogen_Main_Settings', false); if (!isset($aimogen_Main_Settings['app_id']) || trim($aimogen_Main_Settings['app_id']) == '') { $aimogen_result['msg'] = 'You need to add an API key in plugin settings for this shortcode to work.'; wp_send_json($aimogen_result); } else { $appids = preg_split('/\r\n|\r|\n/', trim($aimogen_Main_Settings['app_id'])); $appids = array_filter($appids); $token = $appids[array_rand($appids)]; $token = apply_filters('aimogen_openai_api_key', $token); if(empty($token)) { $aimogen_result['msg'] = 'Invalid API key submitted'; wp_send_json($aimogen_result); } if(aimogen_is_aimogen_key($token)) { $aimogen_result['msg'] = 'Currently only OpenAI API is supported for text moderation.'; wp_send_json($aimogen_result); } } if (aimogen_check_if_azure_or_others($aimogen_Main_Settings)) { $aimogen_result['msg'] = 'Azure/Claude API is not currently supported for moderation.'; wp_send_json($aimogen_result); } require_once (dirname(__FILE__) . "/res/openai/Url.php"); require_once (dirname(__FILE__) . "/res/openai/OpenAi.php"); $open_ai = new OpenAi($token); if(!$open_ai){ $aimogen_result['msg'] = 'Missing API Setting'; wp_send_json($aimogen_result); } if (isset($aimogen_Main_Settings['api_selector']) && trim($aimogen_Main_Settings['api_selector']) == 'custom' && isset($aimogen_Main_Settings['custom_endpoint']) && trim($aimogen_Main_Settings['custom_endpoint'], ' /') != '') { $open_ai->setCustomURL(trim($aimogen_Main_Settings['custom_endpoint'], ' /')); } if (isset($aimogen_Main_Settings['openai_organization']) && $aimogen_Main_Settings['openai_organization'] != '') { $open_ai->setORG($aimogen_Main_Settings['openai_organization']); } $data_request = array( 'input' => $text ); if(isset($_REQUEST['model']) && !empty(trim(sanitize_text_field( wp_unslash($_REQUEST['model']))))) { $data_request['model'] = trim(sanitize_text_field( wp_unslash($_REQUEST['model']))); } $delay = ''; if (isset($aimogen_Main_Settings['request_delay']) && $aimogen_Main_Settings['request_delay'] != '') { if(stristr($aimogen_Main_Settings['request_delay'], ',') !== false) { $tempo = explode(',', $aimogen_Main_Settings['request_delay']); if(isset($tempo[1]) && is_numeric(trim($tempo[1])) && is_numeric(trim($tempo[0]))) { $delay = wp_rand(trim($tempo[0]), trim($tempo[1])); } } else { if(is_numeric(trim($aimogen_Main_Settings['request_delay']))) { $delay = intval(trim($aimogen_Main_Settings['request_delay'])); } } } if($delay != '' && is_numeric($delay)) { usleep($delay); } $moderation = $open_ai->moderation($data_request); $result = json_decode($moderation); if($result && isset($result->error)){ $aimogen_result['msg'] = $result->error->message; wp_send_json($aimogen_result); } $aimogen_result['status'] = 'success'; $aimogen_result['data'] = $moderation; do_action('aimogen_text_moderation_reply', $aimogen_result); wp_send_json($aimogen_result); die(); } ?>