'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 .= '