Files
smilia/wp-content/plugins/smilia-core/includes/class-booking.php
T

353 lines
13 KiB
PHP

<?php
namespace Smilia\Core;
use WP_Post;
use WP_REST_Request;
use WP_REST_Response;
defined( 'ABSPATH' ) || exit;
final class Booking {
public const ROUTE_NAMESPACE = 'smilia/v1';
public const ROUTE = '/booking';
public const NONCE_ACTION = 'smilia_booking';
public const CONSENT_VERSION = '2026-10-22';
private const CLEANUP_HOOK = 'smilia_booking_cleanup';
private const RETENTION_DAYS = 365;
private const MIN_SECONDS = 3;
private const PHONE_CODE = '48';
private const PHONE_DIGITS = 9;
private const MAX_AGE = 2 * DAY_IN_SECONDS;
public static function concerns(): array {
return array(
'first-visit' => __( 'Первый визит, знакомство', 'smilia-core' ),
'checkup' => __( 'Осмотр и гигиена', 'smilia-core' ),
'pain' => __( 'Болит или сколот зуб', 'smilia-core' ),
'caries' => __( 'Лечение кариеса', 'smilia-core' ),
'bite' => __( 'Прикус, пластинка, брекеты', 'smilia-core' ),
'other' => __( 'Другое', 'smilia-core' ),
);
}
public static function form_data(): array {
$started = (string) time();
return array(
'endpoint' => function_exists( 'pll_current_language' ) && pll_current_language()
? add_query_arg( 'lang', pll_current_language(), rest_url( self::ROUTE_NAMESPACE . self::ROUTE ) )
: rest_url( self::ROUTE_NAMESPACE . self::ROUTE ),
'nonce' => wp_create_nonce( self::NONCE_ACTION ),
'rest' => wp_create_nonce( 'wp_rest' ),
'started' => $started . '.' . self::sign( $started ),
'captcha' => Captcha::endpoint(),
'script' => Captcha::script(),
'concerns' => self::concerns(),
'phone' => array(
'code' => self::PHONE_CODE,
'digits' => self::PHONE_DIGITS,
'example' => '+48 512 345 678',
),
'consent' => Markup::url( '/consent/' ),
'privacy' => Markup::url( '/privacy-policy/' ),
);
}
public function register(): void {
add_action( 'rest_api_init', array( $this, 'register_route' ) );
add_action( self::CLEANUP_HOOK, array( $this, 'cleanup' ) );
add_action( 'add_meta_boxes_' . Post_Types::BOOKING, array( $this, 'add_box' ) );
add_filter( 'manage_' . Post_Types::BOOKING . '_posts_columns', array( $this, 'columns' ) );
add_action( 'manage_' . Post_Types::BOOKING . '_posts_custom_column', array( $this, 'column' ), 10, 2 );
}
private static function route_args(): array {
$limits = array(
'smilia_nonce' => 40,
'started' => 100,
'website' => 200,
'name' => 120,
'phone' => 40,
'age' => 20,
'concern' => 40,
'page' => 2048,
'consent' => 2,
'altcha' => 4000,
);
$args = array();
foreach ( $limits as $name => $length ) {
$args[ $name ] = array(
'type' => 'string',
'maxLength' => $length,
'default' => '',
);
}
return $args;
}
public function register_route(): void {
register_rest_route(
self::ROUTE_NAMESPACE,
self::ROUTE,
array(
'methods' => 'POST',
'callback' => array( $this, 'handle' ),
'permission_callback' => '__return_true',
'args' => self::route_args(),
)
);
}
public function handle( WP_REST_Request $request ): WP_REST_Response {
if ( ! $this->same_origin( $request ) ) {
return $this->fail( 403, '', __( 'Заявку можно отправить только с сайта клиники.', 'smilia-core' ) );
}
if ( ! wp_verify_nonce( (string) $request->get_param( 'smilia_nonce' ), self::NONCE_ACTION ) ) {
return $this->fail( 403, '', __( 'Страница устарела. Обновите её и отправьте заявку ещё раз.', 'smilia-core' ) );
}
$started = $this->started_at( (string) $request->get_param( 'started' ) );
if ( null === $started || time() - $started > self::MAX_AGE ) {
return $this->fail( 400, '', __( 'Страница устарела. Обновите её и отправьте заявку ещё раз.', 'smilia-core' ) );
}
if ( '' !== trim( (string) $request->get_param( 'website' ) ) || time() - $started < self::MIN_SECONDS ) {
return $this->success();
}
$name = sanitize_text_field( (string) $request->get_param( 'name' ) );
$phone = sanitize_text_field( (string) $request->get_param( 'phone' ) );
$age = sanitize_text_field( (string) $request->get_param( 'age' ) );
$concern = sanitize_key( (string) $request->get_param( 'concern' ) );
$page = esc_url_raw( (string) $request->get_param( 'page' ) );
if ( mb_strlen( $name ) < 2 || mb_strlen( $name ) > 80 ) {
return $this->fail( 422, 'name', __( 'Проверьте имя.', 'smilia-core' ) );
}
$phone = self::normalize_phone( $phone );
if ( '' === $phone ) {
return $this->fail( 422, 'phone', __( 'Проверьте номер телефона.', 'smilia-core' ) );
}
if ( mb_strlen( $age ) > 20 ) {
return $this->fail( 422, 'age', __( 'Проверьте возраст ребёнка.', 'smilia-core' ) );
}
if ( ! array_key_exists( $concern, self::concerns() ) ) {
return $this->fail( 422, 'concern', __( 'Выберите, что беспокоит.', 'smilia-core' ) );
}
if ( '1' !== (string) $request->get_param( 'consent' ) ) {
return $this->fail( 422, 'consent', __( 'Нужно ваше согласие на обработку персональных данных.', 'smilia-core' ) );
}
if ( ! Captcha::verify( (string) $request->get_param( 'altcha' ) ) ) {
return $this->fail( 422, '', __( 'Не удалось подтвердить отправку. Обновите страницу и отправьте заявку ещё раз.', 'smilia-core' ) );
}
$time = current_time( 'mysql' );
$post_id = wp_insert_post(
array(
'post_type' => Post_Types::BOOKING,
'post_status' => 'private',
'post_title' => $name . ', ' . $phone,
'meta_input' => array(
'smilia_phone' => $phone,
'smilia_age' => $age,
'smilia_concern' => $concern,
'smilia_page' => $page,
'smilia_consent' => 'yes',
'smilia_consent_version' => self::CONSENT_VERSION,
'smilia_consent_url' => Markup::url( '/consent/' ),
'smilia_consent_time' => $time,
),
),
true
);
if ( is_wp_error( $post_id ) ) {
return $this->fail( 500, '', __( 'Не получилось отправить заявку. Позвоните нам, пожалуйста.', 'smilia-core' ) );
}
$this->log_consent( $time, $phone, $page );
$this->notify( $name, $phone, $age, $concern, $page, $time );
return $this->success();
}
private function same_origin( WP_REST_Request $request ): bool {
$home = wp_parse_url( home_url(), PHP_URL_HOST );
$source = (string) ( $request->get_header( 'origin' ) ?: $request->get_header( 'referer' ) );
return '' !== $source && wp_parse_url( $source, PHP_URL_HOST ) === $home;
}
private static function sign( string $value ): string {
return substr( hash_hmac( 'sha256', $value, wp_salt( 'nonce' ) ), 0, 20 );
}
private function started_at( string $token ): ?int {
$parts = explode( '.', $token, 2 );
if ( 2 !== count( $parts ) || ! ctype_digit( $parts[0] ) || ! hash_equals( self::sign( $parts[0] ), $parts[1] ) ) {
return null;
}
return (int) $parts[0];
}
private static function normalize_phone( string $phone ): string {
$digits = (string) preg_replace( '/\D/', '', $phone );
if ( str_starts_with( $digits, '00' . self::PHONE_CODE ) ) {
$digits = substr( $digits, 2 );
}
if ( self::PHONE_DIGITS === strlen( $digits ) ) {
$digits = self::PHONE_CODE . $digits;
}
return preg_match( '/^' . self::PHONE_CODE . '\d{' . self::PHONE_DIGITS . '}$/', $digits ) ? '+' . $digits : '';
}
private function success(): WP_REST_Response {
return new WP_REST_Response(
array(
'ok' => true,
'message' => Settings::get( 'booking_thanks' ),
),
200
);
}
private function fail( int $status, string $field, string $message ): WP_REST_Response {
return new WP_REST_Response(
array(
'ok' => false,
'field' => $field,
'message' => $message,
),
$status
);
}
private static function consent_dir(): string {
return defined( 'SMILIA_CONSENT_DIR' ) ? (string) SMILIA_CONSENT_DIR : '';
}
private function log_consent( string $time, string $phone, string $page ): void {
$dir = self::consent_dir();
if ( '' === $dir || ! is_dir( $dir ) || ! wp_is_writable( $dir ) ) {
return;
}
$line = wp_json_encode(
array(
'time' => $time,
'consent' => true,
'consent_version' => self::CONSENT_VERSION,
'consent_url' => Markup::url( '/consent/' ),
'page' => $page,
'phone' => $phone,
),
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
);
file_put_contents( trailingslashit( $dir ) . 'consents-' . gmdate( 'Y-m' ) . '.jsonl', $line . "\n", FILE_APPEND | LOCK_EX );
}
private function notify( string $name, string $phone, string $age, string $concern, string $page, string $time ): void {
$lines = array(
__( 'Новая заявка на приём', 'smilia-core' ),
__( 'Имя:', 'smilia-core' ) . ' ' . $name,
__( 'Телефон:', 'smilia-core' ) . ' ' . $phone,
__( 'Возраст ребёнка:', 'smilia-core' ) . ' ' . ( '' !== $age ? $age : '-' ),
__( 'Что беспокоит:', 'smilia-core' ) . ' ' . self::concerns()[ $concern ],
__( 'Страница:', 'smilia-core' ) . ' ' . $page,
sprintf(
__( 'Согласие на обработку персональных данных: да, %1$s, текст от %2$s, %3$s', 'smilia-core' ),
$time,
self::CONSENT_VERSION,
Markup::url( '/consent/' )
),
);
$email = Settings::get( 'booking_email' );
wp_mail( is_email( $email ) ? $email : (string) get_option( 'admin_email' ),__( 'Smilia: новая заявка', 'smilia-core' ), implode( "\n", $lines ) );
}
public function add_box(): void {
add_meta_box( 'smilia_booking_box', __( 'Заявка', 'smilia-core' ), array( $this, 'render_box' ), Post_Types::BOOKING, 'normal' );
remove_meta_box( 'submitdiv', Post_Types::BOOKING, 'side' );
}
public function render_box( WP_Post $post ): void {
$rows = array(
__( 'Телефон', 'smilia-core' ) => get_post_meta( $post->ID, 'smilia_phone', true ),
__( 'Возраст ребёнка', 'smilia-core' ) => get_post_meta( $post->ID, 'smilia_age', true ),
__( 'Что беспокоит', 'smilia-core' ) => self::concerns()[ get_post_meta( $post->ID, 'smilia_concern', true ) ] ?? '',
__( 'Страница', 'smilia-core' ) => get_post_meta( $post->ID, 'smilia_page', true ),
__( 'Согласие', 'smilia-core' ) => sprintf( '%s, %s, %s', get_post_meta( $post->ID, 'smilia_consent_time', true ), get_post_meta( $post->ID, 'smilia_consent_version', true ), get_post_meta( $post->ID, 'smilia_consent_url', true ) ),
);
echo '<table class="widefat striped"><tbody>';
foreach ( $rows as $label => $value ) {
printf( '<tr><th>%s</th><td>%s</td></tr>', esc_html( $label ), esc_html( (string) $value ) );
}
echo '</tbody></table>';
}
public function columns( array $columns ): array {
return array(
'cb' => $columns['cb'] ?? '',
'title' => __( 'Имя и телефон', 'smilia-core' ),
'smilia_concern' => __( 'Что беспокоит', 'smilia-core' ),
'date' => $columns['date'] ?? __( 'Дата', 'smilia-core' ),
);
}
public function column( string $column, int $post_id ): void {
if ( 'smilia_concern' === $column ) {
echo esc_html( self::concerns()[ get_post_meta( $post_id, 'smilia_concern', true ) ] ?? '' );
}
}
public static function schedule_cleanup(): void {
if ( ! wp_next_scheduled( self::CLEANUP_HOOK ) ) {
wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', self::CLEANUP_HOOK );
}
}
public static function unschedule_cleanup(): void {
wp_clear_scheduled_hook( self::CLEANUP_HOOK );
}
public function cleanup(): void {
$old = get_posts(
array(
'post_type' => Post_Types::BOOKING,
'post_status' => 'any',
'posts_per_page' => 200,
'fields' => 'ids',
'date_query' => array(
array(
'before' => self::RETENTION_DAYS . ' days ago',
),
),
)
);
foreach ( $old as $post_id ) {
wp_delete_post( (int) $post_id, true );
}
Captcha::cleanup();
$dir = self::consent_dir();
if ( '' === $dir || ! is_dir( $dir ) ) {
return;
}
$cutoff = wp_date( 'Y-m-d H:i:s', time() - self::RETENTION_DAYS * DAY_IN_SECONDS );
foreach ( glob( trailingslashit( $dir ) . 'consents-*.jsonl' ) ?: array() as $file ) {
$kept = array();
foreach ( file( $file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES ) ?: array() as $line ) {
$row = json_decode( $line, true );
if ( is_array( $row ) && isset( $row['time'] ) && (string) $row['time'] >= $cutoff ) {
$kept[] = $line;
}
}
if ( ! $kept ) {
wp_delete_file( $file );
} elseif ( count( $kept ) !== count( file( $file ) ) ) {
file_put_contents( $file, implode( "\n", $kept ) . "\n", LOCK_EX );
}
}
}
}