View file chess/add.php

File size: 6.67Kb
<?php
require_once ($_SERVER['DOCUMENT_ROOT'].'/system/connections/core.php');
acms_header('Шахматы', 'users');
require (ROOT.'/games/chess/plugins/config.php');
chess_stop();

if (post('ok')){
  valid::create(array(
    'PHONE' => ['phone', 'text', [0, 30], 'Цвет фона', 0],
    'PRIVATE' => ['private', 'int', [0,1], 'Приватный стол', 0],
    'PASS' => ['pass', 'text', [0, 40], 'Пароль', 0],
    'TIMECTL' => ['timectl', 'int', [0, 180], 'Контроль времени (мин)', 0],
  'THEME' => ['theme', 'text', [0, 20], 'Тема доски', 0],
  'INCR' => ['incr', 'int', [0, 60], 'Прирост (сек)', 0],
  'RATED' => ['rated', 'int', [0,1], 'Рейтинговая игра', 0],
  'MIN_RATING' => ['min_rating', 'int', [0,4000], 'Мин. рейтинг', 0],
  'MAX_RATING' => ['max_rating', 'int', [0,4000], 'Макс. рейтинг', 0]
  ));
  if (ERROR_LOG == 1){ redirect('/games/chess/add.php'); }
  $url = md5(user('ID').TM.rand(100,999));
  $phoneColor = (string)(post('phone') ?: '#ffffff');
  // sanitize color (#RRGGBB only)
  if(!preg_match('/^#[0-9a-fA-F]{6}$/',$phoneColor)) $phoneColor = '#ffffff';
  $private = intval(post('private')) === 1 ? 1 : 0;
  $pass = (string)(post('pass') ?: '');
  $timectl = intval(post('timectl'));
  $theme = (string)(post('theme') ?: 'default');
  $incr = intval(post('incr'));
  $rated = intval(post('rated')) === 1 ? 1 : 0;
  $prefColor = (string)(post('pref_color') ?: 'auto');
  if(!in_array($prefColor,['auto','white','black'],true)) $prefColor='auto';
  $minRating = max(0, intval(post('min_rating')));
  $maxRating = max(0, intval(post('max_rating')));
  if($maxRating>0 && $minRating>0 && $maxRating<$minRating){ $t=$minRating; $minRating=$maxRating; $maxRating=$t; }
  // initialize timers in seconds
  $whiteTime = ($timectl>0 ? $timectl*60 : 0);
  $blackTime = ($timectl>0 ? $timectl*60 : 0);
  // LAST_MOVE_TIME = 0 пока обе стороны не сядут (правильный старт таймеров)
  $id = db::get_add("INSERT INTO `CHESS` (`USER_ID`,`URL`,`WHITE_ID`,`BLACK_ID`,`FEN`,`TURN`,`TIME`,`PRIVATE`,`PHONE`,`PASS`,`TIMECTL`,`THEME`,`WHITE_TIME`,`BLACK_TIME`,`INCR`,`LAST_MOVE_TIME`,`RATED`,`MIN_RATING`,`MAX_RATING`) VALUES (?, ?, 0, 0, ?, 'w', ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?)", [user('ID'), $url, 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1', TM, $private, $phoneColor, $pass, $timectl, $theme, $whiteTime, $blackTime, $incr, $rated, $minRating, $maxRating]);
  // Try to seat the creator as preferred color immediately
  if ($prefColor==='white'){
    db::get_set("UPDATE `CHESS` SET `WHITE_ID` = ? WHERE `ID` = ? AND `WHITE_ID` = 0 LIMIT 1", [user('ID'), $id]);
  } elseif ($prefColor==='black'){
    db::get_set("UPDATE `CHESS` SET `BLACK_ID` = ? WHERE `ID` = ? AND `BLACK_ID` = 0 LIMIT 1", [user('ID'), $id]);
  } else {
    // auto: take white if free else black
    $row = db::get_string("SELECT `WHITE_ID`,`BLACK_ID` FROM `CHESS` WHERE `ID` = ? LIMIT 1", [$id]);
    if (intval($row['WHITE_ID'])==0) db::get_set("UPDATE `CHESS` SET `WHITE_ID` = ? WHERE `ID` = ? LIMIT 1", [user('ID'), $id]);
    elseif (intval($row['BLACK_ID'])==0) db::get_set("UPDATE `CHESS` SET `BLACK_ID` = ? WHERE `ID` = ? LIMIT 1", [user('ID'), $id]);
  }
  $targetUrl = '/games/chess/game.php?id='.$id.'&url='.tabs($url);
  success('Стол создан');
  // Если запрос пришёл через AJAX/XHR – вернуть явное указание на редирект
  $isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])==='xmlhttprequest';
  if ($isAjax){
    // Универсальный текстовый формат: первая строка = REDIRECT, вторая = URL
    header('Content-Type: text/plain; charset=utf-8');
    echo "REDIRECT\n".$targetUrl; 
    exit;
  }
  redirect($targetUrl);
}
?>
<div class='list'>
<form method='post' action='/games/chess/add.php'>
<?=html::select('phone', array(
  0 => ['Белый (#ffffff)', '#ffffff'],
  1 => ['Светло-серый (#f0f0f0)', '#f0f0f0'],
  2 => ['Бежевый (#f5f5dc)', '#f5f5dc'],
  3 => ['Зелёный (#638F65)', '#638F65'],
  4 => ['Синий (#399AA3)', '#399AA3'],
  5 => ['Тёмный серый (#313738)', '#313738']
), 'Цвет фона', 'form-control-100-modify-select', 'paint-brush')?>
<?=html::select('private', array(
  0 => ['Публичный стол', 0],
  1 => ['Приватный (по паролю/ссылке)', 1]
), 'Приватный стол', 'form-control-100-modify-select', 'lock')?>
<?=html::input('pass', 'Пароль (если приватный)', '', null, null, 'form-control-100', 'text', null, 'lock', 'до 40 символов')?>
<?=html::select('timectl', array(
  0 => ['Без лимита', 0],
  1 => ['1 мин', 1],
  3 => ['3 мин', 3],
  5 => ['5 мин', 5],
  10 => ['10 мин', 10],
  15 => ['15 мин', 15],
  30 => ['30 мин', 30],
  60 => ['60 мин', 60]
), 'Контроль времени (мин)', 'form-control-100-modify-select', 'clock-o')?>
<?=html::select('rated', array(
  1 => ['Рейтинговая (влияет на Elo)', 1],
  0 => ['Без рейтинга (casual)', 0]
), 'Тип игры', 'form-control-100-modify-select', 'trophy')?>
<?=html::select('pref_color', array(
  'auto' => ['Авто (занять свободные)', 'auto'],
  'white' => ['Играть за белых', 'white'],
  'black' => ['Играть за чёрных', 'black']
), 'Цвет при создании', 'form-control-100-modify-select', 'user')?>
<?=html::input('min_rating', 0, null, null, null, 'form-control-100', 'number', null, 'trophy', 'Минимальный рейтинг для входа')?>
<?=html::input('max_rating', 0, null, null, null, 'form-control-100', 'number', null, 'trophy', 'Максимальный рейтинг для входа (0 = без лимита)')?>
<?=html::select('theme', array(
  0 => ['Стандартная (default)', 'default'],
  1 => ['Синяя (blue)', 'blue'],
  2 => ['Зелёная (green)', 'green'],
  3 => ['Серая (gray)', 'gray']
), 'Тема доски', 'form-control-100-modify-select', 'paint-brush')?>
<?=html::select('incr', array(
  0 => ['0 сек', 0],
  1 => ['1 сек', 1],
  2 => ['2 сек', 2],
  3 => ['3 сек', 3],
  5 => ['5 сек', 5],
  10 => ['10 сек', 10]
), 'Прирост (секунд за ход)', 'form-control-100-modify-select', 'plus')?>
<?=html::button('submit', 'ok', 'plus', 'Создать')?>
<a class='button-o' href='/games/chess/'><?=lg('Отмена')?></a>
</form>
</div>
<?php
back('/games/chess/');
acms_footer();