You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
352 lines
12 KiB
352 lines
12 KiB
<?php
|
|
|
|
// include_module('profile');
|
|
|
|
// Сохранить значения полей
|
|
add_action('wp_ajax_edit_user', 'save_custom_user_profile_fields');
|
|
add_action('wp_ajax_nopriv_edit_user', 'save_custom_user_profile_fields'); //
|
|
|
|
function save_custom_user_profile_fields() {
|
|
// Проверка прав пользователя
|
|
wp_update_user( array(
|
|
'ID' => get_current_user_id(),
|
|
'first_name' => $_POST['name'],
|
|
'last_name' => $_POST['l_name'],
|
|
|
|
) );
|
|
|
|
$phone = update_user_meta( get_current_user_id(), 'billing_phone', $_POST['phone'] );
|
|
|
|
}
|
|
|
|
function ajax_add_pet() {
|
|
$current_user = wp_get_current_user();
|
|
// Подготовка данных
|
|
$pet_name = $_POST['name'];
|
|
$old_type = $_POST['old_type'];
|
|
if ($old_type == 'ex'){
|
|
$old= $_POST['old'];
|
|
}
|
|
|
|
$weight= $_POST['weight'];
|
|
$activity = $_POST['activity'];
|
|
$pet = $_POST['pet'];
|
|
$breed = $_POST['breed'];
|
|
$sex = $_POST['sex'];
|
|
$user = $current_user->ID;
|
|
|
|
$post_data = array(
|
|
'post_title' => $pet_name,
|
|
'post_type' => 'pets',
|
|
'post_status' => 'publish',
|
|
);
|
|
|
|
|
|
$post_id = wp_insert_post($post_data);
|
|
var_dump($post_id);
|
|
if ($post_id) {
|
|
// Добавление мета-полей
|
|
if ($old_type == 'ex'){
|
|
|
|
update_field( 'old', $old, $post_id );
|
|
|
|
|
|
}
|
|
else{
|
|
|
|
update_field( 'day', $_POST['day'], $post_id );
|
|
update_field( 'month', $_POST['month'], $post_id );
|
|
update_field( 'year', $_POST['year'], $post_id );
|
|
}
|
|
update_field( 'weight', $weight, $post_id );
|
|
update_field( 'breed', $breed, $post_id );
|
|
update_field( 'sex', $sex, $post_id );
|
|
update_field( 'type', $pet, $post_id );
|
|
update_field( 'user', $user, $post_id );
|
|
update_field( 'activity', $activity, $post_id );
|
|
if($_POST['sterilized']=='1' && $pet=='cat'){
|
|
update_field( 'sterilized', true );
|
|
}
|
|
else{
|
|
update_field( 'sterilized', false );
|
|
}
|
|
wp_send_json_success('Питомец успешно добавлен!');
|
|
} else {
|
|
wp_send_json_error('Ошибка при добавлении питомца.');
|
|
}
|
|
|
|
wp_die(); // Завершение работы
|
|
}
|
|
add_action('wp_ajax_add_pet', 'ajax_add_pet');
|
|
add_action('wp_ajax_nopriv_add_pet', 'ajax_add_pet'); // Если нужно разрешить для незалогиненных пользователей
|
|
|
|
function ajax_edit_pet() {
|
|
$current_user = wp_get_current_user();
|
|
// Подготовка данных
|
|
$pet_name = $_POST['name'];
|
|
$old_type = $_POST['old_type'];
|
|
if ($old_type == 'ex'){
|
|
$old= $_POST['old'];
|
|
}
|
|
else{
|
|
$old_acc = $_POST['day'] . ' ' . $_POST['month'] . ' ' . $_POST['year'];
|
|
}
|
|
$weight= $_POST['weight'];
|
|
$activity = $_POST['activity'];
|
|
$pet = $_POST['pet'];
|
|
$breed = $_POST['breed'];
|
|
$sex = $_POST['sex'];
|
|
$user = $current_user->ID;
|
|
|
|
$post_id = intval($_POST['pet_id']);
|
|
|
|
if (get_field('user', $post_id) == $user) {
|
|
// Добавление мета-полей
|
|
if ($old_type == 'ex'){
|
|
update_field( 'old', $old, $post_id );
|
|
}
|
|
else{
|
|
update_field( 'old', '', $post_id );
|
|
update_field( 'day', $_POST['day'], $post_id );
|
|
update_field( 'month', $_POST['month'], $post_id );
|
|
update_field( 'year', $_POST['year'], $post_id );
|
|
}
|
|
update_field( 'weight', $weight, $post_id );
|
|
update_field( 'breed', $breed, $post_id );
|
|
update_field( 'sex', $sex, $post_id );
|
|
update_field( 'type', $pet, $post_id );
|
|
update_field( 'activity', $activity, $post_id );
|
|
if($_POST['sterilized']=='1' && $pet=='cat'){
|
|
update_field( 'sterilized', true );
|
|
}
|
|
else{
|
|
update_field( 'sterilized', false );
|
|
}
|
|
wp_send_json_success('Питомец успешно отредактирован!');
|
|
} else {
|
|
wp_send_json_error('Ошибка при редактировании питомца.');
|
|
}
|
|
|
|
wp_die(); // Завершение работы
|
|
}
|
|
add_action('wp_ajax_edit_pet', 'ajax_edit_pet');
|
|
add_action('wp_ajax_nopriv_edit_pet', 'ajax_edit_pet');
|
|
|
|
|
|
|
|
add_action('wp_ajax_update_subscription_address', 'handle_subscription_address_update');
|
|
add_action('wp_ajax_nopriv_update_subscription_address', 'handle_subscription_address_update');
|
|
|
|
function handle_subscription_address_update() {
|
|
if (!isset($_POST['address_nonce']) || !wp_verify_nonce($_POST['address_nonce'], 'update_subscription_address')) {
|
|
error_log('[AJAX] Ошибка nonce');
|
|
wp_send_json_error(['message' => pll__('Ошибка безопасности. Обновите страницу.')]);
|
|
}
|
|
|
|
if (!is_user_logged_in()) {
|
|
error_log('[AJAX] Пользователь не авторизован');
|
|
wp_send_json_error(['message' => pll__('Вы не авторизованы.')]);
|
|
}
|
|
|
|
$subscription_id = intval($_POST['subscription_id'] ?? 0);
|
|
$address_1 = sanitize_text_field($_POST['address'] ?? '');
|
|
$city = sanitize_text_field($_POST['city'] ?? '');
|
|
$comment = sanitize_textarea_field($_POST['comment'] ?? '');
|
|
|
|
if (!$subscription_id || empty($address_1)) {
|
|
wp_send_json_error(['message' => pll__('Недостаточно данных.')]);
|
|
}
|
|
|
|
$subscription = wcs_get_subscription($subscription_id);
|
|
|
|
if (!$subscription || $subscription->get_user_id() !== get_current_user_id()) {
|
|
wp_send_json_error(['message' => pll__('Подписка не найдена или не принадлежит вам.')]);
|
|
}
|
|
|
|
update_post_meta($subscription_id, '_shipping_address_1', $address_1);
|
|
update_post_meta($subscription_id, '_shipping_city', $city);
|
|
update_post_meta($subscription_id, '_shipping_comment', $comment);
|
|
|
|
$subscription->set_customer_note($comment);
|
|
$subscription->save();
|
|
|
|
|
|
wp_send_json_success(['message' => pll__('Адрес доставки успешно обновлён.')]);
|
|
}
|
|
|
|
|
|
|
|
// Динамическое определение BOT_USERNAME
|
|
$site_url = site_url();
|
|
if ($site_url === 'https://cosmopet-test-dumb.cp.good-production.xyz') {
|
|
define('BOT_USERNAME', 'cosmopet_test_RU_bot');
|
|
} elseif ($site_url === 'https://cosmopet-test-ae.cp.good-production.xyz') {
|
|
define('BOT_USERNAME', 'cosmopet_test_AE_bot');
|
|
}
|
|
elseif ($site_url === 'https://cosmopet.ru') {
|
|
define('BOT_USERNAME', 'Cosmopet_shop_bot');
|
|
}
|
|
elseif ($site_url === 'https://cosmopet.ae') {
|
|
define('BOT_USERNAME', 'cosmopet_ae_bot');
|
|
} else {
|
|
define('BOT_USERNAME', 'cosmopet_test_default_bot'); // Фallback на случай других доменов
|
|
}
|
|
|
|
// Функция получения данных Telegram
|
|
function getTelegramUserData() {
|
|
if (isset($_SESSION['tg_user'])) {
|
|
return $_SESSION['tg_user'];
|
|
}
|
|
return false;
|
|
}
|
|
|
|
// Функция вывода Telegram Widget
|
|
function tgWidget() {
|
|
if (!is_user_logged_in()) {
|
|
|
|
?>
|
|
<div id="telegram-widget-container"></div>
|
|
<?php
|
|
} else {
|
|
$current_user = wp_get_current_user();
|
|
echo "<h1>Hello, " . esc_html($current_user->display_name) . "!</h1>";
|
|
echo "<p><a href='" . wp_logout_url() . "'>Log out</a></p>";
|
|
}
|
|
}
|
|
|
|
function tgScript(){
|
|
$bot_username = BOT_USERNAME;
|
|
?>
|
|
|
|
<script>
|
|
document.addEventListener('DOMContentLoaded', function() {
|
|
var s = document.createElement('script');
|
|
s.src = 'https://telegram.org/js/telegram-widget.js?2';
|
|
s.async = true;
|
|
s.setAttribute('data-telegram-login', '<?php echo $bot_username?>');
|
|
s.setAttribute('data-size', 'large');
|
|
s.setAttribute('data-onauth', 'onTelegramAuth(user)');
|
|
s.setAttribute('data-request-access', 'write');
|
|
document.getElementById('telegram-widget-container').appendChild(s);
|
|
});
|
|
</script>
|
|
<?php
|
|
}
|
|
|
|
// Обработчик авторизации через Telegram
|
|
add_action('wp_ajax_ontelegramauth', 'onTelegramAuth');
|
|
add_action('wp_ajax_nopriv_ontelegramauth', 'onTelegramAuth');
|
|
|
|
function onTelegramAuth() {
|
|
// Получаем данные от Telegram
|
|
$auth_data = [
|
|
'id' => sanitize_text_field($_POST['userid']),
|
|
'first_name' => sanitize_text_field($_POST['fname']),
|
|
'last_name' => sanitize_text_field($_POST['lname']),
|
|
'username' => sanitize_text_field($_POST['username'] ?? ''),
|
|
];
|
|
|
|
if (!$auth_data['id']) {
|
|
wp_die(json_encode(['status' => 'error', 'message' => 'Invalid Telegram data']));
|
|
}
|
|
|
|
// Проверяем существование пользователя по tg_account
|
|
$users = get_users([
|
|
'meta_key' => 'tg_account',
|
|
'meta_value' => $auth_data['id'],
|
|
'number' => 1
|
|
]);
|
|
|
|
$password = wp_generate_password(12, true, false); // Генерация безопасного пароля
|
|
|
|
if ($users) {
|
|
// Существующий пользователь
|
|
$user = $users[0];
|
|
wp_set_password($password, $user->ID);
|
|
$login = wp_signon([
|
|
'user_login' => $user->user_login,
|
|
'user_password' => $password,
|
|
'remember' => true
|
|
]);
|
|
|
|
if (!is_wp_error($login)) {
|
|
session_start();
|
|
$_SESSION['tg_user'] = $auth_data;
|
|
session_write_close();
|
|
wp_die(json_encode(['status' => 'success', 'redirect' => admin_url()]));
|
|
}
|
|
} else {
|
|
// Новый пользователь
|
|
$username = sanitize_user($auth_data['username'] ?: $auth_data['first_name'] . '_' . $auth_data['last_name'], true);
|
|
$username = wp_slash($username); // Экранируем для безопасности
|
|
$user_id = wp_create_user($username, $password, $username . '@telegram.com');
|
|
|
|
if (!is_wp_error($user_id)) {
|
|
wp_update_user([
|
|
'ID' => $user_id,
|
|
'display_name' => $auth_data['first_name'] . ' ' . $auth_data['last_name'],
|
|
'first_name' => $auth_data['first_name'],
|
|
'last_name' => $auth_data['last_name']
|
|
]);
|
|
add_user_meta($user_id, 'tg_account', $auth_data['id']);
|
|
add_user_meta($user_id, 'tg_username', $auth_data['username']);
|
|
|
|
$login = wp_signon([
|
|
'user_login' => $username,
|
|
'user_password' => $password,
|
|
'remember' => true
|
|
]);
|
|
|
|
if (!is_wp_error($login)) {
|
|
session_start();
|
|
$_SESSION['tg_user'] = $auth_data;
|
|
session_write_close();
|
|
wp_die(json_encode(['status' => 'success', 'redirect' => admin_url()]));
|
|
}
|
|
}
|
|
}
|
|
|
|
wp_die(json_encode(['status' => 'error', 'message' => 'Login failed']));
|
|
}
|
|
|
|
// Функция привязки Telegram к существующему пользователю
|
|
add_action('wp_ajax_linktelegram', 'linkTelegram');
|
|
add_action('wp_ajax_nopriv_linktelegram', 'linkTelegram');
|
|
|
|
function linkTelegram() {
|
|
if (!is_user_logged_in()) {
|
|
wp_die(json_encode(['status' => 'error', 'message' => 'Not logged in']));
|
|
}
|
|
|
|
$tg_id = sanitize_text_field($_POST['userid']);
|
|
$user_id = get_current_user_id();
|
|
|
|
add_user_meta($user_id, 'tg_account', $tg_id);
|
|
wp_update_user([
|
|
'ID' => $user_id,
|
|
'first_name' => sanitize_text_field($_POST['fname']),
|
|
'last_name' => sanitize_text_field($_POST['lname'])
|
|
]);
|
|
|
|
wp_die(json_encode(['status' => 'success']));
|
|
}
|
|
|
|
// Функция обновления email
|
|
add_action('wp_ajax_email_link', 'emailLink');
|
|
add_action('wp_ajax_nopriv_email_link', 'emailLink');
|
|
|
|
function emailLink() {
|
|
if (!is_user_logged_in()) {
|
|
wp_die(json_encode(['status' => 'error', 'message' => 'Not logged in']));
|
|
}
|
|
|
|
$email = sanitize_email($_POST['email']);
|
|
$user_id = get_current_user_id();
|
|
|
|
if (email_exists($email)) {
|
|
wp_die(json_encode(['status' => 'error', 'message' => 'Email is already registered']));
|
|
}
|
|
|
|
wp_update_user(['ID' => $user_id, 'user_email' => $email]);
|
|
wp_die(json_encode(['status' => 'success']));
|
|
}
|