settings = $settings;
// Get the post ID from the URL
$post_id = isset($_GET['post']) ? intval($_GET['post']) : 0; // phpcs:ignore
if (!empty($_GET['post_type'])) { // phpcs:ignore
$post_type = $_GET['post_type']; // phpcs:ignore
} elseif ( $post_id > 0 ) {
$post_type = get_post_type( $post_id );
} else {
$post_type = '';
}
if ( ! empty( $this->isEnabledWriteWithAI() ) && $post_type == 'docs' ) {
add_action( 'admin_footer', [ $this, 'ai_autowrite_button' ] );
}
add_action( 'wp_ajax_generate_openai_content', [ $this, 'generate_openai_content_callback' ] );
}
public function isEnabledWriteWithAI() {
$isEnableAutoWrite = $this->settings->get( 'enable_write_with_ai', true );
return $isEnableAutoWrite;
}
public function isValidAPIKey( $apiKey ) {
if ( empty( $apiKey ) ) {
$api_response['valid'] = false;
$api_response['message'] = 'Please Insert your OpenAI API Key to use this Write with AI feature.';
return $api_response;
}
$ch = curl_init( 'https://api.openai.com/v1/engines' ); //phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_init
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); //phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_setopt
curl_setopt(
$ch,
CURLOPT_HTTPHEADER,
[ //phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_setopt
'Content-Type: application/json',
'Authorization: Bearer ' . $apiKey,
]
);
$api_response = [];
$response = curl_exec( $ch ); //phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_exec
$httpCode = curl_getinfo( $ch, CURLINFO_HTTP_CODE ); //phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_getinfo
curl_close( $ch ); //phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_close
if ( $httpCode == 200 ) {
$api_response['valid'] = true;
$api_response['message'] = 'Valid API Key';
} else {
$responseData = json_decode( $response, true );
// Access the message data (replace 'data' with the actual key used in the response)
$messageData = $responseData['error'] ? $responseData['error'] : '';
$api_response['valid'] = false;
$api_response['message'] = $messageData['message'] ? $messageData['message'] : 'Invalid API Key';
}
// print_r($response);
return $api_response;
}
public function get_api_key() {
$api_key = $this->settings->get( 'ai_autowrite_api_key', '' );
return $api_key;
}
public function generate_openai_response( $prompt, $keywords ) {
try {
$api_key = $this->settings->get( 'ai_autowrite_api_key', '' );
$max_tokens = $this->settings->get( 'ai_autowrite_max_token', 1500 );
$model = $this->settings->get( 'write_with_ai_model', 'gpt-4o-mini' );
$api_endpoint = 'https://api.openai.com/v1/chat/completions'; // Update the endpoint based on OpenAI API version
$request_options = array(
'headers' => array(
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $api_key,
),
'body' => json_encode(
array( //phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode
'model' => $model, // Add the model parameter here
'messages' => array(
array(
'role' => 'system',
'content' => 'You are a helpful assistant who writes documentation for users.'
),
array(
'role' => 'user',
'content' => $prompt
),
),
'max_tokens' => $max_tokens,
)
),
'timeout' => 50,
);
$response = wp_remote_post( $api_endpoint, $request_options );
if ( is_wp_error( $response ) ) {
return 'Error: ' . $response->get_error_message();
} else {
$body = wp_remote_retrieve_body( $response );
$data = json_decode( $body, true );
if ( ! empty( $data['error'] ) ) {
return $data['error']['message'];
}
return $data['choices'][0]['message']['content']; // Update this line to get the assistant's message
}
} catch ( Exception $error ) {
return 'Error: ' . $error->getMessage();
}
}
public function generate_openai_content_callback() {
// Verify the nonce
if (!isset($_POST['ai_nonce']) || !wp_verify_nonce($_POST['ai_nonce'], 'generate_openai_content_nonce')) { //phpcs:ignore
wp_send_json_error( 'Invalid nonce' );
wp_die();
}
$prompt = sanitize_text_field($_POST['prompt']); //phpcs:ignore
// $num_of_sections = sanitize_text_field($_POST['numOfSections']);
// $num_of_paragraphs = sanitize_text_field($_POST['numOfParagraphs']);
$keywords = sanitize_text_field($_POST['keywords']); //phpcs:ignore
$ai_instance = new WriteWithAI( $this->settings );
$generated_content = $ai_instance->generate_openai_response( $prompt, $keywords );
// Send the generated content as the AJAX response
wp_send_json_success( $generated_content );
wp_die();
}
public function ai_autowrite_button() {
?>