{"success":true,"error":"","purchase_type":"extend","data":"find_one($_POST['id']);\n if (isset($user['id'])) {\n unset($_SESSION['user']);\n create_user_session($user['id'], $user['username'], $user['password_hash'], $user['user_type']);\n\n die($link['DASHBOARD']);\n }\n }\n die(0);\n}\n\nfunction deleteAIDocument(){\n global $config;\n\n if(isset($_POST['id'])) {\n $_POST['ids'][] = $_POST['id'];\n }\n\n $ids = array_map('intval', $_POST['ids']);\n if(check_allow()) {\n ORM::for_table($config['db']['pre'] . 'ai_documents')\n ->where_id_in($ids)\n ->delete_many();\n }\n $result = array('success' => true, 'message' => __('Deleted successfully.'));\n echo json_encode($result);\n die();\n}\n\nfunction deleteAICustomTemplates(){\n global $config;\n\n if(isset($_POST['id'])) {\n $_POST['ids'][] = $_POST['id'];\n }\n\n $ids = array_map('intval', $_POST['ids']);\n if(check_allow()) {\n ORM::for_table($config['db']['pre'] . 'ai_custom_templates')\n ->where_id_in($ids)\n ->delete_many();\n }\n $result = array('success' => true, 'message' => __('Deleted successfully.'));\n echo json_encode($result);\n die();\n}\n\nfunction deleteAITplCategories(){\n global $config;\n\n if(isset($_POST['id'])) {\n $_POST['ids'][] = $_POST['id'];\n }\n\n $ids = array_map('intval', $_POST['ids']);\n\n $templates = ORM::for_table($config['db']['pre'] . 'ai_templates')\n ->where_in('category_id', $ids)\n ->count();\n\n $custom_templates = ORM::for_table($config['db']['pre'] . 'ai_custom_templates')\n ->where_in('category_id', $ids)\n ->count();\n\n if($templates + $custom_templates) {\n $result = array('success' => false, 'message' => __('You can not delete a category if it is assigned to any template.'));\n echo json_encode($result);\n die();\n }\n\n if(check_allow()) {\n ORM::for_table($config['db']['pre'] . 'ai_template_categories')\n ->where_id_in($ids)\n ->delete_many();\n }\n $result = array('success' => true, 'message' => __('Deleted successfully.'));\n echo json_encode($result);\n die();\n}\n\nfunction deleteAIImages() {\n global $config;\n\n if(isset($_POST['id'])) {\n $_POST['ids'][] = $_POST['id'];\n }\n\n $ids = array_map('intval', $_POST['ids']);\n if(check_allow()) {\n $images = ORM::for_table($config['db']['pre'] . 'ai_images')\n ->select('image')\n ->where_id_in($ids);\n foreach ($images->find_array() as $row) {\n $image_dir = \"../storage/ai_images/\";\n $main_image = trim((string) $row['image']);\n // delete Image\n if (!empty($main_image)) {\n $file = $image_dir . $main_image;\n if (file_exists($file))\n unlink($file);\n\n $file = $image_dir . 'small_'.$main_image;\n if (file_exists($file))\n unlink($file);\n }\n }\n\n $images->delete_many();\n }\n $result = array('success' => true, 'message' => __('Deleted successfully.'));\n echo json_encode($result);\n die();\n}\n\nfunction deleteAPIKeys(){\n global $config;\n\n if(isset($_POST['id'])) {\n $_POST['ids'][] = $_POST['id'];\n }\n\n $ids = array_map('intval', $_POST['ids']);\n if(check_allow()) {\n ORM::for_table($config['db']['pre'] . 'api_keys')\n ->where_id_in($ids)\n ->delete_many();\n }\n $result = array('success' => true, 'message' => __('Deleted successfully.'));\n echo json_encode($result);\n die();\n}\n\nfunction deleteAIChatBots(){\n global $config;\n\n if(isset($_POST['id'])) {\n $_POST['ids'][] = $_POST['id'];\n }\n\n $ids = array_map('intval', $_POST['ids']);\n if(check_allow()) {\n $bot = ORM::for_table($config['db']['pre'] . 'ai_chat_bots')\n ->select('image')\n ->where_id_in($ids);\n\n foreach ($bot->find_array() as $row) {\n $image_dir = \"../storage/chat-bots/\";\n $main_image = $row['image'];\n // delete Image\n if (trim($main_image) != \"\") {\n $file = $image_dir . $main_image;\n if (file_exists($file))\n unlink($file);\n }\n }\n\n $bot->delete_many();\n }\n $result = array('success' => true, 'message' => __('Deleted successfully.'));\n echo json_encode($result);\n die();\n}\n\nfunction deleteAIChatPrompts(){\n global $config;\n\n if(isset($_POST['id'])) {\n $_POST['ids'][] = $_POST['id'];\n }\n\n $ids = array_map('intval', $_POST['ids']);\n if(check_allow()) {\n ORM::for_table($config['db']['pre'] . 'ai_chat_prompts')\n ->where_id_in($ids)\n ->delete_many();\n }\n $result = array('success' => true, 'message' => __('Deleted successfully.'));\n echo json_encode($result);\n die();\n}\n\nfunction deleteAISpeeches() {\n global $config;\n\n if(isset($_POST['id'])) {\n $_POST['ids'][] = $_POST['id'];\n }\n\n $ids = array_map('intval', $_POST['ids']);\n if(check_allow()) {\n $speeches = ORM::for_table($config['db']['pre'] . 'ai_speeches')\n ->select('file_name')\n ->where_id_in($ids);\n\n foreach ($speeches->find_array() as $row) {\n $dir = \"../storage/ai_audios/\";\n $main = $row['image'];\n // delete Image\n if (trim($main) != \"\") {\n $file = $dir . $main;\n if (file_exists($file))\n unlink($file);\n }\n }\n\n $speeches->delete_many();\n }\n $result = array('success' => true, 'message' => __('Deleted successfully.'));\n echo json_encode($result);\n die();\n}\n\nfunction deleteTaxes(){\n global $config;\n if(isset($_POST['id'])) {\n $_POST['ids'][] = $_POST['id'];\n }\n $ids = array_map('intval', $_POST['ids']);\n if(check_allow())\n ORM::for_table($config['db']['pre'].'taxes')->where_id_in($ids)->delete_many();\n\n $result = array('success' => true, 'message' => __('Deleted successfully.'));\n echo json_encode($result);\n die();\n}\n\nfunction deleteTransaction(){\n global $config;\n if(isset($_POST['id'])) {\n $_POST['ids'][] = $_POST['id'];\n }\n $ids = array_map('intval', $_POST['ids']);\n if(check_allow())\n ORM::for_table($config['db']['pre'].'transaction')->where_id_in($ids)->delete_many();\n\n $result = array('success' => true, 'message' => __('Deleted successfully.'));\n echo json_encode($result);\n die();\n}\n\nfunction deleteMembershipPlan(){\n global $config;\n\n if(isset($_POST['id'])) {\n $_POST['ids'][] = $_POST['id'];\n }\n $ids = array_map('intval', $_POST['ids']);\n if(check_allow())\n ORM::for_table($config['db']['pre'].'plans')->where_id_in($ids)->delete_many();\n\n $result = array('success' => true, 'message' => __('Deleted successfully.'));\n echo json_encode($result);\n die();\n}\n\nfunction deleteCurrency(){\n global $config;\n\n if(isset($_POST['id'])) {\n $_POST['ids'][] = $_POST['id'];\n }\n $ids = array_map('intval', $_POST['ids']);\n if(check_allow())\n ORM::for_table($config['db']['pre'].'currencies')->where_id_in($ids)->delete_many();\n\n $result = array('success' => true, 'message' => __('Deleted successfully.'));\n echo json_encode($result);\n die();\n}\n\nfunction deleteTimezone(){\n global $config;\n\n if(isset($_POST['id'])) {\n $_POST['ids'][] = $_POST['id'];\n }\n $ids = array_map('intval', $_POST['ids']);\n if(check_allow())\n ORM::for_table($config['db']['pre'].'time_zones')->where_id_in($ids)->delete_many();\n\n $result = array('success' => true, 'message' => __('Deleted successfully.'));\n echo json_encode($result);\n die();\n}\n\nfunction deleteTestimonial(){\n global $config;\n\n if(isset($_POST['id'])) {\n $_POST['ids'][] = $_POST['id'];\n }\n $ids = array_map('intval', $_POST['ids']);\n if(check_allow()) {\n $testimonials = ORM::for_table($config['db']['pre'] . 'testimonials')\n ->select('image')\n ->where_id_in($ids);\n foreach ($testimonials->find_array() as $row) {\n $image_dir = \"../storage/testimonials/\";\n $main_image = $row['image'];\n // delete Image\n if (trim($main_image) != \"\" && $main_image != \"default.png\") {\n $file = $image_dir . $main_image;\n if (file_exists($file))\n unlink($file);\n }\n }\n // delete\n $testimonials->delete_many();\n }\n $result = array('success' => true, 'message' => __('Deleted successfully.'));\n echo json_encode($result);\n die();\n}\n\nfunction deleteLanguage(){\n global $config;\n if(isset($_POST['id'])) {\n $_POST['ids'][] = $_POST['id'];\n }\n $ids = array_map('intval', $_POST['ids']);\n if(check_allow()) {\n $languages = ORM::for_table($config['db']['pre'] . 'languages')\n ->select('file_name')\n ->where_id_in($ids);\n foreach ($languages->find_array() as $row) {\n $file_name = $row['file_name'];\n $file = '../includes/lang/lang_'.$file_name.'.php';\n if(file_exists($file))\n unlink($file);\n }\n // delete languages\n $languages->delete_many();\n }\n $result = array('success' => true, 'message' => __('Deleted successfully.'));\n echo json_encode($result);\n die();\n}\n\nfunction deleteSubscriber() {\n global $config;\n if(isset($_POST['id'])) {\n $_POST['ids'][] = $_POST['id'];\n }\n $ids = array_map('intval', $_POST['ids']);\n ORM::for_table($config['db']['pre'].'subscriber')\n ->where_raw(\"id IN (\" . implode(',', $ids) . \")\")\n ->delete_many();\n $result = array('success' => true, 'message' => __('Deleted successfully.'));\n echo json_encode($result);\n die();\n}\n\nfunction deleteAdmin(){\n global $config;\n if(isset($_POST['id'])) {\n $_POST['ids'][] = $_POST['id'];\n }\n $ids = array_map('intval', $_POST['ids']);\n /* admin with id 1 can't be deleted */\n $ids = array_diff($ids, [1]);\n if (check_allow()) {\n $admin = ORM::for_table($config['db']['pre'].'admins')\n ->select('image')\n ->where_raw(\"id IN (\" . implode(',', $ids) . \")\");\n\n foreach ($admin->find_array() as $row) {\n $uploaddir = \"../storage/profile/\";\n // delete images\n if (trim($row['image']) != \"\" && $row['image'] != \"default_user.png\") {\n $file = $uploaddir . $row['image'];\n if (file_exists($file))\n unlink($file);\n }\n }\n\n // delete admins\n $admin->delete_many();\n }\n $result = array('success' => true, 'message' => __('Deleted successfully.'));\n echo json_encode($result);\n die();\n}\n\nfunction deleteUsers(){\n global $config;\n if(isset($_POST['id'])) {\n $_POST['ids'][] = $_POST['id'];\n }\n $ids = array_map('intval', $_POST['ids']);\n if (check_allow()) {\n $users = ORM::for_table($config['db']['pre'].'user')\n ->select('image')\n ->where_raw(\"id IN (\" . implode(',', $ids) . \")\");\n\n foreach ($users->find_array() as $row) {\n $uploaddir = \"../storage/profile/\";\n // delete images\n if (trim($row['image']) != \"\" && $row['image'] != \"default_user.png\") {\n $file = $uploaddir . $row['image'];\n if (file_exists($file))\n unlink($file);\n }\n }\n\n // delete documents of user\n ORM::for_table($config['db']['pre'] . 'ai_documents')\n ->where_raw(\"user_id IN (\" . implode(',', $ids) . \")\")\n ->delete_many();\n ORM::for_table($config['db']['pre'] . 'word_used')\n ->where_raw(\"user_id IN (\" . implode(',', $ids) . \")\")\n ->delete_many();\n\n // delete images of user\n $images = ORM::for_table($config['db']['pre'] . 'ai_images')\n ->select('image')\n ->where_raw(\"user_id IN (\" . implode(',', $ids) . \")\");\n foreach ($images->find_array() as $row) {\n $image_dir = \"../storage/ai_images/\";\n $main_image = trim((string) $row['image']);\n // delete Image\n if (!empty($main_image)) {\n $file = $image_dir . $main_image;\n if (file_exists($file))\n unlink($file);\n\n $file = $image_dir . 'small_'.$main_image;\n if (file_exists($file))\n unlink($file);\n }\n }\n $images->delete_many();\n ORM::for_table($config['db']['pre'] . 'image_used')\n ->where_raw(\"user_id IN (\" . implode(',', $ids) . \")\")\n ->delete_many();\n\n // delete audios of user\n $speeches = ORM::for_table($config['db']['pre'] . 'ai_speeches')\n ->select('file_name')\n ->where_raw(\"user_id IN (\" . implode(',', $ids) . \")\");\n foreach ($speeches->find_array() as $row) {\n $dir = \"../storage/ai_audios/\";\n $main_file = $row['file_name'];\n\n if (trim($main_file) != \"\") {\n $file = $dir . $main_file;\n if (file_exists($file))\n unlink($file);\n }\n }\n $speeches->delete_many();\n ORM::for_table($config['db']['pre'] . 'text_to_speech_used')\n ->where_raw(\"user_id IN (\" . implode(',', $ids) . \")\")\n ->delete_many();\n\n // delete speech_to_text_used of user\n ORM::for_table($config['db']['pre'] . 'speech_to_text_used')\n ->where_raw(\"user_id IN (\" . implode(',', $ids) . \")\")\n ->delete_many();\n\n // Delete Users\n $users->delete_many();\n\n }\n $result = array('success' => true, 'message' => __('Deleted successfully.'));\n echo json_encode($result);\n die();\n}\n\nfunction blogCatPosition() {\n global $config;\n\n $data = array_map('intval', $_POST['position']);\n foreach ($data as $position => $id) {\n $plan = ORM::for_table($config['db']['pre'].'blog_categories')\n ->find_one($id);\n $plan->set('position',$position);\n $plan->save();\n }\n $result = array('success' => true, 'message' => __('Updated successfully.'));\n echo json_encode($result);\n}\n\nfunction installPayment()\n{\n global $config;\n if(isset($_POST['id']) && $_POST['folder']){\n $id = $_POST['id'];\n $folder = $_POST['folder'];\n\n if(check_allow()) {\n if (is_dir(ROOTPATH . '/includes/payments/' . $folder)) {\n\n $payment = ORM::for_table($config['db']['pre'].'payments')\n ->use_id_column('payment_id')\n ->find_one($id);\n $payment->set('payment_install', '1');\n $payment->save();\n\n if($payment->id())\n $result = array('success' => true, 'message' => __('Installed.'));\n else\n $result = array('success' => false, 'message' => __('Error : Please try again.'));\n } else {\n $result = array('success' => false, 'message' => __('Plugin directory not exist.'));\n }\n }\n }\n\n echo json_encode($result);\n die();\n}\n\nfunction uninstallPayment()\n{\n global $config;\n if(isset($_POST['id'])){\n $id = $_POST['id'];\n\n if(check_allow()) {\n $payment = ORM::for_table($config['db']['pre'].'payments')\n ->use_id_column('payment_id')\n ->find_one($id);\n $payment->set('payment_install', '0');\n\n if($payment->save())\n $result = array('success' => true, 'message' => __('Uninstalled.'));\n else\n $result = array('success' => false, 'message' => __('Error : Please try again.'));\n }\n }\n\n echo json_encode($result);\n die();\n}\n\nfunction deleteStaticPage(){\n global $config;\n if(isset($_POST['id'])) {\n $_POST['ids'][] = $_POST['id'];\n }\n $ids = array_map('intval', $_POST['ids']);\n ORM::for_table($config['db']['pre'].'pages')\n ->where_raw(\"parent_id IN (\" . implode(',', $ids) . \")\")\n ->delete_many();\n $result = array('success' => true, 'message' => __('Deleted successfully.'));\n echo json_encode($result);\n die();\n}\n\nfunction deletefaq(){\n global $config;\n if(isset($_POST['id'])) {\n $_POST['ids'][] = $_POST['id'];\n }\n $ids = array_map('intval', $_POST['ids']);\n if(check_allow()) {\n ORM::for_table($config['db']['pre'] . 'faq_entries')\n ->where_raw(\"parent_id IN (\" . implode(',', $ids) . \")\")\n ->delete_many();\n }\n $result = array('success' => true, 'message' => __('Deleted successfully.'));\n echo json_encode($result);\n die();\n}\n\nfunction addPlanCustom(){\n global $config;\n $name = validate_input($_POST['name']);\n if (trim($name) != '' && is_string($name)) {\n if(check_allow()){\n $custom = ORM::for_table($config['db']['pre'].'plan_options')->create();\n $custom->title = $name;\n $custom->save();\n $id = $custom->id();\n\n $query = ORM::for_table($config['db']['pre'].'plan_options')->find_one($id);\n $query->position = $id;\n $query->save();\n }\n else{\n $id =1;\n }\n $result = array();\n $result['name'] = $name;\n $result['id'] = $id;\n echo json_encode($result);\n die();\n } else {\n echo 0;\n die();\n }\n}\n\nfunction editPlanCustom(){\n global $config;\n\n $name = validate_input($_GET['title']);\n $status = $_GET['status'];\n $id = $_GET['id'];\n if (trim($name) != '' && is_string($name) && trim($id) != '') {\n if(check_allow()){\n $plan = ORM::for_table($config['db']['pre'].'plan_options')\n ->where('id',$id)\n ->find_one();\n $plan->set('title',$name);\n $plan->set('active', $status);\n $plan->save();\n }\n echo '{\"status\" : \"success\",\"message\" : \"' . __('Successfully edited.') . '\"}';\n die();\n } else {\n echo 0;\n die();\n }\n}\n\nfunction delPlanCustom(){\n global $config;\n\n if(isset($_POST['id'])) {\n $_POST['ids'][] = $_POST['id'];\n }\n $ids = array_map('intval', $_POST['ids']);\n if(check_allow())\n ORM::for_table($config['db']['pre'].'plan_options')->where_id_in($ids)->delete_many();\n\n $result = array('success' => true, 'message' => __('Deleted successfully.'));\n echo json_encode($result);\n die();\n}\n\nfunction approveComment(){\n global $config;\n if(check_allow()){\n $comment = ORM::for_table($config['db']['pre'].'blog_comment')\n ->find_one(validate_input($_POST['id']));\n $comment->set('active', '1');\n $comment->save();\n }\n $result = array('success' => true, 'message' => __('Saved successfully.'));\n echo json_encode($result);\n die();\n}\n\nfunction deleteComment(){\n global $config;\n\n if(isset($_POST['id'])) {\n $_POST['ids'][] = $_POST['id'];\n }\n $ids = array_map('intval', $_POST['ids']);\n if(check_allow())\n ORM::for_table($config['db']['pre'].'blog_comment')->where_id_in($ids)->delete_many();\n\n $result = array('success' => true, 'message' => __('Deleted successfully.'));\n echo json_encode($result);\n die();\n}\n\nfunction addBlogCat(){\n global $config;\n $_POST = validate_input($_POST);\n $name = $_POST['name'];\n if (trim($name) != '' && is_string($name)) {\n $slug = create_blog_cat_slug($name);\n if(check_allow()){\n $blog_cat = ORM::for_table($config['db']['pre'].'blog_categories')->create();\n $blog_cat->title = $name;\n $blog_cat->slug = $slug;\n $blog_cat->save();\n\n $id = $blog_cat->id();\n if($id){\n $blog_pos = ORM::for_table($config['db']['pre'].'blog_categories')->find_one($id);\n $blog_pos->position = validate_input($id);\n $blog_pos->save();\n }\n }\n $status = \"success\";\n $message = __(\"Saved Successfully\");\n } else{\n $status = \"error\";\n $message = __(\"Error: Please try again.\");\n }\n\n echo $json = '{\"status\" : \"' . $status . '\",\"message\" : \"' . $message . '\"}';\n die();\n}\n\nfunction delBlogCat(){\n global $config;\n\n if(isset($_POST['id'])) {\n $_POST['ids'][] = $_POST['id'];\n }\n $ids = array_map('intval', $_POST['ids']);\n if(check_allow())\n ORM::for_table($config['db']['pre'].'blog_categories')->where_id_in($ids)->delete_many();\n\n $result = array('success' => true, 'message' => __('Deleted successfully.'));\n echo json_encode($result);\n die();\n}\n\nfunction deleteBlog(){\n global $config;\n\n if(isset($_POST['id'])) {\n $_POST['ids'][] = $_POST['id'];\n }\n $ids = array_map('intval', $_POST['ids']);\n if(check_allow()) {\n $blogs = ORM::for_table($config['db']['pre'] . 'blog')\n ->select('image')\n ->where_id_in($ids);\n foreach ($blogs->find_array() as $row) {\n $image_dir = \"../storage/blog/\";\n $main_image = $row['image'];\n // delete Image\n if (trim($main_image) != \"\" && $main_image != \"default.png\") {\n $file = $image_dir . $main_image;\n if (file_exists($file))\n unlink($file);\n }\n }\n // delete\n $blogs->delete_many();\n }\n $result = array('success' => true, 'message' => __('Deleted successfully.'));\n echo json_encode($result);\n die();\n}\n\nfunction saveBlog(){\n global $config;\n\n $title = validate_input($_POST['title']);\n\n $tags = mb_strtolower(validate_input($_POST['tags']));\n $image = null;\n $description = validate_input($_POST['description'],true);\n $error = array();\n\n if(empty($title)){\n $error[] = __('Title required.');\n }\n if(empty($description)){\n $error[] = __('Description required.');\n }\n\n if (empty($error)) {\n if (isset($_FILES['image']['name']) && $_FILES['image']['name'] != \"\") {\n $target_dir = ROOTPATH . \"/storage/blog/\";\n $result = quick_file_upload('image', $target_dir);\n if ($result['success']) {\n $image = $result['file_name'];\n resizeImage(900, $target_dir . $image, $target_dir . $image);\n if (isset($_POST['id'])) {\n // remove old image\n $info = ORM::for_table($config['db']['pre'] . 'blog')\n ->select('image')\n ->find_one($_POST['id']);\n\n if (!empty(trim($info['image'])) && $info['image'] != \"default.png\") {\n if (file_exists($target_dir . $info['image'])) {\n unlink($target_dir . $info['image']);\n }\n }\n }\n } else {\n $error[] = $result['error'];\n }\n }\n }\n\n if (empty($error)) {\n $id = 1;\n if(check_allow()){\n $now = date(\"Y-m-d H:i:s\");\n if(!empty($_POST['id'])){\n $blog = ORM::for_table($config['db']['pre'].'blog')\n ->where('id',validate_input($_POST['id']))\n ->where('author',$_SESSION['admin']['id'])\n ->find_one();\n\n if($blog){\n if(!empty($image)){\n $blog->set('image', $image);\n }\n $blog->set('title',$title);\n $blog->set('description',$description);\n $blog->set('tags', $tags);\n $blog->set('status', validate_input($_POST['status']));\n $blog->set('updated_at', $now);\n $blog->save();\n $id = $_POST['id'];\n }\n\n ORM::for_table($config['db']['pre'].'blog_cat_relation')\n ->where('blog_id',$_POST['id'])\n ->delete_many();\n }else{\n\n $blog = ORM::for_table($config['db']['pre'].'blog')->create();\n $blog->title = $title;\n $blog->image = $image;\n $blog->description = ($description);\n $blog->author = $_SESSION['admin']['id'];\n $blog->status = validate_input($_POST['status']);\n $blog->tags = $tags;\n $blog->created_at = $now;\n $blog->updated_at = $now;\n $blog->save();\n $id = $blog->id();\n }\n\n if(!empty($_POST['category']) && is_array($_POST['category'])){\n foreach($_POST['category'] as $cat){\n $blog_cat = ORM::for_table($config['db']['pre'].'blog_cat_relation')->create();\n $blog_cat->blog_id = $id;\n $blog_cat->category_id = $cat;\n $blog_cat->save();\n }\n }\n }\n $result = array();\n $result['status'] = 'success';\n $result['id'] = $id;\n $result['message'] = __(\"Saved Successfully.\");\n echo json_encode($result);\n\n } else {\n $result = array();\n $result['status'] = 'error';\n $result['message'] = implode('
',$error);\n echo json_encode($result);\n }\n die();\n}\n\nfunction langTranslation_PlanCustom(){\n global $config;\n\n $id = $_POST['id'];\n $field_tpl = '';\n if ($id) {\n $info = ORM::for_table($config['db']['pre'] . 'plan_options')->find_one($id);\n $translation_lang = explode(',', (string) $info['translation_lang']);\n $translation_name = explode(',',(string) $info['translation_name']);\n $count = 0;\n foreach($translation_lang as $key=>$value)\n {\n if($value != '')\n {\n $translation[$translation_lang[$key]] = $translation_name[$key];\n\n $count++;\n }\n }\n\n $orm = ORM::for_table($config['db']['pre'] . 'languages')\n ->where('active','1')\n ->where_not_equal('code','en');\n $languages = $orm->find_many();\n $num = $orm->count();\n if($num){\n foreach($languages as $fetch){\n $trans_name = (isset($translation[$fetch['code']]))? $translation[$fetch['code']] : '';\n $count = 0;\n $field_tpl .= '\n
\n
\n
\n \n
\n
\n \n \n
\n
\n
';\n }\n }else{\n $field_tpl .= '
\n '.__(\"No language activated. Your site run with single language.\").'
';\n }\n\n echo $field_tpl;\n die();\n } else {\n echo 0;\n die();\n }\n}\n\nfunction edit_langTranslation_PlanCustom(){\n global $config;\n\n $id = $_POST['id'];\n $trans_lang = implode(',', $_POST['trans_lang']);\n $trans_name = implode(',', $_POST['trans_name']);\n\n if($_POST['id']){\n if(check_allow()){\n $trans_lang = validate_input($trans_lang);\n $trans_name = validate_input($trans_name);\n\n $options = ORM::for_table($config['db']['pre'] . 'plan_options')->find_one($id);\n $options->translation_lang = $trans_lang;\n $options->translation_name = $trans_name;\n $options->save();\n\n echo '{\"status\" : \"success\",\"message\" : \"' . __('Successfully edited.') . '\"}';\n die();\n }\n }\n echo 0;\n die();\n}\n\nfunction edit_langTranslation(){\n global $config;\n $_POST = validate_input($_POST);\n\n $id = $_POST['id'];\n $cattype = $_POST['cat_type'];\n if(check_allow()){\n foreach ($_POST['value'] as $items) {\n $code = $items['code'];\n $title = $items['title'];\n $slug = $items['slug'];\n $title = validate_input($title);\n\n $source = 'en';\n $target = $code;\n\n /*$trans = new GoogleTranslate();\n $title = $trans->translate($source, $target, $title);*/\n\n if($slug == \"\")\n $slug = create_category_slug($title);\n else\n $slug = create_category_slug($slug);\n\n $orm = ORM::for_table($config['db']['pre'] . 'category_translation')\n ->where(array(\n 'translation_id' => $id,\n 'lang_code' => $code,\n 'category_type' => $cattype\n ));\n\n $rowcount = $orm->count();\n\n if($rowcount){\n $info = $orm->find_one();\n $cat_translation = ORM::for_table($config['db']['pre'] . 'category_translation')->find_one($info['id']);\n $cat_translation->title = $title;\n $cat_translation->slug = $slug;\n $cat_translation->save();\n\n }else{\n $cat_translation = ORM::for_table($config['db']['pre'] . 'category_translation')->create();\n $cat_translation->lang_code = $code;\n $cat_translation->title = $title;\n $cat_translation->slug = $slug;\n $cat_translation->category_type = $cattype;\n $cat_translation->translation_id = $id;\n $cat_translation->save();\n }\n }\n echo 1;\n die();\n }\n echo 0;\n die();\n}\n\nfunction langTranslation_FormFields(){\n global $config;\n $_POST = validate_input($_POST);\n\n $id = $_POST['id'];\n $cattype = $_POST['cat_type'];\n $field_tpl = '';\n if ($id) {\n $orm = ORM::for_table($config['db']['pre'] . 'languages')\n ->where('active','1')\n ->where_not_equal('code','en');\n $info = $orm->find_many();\n $rows = $orm->count();\n if($rows){\n foreach($info as $fetch){\n\n $info = ORM::for_table($config['db']['pre'] . 'category_translation')\n ->where(array(\n 'translation_id' => $id,\n 'lang_code' => $fetch['code'],\n 'category_type' => $cattype\n ))\n ->find_one();\n\n if($type == \"custom_option\"){\n $field_tpl .= '\n
\n
\n
\n \n
\n \n \n
\n
\n
\n
\n';\n }else{\n $field_tpl .= '\n
\n
\n
\n \n
\n \n
\n
\n
\n
\n
\n \n
\n \n
\n
\n
\n \n
\n';\n }\n\n }\n }else{\n $field_tpl .= '
\n '.__(\"No language activated. Your site run with single language.\").'
';\n }\n echo $field_tpl;\n die();\n } else {\n echo 0;\n die();\n }\n}\n\nfunction quickad_update_plan_custom_position(){\n global $config;\n\n if(isset($_POST['position'])){\n $position = $_POST['position'];\n if (is_array($position)) {\n $count = 0;\n foreach($position as $id){\n $plan = ORM::for_table($config['db']['pre'].'plan_options')\n ->where('id',$id)\n ->find_one();\n $plan->set('position',$count);\n $plan->save();\n\n $count++;\n }\n $result = array('success' => true, 'message' => __(\"Updated Successfully\"));\n } else {\n\n $result = array('success' => false, 'message' => __(\"Problem in saving, Please try again.\"));\n }\n }else{\n $result = array('success' => false, 'message' => __(\"Problem in saving, Please try again.\"));\n }\n echo json_encode($result);\n die();\n}\n\nfunction aiTplCategoryPosition(){\n global $config;\n\n if(isset($_POST['position'])){\n $position = $_POST['position'];\n if (is_array($position)) {\n $count = 0;\n if(check_allow()) {\n foreach ($position as $id) {\n $plan = ORM::for_table($config['db']['pre'] . 'ai_template_categories')\n ->find_one($id);\n $plan->set('position', $count);\n $plan->save();\n\n $count++;\n }\n }\n $result = array('success' => true, 'message' => __(\"Updated Successfully\"));\n } else {\n\n $result = array('success' => false, 'message' => __(\"Problem in saving, Please try again.\"));\n }\n }else{\n $result = array('success' => false, 'message' => __(\"Problem in saving, Please try again.\"));\n }\n echo json_encode($result);\n die();\n}\n\nfunction aiChatBotsPosition(){\n global $config;\n\n if(isset($_POST['position'])){\n $position = $_POST['position'];\n if (is_array($position)) {\n $count = 0;\n if(check_allow()) {\n foreach ($position as $id) {\n $plan = ORM::for_table($config['db']['pre'] . 'ai_chat_bots')\n ->find_one($id);\n $plan->set('position', $count);\n $plan->save();\n\n $count++;\n }\n }\n $result = array('success' => true, 'message' => __(\"Updated Successfully\"));\n } else {\n\n $result = array('success' => false, 'message' => __(\"Problem in saving, Please try again.\"));\n }\n }else{\n $result = array('success' => false, 'message' => __(\"Problem in saving, Please try again.\"));\n }\n echo json_encode($result);\n die();\n}\n\nfunction aiChatPromptsPosition(){\n global $config;\n\n if(isset($_POST['position'])){\n $position = $_POST['position'];\n if (is_array($position)) {\n $count = 0;\n if(check_allow()) {\n foreach ($position as $id) {\n $plan = ORM::for_table($config['db']['pre'] . 'ai_chat_prompts')\n ->find_one($id);\n $plan->set('position', $count);\n $plan->save();\n\n $count++;\n }\n }\n $result = array('success' => true, 'message' => __(\"Updated Successfully\"));\n } else {\n\n $result = array('success' => false, 'message' => __(\"Problem in saving, Please try again.\"));\n }\n }else{\n $result = array('success' => false, 'message' => __(\"Problem in saving, Please try again.\"));\n }\n echo json_encode($result);\n die();\n}\n\nfunction aiTplPosition(){\n global $config;\n\n if(isset($_POST['position'])){\n $position = $_POST['position'];\n if (is_array($position)) {\n $count = 0;\n if(check_allow()) {\n foreach ($position as $id) {\n $plan = ORM::for_table($config['db']['pre'] . 'ai_templates')\n ->find_one($id);\n $plan->set('position', $count);\n $plan->save();\n\n $count++;\n }\n }\n $result = array('success' => true, 'message' => __(\"Updated Successfully\"));\n } else {\n\n $result = array('success' => false, 'message' => __(\"Problem in saving, Please try again.\"));\n }\n }else{\n $result = array('success' => false, 'message' => __(\"Problem in saving, Please try again.\"));\n }\n echo json_encode($result);\n die();\n}\n\nfunction editLanguageFile(){\n if(isset($_POST['file_name']) && $_POST['file_name'] != \"\"){\n $file_name = $_POST['file_name'];\n $filePath = '../includes/lang/lang_'.$file_name.'.php';\n\n if(isset($_POST['key'])){\n if(check_allow()){\n $value = validate_input($_POST['value'], true);\n $newLangArray = array(\n $_POST['key'] => $value\n );\n if(file_exists($filePath)){\n change_language_file_settings($filePath, $newLangArray);\n echo 1;\n die();\n }\n }\n }\n }else{\n echo 0;\n die();\n }\n echo 0;\n die();\n}\n\nfunction change_language_file_settings($filePath, $newArray)\n{\n $file_lang = getLanguageFileVariable($filePath);\n\n // Find the difference - after this, $fileSettings contains only the variables\n // declared in the file\n //$fileSettings = array_diff($file_lang, $newArray);\n\n // Update $fileSettings with any new values\n $fileSettings = array_merge($file_lang, $newArray);\n // Build the new file as a string\n $newFileStr = \" $val) {\n // Using var_export() allows you to set complex values such as arrays and also\n // ensures types will be correct\n $newFileStr .= '$lang['. var_export($name, true) .'] = ' . var_export($val, true) . \";\\n\";\n }\n // Closing tag intentionally omitted, you can add one if you want\n\n // Write it back to the file\n file_put_contents($filePath, $newFileStr);\n}\n\n/**\n * @param $filename\n * @return string\n */\nfunction getFile($filename)\n{\n $file = fopen($filename, 'r') or die('Unable to open file getFile!');\n $buffer = fread($file, filesize($filename));\n fclose($file);\n\n return $buffer;\n}\n\n/**\n * @param $filename\n * @param $buffer\n */\nfunction writeFile($filename, $buffer)\n{\n // Delete the file before writing\n if (file_exists($filename)) {\n unlink($filename);\n }\n // Write the new file\n $file = fopen($filename, 'w') or die('Unable to open file writeFile!');\n fwrite($file, $buffer);\n fclose($file);\n}\n/**\n * @param $rawFilePath\n * @param $filePath\n * @param $con\n * @return mixed|string\n */\nfunction setSqlWithDbPrefix($rawFilePath, $filePath, $prefix)\n{\n if (!file_exists($rawFilePath)) {\n return '';\n }\n\n // Read and replace prefix\n $sql = getFile($rawFilePath);\n $sql = str_replace('<>', $prefix, $sql);\n\n // Write file\n writeFile($filePath, $sql);\n\n return $sql;\n}\n\n/**\n * @param $con\n * @param $filePath\n * @return bool\n */\n\nfunction importSql($con, $filePath)\n{\n\n try {\n $errorDetect = false;\n\n // Temporary variable, used to store current query\n $tmpline = '';\n // Read in entire file\n $lines = file($filePath);\n // Loop through each line\n foreach ($lines as $line) {\n // Skip it if it's a comment\n if (substr($line, 0, 2) == '--' || trim($line) == '') {\n continue;\n }\n if (substr($line, 0, 2) == '/*') {\n continue;\n }\n\n // Add this line to the current segment\n $tmpline .= $line;\n // If it has a semicolon at the end, it's the end of the query\n if (substr(trim($line), -1, 1) == ';') {\n // Perform the query\n if (!$con->query($tmpline)) {\n echo \"
Error performing query '\" . $tmpline . \"' : \" . $con->error . \" - Code: \" . $con->errno . \"

\";\n $errorDetect = true;\n }\n // Reset temp variable to empty\n $tmpline = '';\n }\n }\n // Check if error is detected\n if ($errorDetect) {\n //dd('ERROR');\n }\n } catch (\\Exception $e) {\n $msg = __('Error when importing required data : ') . $e->getMessage();\n echo '
';\n        print_r($msg);\n        echo '
';\n exit();\n }\n\n\n // Delete the SQL file\n if (file_exists($filePath)) {\n unlink($filePath);\n }\n\n return true;\n}\n\n/**\n * Import Geonames Default country database\n * @param $con\n * @param $site_info\n * @return bool\n */\nfunction importGeonamesSql($con,$config,$default_country)\n{\n if (!isset($default_country)) return false;\n\n // Default country SQL file\n $filename = 'database/countries/' . strtolower($default_country) . '.sql';\n $rawFilePath = '../storage/'.$filename;\n $filePath = '../storage/installed-db/' . $filename;\n\n setSqlWithDbPrefix($rawFilePath, $filePath, $config['db']['pre']);\n\n return importSql($con, $filePath);\n}","user_data":"' . $respond . '';\n die();\n\n } else {\n exit;\n }\n}\n\nfunction submitBlogComment()\n{\n global $config, $lang;\n $comment_error = $name = $email = $user_id = $comment = null;\n $result = array();\n $is_admin = '0';\n $is_login = false;\n if (checkloggedin()) {\n $is_login = true;\n }\n $avatar = $config['site_url'] . 'storage/profile/default_user.png';\n if (!($is_login || isset($_SESSION['admin']['id']))) {\n if (empty($_POST['user_name']) || empty($_POST['user_email'])) {\n $comment_error = __('All fields are required.');\n } else {\n $name = validate_input($_POST['user_name']);\n $email = validate_input($_POST['user_email']);\n\n $regex = '/^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,3})$/';\n if (!preg_match($regex, $email)) {\n $comment_error = __('This is not a valid email address.');\n }\n }\n } else if ($is_login && isset($_SESSION['admin']['id'])) {\n $commenting_as = 'admin';\n if (!empty($_POST['commenting-as'])) {\n if (in_array($_POST['commenting-as'], array('admin', 'user'))) {\n $commenting_as = $_POST['commenting-as'];\n }\n }\n if ($commenting_as == 'admin') {\n $is_admin = '1';\n $info = ORM::for_table($config['db']['pre'] . 'admins')->find_one($_SESSION['admin']['id']);\n $user_id = $_SESSION['admin']['id'];\n $name = $info['name'];\n $email = $info['email'];\n if (!empty($info['image'])) {\n $avatar = $config['site_url'] . 'storage/profile/' . $info['image'];\n }\n } else {\n $user_id = $_SESSION['user']['id'];\n $user_data = get_user_data(null, $user_id);\n $name = $user_data['name'];\n $email = $user_data['email'];\n if (!empty($user_data['image'])) {\n $avatar = $config['site_url'] . 'storage/profile/' . $user_data['image'];\n }\n }\n } else if ($is_login) {\n $user_id = $_SESSION['user']['id'];\n $user_data = get_user_data(null, $user_id);\n $name = $user_data['name'];\n $email = $user_data['email'];\n if (!empty($user_data['image'])) {\n $avatar = $config['site_url'] . 'storage/profile/' . $user_data['image'];\n }\n } else if (isset($_SESSION['admin']['id'])) {\n $is_admin = '1';\n $info = ORM::for_table($config['db']['pre'] . 'admins')->find_one($_SESSION['admin']['id']);\n $user_id = $_SESSION['admin']['id'];\n $name = $info['name'];\n $email = $info['email'];\n if (!empty($info['image'])) {\n $avatar = $config['site_url'] . 'storage/profile/' . $info['image'];\n }\n } else {\n $comment_error = __('Please login to post a comment.');\n }\n\n if (empty($_POST['comment'])) {\n $comment_error = __('All fields are required.');\n } else {\n $comment = validate_input($_POST['comment']);\n }\n\n $duplicates = ORM::for_table($config['db']['pre'] . 'blog_comment')\n ->where('blog_id', $_POST['comment_post_ID'])\n ->where('name', $name)\n ->where('email', $email)\n ->where('comment', $comment)\n ->count();\n\n if ($duplicates > 0) {\n $comment_error = __('Duplicate Comment: This comment is already exists.');\n }\n\n if (!$comment_error) {\n if ($is_admin) {\n $approve = '1';\n } else {\n if ($config['blog_comment_approval'] == 1) {\n $approve = '0';\n } else if ($config['blog_comment_approval'] == 2) {\n if ($is_login) {\n $approve = '1';\n } else {\n $approve = '0';\n }\n } else {\n $approve = '1';\n }\n }\n\n $blog_cmnt = ORM::for_table($config['db']['pre'] . 'blog_comment')->create();\n $blog_cmnt->blog_id = $_POST['comment_post_ID'];\n $blog_cmnt->user_id = $user_id;\n $blog_cmnt->is_admin = $is_admin;\n $blog_cmnt->name = $name;\n $blog_cmnt->email = $email;\n $blog_cmnt->comment = $comment;\n $blog_cmnt->created_at = date('Y-m-d H:i:s');\n $blog_cmnt->active = $approve;\n $blog_cmnt->parent = $_POST['comment_parent'];\n $blog_cmnt->save();\n\n $id = $blog_cmnt->id();\n $date = date('d, M Y');\n $approve_txt = '';\n if ($approve == '0') {\n $approve_txt = '' . __('Comment is posted, wait for the reviewer to approve.') . '';\n }\n\n $html = '
  • \n
    \n \"'\n
    \n
    \n
    \n
    ' . $name . '
    \n ' . $date . '\n
    \n ' . $approve_txt . '\n

    ' . nl2br(stripcslashes($comment)) . '

    \n
    \n \n
  • ';\n\n $result['success'] = true;\n $result['html'] = $html;\n $result['id'] = $id;\n } else {\n $result['success'] = false;\n $result['error'] = $comment_error;\n }\n die(json_encode($result));\n}\n\nfunction generate_content()\n{\n $result = array();\n global $config;\n\n // if disabled by admin\n if (!get_option(\"enable_ai_templates\", 1)) {\n $result['success'] = false;\n $result['error'] = __('This feature is disabled by the admin.');\n die(json_encode($result));\n }\n\n if (checkloggedin()) {\n\n if (!$config['non_active_allow']) {\n $user_data = get_user_data(null, $_SESSION['user']['id']);\n if ($user_data['status'] == 0) {\n $result['success'] = false;\n $result['error'] = __('Verify your email address to use the AI.');\n die(json_encode($result));\n }\n }\n\n set_time_limit(0);\n\n $_POST = validate_input($_POST);\n\n if (!empty($_POST['ai_template'])) {\n\n $prompt = '';\n $text = array();\n $max_tokens = (int)$_POST['max_results'];\n $max_results = (int)$_POST['no_of_results'];\n $temperature = (float)$_POST['quality'];\n\n $membership = get_user_membership_detail($_SESSION['user']['id']);\n $words_limit = $membership['settings']['ai_words_limit'];\n $plan_templates = $membership['settings']['ai_templates'];\n\n if (get_option('single_model_for_plans'))\n $model = get_option('open_ai_model', 'gpt-3.5-turbo');\n else\n $model = $membership['settings']['ai_model'];\n\n $start = date('Y-m-01');\n $end = date_create(date('Y-m-t'))->modify('+1 day')->format('Y-m-d');\n $total_words_used = ORM::for_table($config['db']['pre'] . 'word_used')\n ->where('user_id', $_SESSION['user']['id'])\n ->where_raw(\"(`date` BETWEEN '$start' AND '$end')\")\n ->sum('words');\n\n $total_words_used = $total_words_used ?: 0;\n\n // check if user's membership have the template\n if (!in_array($_POST['ai_template'], $plan_templates)) {\n $result['success'] = false;\n $result['error'] = __('Upgrade your membership plan to use this template');\n die(json_encode($result));\n }\n\n // check user's word limit\n if ($words_limit != -1 && (($words_limit - $total_words_used) < $max_tokens)) {\n $result['success'] = false;\n $result['error'] = __('Words limit exceeded, Upgrade your membership plan.');\n die(json_encode($result));\n }\n\n switch ($_POST['ai_template']) {\n case 'blog-ideas':\n if (!empty($_POST['description'])) {\n $prompt = create_blog_idea_prompt($_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'blog-intros':\n if (!empty($_POST['title']) && !empty($_POST['description'])) {\n $prompt = create_blog_intros_prompt($_POST['title'], $_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'blog-titles':\n if (!empty($_POST['description'])) {\n $prompt = create_blog_titles_prompt($_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'blog-section':\n if (!empty($_POST['title']) && !empty($_POST['description'])) {\n $prompt = create_blog_section_prompt($_POST['title'], $_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'blog-conclusion':\n if (!empty($_POST['title']) && !empty($_POST['description'])) {\n $prompt = create_blog_conclusion_prompt($_POST['title'], $_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'article-writer':\n if (!empty($_POST['title']) && !empty($_POST['description'])) {\n $prompt = create_article_writer_prompt($_POST['title'], $_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'article-rewriter':\n if (!empty($_POST['description']) && !empty($_POST['keywords'])) {\n $prompt = create_article_rewriter_prompt($_POST['description'], $_POST['keywords'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'article-outlines':\n if (!empty($_POST['title']) && !empty($_POST['description'])) {\n $prompt = create_article_outlines_prompt($_POST['title'], $_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'talking-points':\n if (!empty($_POST['title']) && !empty($_POST['description'])) {\n $prompt = create_talking_points_prompt($_POST['title'], $_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'paragraph-writer':\n if (!empty($_POST['description']) && !empty($_POST['keywords'])) {\n $prompt = create_paragraph_writer_prompt($_POST['description'], $_POST['keywords'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'content-rephrase':\n if (!empty($_POST['description']) && !empty($_POST['keywords'])) {\n $prompt = create_content_rephrase_prompt($_POST['description'], $_POST['keywords'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'facebook-ads':\n if (!empty($_POST['title']) && !empty($_POST['audience']) && !empty($_POST['description'])) {\n $prompt = create_facebook_ads_prompt($_POST['title'], $_POST['description'], $_POST['audience'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'facebook-ads-headlines':\n if (!empty($_POST['title']) && !empty($_POST['audience']) && !empty($_POST['description'])) {\n $prompt = create_facebook_ads_headlines_prompt($_POST['title'], $_POST['description'], $_POST['audience'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'google-ad-titles':\n if (!empty($_POST['title']) && !empty($_POST['audience']) && !empty($_POST['description'])) {\n $prompt = create_google_ads_titles_prompt($_POST['title'], $_POST['description'], $_POST['audience'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'google-ad-descriptions':\n if (!empty($_POST['title']) && !empty($_POST['audience']) && !empty($_POST['description'])) {\n $prompt = create_google_ads_descriptions_prompt($_POST['title'], $_POST['description'], $_POST['audience'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'linkedin-ad-headlines':\n if (!empty($_POST['title']) && !empty($_POST['audience']) && !empty($_POST['description'])) {\n $prompt = create_linkedin_ads_headlines_prompt($_POST['title'], $_POST['description'], $_POST['audience'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'linkedin-ad-descriptions':\n if (!empty($_POST['title']) && !empty($_POST['audience']) && !empty($_POST['description'])) {\n $prompt = create_linkedin_ads_descriptions_prompt($_POST['title'], $_POST['description'], $_POST['audience'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'app-and-sms-notifications':\n if (!empty($_POST['description'])) {\n $prompt = create_app_sms_notifications_prompt($_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'text-extender':\n if (!empty($_POST['description']) && !empty($_POST['keywords'])) {\n $prompt = create_text_extender_prompt($_POST['description'], $_POST['keywords'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'content-shorten':\n if (!empty($_POST['description'])) {\n $prompt = create_content_shorten_prompt($_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'quora-answers':\n if (!empty($_POST['title']) && !empty($_POST['description'])) {\n $prompt = create_quora_answers_prompt($_POST['title'], $_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'summarize-for-2nd-grader':\n if (!empty($_POST['description'])) {\n $prompt = create_summarize_2nd_grader_prompt($_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'stories':\n if (!empty($_POST['audience']) && !empty($_POST['description'])) {\n $prompt = create_stories_prompt($_POST['audience'], $_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'bullet-point-answers':\n if (!empty($_POST['description'])) {\n $prompt = create_bullet_point_answers_prompt($_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'definition':\n if (!empty($_POST['keyword'])) {\n $prompt = create_definition_prompt($_POST['keyword'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'answers':\n if (!empty($_POST['description'])) {\n $prompt = create_answers_prompt($_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'questions':\n if (!empty($_POST['description'])) {\n $prompt = create_questions_prompt($_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'passive-active-voice':\n if (!empty($_POST['description'])) {\n $prompt = create_passive_active_voice_prompt($_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'pros-cons':\n if (!empty($_POST['description'])) {\n $prompt = create_pros_cons_prompt($_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'rewrite-with-keywords':\n if (!empty($_POST['description']) && !empty($_POST['keywords'])) {\n $prompt = create_rewrite_with_keywords_prompt($_POST['description'], $_POST['keywords'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'emails':\n if (!empty($_POST['recipient']) && !empty($_POST['recipient-position']) && !empty($_POST['description'])) {\n $prompt = create_emails_prompt($_POST['recipient'], $_POST['recipient-position'], $_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'emails-v2':\n if (!empty($_POST['from']) && !empty($_POST['to']) && !empty($_POST['goal']) && !empty($_POST['description'])) {\n $prompt = create_emails_v2_prompt($_POST['from'], $_POST['to'], $_POST['goal'], $_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'email-subject-lines':\n if (!empty($_POST['description']) && !empty($_POST['title'])) {\n $prompt = create_email_subject_lines_prompt($_POST['title'], $_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'startup-name-generator':\n if (!empty($_POST['description']) && !empty($_POST['title'])) {\n $prompt = create_startup_name_generator_prompt($_POST['title'], $_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'company-bios':\n if (!empty($_POST['description']) && !empty($_POST['title']) && !empty($_POST['platform'])) {\n $prompt = create_company_bios_prompt($_POST['title'], $_POST['description'], $_POST['platform'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'company-mission':\n if (!empty($_POST['description']) && !empty($_POST['title'])) {\n $prompt = create_company_mission_prompt($_POST['title'], $_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'company-vision':\n if (!empty($_POST['description']) && !empty($_POST['title'])) {\n $prompt = create_company_vision_prompt($_POST['title'], $_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'product-name-generator':\n if (!empty($_POST['description']) && !empty($_POST['title'])) {\n $prompt = create_product_name_generator_prompt($_POST['description'], $_POST['title'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'product-descriptions':\n if (!empty($_POST['title']) && !empty($_POST['audience']) && !empty($_POST['description'])) {\n $prompt = create_product_descriptions_prompt($_POST['title'], $_POST['description'], $_POST['audience'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'amazon-product-titles':\n if (!empty($_POST['title']) && !empty($_POST['audience']) && !empty($_POST['description'])) {\n $prompt = create_amazon_product_titles_prompt($_POST['title'], $_POST['description'], $_POST['audience'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'amazon-product-descriptions':\n if (!empty($_POST['title']) && !empty($_POST['audience']) && !empty($_POST['description'])) {\n $prompt = create_amazon_product_descriptions_prompt($_POST['title'], $_POST['description'], $_POST['audience'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'amazon-product-features':\n if (!empty($_POST['title']) && !empty($_POST['audience']) && !empty($_POST['description'])) {\n $prompt = create_amazon_product_features_prompt($_POST['title'], $_POST['description'], $_POST['audience'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'social-post-personal':\n if (!empty($_POST['description'])) {\n $prompt = create_social_post_personal_prompt($_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'social-post-business':\n if (!empty($_POST['title']) && !empty($_POST['information']) && !empty($_POST['description'])) {\n $prompt = create_social_post_business_prompt($_POST['title'], $_POST['information'], $_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'instagram-captions':\n if (!empty($_POST['description'])) {\n $prompt = create_instagram_captions_prompt($_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'instagram-hashtags':\n if (!empty($_POST['description'])) {\n $prompt = create_instagram_hashtags_prompt($_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'twitter-tweets':\n if (!empty($_POST['description'])) {\n $prompt = create_twitter_tweets_prompt($_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'youtube-titles':\n if (!empty($_POST['description'])) {\n $prompt = create_youtube_titles_prompt($_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'youtube-descriptions':\n if (!empty($_POST['description'])) {\n $prompt = create_youtube_descriptions_prompt($_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'youtube-outlines':\n if (!empty($_POST['description'])) {\n $prompt = create_youtube_outlines_prompt($_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n case 'linkedin-posts':\n if (!empty($_POST['description'])) {\n $prompt = create_linkedin_posts_prompt($_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'tiktok-video-scripts':\n if (!empty($_POST['description'])) {\n $prompt = create_tiktok_video_scripts_prompt($_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'meta-tags-blog':\n if (!empty($_POST['title']) && !empty($_POST['keywords']) && !empty($_POST['description'])) {\n $prompt = create_meta_tags_blog_prompt($_POST['title'], $_POST['description'], $_POST['keywords'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'meta-tags-homepage':\n if (!empty($_POST['title']) && !empty($_POST['keywords']) && !empty($_POST['description'])) {\n $prompt = create_meta_tags_homepage_prompt($_POST['title'], $_POST['description'], $_POST['keywords'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'meta-tags-product':\n if (!empty($_POST['title']) && !empty($_POST['keywords']) && !empty($_POST['description']) && !empty($_POST['company_name'])) {\n $prompt = create_meta_tags_product_prompt($_POST['company_name'], $_POST['title'], $_POST['description'], $_POST['keywords'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'tone-changer':\n if (!empty($_POST['description'])) {\n $prompt = create_tone_changer_prompt($_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'song-lyrics':\n if (!empty($_POST['genre']) && !empty($_POST['title'])) {\n $prompt = create_song_lyrics_prompt($_POST['title'], $_POST['genre'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'translate':\n if (!empty($_POST['description'])) {\n $prompt = create_translate_prompt($_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'faqs':\n if (!empty($_POST['description']) && !empty($_POST['title'])) {\n $prompt = create_faqs_prompt($_POST['title'], $_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'faq-answers':\n if (!empty($_POST['description']) && !empty($_POST['title']) && !empty($_POST['question'])) {\n $prompt = create_faq_answers_prompt($_POST['title'], $_POST['description'], $_POST['question'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n case 'testimonials-reviews':\n if (!empty($_POST['description']) && !empty($_POST['title'])) {\n $prompt = create_testimonials_reviews_prompt($_POST['title'], $_POST['description'], $_POST['language'], $_POST['tone']);\n } else {\n $result['success'] = false;\n $result['error'] = __('All fields with (*) are required.');\n die(json_encode($result));\n }\n break;\n default:\n // check for custom template\n $ai_template = ORM::for_table($config['db']['pre'] . 'ai_custom_templates')\n ->where('active', '1')\n ->where('slug', $_POST['ai_template'])\n ->find_one();\n if (!empty($ai_template)) {\n $prompt = $ai_template['prompt'];\n\n if ($_POST['language'] == 'en') {\n $prompt = $ai_template['prompt'];\n } else {\n $languages = get_ai_languages();\n $prompt = \"Provide response in \" . $languages[$_POST['language']] . \".\\n\\n \" . $ai_template['prompt'];\n }\n\n if (!empty($ai_template['parameters'])) {\n $parameters = json_decode($ai_template['parameters'], true);\n foreach ($parameters as $key => $parameter) {\n if (!empty($_POST['parameter'][$key])) {\n if (strpos($prompt, '{{' . $parameter['title'] . '}}') !== false) {\n $prompt = str_replace('{{' . $parameter['title'] . '}}', $_POST['parameter'][$key], $prompt);\n } else {\n $prompt .= \"\\n\\n \" . $parameter['title'] . \": \" . $_POST['parameter'][$key];\n }\n }\n }\n }\n\n $prompt .= \" \\n\\n Voice of tone of the response must be \" . $_POST['tone'] . '.';\n } else {\n $result['success'] = false;\n $result['error'] = __('Unexpected error, please try again.');\n die(json_encode($result));\n }\n\n break;\n }\n\n // check bad words\n if ($word = check_bad_words($prompt)) {\n $result['success'] = false;\n $result['error'] = __('Your request contains a banned word:') . ' ' . $word;\n die(json_encode($result));\n }\n\n require_once ROOTPATH . '/includes/lib/orhanerday/open-ai/src/OpenAi.php';\n require_once ROOTPATH . '/includes/lib/orhanerday/open-ai/src/Url.php';\n\n $open_ai = new Orhanerday\\OpenAi\\OpenAi(get_api_key());\n\n if ($model == 'gpt-3.5-turbo' || $model == 'gpt-4') {\n $complete = $open_ai->chat([\n 'model' => $model,\n 'messages' => [\n [\n \"role\" => \"user\",\n \"content\" => $prompt\n ],\n ],\n 'temperature' => $temperature,\n 'frequency_penalty' => 0,\n 'presence_penalty' => 0,\n 'max_tokens' => $max_tokens,\n 'n' => $max_results,\n 'user' => $_SESSION['user']['id']\n ]);\n } else {\n $complete = $open_ai->completion([\n 'model' => $model,\n 'prompt' => $prompt,\n 'temperature' => $temperature,\n 'frequency_penalty' => 0,\n 'presence_penalty' => 0,\n 'max_tokens' => $max_tokens,\n 'n' => $max_results,\n 'user' => $_SESSION['user']['id']\n ]);\n }\n\n $response = json_decode($complete, true);\n\n if (isset($response['choices'])) {\n if ($model == 'gpt-3.5-turbo' || $model == 'gpt-4') {\n if (count($response['choices']) > 1) {\n foreach ($response['choices'] as $value) {\n $text[] = nl2br(trim($value['message']['content'])) . \"



    \";\n }\n } else {\n $text[] = nl2br(trim($response['choices'][0]['message']['content']));\n }\n } else {\n if (count($response['choices']) > 1) {\n foreach ($response['choices'] as $value) {\n $text[] = nl2br(trim($value['text'])) . \"



    \";\n }\n } else {\n $text[] = nl2br(trim($response['choices'][0]['text']));\n }\n }\n\n $tokens = $response['usage']['completion_tokens'];\n\n $word_used = ORM::for_table($config['db']['pre'] . 'word_used')->create();\n $word_used->user_id = $_SESSION['user']['id'];\n $word_used->words = $tokens;\n $word_used->date = date('Y-m-d H:i:s');\n $word_used->save();\n\n $result['success'] = true;\n $result['text'] = implode(\"




    \", $text);\n $result['old_used_words'] = $total_words_used;\n $result['current_used_words'] = $total_words_used + $tokens;\n } else {\n // error log default message\n if (!empty($response['error']['message']))\n error_log('OpenAI: ' . $response['error']['message']);\n\n $result['success'] = false;\n $result['api_error'] = $response['error']['message'];\n $result['error'] = get_api_error_message($open_ai->getCURLInfo()['http_code']);\n die(json_encode($result));\n }\n die(json_encode($result));\n }\n }\n $result['success'] = false;\n $result['error'] = __('Unexpected error, please try again.');\n die(json_encode($result));\n}\n\nfunction generate_image()\n{\n $result = array();\n if (checkloggedin()) {\n global $config;\n\n // if disabled by admin\n if (!$config['enable_ai_images']) {\n $result['success'] = false;\n $result['error'] = __('This feature is disabled by the admin.');\n die(json_encode($result));\n }\n\n if (!$config['non_active_allow']) {\n $user_data = get_user_data(null, $_SESSION['user']['id']);\n if ($user_data['status'] == 0) {\n $result['success'] = false;\n $result['error'] = __('Verify your email address to use the AI.');\n die(json_encode($result));\n }\n }\n\n set_time_limit(0);\n\n $_POST = validate_input($_POST);\n\n if (!empty($_POST['description'])) {\n\n $membership = get_user_membership_detail($_SESSION['user']['id']);\n $images_limit = $membership['settings']['ai_images_limit'];\n\n $start = date('Y-m-01');\n $end = date_create(date('Y-m-t'))->modify('+1 day')->format('Y-m-d');\n $total_images_used = ORM::for_table($config['db']['pre'] . 'image_used')\n ->where('user_id', $_SESSION['user']['id'])\n ->where_raw(\"(`date` BETWEEN '$start' AND '$end')\")\n ->sum('images');\n\n $total_images_used = $total_images_used ?: 0;\n\n // check user's images limit\n if ($images_limit != -1 && (($images_limit - $total_images_used) < $_POST['no_of_images'])) {\n $result['success'] = false;\n $result['error'] = __('Images limit exceeded, Upgrade your membership plan.');\n die(json_encode($result));\n }\n\n $prompt = $_POST['description'];\n $prompt .= !empty($_POST['style']) ? ', ' . $_POST['style'] . ' style' : '';\n $prompt .= !empty($_POST['lighting']) ? ', ' . $_POST['lighting'] . ' lighting' : '';\n $prompt .= !empty($_POST['mood']) ? ', ' . $_POST['mood'] . ' mood' : '';\n\n // check bad words\n if ($word = check_bad_words($prompt)) {\n $result['success'] = false;\n $result['error'] = __('Your request contains a banned word:') . ' ' . $word;\n die(json_encode($result));\n }\n\n // check image api\n $image_api = get_option('ai_image_api');\n if ($image_api == 'any') {\n // check random\n $data = ['openai', 'stable-diffusion'];\n $image_api = $data[array_rand($data)];\n }\n\n if ($image_api == 'stable-diffusion') {\n include ROOTPATH . '/includes/lib/StableDiffusion.php';\n\n $stableDiffusion = new StableDiffusion(get_image_api_key($image_api));\n\n $width = 512;\n $height = 512;\n\n $response = $stableDiffusion->image([\n \"text_prompts\" => [\n [\"text\" => $prompt]\n ],\n \"height\" => $height,\n \"width\" => $width,\n \"samples\" => (int)$_POST['no_of_images'],\n \"steps\" => 50,\n ]);\n $response = json_decode($response, true);\n if (isset($response['artifacts'])) {\n foreach ($response['artifacts'] as $image) {\n\n $name = uniqid() . '.png';\n $target_dir = ROOTPATH . '/storage/ai_images/';\n file_put_contents($target_dir . $name, base64_decode($image['base64']));\n resizeImage(200, $target_dir . 'small_' . $name, $target_dir . $name);\n $content = ORM::for_table($config['db']['pre'] . 'ai_images')->create();\n $content->user_id = $_SESSION['user']['id'];\n $content->title = $_POST['title'];\n $content->description = $_POST['description'];\n $content->resolution = $_POST['resolution'];\n $content->image = $name;\n $content->created_at = date('Y-m-d H:i:s');\n $content->save();\n\n $array = [\n 'small' => $config['site_url'] . 'storage/ai_images/small_' . $name,\n 'large' => $config['site_url'] . 'storage/ai_images/' . $name,\n ];\n $images[] = $array;\n }\n\n $image_used = ORM::for_table($config['db']['pre'] . 'image_used')->create();\n $image_used->user_id = $_SESSION['user']['id'];\n $image_used->images = (int)$_POST['no_of_images'];\n $image_used->date = date('Y-m-d H:i:s');\n $image_used->save();\n\n $result['success'] = true;\n $result['data'] = $images;\n $result['description'] = $_POST['description'];\n $result['old_used_images'] = $total_images_used;\n $result['current_used_images'] = $total_images_used + $_POST['no_of_images'];\n } else {\n // error log default message\n if (!empty($response['message']))\n error_log('Stable Diffusion: ' . $response['message']);\n\n $result['success'] = false;\n $result['api_error'] = $response['message'];\n $result['error'] = get_api_error_message($stableDiffusion->getCURLInfo()['http_code']);\n die(json_encode($result));\n }\n } else {\n // openai\n require_once ROOTPATH . '/includes/lib/orhanerday/open-ai/src/OpenAi.php';\n require_once ROOTPATH . '/includes/lib/orhanerday/open-ai/src/Url.php';\n\n $open_ai = new Orhanerday\\OpenAi\\OpenAi(get_image_api_key($image_api));\n\n $complete = $open_ai->image([\n 'prompt' => $prompt,\n 'size' => $_POST['resolution'],\n 'n' => (int)$_POST['no_of_images'],\n \"response_format\" => \"url\",\n 'user' => $_SESSION['user']['id']\n ]);\n\n $response = json_decode($complete, true);\n\n if (isset($response['data'])) {\n $images = array();\n\n foreach ($response['data'] as $key => $value) {\n $url = $value['url'];\n\n $name = uniqid() . '.png';\n\n $image = file_get_contents($url);\n\n $target_dir = ROOTPATH . '/storage/ai_images/';\n file_put_contents($target_dir . $name, $image);\n\n resizeImage(200, $target_dir . 'small_' . $name, $target_dir . $name);\n\n $content = ORM::for_table($config['db']['pre'] . 'ai_images')->create();\n $content->user_id = $_SESSION['user']['id'];\n $content->title = $_POST['title'];\n $content->description = $_POST['description'];\n $content->resolution = $_POST['resolution'];\n $content->image = $name;\n $content->created_at = date('Y-m-d H:i:s');\n $content->save();\n\n $array = [\n 'small' => $config['site_url'] . 'storage/ai_images/small_' . $name,\n 'large' => $config['site_url'] . 'storage/ai_images/' . $name,\n ];\n $images[] = $array;\n }\n\n $image_used = ORM::for_table($config['db']['pre'] . 'image_used')->create();\n $image_used->user_id = $_SESSION['user']['id'];\n $image_used->images = (int)$_POST['no_of_images'];\n $image_used->date = date('Y-m-d H:i:s');\n $image_used->save();\n\n $result['success'] = true;\n $result['data'] = $images;\n $result['description'] = $_POST['description'];\n $result['old_used_images'] = $total_images_used;\n $result['current_used_images'] = $total_images_used + $_POST['no_of_images'];\n } else {\n // error log default message\n if (!empty($response['error']['message']))\n error_log('OpenAI: ' . $response['error']['message']);\n\n $result['success'] = false;\n $result['api_error'] = $response['error']['message'];\n $result['error'] = get_api_error_message($open_ai->getCURLInfo()['http_code']);\n die(json_encode($result));\n }\n }\n die(json_encode($result));\n }\n }\n $result['success'] = false;\n $result['error'] = __('Unexpected error, please try again.');\n die(json_encode($result));\n}\n\nfunction save_document()\n{\n $result = array();\n if (checkloggedin()) {\n global $config;\n\n $content = validate_input($_POST['content'], true);\n $_POST = validate_input($_POST);\n $_POST['content'] = $content;\n\n if (!empty($_POST['id'])) {\n $content = ORM::for_table($config['db']['pre'] . 'ai_documents')->find_one($_POST['id']);\n } else {\n $content = ORM::for_table($config['db']['pre'] . 'ai_documents')->create();\n }\n\n $content->user_id = $_SESSION['user']['id'];\n $content->title = $_POST['title'];\n\n if (!empty($_POST['content']))\n $content->content = $_POST['content'];\n\n $content->template = $_POST['ai_template'];\n $content->created_at = date('Y-m-d H:i:s');\n $content->save();\n\n $result['success'] = true;\n $result['id'] = $content->id();\n $result['message'] = __('Successfully Saved.');\n die(json_encode($result));\n }\n $result['success'] = false;\n $result['error'] = __('Unexpected error, please try again.');\n die(json_encode($result));\n}\n\nfunction delete_document()\n{\n $result = array();\n if (checkloggedin()) {\n global $config;\n\n $data = ORM::for_table($config['db']['pre'] . 'ai_documents')\n ->where(array(\n 'id' => $_POST['id'],\n 'user_id' => $_SESSION['user']['id'],\n ))\n ->delete_many();\n\n if ($data) {\n $result['success'] = true;\n $result['message'] = __('Deleted Successfully');\n die(json_encode($result));\n }\n }\n $result['success'] = false;\n $result['error'] = __('Unexpected error, please try again.');\n die(json_encode($result));\n}\n\nfunction delete_image()\n{\n $result = array();\n if (checkloggedin()) {\n global $config;\n\n $images = ORM::for_table($config['db']['pre'] . 'ai_images')\n ->select('image')\n ->where(array(\n 'id' => $_POST['id'],\n 'user_id' => $_SESSION['user']['id'],\n ));\n\n foreach ($images->find_array() as $row) {\n $image_dir = \"../storage/ai_images/\";\n $main_image = trim((string) $row['image']);\n // delete Image\n if (!empty($main_image)) {\n $file = $image_dir . $main_image;\n if (file_exists($file))\n unlink($file);\n\n $file = $image_dir . 'small_'.$main_image;\n if (file_exists($file))\n unlink($file);\n }\n }\n\n if ($images->delete_many()) {\n $result['success'] = true;\n $result['message'] = __('Deleted Successfully');\n die(json_encode($result));\n }\n }\n $result['success'] = false;\n $result['error'] = __('Unexpected error, please try again.');\n die(json_encode($result));\n}\n\nfunction load_ai_chats()\n{\n $result = array();\n global $config;\n\n // if disabled by admin\n if (!$config['enable_ai_chat']) {\n $result['success'] = false;\n $result['error'] = __('This feature is disabled by the admin.');\n die(json_encode($result));\n }\n\n if (checkloggedin()) {\n\n if (empty($_POST['conv_id'])) {\n $result['success'] = false;\n $result['error'] = __('Unexpected error, please try again.');\n die(json_encode($result));\n }\n\n /* load chats */\n $data = ORM::for_table($config['db']['pre'] . 'ai_chat')\n ->where('user_id', $_SESSION['user']['id']);\n\n if ($_POST['conv_id'] == 'default') {\n $data->where_null('conversation_id');\n\n if (!empty($_POST['bot_id']))\n $data->where('bot_id', $_POST['bot_id']);\n else\n $data->where_null('bot_id');\n\n } else {\n $data->where('conversation_id', $_POST['conv_id']);\n }\n\n $chats = $data->find_array();\n\n // format date\n foreach ($chats as &$chat) {\n $chat['date_formatted'] = date('F d, Y', strtotime($chat['date']));\n }\n\n $result['success'] = true;\n $result['chats'] = $chats;\n die(json_encode($result));\n }\n}\n\nfunction edit_conversation_title()\n{\n $result = array();\n global $config;\n\n // if disabled by admin\n if (!$config['enable_ai_chat']) {\n $result['success'] = false;\n $result['error'] = __('This feature is disabled by the admin.');\n die(json_encode($result));\n }\n\n if (checkloggedin()) {\n\n $_POST = validate_input($_POST);\n\n if (!empty($_POST['id'])) {\n $conversations = ORM::for_table($config['db']['pre'] . 'ai_chat_conversations')\n ->where('user_id', $_SESSION['user']['id'])\n ->find_one($_POST['id']);\n $conversations->set('title', $_POST['title']);\n\n $conversations->save();\n }\n\n $result['success'] = true;\n die(json_encode($result));\n }\n}\n\nfunction send_ai_message()\n{\n $result = array();\n global $config;\n\n // if disabled by admin\n if (!$config['enable_ai_chat']) {\n $result['success'] = false;\n $result['error'] = __('This feature is disabled by the admin.');\n die(json_encode($result));\n }\n\n if (checkloggedin()) {\n\n if (!$config['non_active_allow']) {\n $user_data = get_user_data(null, $_SESSION['user']['id']);\n if ($user_data['status'] == 0) {\n $result['success'] = false;\n $result['error'] = __('Verify your email address to use the AI.');\n die(json_encode($result));\n }\n }\n\n set_time_limit(0);\n\n $membership = get_user_membership_detail($_SESSION['user']['id']);\n $words_limit = $membership['settings']['ai_words_limit'];\n $plan_ai_chat = $membership['settings']['ai_chat'];\n\n if (!$plan_ai_chat) {\n $result['success'] = false;\n $result['error'] = __('Upgrade your membership plan to use this feature.');\n die(json_encode($result));\n }\n\n if (get_option('single_model_for_plans'))\n $model = get_option('open_ai_model', 'gpt-3.5-turbo');\n else\n $model = $membership['settings']['ai_model'];\n\n if ($model != 'gpt-3.5-turbo' && $model != 'gpt-4') {\n $result['success'] = false;\n $result['error'] = __('You can not use the chat feature with your OpenAI model. ChatGPT model is required.');\n die(json_encode($result));\n }\n\n $start = date('Y-m-01');\n $end = date_create(date('Y-m-t'))->modify('+1 day')->format('Y-m-d');\n $total_words_used = ORM::for_table($config['db']['pre'] . 'word_used')\n ->where('user_id', $_SESSION['user']['id'])\n ->where_raw(\"(`date` BETWEEN '$start' AND '$end')\")\n ->sum('words');\n\n $total_words_used = $total_words_used ?: 0;\n $total_available_words = $words_limit - $total_words_used;\n\n $max_tokens = (int)get_option(\"ai_chat_max_token\", '-1');\n // check user's word limit\n $max_tokens_limit = $max_tokens == -1 ? 500 : $max_tokens;\n if ($words_limit != -1 && (($words_limit - $total_words_used) < $max_tokens_limit)) {\n $result['success'] = false;\n $result['error'] = __('Words limit exceeded, Upgrade your membership plan.');\n die(json_encode($result));\n }\n\n /* check bad words */\n if ($word = check_bad_words($_POST['msg'])) {\n $result['success'] = false;\n $result['error'] = __('Your request contains a banned word:') . ' ' . $word;\n die(json_encode($result));\n }\n\n $conversation_id = null;\n if (empty($_POST['conv_id']) || (!empty($_POST['conv_id']) && $_POST['conv_id'] == 'default')) {\n $conversations = ORM::for_table($config['db']['pre'] . 'ai_chat_conversations')->create();\n $conversations->title = __('New Conversation');\n $conversations->user_id = $_SESSION['user']['id'];\n $conversations->last_message = '...';\n $conversations->updated_at = date('Y-m-d H:i:s');\n\n if (!empty($_POST['bot_id']))\n $conversations->bot_id = $_POST['bot_id'];\n\n $conversations->save();\n\n $conversation_id = $conversations->id();\n\n if (!empty($_POST['conv_id']) && $_POST['conv_id'] == 'default') {\n $data = ORM::for_table($config['db']['pre'] . 'ai_chat')\n ->where('user_id', $_SESSION['user']['id'])\n ->where_null('conversation_id');\n\n if (!empty($_POST['bot_id']))\n $data->where('bot_id', $_POST['bot_id']);\n else\n $data->where_null('bot_id');\n\n $chats = $data->find_result_set();\n\n $chats->set('conversation_id', $conversation_id);\n $chats->save();\n }\n } else {\n $conversation_id = $_POST['conv_id'];\n }\n\n /* save user message */\n $chat = ORM::for_table($config['db']['pre'] . 'ai_chat')->create();\n $chat->user_id = $_SESSION['user']['id'];\n $chat->user_message = $_POST['msg'];\n $chat->conversation_id = $conversation_id;\n $chat->date = date('Y-m-d H:i:s');\n\n if (!empty($_POST['bot_id']))\n $chat->bot_id = $_POST['bot_id'];\n\n $chat->save();\n\n $result['success'] = true;\n $result['conversation_id'] = $conversation_id;\n $result['last_message_id'] = $chat->id();\n die(json_encode($result));\n }\n $result['success'] = false;\n $result['error'] = __('Unexpected error, please try again.');\n die(json_encode($result));\n}\n\nfunction chat_stream()\n{\n $result = array();\n global $config;\n\n @ini_set('memory_limit', '256M');\n @ini_set('output_buffering', 'on');\n session_write_close(); // make session read-only\n\n // disable default disconnect checks\n ignore_user_abort(true);\n\n //Disable time limit\n @set_time_limit(0);\n\n //Initialize the output buffer\n if(function_exists('apache_setenv')){\n @apache_setenv('no-gzip', 1);\n }\n @ini_set('zlib.output_compression', 0);\n @ini_set('implicit_flush', 1);\n while (ob_get_level() != 0) {\n ob_end_flush();\n }\n ob_implicit_flush(1);\n ob_start();\n\n // connection_aborted() use this\n\n header('Content-type: text/event-stream');\n header('Cache-Control: no-cache');\n header('X-Accel-Buffering: no');\n header(\"Content-Encoding: none\");\n\n // if disabled by admin\n if (!$config['enable_ai_chat']) {\n $result['success'] = false;\n $result['error'] = __('This feature is disabled by the admin.');\n die('data: '. json_encode($result).PHP_EOL);\n }\n\n if (checkloggedin()) {\n if (!$config['non_active_allow']) {\n $user_data = get_user_data(null, $_SESSION['user']['id']);\n if ($user_data['status'] == 0) {\n $result['success'] = false;\n $result['error'] = __('Verify your email address to use the AI.');\n die('data: '. json_encode($result).PHP_EOL);\n }\n }\n\n $membership = get_user_membership_detail($_SESSION['user']['id']);\n $words_limit = $membership['settings']['ai_words_limit'];\n $plan_ai_chat = $membership['settings']['ai_chat'];\n\n if (!$plan_ai_chat) {\n $result['success'] = false;\n $result['error'] = __('Upgrade your membership plan to use this feature.');\n die('data: '. json_encode($result).PHP_EOL);\n }\n\n if (get_option('single_model_for_plans'))\n $model = get_option('open_ai_model', 'gpt-3.5-turbo');\n else\n $model = $membership['settings']['ai_model'];\n\n if ($model != 'gpt-3.5-turbo' && $model != 'gpt-4') {\n $result['success'] = false;\n $result['error'] = __('You can not use the chat feature with your OpenAI model. ChatGPT model is required.');\n die('data: '. json_encode($result).PHP_EOL);\n }\n\n $start = date('Y-m-01');\n $end = date_create(date('Y-m-t'))->modify('+1 day')->format('Y-m-d');\n $total_words_used = ORM::for_table($config['db']['pre'] . 'word_used')\n ->where('user_id', $_SESSION['user']['id'])\n ->where_raw(\"(`date` BETWEEN '$start' AND '$end')\")\n ->sum('words');\n\n $total_words_used = $total_words_used ?: 0;\n $total_available_words = $words_limit - $total_words_used;\n\n $max_tokens = (int)get_option(\"ai_chat_max_token\", '-1');\n // check user's word limit\n $max_tokens_limit = $max_tokens == -1 ? 500 : $max_tokens;\n if ($words_limit != -1 && (($words_limit - $total_words_used) < $max_tokens_limit)) {\n $result['success'] = false;\n $result['error'] = __('Words limit exceeded, Upgrade your membership plan.');\n die('data: '. json_encode($result).PHP_EOL);\n }\n\n if(is_numeric($_GET['conv_id'])) {\n $conversation_id = (int) $_GET['conv_id'];\n } else{\n $result['success'] = false;\n $result['error'] = __('Unexpected error, please try again.');\n die('data: '. json_encode($result).PHP_EOL);\n }\n\n /* create message history */\n $ROLE = \"role\";\n $CONTENT = \"content\";\n $USER = \"user\";\n $SYS = \"system\";\n $ASSISTANT = \"assistant\";\n\n $system_prompt = \"You are a helpful assistant.\";\n if (!empty($_GET['bot_id'])) {\n $bot_sql = \"and `bot_id` = {$_GET['bot_id']}\";\n\n $chat_bot = ORM::for_table($config['db']['pre'] . 'ai_chat_bots')\n ->find_one($_GET['bot_id']);\n\n /* Check bot exist */\n if (empty($chat_bot['id'])) {\n $result['success'] = false;\n $result['error'] = __('Unexpected error, please try again.');\n die('data: '. json_encode($result).PHP_EOL);\n }\n\n if (!empty($chat_bot['prompt'])) {\n $system_prompt = $chat_bot['prompt'];\n }\n } else {\n $bot_sql = \"and `bot_id` IS NULL\";\n }\n\n // get last 8 messages\n $sql = \"SELECT * FROM\n (\n SELECT * FROM \" . $config['db']['pre'] . 'ai_chat' . \" \n WHERE `user_id` = {$_SESSION['user']['id']} \n AND `conversation_id` = $conversation_id \n $bot_sql ORDER BY id DESC LIMIT 8\n ) AS sub\n ORDER BY id ASC;\";\n $chats = ORM::for_table($config['db']['pre'] . 'ai_chat')\n ->raw_query($sql)\n ->find_array();\n\n $used_tokens = 0;\n\n require_once ROOTPATH . '/includes/lib/Tokenizer-GPT3/autoload.php';\n $tokenizer = new \\Ze\\TokenizerGpt3\\Gpt3Tokenizer(new \\Ze\\TokenizerGpt3\\Gpt3TokenizerConfig());\n\n $history[] = [$ROLE => $SYS, $CONTENT => $system_prompt];\n foreach ($chats as $chat) {\n $history[] = [$ROLE => $USER, $CONTENT => $chat['user_message']];\n if (!empty($chat['ai_message'])) {\n $history[] = [$ROLE => $ASSISTANT, $CONTENT => $chat['ai_message']];\n }\n }\n\n require_once ROOTPATH . '/includes/lib/orhanerday/open-ai/src/OpenAi.php';\n require_once ROOTPATH . '/includes/lib/orhanerday/open-ai/src/Url.php';\n\n $open_ai = new Orhanerday\\OpenAi\\OpenAi(get_api_key());\n\n $opts = [\n 'model' => $model,\n 'messages' => $history,\n 'temperature' => 1.0,\n 'frequency_penalty' => 0,\n 'presence_penalty' => 0,\n 'user' => $_SESSION['user']['id'],\n 'stream' => true\n ];\n if ($max_tokens != -1) {\n $opts['max_tokens'] = $max_tokens;\n }\n\n $txt = \"\";\n $complete = $open_ai->chat($opts, function ($curl_info, $data) use (&$txt) {\n if ($obj = json_decode($data) and $obj->error->message != \"\") {\n $result = [];\n $result['api_error'] = $obj->error->message;\n $result['error'] = get_api_error_message( curl_getinfo($curl_info, CURLINFO_HTTP_CODE));\n echo $data = 'data: '. json_encode($result).PHP_EOL;\n } else {\n echo $data;\n\n $array = explode('data: ', $data);\n foreach ($array as $ar){\n $ar = json_decode($ar, true);\n if(isset($ar[\"choices\"][0][\"delta\"][\"content\"])) {\n $txt .= $ar[\"choices\"][0][\"delta\"][\"content\"];\n }\n }\n }\n\n echo PHP_EOL;\n while(ob_get_level() > 0) {\n ob_end_flush();\n }\n ob_flush();\n flush();\n return strlen($data);\n });\n\n $ai_message = $txt;\n if (!empty($ai_message)) {\n\n // save chat\n $chat = ORM::for_table($config['db']['pre'] . 'ai_chat')\n ->where('user_id', $_SESSION['user']['id'])\n ->find_one($_GET['last_message_id']);\n\n $chat->set('ai_message', $ai_message);\n $chat->set('date', date('Y-m-d H:i:s'));\n $chat->save();\n\n /* update conversation */\n $last_message = strlimiter(strip_tags($ai_message), 100);\n $update_conversation = ORM::for_table($config['db']['pre'] . 'ai_chat_conversations')\n ->find_one($conversation_id);\n $update_conversation->set('updated_at', date('Y-m-d H:i:s'));\n $update_conversation->set('last_message', $last_message);\n $update_conversation->save();\n\n $used_tokens += $tokenizer->count($ai_message);\n /* GPT 4 uses more tokens */\n if($model == 'gpt-4'){\n $used_tokens *= ceil(1.1);\n }\n\n $word_used = ORM::for_table($config['db']['pre'] . 'word_used')->create();\n $word_used->user_id = $_SESSION['user']['id'];\n $word_used->words = $used_tokens;\n $word_used->date = date('Y-m-d H:i:s');\n $word_used->save();\n }\n }\n}\n\nfunction delete_ai_chats()\n{\n $result = array();\n if (checkloggedin()) {\n global $config;\n\n if (!empty($_GET['conv_id'])) {\n /* Delete chats */\n $data = ORM::for_table($config['db']['pre'] . 'ai_chat')\n ->where('user_id', $_SESSION['user']['id']);\n\n if ($_GET['conv_id'] == 'default')\n $data->where_null('conversation_id');\n else\n $data->where('conversation_id', $_GET['conv_id']);\n\n if (!empty($_GET['bot_id']))\n $data->where('bot_id', $_GET['bot_id']);\n\n $data->delete_many();\n\n /* Delete conversation */\n if ($_GET['conv_id'] != 'default') {\n ORM::for_table($config['db']['pre'] . 'ai_chat_conversations')\n ->where('user_id', $_SESSION['user']['id'])\n ->where('id', $_GET['conv_id'])\n ->delete_many();\n }\n\n if ($data) {\n $result['success'] = true;\n $result['message'] = __('Deleted Successfully');\n die(json_encode($result));\n }\n }\n }\n $result['success'] = false;\n $result['error'] = __('Unexpected error, please try again.');\n die(json_encode($result));\n}\n\nfunction export_ai_chats()\n{\n $result = array();\n if (checkloggedin()) {\n global $config;\n\n $text = '';\n\n if (!empty($_GET['conv_id'])) {\n\n $data = ORM::for_table($config['db']['pre'] . 'ai_chat')\n ->table_alias('c')\n ->select_many_expr('c.*', 'u.name full_name')\n ->where('c.user_id', $_SESSION['user']['id'])\n ->join($config['db']['pre'] . 'user', 'u.id = c.user_id', 'u');\n\n if ($_GET['conv_id'] == 'default')\n $data->where_null('conversation_id');\n else\n $data->where('conversation_id', $_GET['conv_id']);\n\n if (!empty($_GET['bot_id'])) {\n $data->where('bot_id', $_GET['bot_id']);\n\n $chat_bot = ORM::for_table($config['db']['pre'] . 'ai_chat_bots')\n ->find_one($_GET['bot_id']);\n\n /* Check bot exist */\n if (empty($chat_bot['id'])) {\n $result['success'] = false;\n $result['error'] = __('Unexpected error, please try again.');\n die(json_encode($result));\n }\n\n $ai_name = $chat_bot['name'];\n } else {\n $ai_name = get_option('ai_chat_bot_name', __('AI Chat Bot'));\n }\n\n foreach ($data->find_array() as $chat) {\n // user\n $text .= \"[{$chat['date']}] \";\n $text .= $chat['full_name'] . ': ';\n $text .= $chat['user_message'] . \"\\n\\n\";\n\n // ai\n if (!empty($chat['ai_message'])) {\n $text .= \"[{$chat['date']}] \";\n $text .= $ai_name . ': ';\n $text .= $chat['ai_message'] . \"\\n\\n\";\n }\n }\n }\n\n $result['success'] = true;\n $result['text'] = $text;\n die(json_encode($result));\n }\n $result['success'] = false;\n $result['error'] = __('Unexpected error, please try again.');\n die(json_encode($result));\n}\n\nfunction speech_to_text()\n{\n $result = array();\n global $config;\n\n // if disabled by admin\n if (!$config['enable_speech_to_text']) {\n $result['success'] = false;\n $result['error'] = __('This feature is disabled by the admin.');\n die(json_encode($result));\n }\n\n if (checkloggedin()) {\n if (!$config['non_active_allow']) {\n $user_data = get_user_data(null, $_SESSION['user']['id']);\n if ($user_data['status'] == 0) {\n $result['success'] = false;\n $result['error'] = __('Verify your email address to use the AI.');\n die(json_encode($result));\n }\n }\n\n set_time_limit(0);\n\n $_POST = validate_input($_POST);\n\n if (!empty($_FILES['file']['tmp_name'])) {\n\n $membership = get_user_membership_detail($_SESSION['user']['id']);\n $speech_to_text_limit = $membership['settings']['ai_speech_to_text_limit'];\n $speech_text_file_limit = $membership['settings']['ai_speech_to_text_file_limit'];\n\n $start = date('Y-m-01');\n $end = date_create(date('Y-m-t'))->modify('+1 day')->format('Y-m-d');\n $total_speech_used = ORM::for_table($config['db']['pre'] . 'speech_to_text_used')\n ->where('user_id', $_SESSION['user']['id'])\n ->where_raw(\"(`date` BETWEEN '$start' AND '$end')\")\n ->count();\n\n $total_speech_used = $total_speech_used ?: 0;\n\n // check user's images limit\n if ($speech_to_text_limit != -1 && (($speech_to_text_limit - $total_speech_used) < 1)) {\n $result['success'] = false;\n $result['error'] = __('Audio transcription limit exceeded, Upgrade your membership plan.');\n die(json_encode($result));\n }\n\n if ($speech_text_file_limit != -1 && ($_FILES['file']['size'] > $speech_text_file_limit * 1024 * 1024)) {\n $result['success'] = false;\n $result['error'] = __('File size limit exceeded, Upgrade your membership plan.');\n die(json_encode($result));\n }\n\n // check bad words\n if ($word = check_bad_words($_POST['description'])) {\n $result['success'] = false;\n $result['error'] = __('Your request contains a banned word:') . ' ' . $word;\n die(json_encode($result));\n }\n\n require_once ROOTPATH . '/includes/lib/orhanerday/open-ai/src/OpenAi.php';\n require_once ROOTPATH . '/includes/lib/orhanerday/open-ai/src/Url.php';\n\n $open_ai = new Orhanerday\\OpenAi\\OpenAi(get_api_key());\n\n $tmp_file = $_FILES['file']['tmp_name'];\n $file_name = basename($_FILES['file']['name']);\n $c_file = curl_file_create($tmp_file, $_FILES['file']['type'], $file_name);\n $complete = $open_ai->transcribe([\n \"model\" => \"whisper-1\",\n \"file\" => $c_file,\n \"prompt\" => $_POST['description'],\n 'user' => $_SESSION['user']['id']\n ]);\n\n $response = json_decode($complete, true);\n\n if (isset($response['text'])) {\n $response['text'] = nl2br(trim($response['text']));\n\n $content = ORM::for_table($config['db']['pre'] . 'ai_documents')->create();\n $content->user_id = $_SESSION['user']['id'];\n $content->title = !empty($_POST['title']) ? $_POST['title'] : __('Untitled Document');\n $content->content = $response['text'];\n $content->template = 'quickai-speech-to-text';\n $content->created_at = date('Y-m-d H:i:s');\n $content->save();\n\n $speech_used = ORM::for_table($config['db']['pre'] . 'speech_to_text_used')->create();\n $speech_used->user_id = $_SESSION['user']['id'];\n $speech_used->date = date('Y-m-d H:i:s');\n $speech_used->save();\n\n $result['success'] = true;\n $result['text'] = $response['text'];\n $result['old_used_speech'] = $speech_to_text_limit;\n $result['current_used_speech'] = $total_speech_used + 1;\n } else {\n // error log default message\n if (!empty($response['error']['message']))\n error_log('OpenAI: ' . $response['error']['message']);\n\n $result['success'] = false;\n $result['api_error'] = $response['error']['message'];\n $result['error'] = get_api_error_message($open_ai->getCURLInfo()['http_code']);\n die(json_encode($result));\n }\n die(json_encode($result));\n }\n }\n $result['success'] = false;\n $result['error'] = __('Unexpected error, please try again.');\n die(json_encode($result));\n}\n\nfunction ai_code()\n{\n $result = array();\n\n global $config;\n\n // if disabled by admin\n if (!$config['enable_ai_code']) {\n $result['success'] = false;\n $result['error'] = __('This feature is disabled by the admin.');\n die(json_encode($result));\n }\n\n if (checkloggedin()) {\n\n if (!$config['non_active_allow']) {\n $user_data = get_user_data(null, $_SESSION['user']['id']);\n if ($user_data['status'] == 0) {\n $result['success'] = false;\n $result['error'] = __('Verify your email address to use the AI.');\n die(json_encode($result));\n }\n }\n\n set_time_limit(0);\n\n $_POST = validate_input($_POST);\n\n if (!empty($_POST['description'])) {\n\n $prompt = $_POST['description'];\n $max_tokens = (int)get_option(\"ai_code_max_token\", '-1');\n\n $membership = get_user_membership_detail($_SESSION['user']['id']);\n $words_limit = $membership['settings']['ai_words_limit'];\n $plan_ai_code = $membership['settings']['ai_code'];\n\n if (get_option('single_model_for_plans'))\n $model = get_option('open_ai_model', 'gpt-3.5-turbo');\n else\n $model = $membership['settings']['ai_model'];\n\n $start = date('Y-m-01');\n $end = date_create(date('Y-m-t'))->modify('+1 day')->format('Y-m-d');\n $total_words_used = ORM::for_table($config['db']['pre'] . 'word_used')\n ->where('user_id', $_SESSION['user']['id'])\n ->where_raw(\"(`date` BETWEEN '$start' AND '$end')\")\n ->sum('words');\n\n $total_words_used = $total_words_used ?: 0;\n\n // check if user's membership have the template\n if (!$plan_ai_code) {\n $result['success'] = false;\n $result['error'] = __('Upgrade your membership plan to use this feature');\n die(json_encode($result));\n }\n\n // check user's word limit\n $max_tokens_limit = $max_tokens == -1 ? 500 : $max_tokens;\n if ($words_limit != -1 && (($words_limit - $total_words_used) < $max_tokens_limit)) {\n $result['success'] = false;\n $result['error'] = __('Words limit exceeded, Upgrade your membership plan.');\n die(json_encode($result));\n }\n\n // check bad words\n if ($word = check_bad_words($prompt)) {\n $result['success'] = false;\n $result['error'] = __('Your request contains a banned word:') . ' ' . $word;\n die(json_encode($result));\n }\n\n require_once ROOTPATH . '/includes/lib/orhanerday/open-ai/src/OpenAi.php';\n require_once ROOTPATH . '/includes/lib/orhanerday/open-ai/src/Url.php';\n\n $open_ai = new Orhanerday\\OpenAi\\OpenAi(get_api_key());\n\n if ($model == 'gpt-3.5-turbo' || $model == 'gpt-4') {\n $opt = [\n 'model' => $model,\n 'messages' => [\n [\n \"role\" => \"user\",\n \"content\" => $prompt\n ],\n ],\n 'temperature' => 1,\n 'n' => 1,\n 'user' => $_SESSION['user']['id']\n ];\n if ($max_tokens != -1) {\n $opt['max_tokens'] = $max_tokens;\n }\n $complete = $open_ai->chat($opt);\n } else {\n $opt = [\n 'model' => $model,\n 'prompt' => $prompt,\n 'temperature' => 1,\n 'n' => 1,\n ];\n if ($max_tokens != -1) {\n $opt['max_tokens'] = $max_tokens;\n }\n $complete = $open_ai->completion($opt);\n }\n\n $response = json_decode($complete, true);\n\n if (isset($response['choices'])) {\n if ($model == 'gpt-3.5-turbo' || $model == 'gpt-4') {\n $text = trim($response['choices'][0]['message']['content']);\n } else {\n $text = trim($response['choices'][0]['text']);\n }\n\n $tokens = $response['usage']['completion_tokens'];\n\n $content = ORM::for_table($config['db']['pre'] . 'ai_documents')->create();\n $content->user_id = $_SESSION['user']['id'];\n $content->title = !empty($_POST['title']) ? $_POST['title'] : __('Untitled Document');\n $content->content = $text;\n $content->template = 'quickai-ai-code';\n $content->created_at = date('Y-m-d H:i:s');\n $content->save();\n\n $word_used = ORM::for_table($config['db']['pre'] . 'word_used')->create();\n $word_used->user_id = $_SESSION['user']['id'];\n $word_used->words = $tokens;\n $word_used->date = date('Y-m-d H:i:s');\n $word_used->save();\n\n $result['success'] = true;\n $result['text'] = filter_ai_response($text);\n $result['old_used_words'] = $total_words_used;\n $result['current_used_words'] = $total_words_used + $tokens;\n } else {\n // error log default message\n if (!empty($response['error']['message']))\n error_log('OpenAI: ' . $response['error']['message']);\n\n $result['success'] = false;\n $result['api_error'] = $response['error']['message'];\n $result['error'] = get_api_error_message($open_ai->getCURLInfo()['http_code']);\n die(json_encode($result));\n }\n die(json_encode($result));\n }\n }\n $result['success'] = false;\n $result['error'] = __('Unexpected error, please try again.');\n die(json_encode($result));\n}\n\nfunction text_to_speech()\n{\n $result = array();\n global $config;\n\n // if disabled by admin\n if (!get_option('enable_text_to_speech', 0)) {\n $result['success'] = false;\n $result['error'] = __('This feature is disabled by the admin.');\n die(json_encode($result));\n }\n\n if (checkloggedin()) {\n\n\n if (!$config['non_active_allow']) {\n $user_data = get_user_data(null, $_SESSION['user']['id']);\n if ($user_data['status'] == 0) {\n $result['success'] = false;\n $result['error'] = __('Verify your email address to use the AI.');\n die(json_encode($result));\n }\n }\n\n set_time_limit(0);\n\n $_POST = validate_input($_POST);\n\n if (!empty($_POST['description'])) {\n $no_ssml_tags = preg_replace('/<[\\s\\S]+?>/',\n'', $_POST['description']);\n $text_characters = mb_strlen($no_ssml_tags, 'UTF-8');\n\n $membership =\nget_user_membership_detail($_SESSION['user']['id']);\n $characters_limit =\n$membership['settings']['ai_text_to_speech_limit'];\n\n $start = date('Y-m-01');\n $end =\ndate_create(date('Y-m-t'))->modify('+1 day')->format('Y-m-d');\n\n $total_character_used =\nORM::for_table($config['db']['pre'] . 'text_to_speech_used')\n ->where('user_id', $_SESSION['user']['id'])\n\n->where_raw(\"(`date` BETWEEN '$start' AND '$end')\")\n ->sum('characters');\n $total_character_used =\n$total_character_used ?: 0;\n\n // check user's character limit\n if ($characters_limit != -1 && (($characters_limit -\n$total_character_used) <= $text_characters)) {\n $result['success']=false;\n $result['error']=__('Character limit\n\texceeded, Upgrade your membership plan.');\n die(json_encode($result));\n }\n\n // check voice is available\n\n\t$voices=get_ai_voices();\n if (isset($voices[$_POST['language']]['voices'][$_POST['voice_id']])) {\n\n\t$voice=$voices[$_POST['language']]['voices'][$_POST['voice_id']];\n\n require_once ROOTPATH\n\t. '/includes/lib/aws/aws-autoloader.php' ;\n\n try {\n $credentials=new\n\t\\Aws\\Credentials\\Credentials(get_option('ai_tts_aws_access_key', '' ), get_option('ai_tts_aws_secret_key', ''\n\t));\n $client=new \\Aws\\Polly\\PollyClient([\n 'region'=> get_option('ai_tts_aws_region'),\n 'version' =>\n\t'latest',\n 'credentials' => $credentials\n ]);\n } catch (Exception $e) {\n $result['success'] = false;\n\n\t$result['error'] = __('Incorrect AWS credentials.');\n $result['api_error'] = $e->getMessage();\n\n\tdie(json_encode($result));\n }\n\n $language = ($_POST['voice_id'] == 'br-aws-std-camila') ? 'pt-BR' :\n\t$_POST['language'];\n\n $text = preg_replace(\"/\\&/\", \"&\", $_POST['description']);\n $text =\n\tpreg_replace(\"/(^|(?<=\\s))<((?=\\s)|$)/i\", \"<\", $text);\n $text=preg_replace(\"/(^|(? <=\\s))>\n\t\t((?=\\s)|$)/i\", \">\", $text);\n\n $ssml_text = \"\" . $text . \"\";\n\n try {\n //Create synthesize speech\n $polly_result=$client->synthesizeSpeech([\n 'Engine' =>\n\t\t\t\t$voice['voice_type'],\n 'LanguageCode' => $language,\n 'Text' => $ssml_text,\n 'TextType' => 'ssml',\n\n\t\t\t\t'OutputFormat' => 'mp3',\n 'VoiceId' => $voice['voice'],\n ]);\n\n $audio_stream =\n\t\t\t\t$polly_result->get('AudioStream')->getContents();\n\n $name = uniqid() . '.mp3';\n\n $target_dir =\n\t\t\t\tROOTPATH . '/storage/ai_audios/';\n file_put_contents($target_dir . $name, $audio_stream);\n\n\n\t\t\t\t$content = ORM::for_table($config['db']['pre'] . 'ai_speeches')->create();\n $content->user_id =\n\t\t\t\t$_SESSION['user']['id'];\n $content->title = $_POST['title'];\n $content->voice_id =\n\t\t\t\t$_POST['voice_id'];\n $content->language = $_POST['language'];\n $content->characters =\n\t\t\t\t$text_characters;\n $content->text = $_POST['description'];\n $content->file_name = $name;\n\n\t\t\t\t$content->vendor_id = $voice['vendor_id'];\n $content->created_at = date('Y-m-d H:i:s');\n\n\t\t\t\t$content->save();\n\n $speech_used = ORM::for_table($config['db']['pre'] .\n\t\t\t\t'text_to_speech_used')->create();\n $speech_used->user_id = $_SESSION['user']['id'];\n\n\t\t\t\t$speech_used->characters = $text_characters;\n $speech_used->date = date('Y-m-d H:i:s');\n\n\t\t\t\t$speech_used->save();\n\n $result['success'] = true;\n $result['url'] = url('ALL_SPEECHES', false);\n\n\t\t\t\tdie(json_encode($result));\n\n } catch (Exception $e) {\n $result['success'] = false;\n $result['error']\n\t\t\t\t= __('AWS Synthesize Speech is not working, please try again.');\n $result['api_error'] =\n\t\t\t\t$e->getMessage();\n die(json_encode($result));\n }\n }\n }\n }\n $result['success'] = false;\n\n\t\t\t\t$result['error'] = __('Unexpected error, please try again.');\n\n\t\t\t\tdie(json_encode($result));\n}\n\nfunction delete_speech()\n{\n $result = array();\n if (checkloggedin())\n\t\t\t\t{\n global $config;\n\n $speech = ORM::for_table($config['db']['pre'] . 'ai_speeches')\n\n\t\t\t\t->select('file_name')\n ->where(array(\n 'id' => $_POST['id'],\n 'user_id' => $_SESSION['user']['id'],\n\n\t\t\t\t));\n\n foreach ($speech->find_array() as $row) {\n $dir = \"../storage/ai_audios/\";\n $main_file =\n\t\t\t\t$row['file_name'];\n\n if (trim($main_file) != \"\") {\n $file = $dir . $main_file;\n if\n\t\t\t\t(file_exists($file))\n unlink($file);\n }\n }\n\n if ($speech->delete_many()) {\n $result['success'] =\n\t\t\t\ttrue;\n $result['message'] = __('Deleted Successfully');\n die(json_encode($result));\n }\n }\n\n\t\t\t\t$result['success'] = false;\n $result['error'] = __('Unexpected error, please try again.');\n\n\t\t\t\tdie(json_encode($result));\n}"}