RegisterPrivate('CreateEmailTemplate','CreateEmailTemplate'); $this->RegisterPrivate('CreateEmailTemplateUsingFile','CreateEmailTemplateUsingFile'); $this->RegisterPrivate('clone_email','CloneEmail'); $this->RegisterPrivate('delete_email','DeleteEmail'); $this->RegisterPrivate('bulk_delete_emails','BulkDeleteEmails'); $this->RegisterPrivate('export_email_template','ExportTemplate'); $this->RegisterPrivate('import_email_template','ImportTemplate'); $this->RegisterPrivate('list_email','ListEmail'); $this->RegisterPrivate('activate_license','ActivateLicense'); $this->RegisterPrivate('deactivate_license','DeactivateLicense'); $this->RegisterPrivate('save_ai_settings','SaveAISettings'); $this->RegisterPrivate('save_log_settings','SaveLogSettings'); $this->RegisterPrivate('download_log','DownloadLog'); $this->RegisterPrivate('delete_log','DeleteLog'); $this->RegisterPrivate('ai_generate_template','AIGenerateTemplate','administrator',false); $this->RegisterPrivate('ai_get_prompt','AIGetPrompt','administrator',false); $this->RegisterPrivate('create_email_from_options','CreateEmailTemplateFromOptions'); $this->RegisterPrivate('preview_ai_template','PreviewAITemplate'); } public function SaveAISettings(){ $aiModels = $this->GetRequired('AIModels'); update_option('rnadem_ai_models', $aiModels); $this->SendSuccessMessage(__('AI settings saved successfully','advanced-emailing-for-woocommerce')); } public function SaveLogSettings(){ $enableLog = $this->GetRequired('EnableLog'); if($enableLog == '1'){ update_option('rnadem_enable_log', '1'); } else { delete_option('rnadem_enable_log'); } LogManager::SetShouldLog(null); $this->SendSuccessMessage(__('Log settings saved successfully','advanced-emailing-for-woocommerce')); } public function DownloadLog(){ $this->Loader->CheckIfPDFAdmin(); if(!\file_exists(LogManager::GetLogFilePath())){ echo __('No log file found','advanced-emailing-for-woocommerce'); die(); } header('Content-Disposition: attachment; filename="log.txt"'); header('Content-Type: text/plain'); header('Content-Length: ' . filesize(LogManager::GetLogFilePath())); echo file_get_contents(LogManager::GetLogFilePath()); die(); } public function DeleteLog(){ $this->Loader->CheckIfPDFAdmin(); LogManager::RemoveLog(); $this->SendSuccessMessage(true); } public function CreateEmailTemplateUsingFile() { if(!isset($_FILES['File'])) { $this->SendErrorMessage(__('Template not found','advanced-emailing-for-woocommerce')); } $importer=new ImportManager($this->Loader); try{ $options=$importer->Import($_FILES['File']['tmp_name']); }catch (\Exception $e) { $this->SendErrorMessage($e->getMessage()); die(); } // Validate PHP code security for imported template $error = SaveManager::ValidatePHPCodeSecurity(0, $options->CustomFields, $this->Loader); if($error !== null) $this->SendErrorMessage($error); $this->SendSuccessMessage(['Name'=>$options->Name,'Id'=>$options->Id]); } public function ListEmail(){ $search=$this->GetRequired('Search'); $repository=new EmailRepository($this->Loader); $this->SendSuccessMessage(['Result'=>$repository->GetEmailList($search),'Count'=>$repository->GetEmailListCount($search)]); } public function DeleteEmail(){ $repository=new EmailRepository($this->Loader); $repository->DeleteEmail(intval($this->GetRequired('Id'))); $this->SendSuccessMessage(true); } public function BulkDeleteEmails(){ $ids=$this->GetRequired('Ids'); if(!is_array($ids)) $this->SendErrorMessage(__('Invalid ids','advanced-emailing-for-woocommerce')); $repository=new EmailRepository($this->Loader); foreach($ids as $id){ $repository->DeleteEmail(intval($id)); } $this->SendSuccessMessage(true); } public function ActivateLicense(){ $licenseKey=$this->GetRequired('LicenseKey'); $expirationDate=$this->GetRequired('ExpirationDate'); $url=$this->GetRequired('URL'); (new Activator())->SaveLicense($licenseKey,$expirationDate,$url); $this->SendSuccessMessage(''); } public function ImportTemplate(){ if(!isset($_FILES['TemplateToImport'])) { $this->SendErrorMessage(__('Template not found','advanced-emailing-for-woocommerce')); } $importer=new ImportManager($this->Loader); try{ $options=$importer->Import($_FILES['TemplateToImport']['tmp_name']); }catch (\Exception $e) { $this->SendErrorMessage($e->getMessage()); die(); } // Validate PHP code security for imported template $error = SaveManager::ValidatePHPCodeSecurity(0, $options->CustomFields, $this->Loader); if($error !== null) $this->SendErrorMessage($error); $this->SendSuccessMessage(['Name'=>$options->Name,'Id'=>$options->Id]); } public function ExportTemplate(){ $emailId=intval($this->GetRequired('EmailId')); $exportManager=new ExportManager($this->Loader); try { $path=$exportManager->Export($emailId); header("Content-Type: application/zip"); header("Content-Disposition: attachment; filename=".$exportManager->Options->Name.'.zip'); header("Content-Length: " . filesize($path)); readfile($path); }catch (\Exception $e) { echo Sanitizer::SanitizeHTML($e->getMessage()); die(); } $exportManager->Remove(); die(); } public function CreateEmailTemplate(){ $templateId=$this->GetRequired('TemplateId'); $templatePath=$this->Loader->DIR.'Templates/Locals/'.$templateId.'/Template.json'; if(!file_exists($templatePath)) $this->SendErrorMessage(__('Template not found','advanced-emailing-for-woocommerce')); $options=json_decode(file_get_contents($templatePath)); if($options==false) $this->SendErrorMessage(__('Template not found','advanced-emailing-for-woocommerce')); /** @var EmailBuilderOptionsDTO $templateOption */ $templateOption=(new EmailBuilderOptionsDTO())->Merge($options); $templateOption->Id=0; $repository=new EmailRepository($this->Loader); $repository->SaveEmail($templateOption,true); $this->SendSuccessMessage(['Id'=>$templateOption->Id]); } /** * Create an email template from raw EmailBuilderOptionsDTO JSON (used by AI generator). */ public function CreateEmailTemplateFromOptions(){ $options = $this->GetRequired('Options'); $name = $this->GetRequired('Name'); /** @var EmailBuilderOptionsDTO $templateOption */ $templateOption = (new EmailBuilderOptionsDTO())->Merge($options); $templateOption->Id = 0; $templateOption->Name = $name; // Upload any base64 data URI images to WordPress media library $this->UploadBase64Images($templateOption); // Validate PHP code security for AI-generated template $error = SaveManager::ValidatePHPCodeSecurity(0, $templateOption->CustomFields, $this->Loader); if($error !== null) $this->SendErrorMessage($error); $repository = new EmailRepository($this->Loader); try { $repository->SaveEmail($templateOption, true); } catch (\Exception $e) { $this->SendException($e); } $this->SendSuccessMessage(['Id' => $templateOption->Id]); } /** * Scans all blocks in the template for base64 data URI images and uploads them * to the WordPress media library, replacing the base64 URLs with permanent file URLs. * * @param EmailBuilderOptionsDTO $templateOption */ private function UploadBase64Images($templateOption){ if(!isset($templateOption->ContentOptions) || !isset($templateOption->ContentOptions->Sections)) return; foreach($templateOption->ContentOptions->Sections as $section){ $this->ProcessSectionBase64Images($section); } } /** * Recursively processes a section's blocks looking for base64 images. */ private function ProcessSectionBase64Images($section){ if(!isset($section->Rows)) return; foreach($section->Rows as $row){ if(!isset($row->Columns)) continue; foreach($row->Columns as $column){ if(!isset($column->Blocks)) continue; foreach($column->Blocks as $block){ // Image block: check MediaData.URL if(isset($block->Type) && $block->Type == 'Image' && isset($block->MediaData)){ $this->MaybeUploadBase64MediaData($block->MediaData); } // HeaderBuilder block: check Elements[].ImageData.URL and BackgroundImage if(isset($block->Type) && $block->Type == 'HeaderBuilder'){ if(isset($block->BackgroundImage)){ $this->MaybeUploadBase64MediaData($block->BackgroundImage); } if(isset($block->Elements) && is_array($block->Elements)){ foreach($block->Elements as $element){ if(isset($element->Type) && $element->Type == 'Image' && isset($element->ImageData)){ $this->MaybeUploadBase64MediaData($element->ImageData); } } } } // SubSection block: recurse into nested sections if(isset($block->Type) && $block->Type == 'Subsection' && isset($block->Sections)){ foreach($block->Sections as $subSection){ $this->ProcessSectionBase64Images($subSection); } } } } } } /** * If the given media data object has a base64 data URI in its URL property, * uploads it to WordPress media library and updates URL and Id in place. * * @param object $mediaData Object with URL (and optionally Id) properties */ private function MaybeUploadBase64MediaData(&$mediaData){ if($mediaData == null || !is_object($mediaData)) return; $url = isset($mediaData->URL) ? $mediaData->URL : ''; if($url == '' || strpos($url, 'data:image/') !== 0) return; // Extract mime type and base64 data $matches = []; if(!preg_match('/^data:image\/(\w+);base64,(.+)$/', $url, $matches)) return; $extension = $matches[1]; // Normalize jpeg extension if($extension == 'jpeg') $extension = 'jpg'; $base64Data = $matches[2]; $imageData = base64_decode($base64Data); if($imageData === false) return; // Validate it's actually an image $imageInfo = @getimagesizefromstring($imageData); if($imageInfo === false) return; // Write to a temp file $tmpFile = wp_tempnam('ai_image_.' . $extension); file_put_contents($tmpFile, $imageData); // Prepare the file array for media_handle_sideload $fileArray = [ 'name' => 'ai-generated-image.' . $extension, 'tmp_name' => $tmpFile ]; // Ensure required WordPress functions are available if(!function_exists('media_handle_sideload')){ require_once ABSPATH . 'wp-admin/includes/image.php'; require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/media.php'; } $attachmentId = media_handle_sideload($fileArray, 0); // Clean up temp file if it still exists if(file_exists($tmpFile)) @unlink($tmpFile); if(is_wp_error($attachmentId)) return; // Update the media data with the permanent WordPress attachment info $mediaData->URL = wp_get_attachment_url($attachmentId); $mediaData->Id = $attachmentId; } public function CloneEmail() { $name=$this->GetRequired('Name'); $id=Sanitizer::SanitizeNumber($this->GetRequired('Id')); $repository=new EmailRepository($this->Loader); $email=$repository->GetEmailOptions($id); $email->Id=0; $email->Name=$name; // Validate PHP code security for cloned template $error = SaveManager::ValidatePHPCodeSecurity(0, $email->CustomFields, $this->Loader); if($error !== null) $this->SendErrorMessage($error); try{ $repository->SaveEmail($email);; }catch (\Exception $e) { $this->SendException($e); } $this->SendSuccessMessage($email->Id); } public function DeactivateLicense(){ Activator::DeleteLicense(); $this->SendSuccessMessage(''); } /** * AI Generate Template — calls the AI provider to generate an email template. */ public function AIGenerateTemplate(){ $this->VerifyAINonce(); $message = $this->GetRequired('message'); $history = $this->GetOptional('history', []); $model = $this->GetRequired('model'); $files = $this->GetOptional('files', []); $promptName = $this->GetOptional('promptName', 'email_template_prompt'); // Get API key for the selected model from saved settings $aiModels = get_option('rnadem_ai_models', []); $apiKey = ''; if (is_array($aiModels) || is_object($aiModels)) { foreach ($aiModels as $m) { $m = (object) $m; if (isset($m->Name) && $m->Name === $model && !empty($m->APIKey)) { $apiKey = $m->APIKey; break; } } } require_once $this->Loader->DIR . 'api/ai/AITemplateProcessor.php'; $processor = new \rnadvanceemailingwc\api\AITemplateProcessor(); $result = $processor->process( $message, is_array($history) ? $history : [], $model, $apiKey, is_array($files) ? $files : [], $promptName ); if (isset($result['error'])) { $this->SendErrorMessage($result['error']); } $this->SendSuccessMessage($result); } /** * AI Get Prompt — returns the system prompt for external mode. */ public function AIGetPrompt(){ $this->VerifyAINonce(); $promptName = $this->GetOptional('promptName', 'email_template_prompt'); require_once $this->Loader->DIR . 'api/ai/AITemplateProcessor.php'; $processor = new \rnadvanceemailingwc\api\AITemplateProcessor(); $systemPrompt = $processor->getSystemPrompt($promptName); if ($systemPrompt === false) { $this->SendErrorMessage(__('Could not load AI prompt template file.', 'advanced-emailing-for-woocommerce')); } $this->SendSuccessMessage([ 'systemPrompt' => $systemPrompt ]); } /** * Verifies the nonce for AI endpoints, accepting either the EmailList or EmailBuilder nonce. * This is needed because AI features are used from both pages. */ private function VerifyAINonce(){ $nonce = ''; if (isset($_GET['_nonce'])) $nonce = $_GET['_nonce']; if (isset($_POST['_nonce'])) $nonce = $_POST['_nonce']; $prefix = $this->Loader->Prefix; if ($nonce === '' || (!wp_verify_nonce($nonce, $prefix . '_RNEmailList') && !wp_verify_nonce($nonce, $prefix . '_RNEmailBuilder'))) { $this->SendErrorMessage(__('Invalid request, please refresh the screen and try again', 'advanced-emailing-for-woocommerce')); } } /** * Preview AI Template — renders converted EmailBuilderOptionsDTO through the plugin's EmailRenderer. * Returns the rendered HTML so the AI dialog can display the plugin's actual output. */ public function PreviewAITemplate(){ $options = $this->GetRequired('Options'); $emailBuilder = (new EmailBuilderOptionsDTO())->Merge($options); $retriever = new TestOrderRetriever($this->Loader); $emailRenderer = new EmailRenderer($this->Loader, $emailBuilder, $retriever); $emailRenderer->Initialize(); $renderedHtml = $emailRenderer->Render(); $this->SendSuccessMessage([ 'html' => $renderedHtml ]); } }