(.+?)<\/code>#isUe",
+ "#\[quote\](.+?)\[\/quote\]#is",
+ "#\[url=(.+?)\](.+?)\[\/url\]#is",
+ "#(^|[\n ])([\w]+?://[\w\#$%&~/.\-;:=,?@\[\]+]*)#is"
+ );
- $str_replace = array(
- "",
- "",
- "\\1 ",
- "\\1 ",
- "",
- "''.htmlspecialchars('$1').'
'",
- "\\1
",
- "\\2 ",
- "\\2 "
- );
+ $str_replace = array(
+ "",
+ "",
+ "\\1 ",
+ "\\1 ",
+ "",
+ "''.htmlspecialchars('$1').'
'",
+ "\\1
",
+ "\\2 ",
+ "\\2 "
+ );
- $uptext = '';
+ $uptext = '';
- foreach($lines as $line)
- $uptext .= preg_replace($str_search, $str_replace, $line).PHP_EOL;
+ foreach($lines as $line)
+ $uptext .= preg_replace($str_search, $str_replace, $line).PHP_EOL;
- return $uptext;
- }
+ return $uptext;
+ }
- public static function text($section, $name)
- {
- global $cfg, $user;
+ public static function text($section, $name)
+ {
+ global $cfg, $user;
- $group = isset($user['group']) ? $user['group'] : 'user';
+ $group = isset($user['group']) ? $user['group'] : 'user';
- if($section != 'error' || !$cfg['text_group'])
- $group = 'all';
+ if($section != 'error' || !$cfg['text_group'])
+ $group = 'all';
- include(DATA.'text/'.$section.'.php');
+ include(DATA.'text/'.$section.'.php');
- return isset($text[$name][$group]) ? $text[$name][$group] : $text[$name];
- }
+ return isset($text[$name][$group]) ? $text[$name][$group] : $text[$name];
+ }
- public static function updtext($text, $data)
- {
- foreach($data as $name => $val)
- $text = str_replace('['.$name.']', $val, $text);
-
- return $text;
- }
- }
+ public static function updtext($text, $data)
+ {
+ foreach($data as $name => $val)
+ $text = str_replace('['.$name.']', $val, $text);
+
+ return $text;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/api.php b/system/library/api.php
index 478f980..40b0a11 100644
--- a/system/library/api.php
+++ b/system/library/api.php
@@ -1,95 +1,95 @@
query('SELECT `unit`, `tarif`, `address`, `game`, `slots_start`, `online`, `players`, `status`, `name`, `map`, `pack`, `fps`, `tickrate`, `ram`, `time`, `date`, `overdue` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- if(!$sql->num())
- return array('e' => 'сервер не найден');
+ $sql->query('SELECT `unit`, `tarif`, `address`, `game`, `slots_start`, `online`, `players`, `status`, `name`, `map`, `pack`, `fps`, `tickrate`, `ram`, `time`, `date`, `overdue` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ if(!$sql->num())
+ return array('e' => 'сервер не найден');
- $server = $sql->get();
+ $server = $sql->get();
- $sql->query('SELECT `name` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- if(!$sql->num())
- return array('e' => 'локация не найдена');
+ $sql->query('SELECT `name` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ if(!$sql->num())
+ return array('e' => 'локация не найдена');
- $unit = $sql->get();
-
- $sql->query('SELECT `name`, `packs` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
- if(!$sql->num())
- return array('e' => 'тариф не найден');
+ $unit = $sql->get();
+
+ $sql->query('SELECT `name`, `packs` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
+ if(!$sql->num())
+ return array('e' => 'тариф не найден');
- $tarif = $sql->get();
- $packs = sys::b64djs($tarif['packs']);
+ $tarif = $sql->get();
+ $packs = sys::b64djs($tarif['packs']);
- $time_end = $server['status'] == 'overdue' ? 'Удаление через: '.sys::date('min', $server['overdue']+$cfg['server_delete']*86400) : 'Осталось: '.sys::date('min', $server['time']);
+ $time_end = $server['status'] == 'overdue' ? 'Удаление через: '.sys::date('min', $server['overdue']+$cfg['server_delete']*86400) : 'Осталось: '.sys::date('min', $server['time']);
- return array(
- 'id' => $id,
- 'address' => $server['address'],
- 'unit' => $unit['name'],
- 'tarif' => games::info_tarif($server['game'], $tarif['name'], array('fps' => $server['fps'], 'tickrate' => $server['tickrate'], 'ram' => $server['ram'])),
- 'game' => $server['game'],
- 'name' => $server['name'],
- 'slots' => $server['slots_start'],
- 'online' => $server['online'],
- 'players' => $server['players'],
- 'status' => sys::status($server['status'], $server['game'], $server['map']),
- 'img' => sys::status($server['status'], $server['game'], $server['map'], 'img'),
- 'time_end' => $time_end,
- 'time' => sys::today($server['time']),
- 'date' => sys::today($server['date']),
- 'pack' => $packs[$server['pack']]
- );
- }
+ return array(
+ 'id' => $id,
+ 'address' => $server['address'],
+ 'unit' => $unit['name'],
+ 'tarif' => games::info_tarif($server['game'], $tarif['name'], array('fps' => $server['fps'], 'tickrate' => $server['tickrate'], 'ram' => $server['ram'])),
+ 'game' => $server['game'],
+ 'name' => $server['name'],
+ 'slots' => $server['slots_start'],
+ 'online' => $server['online'],
+ 'players' => $server['players'],
+ 'status' => sys::status($server['status'], $server['game'], $server['map']),
+ 'img' => sys::status($server['status'], $server['game'], $server['map'], 'img'),
+ 'time_end' => $time_end,
+ 'time' => sys::today($server['time']),
+ 'date' => sys::today($server['date']),
+ 'pack' => $packs[$server['pack']]
+ );
+ }
- public function load($id)
- {
- global $sql, $cfg;
+ public function load($id)
+ {
+ global $sql, $cfg;
- $sql->query('SELECT `online`, `slots_start`, `ram_use`, `cpu_use`, `hdd_use` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- if(!$sql->num())
- return array('e' => 'сервер не найден');
+ $sql->query('SELECT `online`, `slots_start`, `ram_use`, `cpu_use`, `hdd_use` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ if(!$sql->num())
+ return array('e' => 'сервер не найден');
- $server = $sql->get();
+ $server = $sql->get();
- $online = 100/$server['slots_start']*$server['online'];
- $online = $online > 100 ? 100: $online;
+ $online = 100/$server['slots_start']*$server['online'];
+ $online = $online > 100 ? 100: $online;
- return array(
- 'id' => $id,
- 'cpu' => $server['cpu_use'],
- 'ram' => $server['ram_use'],
- 'hdd' => $server['hdd_use'],
- 'onl' => $online
- );
- }
+ return array(
+ 'id' => $id,
+ 'cpu' => $server['cpu_use'],
+ 'ram' => $server['ram_use'],
+ 'hdd' => $server['hdd_use'],
+ 'onl' => $online
+ );
+ }
- public function console($id, $cmd)
- {
- global $sql, $cfg;
+ public function console($id, $cmd)
+ {
+ global $sql, $cfg;
- $aGames = array('cs', 'css', 'cssold', 'csgo', 'mc', 'mta');
+ $aGames = array('cs', 'css', 'cssold', 'csgo', 'mc', 'mta');
- $sql->query('SELECT `game` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- if(!$sql->num())
- return 'сервер не найден';
+ $sql->query('SELECT `game` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ if(!$sql->num())
+ return 'сервер не найден';
- $server = $sql->get();
+ $server = $sql->get();
- if(!in_array($server['game'], $aGames))
- return 'Игра не поддерживает команды';
+ if(!in_array($server['game'], $aGames))
+ return 'Игра не поддерживает команды';
- $go = true;
+ $go = true;
- $_POST['command'] = isset($cmd{0}) ? urldecode($cmd) : '';
+ $_POST['command'] = isset($cmd{0}) ? urldecode($cmd) : '';
- include(SEC.'servers/'.$server['game'].'/console.php');
- }
- }
+ include(SEC.'servers/'.$server['game'].'/console.php');
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/control/actions.php b/system/library/control/actions.php
index 2972f05..14f8abc 100644
--- a/system/library/control/actions.php
+++ b/system/library/control/actions.php
@@ -1,360 +1,360 @@
query('SELECT `uid`, `unit`, `game`, `address`, `name` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `uid`, `unit`, `game`, `address`, `name` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `address`, `passwd` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return array('e' => sys::text('error', 'ssh'));
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return array('e' => sys::text('error', 'ssh'));
- $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
- .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
+ $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
+ .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
- // Обновление информации в базе
- $sql->query('UPDATE `control_servers` set `status`="off", `online`="0", `players`="", `stop`="0" WHERE `id`="'.$id.'" LIMIT 1');
+ // Обновление информации в базе
+ $sql->query('UPDATE `control_servers` set `status`="off", `online`="0", `players`="", `stop`="0" WHERE `id`="'.$id.'" LIMIT 1');
- // Сброс кеша
- actions::clmcache($id);
+ // Сброс кеша
+ actions::clmcache($id);
- sys::reset_mcache('ctrl_server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0, 'players' => ''));
- sys::reset_mcache('ctrl_server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0));
+ sys::reset_mcache('ctrl_server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0, 'players' => ''));
+ sys::reset_mcache('ctrl_server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0));
- return array('s' => 'ok');
- }
+ return array('s' => 'ok');
+ }
- public static function change($id, $map = false)
- {
- global $cfg, $sql, $html, $user, $mcache;
+ public static function change($id, $map = false)
+ {
+ global $cfg, $sql, $html, $user, $mcache;
- // Если в кеше есть карты
- if($mcache->get('ctrl_server_maps_change_'.$id) != '' && !$map)
- return array('maps' => $mcache->get('ctrl_server_maps_change_'.$id));
+ // Если в кеше есть карты
+ if($mcache->get('ctrl_server_maps_change_'.$id) != '' && !$map)
+ return array('maps' => $mcache->get('ctrl_server_maps_change_'.$id));
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- $sql->query('SELECT `uid`, `unit`, `game`, `online`, `players`, `name` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `uid`, `unit`, `game`, `online`, `players`, `name` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `address`, `passwd` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return array('e' => sys::text('error', 'ssh'));
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return array('e' => sys::text('error', 'ssh'));
- // Массив карт игрового сервера (папка "maps")
- $aMaps = explode("\n", $ssh->get('cd /servers/'.$server['uid'].'/cstrike/maps/ && ls | grep .bsp | grep -v .bsp.'));
+ // Массив карт игрового сервера (папка "maps")
+ $aMaps = explode("\n", $ssh->get('cd /servers/'.$server['uid'].'/cstrike/maps/ && ls | grep .bsp | grep -v .bsp.'));
- // Удаление пустого элемента
- unset($aMaps[count($aMaps)-1]);
+ // Удаление пустого элемента
+ unset($aMaps[count($aMaps)-1]);
- // Удаление ".bsp"
- $aMaps = str_replace('.bsp', '', $aMaps);
+ // Удаление ".bsp"
+ $aMaps = str_replace('.bsp', '', $aMaps);
- // Если выбрана карта
- if($map)
- {
- // Проверка наличия выбранной карты
- if(!in_array($map, $aMaps))
- return array('e' => sys::updtext(sys::text('servers', 'change'), array('map' => $map.'.bsp')));
+ // Если выбрана карта
+ if($map)
+ {
+ // Проверка наличия выбранной карты
+ if(!in_array($map, $aMaps))
+ return array('e' => sys::updtext(sys::text('servers', 'change'), array('map' => $map.'.bsp')));
- // Отправка команды changelevel
- $ssh->set('sudo -u server'.$server['uid'].' screen -p 0 -S s_'.$server['uid'].' -X eval '."'stuff \"changelevel ".sys::cmd($map)."\"\015'");
+ // Отправка команды changelevel
+ $ssh->set('sudo -u server'.$server['uid'].' screen -p 0 -S s_'.$server['uid'].' -X eval '."'stuff \"changelevel ".sys::cmd($map)."\"\015'");
- // Обновление информации в базе
- $sql->query('UPDATE `control_servers` set `status`="change" WHERE `id`="'.$id.'" LIMIT 1');
+ // Обновление информации в базе
+ $sql->query('UPDATE `control_servers` set `status`="change" WHERE `id`="'.$id.'" LIMIT 1');
- // Сброс кеша
- actions::clmcache($id);
+ // Сброс кеша
+ actions::clmcache($id);
- sys::reset_mcache('ctrl_server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'change', 'online' => $server['online'], 'players' => base64_decode($server['players'])));
- sys::reset_mcache('ctrl_server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'change', 'online' => $server['online']));
+ sys::reset_mcache('ctrl_server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'change', 'online' => $server['online'], 'players' => base64_decode($server['players'])));
+ sys::reset_mcache('ctrl_server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'change', 'online' => $server['online']));
- return array('s' => 'ok');
- }
+ return array('s' => 'ok');
+ }
- // Сортировка списка карт
- sort($aMaps);
- reset($aMaps);
+ // Сортировка списка карт
+ sort($aMaps);
+ reset($aMaps);
- // Генерация списка карт для выбора
- foreach($aMaps as $map)
- {
- $html->get('change_list', 'sections/control/servers/games');
- $html->set('img', file_exists(DIR.'/maps/'.$server['game'].'/'.$map.'.jpg') ? $cfg['http'].'maps/'.$server['game'].'/'.$map.'.jpg' : $cfg['http'].'template/images/status/none.jpg');
- $html->set('name', $map);
- $html->set('id', $server['unit']);
- $html->set('server', $id);
- $html->pack('maps');
- }
+ // Генерация списка карт для выбора
+ foreach($aMaps as $map)
+ {
+ $html->get('change_list', 'sections/control/servers/games');
+ $html->set('img', file_exists(DIR.'/maps/'.$server['game'].'/'.$map.'.jpg') ? $cfg['http'].'maps/'.$server['game'].'/'.$map.'.jpg' : $cfg['http'].'template/images/status/none.jpg');
+ $html->set('name', $map);
+ $html->set('id', $server['unit']);
+ $html->set('server', $id);
+ $html->pack('maps');
+ }
- // Запись карт в кеш
- $mcache->set('ctrl_server_maps_change_'.$id, $html->arr['maps'], false, 30);
+ // Запись карт в кеш
+ $mcache->set('ctrl_server_maps_change_'.$id, $html->arr['maps'], false, 30);
- return array('maps' => $html->arr['maps']);
- }
+ return array('maps' => $html->arr['maps']);
+ }
- public static function reinstall($id)
- {
- global $cfg, $sql, $user, $start_point;
+ public static function reinstall($id)
+ {
+ global $cfg, $sql, $user, $start_point;
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- $sql->query('SELECT `uid`, `unit`, `address`, `game`, `name`, `pack`, `ftp`, `core_fix` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `uid`, `unit`, `address`, `game`, `name`, `pack`, `ftp`, `core_fix` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `address`, `passwd`, `fcpu` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd`, `fcpu` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return array('e' => sys::text('error', 'ssh'));
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return array('e' => sys::text('error', 'ssh'));
- $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
- .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
+ $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
+ .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
- $taskset = '';
+ $taskset = '';
- // Если включена система автораспределения и не установлен фиксированный поток
- if(!$server['core_fix'])
- {
- $proc_stat = array();
+ // Если включена система автораспределения и не установлен фиксированный поток
+ if(!$server['core_fix'])
+ {
+ $proc_stat = array();
- $proc_stat[0] = $ssh->get('cat /proc/stat');
- }
+ $proc_stat[0] = $ssh->get('cat /proc/stat');
+ }
- $path = 'rm '.$server['pack'].'.zip; wget '.$cfg['control_server'].'/'.$server['pack'].'.zip; unzip '.$server['pack'].'.zip; rm '.$server['pack'].'.zip;';
+ $path = 'rm '.$server['pack'].'.zip; wget '.$cfg['control_server'].'/'.$server['pack'].'.zip; unzip '.$server['pack'].'.zip; rm '.$server['pack'].'.zip;';
- if(in_array($server['game'], array('css', 'csgo')))
- $path = 'cd '.$cfg['steamcmd'].'; ./steamcmd.sh +login anonymous +force_install_dir "/servers/'.$uid.'" +app_update '.$cfg['control_steamcmd'][$game].' +quit;';
+ if(in_array($server['game'], array('css', 'csgo')))
+ $path = 'cd '.$cfg['steamcmd'].'; ./steamcmd.sh +login anonymous +force_install_dir "/servers/'.$uid.'" +app_update '.$cfg['control_steamcmd'][$game].' +quit;';
- // Директория игрового сервера
- $install = '/servers/'.$server['uid'];
+ // Директория игрового сервера
+ $install = '/servers/'.$server['uid'];
- // Если система автораспределения продолжить парсинг загрузки процессора
- if(isset($proc_stat))
- {
- $proc_stat[1] = $ssh->get('cat /proc/stat');
+ // Если система автораспределения продолжить парсинг загрузки процессора
+ if(isset($proc_stat))
+ {
+ $proc_stat[1] = $ssh->get('cat /proc/stat');
- // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
- $core = sys::cpu_idle($proc_stat, $server['unit'], $unit['fcpu'], true); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
+ // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
+ $core = sys::cpu_idle($proc_stat, $server['unit'], $unit['fcpu'], true); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
- if(!is_numeric($core))
- return array('e' => 'Не удается выполнить операцию, нет свободного потока.');
+ if(!is_numeric($core))
+ return array('e' => 'Не удается выполнить операцию, нет свободного потока.');
- $taskset = 'taskset -c '.$core;
- }
+ $taskset = 'taskset -c '.$core;
+ }
- if($server['core_fix'])
- {
- $core = $server['core_fix']-1;
- $taskset = 'taskset -c '.$core;
- }
+ if($server['core_fix'])
+ {
+ $core = $server['core_fix']-1;
+ $taskset = 'taskset -c '.$core;
+ }
- $ssh->set('rm -r '.$install.';' // Удаление директории игрового сервера
- .'mkdir '.$install.';' // Создание директории
- .'chown server'.$server['uid'].':1000 '.$install.';' // Изменение владельца и группы директории
- .'cd '.$install.' && sudo -u server'.$server['uid'].' '.$taskset.' screen -dmS r_'.$server['uid'].' sh -c "'
- .$path // Копирование файлов сборки для сервера
- .'find . -type d -exec chmod 700 {} \;;'
- .'find . -type f -exec chmod 600 {} \;;'
- .'chmod 500 '.params::$aFileGame[$server['game']].'"');
+ $ssh->set('rm -r '.$install.';' // Удаление директории игрового сервера
+ .'mkdir '.$install.';' // Создание директории
+ .'chown server'.$server['uid'].':1000 '.$install.';' // Изменение владельца и группы директории
+ .'cd '.$install.' && sudo -u server'.$server['uid'].' '.$taskset.' screen -dmS r_'.$server['uid'].' sh -c "'
+ .$path // Копирование файлов сборки для сервера
+ .'find . -type d -exec chmod 700 {} \;;'
+ .'find . -type f -exec chmod 600 {} \;;'
+ .'chmod 500 '.params::$aFileGame[$server['game']].'"');
- // Очистка записей в базе
- $sql->query('DELETE FROM `control_admins_'.$server['game'].'` WHERE `server`="'.$id.'"'); // Список админов на сервере
- $sql->query('DELETE FROM `control_plugins_install` WHERE `server`="'.$id.'"'); // Список установленных плагинов на сервере
+ // Очистка записей в базе
+ $sql->query('DELETE FROM `control_admins_'.$server['game'].'` WHERE `server`="'.$id.'"'); // Список админов на сервере
+ $sql->query('DELETE FROM `control_plugins_install` WHERE `server`="'.$id.'"'); // Список установленных плагинов на сервере
- $core = !isset($core) ? 0 : $core+1;
+ $core = !isset($core) ? 0 : $core+1;
- // Обновление информации в базе
- $sql->query('UPDATE `control_servers` set `status`="reinstall", `core_use`="'.$core.'", `fastdl`="0" WHERE `id`="'.$id.'" LIMIT 1');
+ // Обновление информации в базе
+ $sql->query('UPDATE `control_servers` set `status`="reinstall", `core_use`="'.$core.'", `fastdl`="0" WHERE `id`="'.$id.'" LIMIT 1');
- // Сброс кеша
- actions::clmcache($id);
+ // Сброс кеша
+ actions::clmcache($id);
- sys::reset_mcache('ctrl_server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'reinstall', 'online' => 0, 'players' => ''));
- sys::reset_mcache('ctrl_server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'reinstall', 'online' => 0));
+ sys::reset_mcache('ctrl_server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'reinstall', 'online' => 0, 'players' => ''));
+ sys::reset_mcache('ctrl_server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'reinstall', 'online' => 0));
- return array('s' => 'ok');
- }
+ return array('s' => 'ok');
+ }
- public static function update($id)
- {
- global $cfg, $sql, $user, $start_point;
+ public static function update($id)
+ {
+ global $cfg, $sql, $user, $start_point;
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- $sql->query('SELECT `uid`, `unit`, `address`, `game`, `name`, `pack`, `ftp` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `uid`, `unit`, `address`, `game`, `name`, `pack`, `ftp` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `address`, `passwd`, `fcpu` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd`, `fcpu` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return array('e' => sys::text('error', 'ssh'));
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return array('e' => sys::text('error', 'ssh'));
- $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
- .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
+ $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
+ .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
- $taskset = '';
+ $taskset = '';
- // Если включена система автораспределения и не установлен фиксированный поток
- if(!$server['core_fix'])
- {
- $proc_stat = array();
+ // Если включена система автораспределения и не установлен фиксированный поток
+ if(!$server['core_fix'])
+ {
+ $proc_stat = array();
- $proc_stat[0] = $ssh->get('cat /proc/stat');
- }
+ $proc_stat[0] = $ssh->get('cat /proc/stat');
+ }
- $path = 'rm '.$server['pack'].'_udp.zip; wget '.$cfg['control_server'].'/'.$server['pack'].'_udp.zip; unzip -u '.$server['pack'].'_udp.zip; rm '.$server['pack'].'_udp.zip;';
+ $path = 'rm '.$server['pack'].'_udp.zip; wget '.$cfg['control_server'].'/'.$server['pack'].'_udp.zip; unzip -u '.$server['pack'].'_udp.zip; rm '.$server['pack'].'_udp.zip;';
- // Директория игрового сервера
- $install = '/servers/'.$server['uid'];
+ // Директория игрового сервера
+ $install = '/servers/'.$server['uid'];
- // Если система автораспределения продолжить парсинг загрузки процессора
- if(isset($proc_stat))
- {
- $proc_stat[1] = $ssh->get('cat /proc/stat');
+ // Если система автораспределения продолжить парсинг загрузки процессора
+ if(isset($proc_stat))
+ {
+ $proc_stat[1] = $ssh->get('cat /proc/stat');
- // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
- $core = sys::cpu_idle($proc_stat, $server['unit'], $unit['fcpu'], true); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
+ // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
+ $core = sys::cpu_idle($proc_stat, $server['unit'], $unit['fcpu'], true); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
- if(!is_numeric($core))
- return array('e' => 'Не удается выполнить операцию, нет свободного потока.');
+ if(!is_numeric($core))
+ return array('e' => 'Не удается выполнить операцию, нет свободного потока.');
- $taskset = 'taskset -c '.$core;
- }
+ $taskset = 'taskset -c '.$core;
+ }
- if($server['core_fix'])
- {
- $core = $server['core_fix']-1;
- $taskset = 'taskset -c '.$core;
- }
+ if($server['core_fix'])
+ {
+ $core = $server['core_fix']-1;
+ $taskset = 'taskset -c '.$core;
+ }
- $ssh->set('cd '.$install.' && sudo -u server'.$server['uid'].' '.$taskset.' screen -dmS u_'.$server['uid'].' sh -c "'.$path // Копирование файлов обвновления сборки для сервера
- .'find . -type d -exec chmod 700 {} \;;'
- .'find . -type f -exec chmod 600 {} \;;'
- .'chmod 500 '.params::$aFileGame[$server['game']].'"');
+ $ssh->set('cd '.$install.' && sudo -u server'.$server['uid'].' '.$taskset.' screen -dmS u_'.$server['uid'].' sh -c "'.$path // Копирование файлов обвновления сборки для сервера
+ .'find . -type d -exec chmod 700 {} \;;'
+ .'find . -type f -exec chmod 600 {} \;;'
+ .'chmod 500 '.params::$aFileGame[$server['game']].'"');
- $core = !isset($core) ? 0 : $core+1;
+ $core = !isset($core) ? 0 : $core+1;
- // Обновление информации в базе
- $sql->query('UPDATE `control_servers` set `status`="update", `core_use`="'.$core.'" WHERE `id`="'.$id.'" LIMIT 1');
+ // Обновление информации в базе
+ $sql->query('UPDATE `control_servers` set `status`="update", `core_use`="'.$core.'" WHERE `id`="'.$id.'" LIMIT 1');
- // Сброс кеша
- actions::clmcache($id);
+ // Сброс кеша
+ actions::clmcache($id);
- sys::reset_mcache('ctrl_server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'update', 'online' => 0, 'players' => ''));
- sys::reset_mcache('ctrl_server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'update', 'online' => 0));
+ sys::reset_mcache('ctrl_server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'update', 'online' => 0, 'players' => ''));
+ sys::reset_mcache('ctrl_server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'update', 'online' => 0));
- return array('s' => 'ok');
- }
+ return array('s' => 'ok');
+ }
- public static function delete($id)
- {
- global $cfg, $sql, $user;
+ public static function delete($id)
+ {
+ global $cfg, $sql, $user;
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- $sql->query('SELECT `uid`, `unit`, `game`, `slots`, `address` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `uid`, `unit`, `game`, `slots`, `address` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- if(!$server['uid'])
- return array('e' => 'uid 404');
+ if(!$server['uid'])
+ return array('e' => 'uid 404');
- $sql->query('SELECT `address`, `passwd`, `sql_login`, `sql_passwd`, `sql_port`, `sql_ftp` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd`, `sql_login`, `sql_passwd`, `sql_port`, `sql_ftp` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return array('e' => sys::text('error', 'ssh'));
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return array('e' => sys::text('error', 'ssh'));
- // Убить процессы
- $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
- .'lsof -i@:'.$server['address'].' | awk '."'{print $2}'".' | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
+ // Убить процессы
+ $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
+ .'lsof -i@:'.$server['address'].' | awk '."'{print $2}'".' | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
- // Директория игрового сервера
- $install = '/servers/'.$server['uid'];
+ // Директория игрового сервера
+ $install = '/servers/'.$server['uid'];
- $copys = 'screen -dmS r_copy_'.$server['uid'].' sh -c "';
+ $copys = 'screen -dmS r_copy_'.$server['uid'].' sh -c "';
- $scopy = $sql->query('SELECT `id`, `name` FROM `control_copy` WHERE `server`="'.$id.'"');
- while($copy = $sql->get($scopy))
- {
- $copys .= 'rm /copy/'.$copy['name'].'.tar;';
+ $scopy = $sql->query('SELECT `id`, `name` FROM `control_copy` WHERE `server`="'.$id.'"');
+ while($copy = $sql->get($scopy))
+ {
+ $copys .= 'rm /copy/'.$copy['name'].'.tar;';
- $sql->query('DELETE FROM `control_copy` WHERE `id`="'.$copy['id'].'" LIMIT 1');
- }
+ $sql->query('DELETE FROM `control_copy` WHERE `id`="'.$copy['id'].'" LIMIT 1');
+ }
- $copys .= '";';
+ $copys .= '";';
- $ssh->set($copys // Удаление резервных копий
- .'screen -dmS r_'.$server['uid'].' sh -c "rm -r '.$install.';' // Удаление директории сервера
- .'userdel server'.$server['uid'].'"'); // Удаление пользователя сервера c локации
+ $ssh->set($copys // Удаление резервных копий
+ .'screen -dmS r_'.$server['uid'].' sh -c "rm -r '.$install.';' // Удаление директории сервера
+ .'userdel server'.$server['uid'].'"'); // Удаление пользователя сервера c локации
- // Удаление ftp доступа
- $qSql = 'DELETE FROM users WHERE username=\''.$server['uid'].'\';';
+ // Удаление ftp доступа
+ $qSql = 'DELETE FROM users WHERE username=\''.$server['uid'].'\';';
$ssh->set('screen -dmS ftp'.$server['uid'].' mysql -P '.$unit['sql_port'].' -u'.$unit['sql_login'].' -p'.$unit['sql_passwd'].' --database '.$unit['sql_ftp'].' -e "'.$qSql.'"');
- // Очистка правил FireWall
- ctrl::iptables($id, 'remove', NULL, NULL, $server['unit'], false, $ssh);
+ // Очистка правил FireWall
+ ctrl::iptables($id, 'remove', NULL, NULL, $server['unit'], false, $ssh);
- // Удаление заданий из crontab
- $sql->query('SELECT `address`, `passwd` FROM `panel` LIMIT 1');
- $panel = $sql->get();
+ // Удаление заданий из crontab
+ $sql->query('SELECT `address`, `passwd` FROM `panel` LIMIT 1');
+ $panel = $sql->get();
- if(!$ssh->auth($panel['passwd'], $panel['address']))
- return array('e' => 'Неудалось создать связь с панелью');
+ if(!$ssh->auth($panel['passwd'], $panel['address']))
+ return array('e' => 'Неудалось создать связь с панелью');
- $crons = $sql->query('SELECT `id`, `cron` FROM `control_crontab` WHERE `server`="'.$id.'"');
- while($cron = $sql->get($crons))
- {
- $ssh->set('echo "" >> /etc/crontab && cat /etc/crontab');
- $crontab = str_replace($cron['cron'], '', $ssh->get());
+ $crons = $sql->query('SELECT `id`, `cron` FROM `control_crontab` WHERE `server`="'.$id.'"');
+ while($cron = $sql->get($crons))
+ {
+ $ssh->set('echo "" >> /etc/crontab && cat /etc/crontab');
+ $crontab = str_replace($cron['cron'], '', $ssh->get());
- // Временный файл
- $temp = sys::temp($crontab);
+ // Временный файл
+ $temp = sys::temp($crontab);
- $ssh->setfile($temp, '/etc/crontab', 0644);
+ $ssh->setfile($temp, '/etc/crontab', 0644);
- $ssh->set("sed -i '/^$/d' /etc/crontab");
- $ssh->set('crontab -u root /etc/crontab');
+ $ssh->set("sed -i '/^$/d' /etc/crontab");
+ $ssh->set('crontab -u root /etc/crontab');
- unlink($temp);
+ unlink($temp);
- $sql->query('DELETE FROM `control_crontab` WHERE `id`="'.$cron['id'].'" LIMIT 1');
- }
+ $sql->query('DELETE FROM `control_crontab` WHERE `id`="'.$cron['id'].'" LIMIT 1');
+ }
- // Удаление различной информации игрового сервера
- $sql->query('DELETE FROM `control_admins_'.$server['game'].'` WHERE `server`="'.$id.'" LIMIT 1');
- $sql->query('DELETE FROM `control_plugins_install` WHERE `server`="'.$id.'" LIMIT 1');
- $sql->query('DELETE FROM `control_plugins_buy` WHERE `server`="'.$id.'" LIMIT 1');
- $sql->query('DELETE FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
+ // Удаление различной информации игрового сервера
+ $sql->query('DELETE FROM `control_admins_'.$server['game'].'` WHERE `server`="'.$id.'" LIMIT 1');
+ $sql->query('DELETE FROM `control_plugins_install` WHERE `server`="'.$id.'" LIMIT 1');
+ $sql->query('DELETE FROM `control_plugins_buy` WHERE `server`="'.$id.'" LIMIT 1');
+ $sql->query('DELETE FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
- return array('s' => 'ok');
- }
+ return array('s' => 'ok');
+ }
- public static function clmcache($id)
- {
- global $mcache;
+ public static function clmcache($id)
+ {
+ global $mcache;
- $mcache->delete('ctrl_server_index_'.$id);
- $mcache->delete('ctrl_server_resources_'.$id);
- $mcache->delete('ctrl_server_status_'.$id);
- }
- }
\ No newline at end of file
+ $mcache->delete('ctrl_server_index_'.$id);
+ $mcache->delete('ctrl_server_resources_'.$id);
+ $mcache->delete('ctrl_server_status_'.$id);
+ }
+ }
\ No newline at end of file
diff --git a/system/library/control/control.php b/system/library/control/control.php
index 73470eb..36718e9 100644
--- a/system/library/control/control.php
+++ b/system/library/control/control.php
@@ -1,448 +1,448 @@
arr['btn'] = '';
+ $html->arr['btn'] = '';
- if($status == 'working')
- {
- $html->get('restart', 'sections/control/buttons');
- $html->set('id', $id);
- $html->pack('btn');
+ if($status == 'working')
+ {
+ $html->get('restart', 'sections/control/buttons');
+ $html->set('id', $id);
+ $html->pack('btn');
- return $html->arr['btn'];
- }
+ return $html->arr['btn'];
+ }
- return '';
- }
+ return '';
+ }
- public static function resources($id)
- {
- global $sql;
+ public static function resources($id)
+ {
+ global $sql;
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- $aData = array(
- 'cpu' => '0%',
- 'ram' => '0%',
- 'hdd' => '0%'
- );
+ $aData = array(
+ 'cpu' => '0%',
+ 'ram' => '0%',
+ 'hdd' => '0%'
+ );
- $sql->query('SELECT `address`, `passwd` FROM `control` WHERE `id`="'.$id.'" LIMIT 1');
- $ctrl = $sql->get();
+ $sql->query('SELECT `address`, `passwd` FROM `control` WHERE `id`="'.$id.'" LIMIT 1');
+ $ctrl = $sql->get();
- if(!$ssh->auth($ctrl['passwd'], $ctrl['address']))
- sys::outjs($aData);
+ if(!$ssh->auth($ctrl['passwd'], $ctrl['address']))
+ sys::outjs($aData);
- $data = $ssh->get('echo `cat /proc/meminfo | grep MemTotal | awk \'{print $2}\'; cat /proc/meminfo | grep MemFree | awk \'{print $2}\'; cat /proc/meminfo | grep Buffers | awk \'{print $2}\'; cat /proc/meminfo | grep Cached | grep -v SwapCached | awk \'{print $2}\'`');
- $aData['ram'] = ceil(ctrl::ram_load($data)).'%';
+ $data = $ssh->get('echo `cat /proc/meminfo | grep MemTotal | awk \'{print $2}\'; cat /proc/meminfo | grep MemFree | awk \'{print $2}\'; cat /proc/meminfo | grep Buffers | awk \'{print $2}\'; cat /proc/meminfo | grep Cached | grep -v SwapCached | awk \'{print $2}\'`');
+ $aData['ram'] = ceil(ctrl::ram_load($data)).'%';
- $aData['hdd'] = trim($ssh->get('df -h | awk \'/rootfs/ {print $5}\''));
+ $aData['hdd'] = trim($ssh->get('df -h | awk \'/rootfs/ {print $5}\''));
- $aData['cpu'] = ctrl::cpu_load($ssh->get('echo "`ps -A -o pcpu | tail -n+2 | paste -sd+ | bc | awk \'{print $0}\'` `cat /proc/cpuinfo | grep processor | wc -l | awk \'{print $1}\'`"')).'%';
+ $aData['cpu'] = ctrl::cpu_load($ssh->get('echo "`ps -A -o pcpu | tail -n+2 | paste -sd+ | bc | awk \'{print $0}\'` `cat /proc/cpuinfo | grep processor | wc -l | awk \'{print $1}\'`"')).'%';
- sys::outjs($aData);
- }
+ sys::outjs($aData);
+ }
- public static function update_info($id)
- {
- global $sql;
+ public static function update_info($id)
+ {
+ global $sql;
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- $aData = array(
- 'cpu' => 'произошла ошибка',
- 'ram' => 'произошла ошибка',
- 'hdd' => 'произошла ошибка'
- );
+ $aData = array(
+ 'cpu' => 'произошла ошибка',
+ 'ram' => 'произошла ошибка',
+ 'hdd' => 'произошла ошибка'
+ );
- $sql->query('SELECT `address`, `passwd` FROM `control` WHERE `id`="'.$id.'" LIMIT 1');
- $ctrl = $sql->get();
+ $sql->query('SELECT `address`, `passwd` FROM `control` WHERE `id`="'.$id.'" LIMIT 1');
+ $ctrl = $sql->get();
- if(!$ssh->auth($ctrl['passwd'], $ctrl['address'].':22'))
- sys::outjs($aData);
+ if(!$ssh->auth($ctrl['passwd'], $ctrl['address'].':22'))
+ sys::outjs($aData);
- $data = $ssh->get('cat /proc/meminfo | grep MemTotal | cut -d \' \' -f 2-');
- $aData['ram'] = $data.' ('.(round(sys::int($data)/1024/1024, 2)).'Gb)';
+ $data = $ssh->get('cat /proc/meminfo | grep MemTotal | cut -d \' \' -f 2-');
+ $aData['ram'] = $data.' ('.(round(sys::int($data)/1024/1024, 2)).'Gb)';
- $aData['hdd'] = trim($ssh->get('df -h | awk \'/rootfs/ {print $2}\''));
+ $aData['hdd'] = trim($ssh->get('df -h | awk \'/rootfs/ {print $2}\''));
- $aCPU = explode("\n", trim($ssh->get('cat /proc/cpuinfo | grep -c processor && cat /proc/cpuinfo | grep "MHz" | awk \'{print $4}\' | head -n 1')));
-
- $aData['cpu'] = $aCPU[0].'x'.round($aCPU[1], 0).' MHz ['.trim($ssh->get('cat /proc/cpuinfo | grep -m 1 "model name" | cut -d \' \' -f 3-')).']';
+ $aCPU = explode("\n", trim($ssh->get('cat /proc/cpuinfo | grep -c processor && cat /proc/cpuinfo | grep "MHz" | awk \'{print $4}\' | head -n 1')));
+
+ $aData['cpu'] = $aCPU[0].'x'.round($aCPU[1], 0).' MHz ['.trim($ssh->get('cat /proc/cpuinfo | grep -m 1 "model name" | cut -d \' \' -f 3-')).']';
- sys::outjs($aData);
- }
+ sys::outjs($aData);
+ }
- public static function update_status($id, $ssh = false)
- {
- global $cfg, $sql, $start_point, $mcache;
+ public static function update_status($id, $ssh = false)
+ {
+ global $cfg, $sql, $start_point, $mcache;
- if(!$ssh)
- include(LIB.'ssh.php');
+ if(!$ssh)
+ include(LIB.'ssh.php');
- $sql->query('SELECT `address`, `passwd`, `time`, `overdue`, `block`, `status` FROM `control` WHERE `id`="'.$id.'" LIMIT 1');
- $ctrl = $sql->get();
+ $sql->query('SELECT `address`, `passwd`, `time`, `overdue`, `block`, `status` FROM `control` WHERE `id`="'.$id.'" LIMIT 1');
+ $ctrl = $sql->get();
- $status = $ctrl['status'];
+ $status = $ctrl['status'];
- if($ctrl['status'] == 'blocked' && $ctrl['block'] < $start_point)
- $sql->query('UPDATE `control` set `block`="0", `status`="working" WHERE `id`="'.$id.'" LIMIT 1');
+ if($ctrl['status'] == 'blocked' && $ctrl['block'] < $start_point)
+ $sql->query('UPDATE `control` set `block`="0", `status`="working" WHERE `id`="'.$id.'" LIMIT 1');
- if($ctrl['status'] == 'blocked')
- return 'blocked';
+ if($ctrl['status'] == 'blocked')
+ return 'blocked';
- // Если аренда закончилась и сервер просрочен длительное время
- if($ctrl['time'] < $start_point && $ctrl['status'] == 'overdue' && ($ctrl['overdue']+$cfg['control_delete']*86400) < $start_point)
- {
- $sql->query('UPDATE `control` set `user`="-1" WHERE `id`="'.$id.'" LIMIT 1');
+ // Если аренда закончилась и сервер просрочен длительное время
+ if($ctrl['time'] < $start_point && $ctrl['status'] == 'overdue' && ($ctrl['overdue']+$cfg['control_delete']*86400) < $start_point)
+ {
+ $sql->query('UPDATE `control` set `user`="-1" WHERE `id`="'.$id.'" LIMIT 1');
- return 'delete';
- }
+ return 'delete';
+ }
- // Если аренда закончилась, а услуга не просрочена
- if($ctrl['time'] < $start_point && !in_array($ctrl['status'], array('overdue', 'blocked')))
- {
- $sql->query('UPDATE `control` set `status`="overdue" WHERE `id`="'.$id.'" LIMIT 1');
+ // Если аренда закончилась, а услуга не просрочена
+ if($ctrl['time'] < $start_point && !in_array($ctrl['status'], array('overdue', 'blocked')))
+ {
+ $sql->query('UPDATE `control` set `status`="overdue" WHERE `id`="'.$id.'" LIMIT 1');
- $status = 'overdue';
- }
+ $status = 'overdue';
+ }
- // Если аренда не закончилась, а услуга просрочена
- if($ctrl['time'] > $start_point && $ctrl['status'] == 'overdue')
- $sql->query('UPDATE `control` set `status`="working" WHERE `id`="'.$id.'" LIMIT 1');
+ // Если аренда не закончилась, а услуга просрочена
+ if($ctrl['time'] > $start_point && $ctrl['status'] == 'overdue')
+ $sql->query('UPDATE `control` set `status`="working" WHERE `id`="'.$id.'" LIMIT 1');
- if(in_array($ctrl['status'], array('working', 'error')))
- {
- $status = 'working';
- if(!$ssh->auth($ctrl['passwd'], $ctrl['address']))
- $status = 'error';
+ if(in_array($ctrl['status'], array('working', 'error')))
+ {
+ $status = 'working';
+ if(!$ssh->auth($ctrl['passwd'], $ctrl['address']))
+ $status = 'error';
- $sql->query('UPDATE `control` set `status`="'.$status.'" WHERE `id`="'.$id.'" LIMIT 1');
- }
+ $sql->query('UPDATE `control` set `status`="'.$status.'" WHERE `id`="'.$id.'" LIMIT 1');
+ }
- if($ctrl['status'] == 'reboot' && !$mcache->get('reboot_control_'.$id))
- {
- if($ssh->auth($ctrl['passwd'], $ctrl['address']))
- {
- $sql->query('UPDATE `control` set `status`="working" WHERE `id`="'.$id.'" LIMIT 1');
+ if($ctrl['status'] == 'reboot' && !$mcache->get('reboot_control_'.$id))
+ {
+ if($ssh->auth($ctrl['passwd'], $ctrl['address']))
+ {
+ $sql->query('UPDATE `control` set `status`="working" WHERE `id`="'.$id.'" LIMIT 1');
- $status = 'working';
- }
- }
+ $status = 'working';
+ }
+ }
- $time_end = $ctrl['status'] == 'overdue' ? 'Удаление через: '.sys::date('min', $ctrl['overdue']+$cfg['control_delete']*86400) : 'Осталось: '.sys::date('min', $ctrl['time']);
+ $time_end = $ctrl['status'] == 'overdue' ? 'Удаление через: '.sys::date('min', $ctrl['overdue']+$cfg['control_delete']*86400) : 'Осталось: '.sys::date('min', $ctrl['time']);
- $aData = array(
- 'time' => sys::today($ctrl['time']),
- 'time_end' => $time_end,
- 'buttons' => ctrl::buttons($id, $status),
- 'status' => ctrl::status($status)
- );
+ $aData = array(
+ 'time' => sys::today($ctrl['time']),
+ 'time_end' => $time_end,
+ 'buttons' => ctrl::buttons($id, $status),
+ 'status' => ctrl::status($status)
+ );
- return $aData;
- }
+ return $aData;
+ }
- public static function ram_load($data)
- {
- $aData = explode(' ', $data);
+ public static function ram_load($data)
+ {
+ $aData = explode(' ', $data);
- return ceil(($aData[0]-($aData[1]+$aData[2]+$aData[3]))*100/$aData[0]);
- }
+ return ceil(($aData[0]-($aData[1]+$aData[2]+$aData[3]))*100/$aData[0]);
+ }
- public static function cpu_load($data)
- {
- $aData = explode(' ', $data);
+ public static function cpu_load($data)
+ {
+ $aData = explode(' ', $data);
- $load = ceil($aData[0]/$aData[1]);
+ $load = ceil($aData[0]/$aData[1]);
- return $load > 100 ? 100 : $load;
- }
+ return $load > 100 ? 100 : $load;
+ }
- public static function nav($server, $id, $sid, $active)
- {
- global $cfg, $html, $sql, $mcache, $start_point;
+ public static function nav($server, $id, $sid, $active)
+ {
+ global $cfg, $html, $sql, $mcache, $start_point;
- $aUnit = array('index', 'console', 'settings', 'plugins', 'filetp', 'copy', 'boost');
+ $aUnit = array('index', 'console', 'settings', 'plugins', 'filetp', 'copy', 'boost');
- $html->get('gmenu', 'sections/control/servers/'.$server['game']);
+ $html->get('gmenu', 'sections/control/servers/'.$server['game']);
- $html->set('id', $id);
- $html->set('server', $sid);
- $html->set('home', $cfg['http']);
+ $html->set('id', $id);
+ $html->set('server', $sid);
+ $html->set('home', $cfg['http']);
- foreach($aUnit as $unit)
- if($unit == $active) $html->unit($unit, 1); else $html->unit($unit);
+ foreach($aUnit as $unit)
+ if($unit == $active) $html->unit($unit, 1); else $html->unit($unit);
- $html->pack('main');
+ $html->pack('main');
- $html->get('vmenu', 'sections/control/servers/'.$server['game']);
+ $html->get('vmenu', 'sections/control/servers/'.$server['game']);
- $html->set('id', $id);
- $html->set('server', $sid);
- $html->set('home', $cfg['http']);
+ $html->set('id', $id);
+ $html->set('server', $sid);
+ $html->set('home', $cfg['http']);
- foreach($aUnit as $unit)
- if($unit == $active) $html->unit($unit, 1); else $html->unit($unit);
+ foreach($aUnit as $unit)
+ if($unit == $active) $html->unit($unit, 1); else $html->unit($unit);
- $html->pack('vmenu');
+ $html->pack('vmenu');
- return NULL;
- }
+ return NULL;
+ }
- public static function route($server, $inc, $go)
- {
- global $device, $start_point;
+ public static function route($server, $inc, $go)
+ {
+ global $device, $start_point;
- if(in_array($server['status'], array('install', 'reinstall', 'update', 'recovery')))
- {
- if($go)
- sys::out('Раздел недоступен');
+ if(in_array($server['status'], array('install', 'reinstall', 'update', 'recovery')))
+ {
+ if($go)
+ sys::out('Раздел недоступен');
- return SEC.'control/servers/noaccess.php';
- }
+ return SEC.'control/servers/noaccess.php';
+ }
- if(!file_exists(SEC.'control/servers/'.$server['game'].'/'.$inc.'.php'))
- return SEC.'control/servers/'.$server['game'].'/index.php';
+ if(!file_exists(SEC.'control/servers/'.$server['game'].'/'.$inc.'.php'))
+ return SEC.'control/servers/'.$server['game'].'/index.php';
- return SEC.'control/servers/'.$server['game'].'/'.$inc.'.php';
- }
+ return SEC.'control/servers/'.$server['game'].'/'.$inc.'.php';
+ }
- public static function cpulist($unit, $core, $count = false)
- {
- global $device, $start_point;
+ public static function cpulist($unit, $core, $count = false)
+ {
+ global $device, $start_point;
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- {
- if($count)
- return 1;
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ {
+ if($count)
+ return 1;
- $out = $core ? 'Автоматическое определение 1 ядро/поток ' : ''.$core.' ядро/поток Автоматическое определение ';
+ $out = $core ? 'Автоматическое определение 1 ядро/поток ' : ''.$core.' ядро/поток Автоматическое определение ';
- sys::outjs(array('core_fix' => $core));
- }
+ sys::outjs(array('core_fix' => $core));
+ }
- $n = sys::int($ssh->get('cat /proc/cpuinfo | grep "cpu MHz" | wc -l'));
+ $n = sys::int($ssh->get('cat /proc/cpuinfo | grep "cpu MHz" | wc -l'));
- if($count)
- return $n;
+ if($count)
+ return $n;
- $list = 'Автоматическое определение ';
+ $list = 'Автоматическое определение ';
- for($i = 1; $i <= $n; $i+=1)
- $list .= ''.$i.' ядро/поток ';
+ for($i = 1; $i <= $n; $i+=1)
+ $list .= ''.$i.' ядро/поток ';
- sys::outjs(array('core_fix' => str_replace($core.'"', $core.'" selected="select"', $list)));
- }
+ sys::outjs(array('core_fix' => str_replace($core.'"', $core.'" selected="select"', $list)));
+ }
- public static function iptables($id, $action, $source, $dest, $unit, $snw = false, $ssh = false)
- {
- global $cfg, $sql, $start_point;
+ public static function iptables($id, $action, $source, $dest, $unit, $snw = false, $ssh = false)
+ {
+ global $cfg, $sql, $start_point;
- if(!$ssh)
- {
- $sql->query('SELECT `address`, `passwd` FROM `control` WHERE `id`="'.$unit.'" LIMIT 1');
- $unit = $sql->get();
+ if(!$ssh)
+ {
+ $sql->query('SELECT `address`, `passwd` FROM `control` WHERE `id`="'.$unit.'" LIMIT 1');
+ $unit = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return array('e' => sys::text('all', 'ssh'));
- }
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return array('e' => sys::text('all', 'ssh'));
+ }
- switch($action)
- {
- case 'block':
- if(sys::valid($source, 'ip'))
- return array('e' => sys::text('servers', 'firewall'));
+ switch($action)
+ {
+ case 'block':
+ if(sys::valid($source, 'ip'))
+ return array('e' => sys::text('servers', 'firewall'));
- // Если подсеть
- if($snw)
- {
- $source = sys::whois($source);
+ // Если подсеть
+ if($snw)
+ {
+ $source = sys::whois($source);
- if($source == 'не определена')
- return array('e' => 'Не удалось определить подсеть для указанного адреса.');
- }
+ if($source == 'не определена')
+ return array('e' => 'Не удалось определить подсеть для указанного адреса.');
+ }
- $sql->query('SELECT `id` FROM `control_firewall` WHERE `sip`="'.$source.'" AND `server`="'.$id.'" LIMIT 1');
+ $sql->query('SELECT `id` FROM `control_firewall` WHERE `sip`="'.$source.'" AND `server`="'.$id.'" LIMIT 1');
- // Если такое правило уже добавлено или указан адрес сайта (ПУ)
- if($sql->num() || ($source == $cfg['ip'] || $source == $cfg['subnet']))
- return array('s' => 'ok');
+ // Если такое правило уже добавлено или указан адрес сайта (ПУ)
+ if($sql->num() || ($source == $cfg['ip'] || $source == $cfg['subnet']))
+ return array('s' => 'ok');
- $sql->query('INSERT INTO `control_firewall` set `sip`="'.$source.'", `dest`="'.$dest[0].':'.$dest[1].'", `server`="'.$id.'", `time`="'.$start_point.'"');
+ $sql->query('INSERT INTO `control_firewall` set `sip`="'.$source.'", `dest`="'.$dest[0].':'.$dest[1].'", `server`="'.$id.'", `time`="'.$start_point.'"');
- $line = $sql->id();
+ $line = $sql->id();
- $rule = 'iptables -I INPUT -s '.$source.' -p udp -d '.$dest[0].' --dport '.$dest[1].' -j DROP;';
+ $rule = 'iptables -I INPUT -s '.$source.' -p udp -d '.$dest[0].' --dport '.$dest[1].' -j DROP;';
- $ssh->set($rule.' echo -e "#'.$line.';\n'.$rule.'" >> /root/'.$cfg['iptables']);
+ $ssh->set($rule.' echo -e "#'.$line.';\n'.$rule.'" >> /root/'.$cfg['iptables']);
- return array('s' => 'ok');
+ return array('s' => 'ok');
- case 'unblock':
- if(!is_numeric($source) AND sys::valid($source, 'ip'))
- return array('e' => sys::text('servers', 'firewall'));
+ case 'unblock':
+ if(!is_numeric($source) AND sys::valid($source, 'ip'))
+ return array('e' => sys::text('servers', 'firewall'));
- if(is_numeric($source))
- {
- $sql->query('SELECT `id`, `sip` FROM `control_firewall` WHERE `id`="'.$source.'" AND `server`="'.$id.'" LIMIT 1');
+ if(is_numeric($source))
+ {
+ $sql->query('SELECT `id`, `sip` FROM `control_firewall` WHERE `id`="'.$source.'" AND `server`="'.$id.'" LIMIT 1');
- // Если такое правило отсутствует
- if(!$sql->num())
- return array('s' => 'ok');
- }else{
- $sql->query('SELECT `id`, `sip` FROM `control_firewall` WHERE `sip`="'.$source.'" AND `server`="'.$id.'" LIMIT 1');
+ // Если такое правило отсутствует
+ if(!$sql->num())
+ return array('s' => 'ok');
+ }else{
+ $sql->query('SELECT `id`, `sip` FROM `control_firewall` WHERE `sip`="'.$source.'" AND `server`="'.$id.'" LIMIT 1');
- // Если одиночный адрес не найден, проверить на блокировку подсети
- if(!$sql->num())
- {
- $source = sys::whois($source);
+ // Если одиночный адрес не найден, проверить на блокировку подсети
+ if(!$sql->num())
+ {
+ $source = sys::whois($source);
- $sql->query('SELECT `id` FROM `control_firewall` WHERE `sip`="'.$source.'" AND `server`="'.$id.'" LIMIT 1');
+ $sql->query('SELECT `id` FROM `control_firewall` WHERE `sip`="'.$source.'" AND `server`="'.$id.'" LIMIT 1');
- if($sql->num())
- {
- $firewall = $sql->get();
+ if($sql->num())
+ {
+ $firewall = $sql->get();
- return array('i' => 'Указанный адрес входит в заблокированную подсеть, разблокировать подсеть?', 'id' => $firewall['id']);
- }
+ return array('i' => 'Указанный адрес входит в заблокированную подсеть, разблокировать подсеть?', 'id' => $firewall['id']);
+ }
- return array('s' => 'ok');
- }
- }
+ return array('s' => 'ok');
+ }
+ }
- $firewall = $sql->get();
+ $firewall = $sql->get();
- $ssh->set('iptables -D INPUT -s '.$firewall['sip'].' -p udp -d '.$dest[0].' --dport '.$dest[1].' -j DROP;'
- .'sed "`nl '.$cfg['iptables'].' | grep \"#'.$firewall['id'].'\" | awk \'{print $1","$1+1}\'`d" '.$cfg['iptables'].' > '.$cfg['iptables'].'_temp; cat '.$cfg['iptables'].'_temp > '.$cfg['iptables'].'; rm '.$cfg['iptables'].'_temp');
+ $ssh->set('iptables -D INPUT -s '.$firewall['sip'].' -p udp -d '.$dest[0].' --dport '.$dest[1].' -j DROP;'
+ .'sed "`nl '.$cfg['iptables'].' | grep \"#'.$firewall['id'].'\" | awk \'{print $1","$1+1}\'`d" '.$cfg['iptables'].' > '.$cfg['iptables'].'_temp; cat '.$cfg['iptables'].'_temp > '.$cfg['iptables'].'; rm '.$cfg['iptables'].'_temp');
- $sql->query('DELETE FROM `control_firewall` WHERE `id`="'.$firewall['id'].'" LIMIT 1');
+ $sql->query('DELETE FROM `control_firewall` WHERE `id`="'.$firewall['id'].'" LIMIT 1');
- return array('s' => 'ok');
+ return array('s' => 'ok');
- case 'remove':
- $sql->query('SELECT `id`, `sip`, `dest` FROM `control_firewall` WHERE `server`="'.$id.'"');
+ case 'remove':
+ $sql->query('SELECT `id`, `sip`, `dest` FROM `control_firewall` WHERE `server`="'.$id.'"');
- $aRule = array();
+ $aRule = array();
- while($firewall = $sql->get())
- {
- list($ip, $port) = explode(':', $firewall['dest']);
+ while($firewall = $sql->get())
+ {
+ list($ip, $port) = explode(':', $firewall['dest']);
- $aRule[$firewall['id']] = 'iptables -D INPUT -s '.$firewall['sip'].' -p udp -d '.$ip.' --dport '.$port.' -j DROP;';
- }
+ $aRule[$firewall['id']] = 'iptables -D INPUT -s '.$firewall['sip'].' -p udp -d '.$ip.' --dport '.$port.' -j DROP;';
+ }
- $nRule = count($aRule);
+ $nRule = count($aRule);
- if(!$nRule)
- return NULL;
+ if(!$nRule)
+ return NULL;
- $cmd = '';
+ $cmd = '';
- foreach($aRule as $line => $rule)
- $cmd .= $rule.'sed "`nl '.$cfg['iptables'].' | grep "#'.$line.'" | awk \'{print $1","$1+1}\'`d" '.$cfg['iptables'].' > '.$cfg['iptables'].'_temp; cat '.$cfg['iptables'].'_temp > '.$cfg['iptables'].'; rm '.$cfg['iptables'].'_temp';
+ foreach($aRule as $line => $rule)
+ $cmd .= $rule.'sed "`nl '.$cfg['iptables'].' | grep "#'.$line.'" | awk \'{print $1","$1+1}\'`d" '.$cfg['iptables'].' > '.$cfg['iptables'].'_temp; cat '.$cfg['iptables'].'_temp > '.$cfg['iptables'].'; rm '.$cfg['iptables'].'_temp';
- $ssh->set($cmd);
+ $ssh->set($cmd);
- $sql->query('DELETE FROM `control_firewall` WHERE `server`="'.$id.'" LIMIT '.$nRule);
+ $sql->query('DELETE FROM `control_firewall` WHERE `server`="'.$id.'" LIMIT '.$nRule);
- return array('s' => 'ok');
- }
- }
+ return array('s' => 'ok');
+ }
+ }
- public static function crontab($id, $cid, $data = array())
- {
- global $cfg;
+ public static function crontab($id, $cid, $data = array())
+ {
+ global $cfg;
- if($data['allhour'])
- $time = '0 * * * ';
- else{
- $hour = array(
- '00', '01', '02',
- '03', '04', '05',
- '06', '07', '08',
- '09', '10', '11',
- '12', '13', '14',
- '15', '16', '17',
- '18', '19', '20',
- '21', '22', '23'
- );
+ if($data['allhour'])
+ $time = '0 * * * ';
+ else{
+ $hour = array(
+ '00', '01', '02',
+ '03', '04', '05',
+ '06', '07', '08',
+ '09', '10', '11',
+ '12', '13', '14',
+ '15', '16', '17',
+ '18', '19', '20',
+ '21', '22', '23'
+ );
- $minute = array(
- '00', '05', '10',
- '15', '20', '25',
- '30', '35', '40',
- '45', '50', '55'
- );
+ $minute = array(
+ '00', '05', '10',
+ '15', '20', '25',
+ '30', '35', '40',
+ '45', '50', '55'
+ );
- if(!in_array($data['hour'], $hour))
- $data['hour'] = '00';
+ if(!in_array($data['hour'], $hour))
+ $data['hour'] = '00';
- if(!in_array($data['minute'], $minute))
- $data['minute'] = '00';
+ if(!in_array($data['minute'], $minute))
+ $data['minute'] = '00';
- $time = $data['minute'].' '.$data['hour'].' * * ';
- }
+ $time = $data['minute'].' '.$data['hour'].' * * ';
+ }
- $week = array();
- $week[1] = isset($data['week']['\'1\'']) ? 1 : 0;
- $week[2] = isset($data['week']['\'2\'']) ? 2 : 0;
- $week[3] = isset($data['week']['\'3\'']) ? 3 : 0;
- $week[4] = isset($data['week']['\'4\'']) ? 4 : 0;
- $week[5] = isset($data['week']['\'5\'']) ? 5 : 0;
- $week[6] = isset($data['week']['\'6\'']) ? 6 : 0;
- $week[7] = isset($data['week']['\'7\'']) ? 7 : 0;
+ $week = array();
+ $week[1] = isset($data['week']['\'1\'']) ? 1 : 0;
+ $week[2] = isset($data['week']['\'2\'']) ? 2 : 0;
+ $week[3] = isset($data['week']['\'3\'']) ? 3 : 0;
+ $week[4] = isset($data['week']['\'4\'']) ? 4 : 0;
+ $week[5] = isset($data['week']['\'5\'']) ? 5 : 0;
+ $week[6] = isset($data['week']['\'6\'']) ? 6 : 0;
+ $week[7] = isset($data['week']['\'7\'']) ? 7 : 0;
- $check = 0;
+ $check = 0;
- foreach($week as $index => $val)
- $check+= $val;
+ foreach($week as $index => $val)
+ $check+= $val;
- if($check == 28 || !$check)
- $week = '*';
- else{
- $weeks = $week[1].','.$week[2].','.$week[3].','.$week[4].','.$week[5].','.$week[6].','.$week[7];
- $weeks = str_replace(array(',0', '0'), '', $weeks);
- $week = $weeks{0} == ',' ? substr($weeks, 1) : $weeks;
- }
+ if($check == 28 || !$check)
+ $week = '*';
+ else{
+ $weeks = $week[1].','.$week[2].','.$week[3].','.$week[4].','.$week[5].','.$week[6].','.$week[7];
+ $weeks = str_replace(array(',0', '0'), '', $weeks);
+ $week = $weeks{0} == ',' ? substr($weeks, 1) : $weeks;
+ }
- $cron_task = $time.$week.' screen -dmS s'.$id.' bash -c \'cd /var/enginegp && php cron.php '.$cfg['cron_key'].' control_server_cron '.$id.' '.$cid.'\'';
+ $cron_task = $time.$week.' screen -dmS s'.$id.' bash -c \'cd /var/enginegp && php cron.php '.$cfg['cron_key'].' control_server_cron '.$id.' '.$cid.'\'';
- return $cron_task;
- }
- }
+ return $cron_task;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/control/cs/action.php b/system/library/control/cs/action.php
index 492e689..01a6af1 100644
--- a/system/library/control/cs/action.php
+++ b/system/library/control/cs/action.php
@@ -1,109 +1,109 @@
query('SELECT `uid`, `unit`, `game`, `address`, `slots`, `name`, `fps`, `map_start`, `vac`, `pingboost`, `time_start`, `core_fix` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `uid`, `unit`, `game`, `address`, `slots`, `name`, `fps`, `map_start`, `vac`, `pingboost`, `time_start`, `core_fix` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- $sql->query('SELECT `address`, `passwd`, `fcpu` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd`, `fcpu` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return array('e' => sys::text('error', 'ssh'));
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return array('e' => sys::text('error', 'ssh'));
- list($ip, $port) = explode(':', $server['address']);
+ list($ip, $port) = explode(':', $server['address']);
- // Убить процессы
- $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
- .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
+ // Убить процессы
+ $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
+ .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
- $taskset = '';
+ $taskset = '';
- // Если включена система автораспределения и не установлен фиксированный поток
- if(!$server['core_fix'])
- {
- $proc_stat = array();
+ // Если включена система автораспределения и не установлен фиксированный поток
+ if(!$server['core_fix'])
+ {
+ $proc_stat = array();
- $proc_stat[0] = $ssh->get('cat /proc/stat');
- }
+ $proc_stat[0] = $ssh->get('cat /proc/stat');
+ }
- // Проверка наличия стартовой карты
- $ssh->set('cd /servers/'.$server['uid'].'/cstrike/maps/ && ls | grep .bsp | grep -v .bsp.');
+ // Проверка наличия стартовой карты
+ $ssh->set('cd /servers/'.$server['uid'].'/cstrike/maps/ && ls | grep .bsp | grep -v .bsp.');
- if($server['map_start'] != '' AND !in_array($server['map_start'], str_replace('.bsp', '', explode("\n", $ssh->get()))))
- return array('e' => sys::updtext(sys::text('servers', 'nomap'), array('map' => $server['map_start'].'.bsp')));
+ if($server['map_start'] != '' AND !in_array($server['map_start'], str_replace('.bsp', '', explode("\n", $ssh->get()))))
+ return array('e' => sys::updtext(sys::text('servers', 'nomap'), array('map' => $server['map_start'].'.bsp')));
- // Если система автораспределения продолжить парсинг загрузки процессора
- if(isset($proc_stat))
- {
- $proc_stat[1] = $ssh->get('cat /proc/stat');
+ // Если система автораспределения продолжить парсинг загрузки процессора
+ if(isset($proc_stat))
+ {
+ $proc_stat[1] = $ssh->get('cat /proc/stat');
- // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
- $core = sys::cpu_idle($proc_stat, $server['unit'], $unit['fcpu'], true); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
+ // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
+ $core = sys::cpu_idle($proc_stat, $server['unit'], $unit['fcpu'], true); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
- if(!is_numeric($core))
- return array('e' => sys::text('error', 'cpu'));
+ if(!is_numeric($core))
+ return array('e' => sys::text('error', 'cpu'));
- $taskset = 'taskset -c '.$core;
- }
+ $taskset = 'taskset -c '.$core;
+ }
- if($server['core_fix'])
- {
- $core = $server['core_fix']-1;
- $taskset = 'taskset -c '.$core;
- }
+ if($server['core_fix'])
+ {
+ $core = $server['core_fix']-1;
+ $taskset = 'taskset -c '.$core;
+ }
- // Античит VAC
- $vac = $server['vac'] == 0 ? '-insecure' : '-secure';
+ // Античит VAC
+ $vac = $server['vac'] == 0 ? '-insecure' : '-secure';
- // Значение PingBoost
- $pingboost = $server['pingboost'] ? '-pingboost '.$pingboost : '';
+ // Значение PingBoost
+ $pingboost = $server['pingboost'] ? '-pingboost '.$pingboost : '';
- // Значение sys_ticrate (FPS)
- $fps = $server['fps'];
+ // Значение sys_ticrate (FPS)
+ $fps = $server['fps'];
- // Параметры запуска
- $bash = './hlds_run -debug -game cstrike -norestart -condebug -sys_ticrate '.$fps.' +servercfgfile server.cfg +sys_ticrate '.$fps.' +map \''.$server['map_start'].'\' +maxplayers '.$server['slots'].' +ip '.$ip.' +port '.$port.' +sv_lan 0 '.$vac.' '.$pingboost;
+ // Параметры запуска
+ $bash = './hlds_run -debug -game cstrike -norestart -condebug -sys_ticrate '.$fps.' +servercfgfile server.cfg +sys_ticrate '.$fps.' +map \''.$server['map_start'].'\' +maxplayers '.$server['slots'].' +ip '.$ip.' +port '.$port.' +sv_lan 0 '.$vac.' '.$pingboost;
- // Временный файл
- $temp = sys::temp($bash);
+ // Временный файл
+ $temp = sys::temp($bash);
- // Обновление файла start.sh
- $ssh->setfile($temp, '/servers/'.$server['uid'].'/start.sh', 0500);
+ // Обновление файла start.sh
+ $ssh->setfile($temp, '/servers/'.$server['uid'].'/start.sh', 0500);
- // Строка запуска
- $ssh->set('cd /servers/'.$server['uid'].';' // переход в директорию игрового сервера
- .'rm *.pid;' // Удаление *.pid файлов
- .'sudo -u server'.$server['uid'].' mkdir -p cstrike/oldstart;' // Создание папки логов
- .'cat cstrike/qconsole.log >> cstrike/oldstart/'.date('d.m.Y_H:i:s', $server['time_start']).'.log; rm cstrike/qconsole.log; rm cstrike/oldstart/01.01.1970_03:00:00.log;' // Перемещение лога предыдущего запуска
- .'chown server'.$server['uid'].':1000 start.sh;' // Обновление владельца файла start.sh
- .'sudo -u server'.$server['uid'].' screen -dmS s_'.$server['uid'].' '.$taskset.' sh -c ./start.sh'); // Запуск игровго сервера
+ // Строка запуска
+ $ssh->set('cd /servers/'.$server['uid'].';' // переход в директорию игрового сервера
+ .'rm *.pid;' // Удаление *.pid файлов
+ .'sudo -u server'.$server['uid'].' mkdir -p cstrike/oldstart;' // Создание папки логов
+ .'cat cstrike/qconsole.log >> cstrike/oldstart/'.date('d.m.Y_H:i:s', $server['time_start']).'.log; rm cstrike/qconsole.log; rm cstrike/oldstart/01.01.1970_03:00:00.log;' // Перемещение лога предыдущего запуска
+ .'chown server'.$server['uid'].':1000 start.sh;' // Обновление владельца файла start.sh
+ .'sudo -u server'.$server['uid'].' screen -dmS s_'.$server['uid'].' '.$taskset.' sh -c ./start.sh'); // Запуск игровго сервера
- $core = !isset($core) ? 0 : $core+1;
+ $core = !isset($core) ? 0 : $core+1;
- // Обновление информации в базе
- $sql->query('UPDATE `control_servers` set `status`="'.$type.'", `online`="0", `players`="", `core_use`="'.$core.'", `time_start`="'.$start_point.'", `stop`="1" WHERE `id`="'.$id.'" LIMIT 1');
+ // Обновление информации в базе
+ $sql->query('UPDATE `control_servers` set `status`="'.$type.'", `online`="0", `players`="", `core_use`="'.$core.'", `time_start`="'.$start_point.'", `stop`="1" WHERE `id`="'.$id.'" LIMIT 1');
- unlink($temp);
+ unlink($temp);
- // Сброс кеша
- actions::clmcache($id);
+ // Сброс кеша
+ actions::clmcache($id);
- sys::reset_mcache('ctrl_server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0, 'players' => ''));
- sys::reset_mcache('ctrl_server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0));
+ sys::reset_mcache('ctrl_server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0, 'players' => ''));
+ sys::reset_mcache('ctrl_server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0));
- return array('s' => 'ok');
- }
- }
+ return array('s' => 'ok');
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/control/cs/rcon.php b/system/library/control/cs/rcon.php
index 08717ed..21b2649 100644
--- a/system/library/control/cs/rcon.php
+++ b/system/library/control/cs/rcon.php
@@ -1,107 +1,107 @@
Connect($ip, $port, 3, SourceQuery::GOLDSOURCE);
+ $sq->Connect($ip, $port, 3, SourceQuery::GOLDSOURCE);
- $sq->SetRconPassword(rcon::rcon_passwd($server));
+ $sq->SetRconPassword(rcon::rcon_passwd($server));
- $out = $sq->Rcon($cmd);
+ $out = $sq->Rcon($cmd);
- $sq->Disconnect();
+ $sq->Disconnect();
- return $out;
- }
+ return $out;
+ }
- public static function players($data)
- {
- $aPlayers = array();
- $n = 1;
+ public static function players($data)
+ {
+ $aPlayers = array();
+ $n = 1;
- $lines = explode("\n", $data);
+ $lines = explode("\n", $data);
- foreach($lines as $line)
- {
- if(strpos($line, '#') === FALSE)
- continue;
+ foreach($lines as $line)
+ {
+ if(strpos($line, '#') === FALSE)
+ continue;
- $start = strpos($line, '"')+1;
- $end = strrpos($line, '"');
+ $start = strpos($line, '"')+1;
+ $end = strrpos($line, '"');
- $name = htmlspecialchars(substr($line, $start, $end-$start));
+ $name = htmlspecialchars(substr($line, $start, $end-$start));
- $line = trim(substr($line, $end + 1));
+ $line = trim(substr($line, $end + 1));
- $aData = array_values(array_diff(explode(' ', $line), array('', ' ')));
+ $aData = array_values(array_diff(explode(' ', $line), array('', ' ')));
- $steamid = trim($aData[1]);
- $ip = trim(sys::first(explode(':', $aData[6])));
+ $steamid = trim($aData[1]);
+ $ip = trim(sys::first(explode(':', $aData[6])));
- if(sys::valid($steamid, 'steamid') || sys::valid($ip, 'ip'))
- continue;
+ if(sys::valid($steamid, 'steamid') || sys::valid($ip, 'ip'))
+ continue;
- $aPlayers[$n]['name'] = $name;
- $aPlayers[$n]['steamid'] = $steamid;
- $aPlayers[$n]['frags'] = trim($aData[2]);
- $aPlayers[$n]['time'] = trim($aData[3]);
- $aPlayers[$n]['ping'] = trim($aData[4]);
- $aPlayers[$n]['ip'] = $ip;
+ $aPlayers[$n]['name'] = $name;
+ $aPlayers[$n]['steamid'] = $steamid;
+ $aPlayers[$n]['frags'] = trim($aData[2]);
+ $aPlayers[$n]['time'] = trim($aData[3]);
+ $aPlayers[$n]['ping'] = trim($aData[4]);
+ $aPlayers[$n]['ip'] = $ip;
- $whois = rcon::country($ip);
+ $whois = rcon::country($ip);
- $aPlayers[$n]['ico'] = $whois['ico'];
- $aPlayers[$n]['country'] = $whois['name'];
+ $aPlayers[$n]['ico'] = $whois['ico'];
+ $aPlayers[$n]['country'] = $whois['name'];
- $n+=1;
- }
+ $n+=1;
+ }
- return $aPlayers;
- }
+ return $aPlayers;
+ }
- public static function rcon_passwd($server)
- {
- global $cfg, $sql, $user;
+ public static function rcon_passwd($server)
+ {
+ global $cfg, $sql, $user;
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- $sql->query('SELECT `address`, `passwd` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $sql->query('SELECT `address`, `passwd` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
$unit = $sql->get();
- if(!$ssh->auth($unit['passwd'], $unit['address']))
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
sys::outjs(array('e' => sys::text('error', 'ssh')));
- $ssh->set('cat /servers/'.$server['uid'].'/cstrike/server.cfg | grep rcon_password');
- $get = explode(' ', str_replace('"', '', trim($ssh->get())));
- $rcon = trim(end($get));
+ $ssh->set('cat /servers/'.$server['uid'].'/cstrike/server.cfg | grep rcon_password');
+ $get = explode(' ', str_replace('"', '', trim($ssh->get())));
+ $rcon = trim(end($get));
- if(!isset($rcon{0}))
- sys::outjs(array('r' => 'Необходимо установить rcon пароль (rcon_password).', 'url' => $cfg['http'].'control/id/'.$server['unit'].'/server/'.$server['unit'].'/section/settings/subsection/server'), $nmch);
+ if(!isset($rcon{0}))
+ sys::outjs(array('r' => 'Необходимо установить rcon пароль (rcon_password).', 'url' => $cfg['http'].'control/id/'.$server['unit'].'/server/'.$server['unit'].'/section/settings/subsection/server'), $nmch);
- return $rcon;
- }
+ return $rcon;
+ }
- public static function country($ip)
- {
- global $SxGeo;
+ public static function country($ip)
+ {
+ global $SxGeo;
- $cData = $SxGeo->getCityFull($ip);
- $ico = sys::country($cData['country']['iso']);
+ $cData = $SxGeo->getCityFull($ip);
+ $ico = sys::country($cData['country']['iso']);
- return array('ico' => $ico, 'name' => empty($cData['country']['name_ru']) ? 'Не определена' : $cData['country']['name_ru']);
- }
- }
+ return array('ico' => $ico, 'name' => empty($cData['country']['name_ru']) ? 'Не определена' : $cData['country']['name_ru']);
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/control/cs/scan.php b/system/library/control/cs/scan.php
index 20e3fe1..ff1c37f 100644
--- a/system/library/control/cs/scan.php
+++ b/system/library/control/cs/scan.php
@@ -1,133 +1,133 @@
get($nmch)))
- return $mcache->get($nmch);
+ if(is_array($mcache->get($nmch)))
+ return $mcache->get($nmch);
- $out = array();
+ $out = array();
- $info = scan::info($sq, $id);
+ $info = scan::info($sq, $id);
- $sql->query('SELECT `unit`, `game`, `name`, `map`, `online`, `players`, `status` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `unit`, `game`, `name`, `map`, `online`, `players`, `status` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- if(!$info['status'])
- {
- $out['name'] = $server['name'];
- $out['status'] = sys::status($server['status'], $server['game'], $server['map']);
- $out['online'] = $server['online'];
- $out['image'] = ' ';
- $out['buttons'] = sys::buttons($id, $server['status'], $server['game'], $server['unit']);
+ if(!$info['status'])
+ {
+ $out['name'] = $server['name'];
+ $out['status'] = sys::status($server['status'], $server['game'], $server['map']);
+ $out['online'] = $server['online'];
+ $out['image'] = ' ';
+ $out['buttons'] = sys::buttons($id, $server['status'], $server['game'], $server['unit']);
- if($players_get)
- $out['players'] = base64_decode($server['players']);
+ if($players_get)
+ $out['players'] = base64_decode($server['players']);
- $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
+ $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
- return $out;
- }
+ return $out;
+ }
- if($players_get)
- $players = scan::info($sq, $id, true);
+ if($players_get)
+ $players = scan::info($sq, $id, true);
- $out['name'] = htmlspecialchars($info['name']);
- $out['status'] = sys::status('working', $server['game'], $info['map']);
- $out['online'] = $info['online'];
- $out['image'] = ' ';
- $out['buttons'] = sys::buttons($id, 'working', $server['game'], $server['unit']);
- $out['players'] = '';
+ $out['name'] = htmlspecialchars($info['name']);
+ $out['status'] = sys::status('working', $server['game'], $info['map']);
+ $out['online'] = $info['online'];
+ $out['image'] = ' ';
+ $out['buttons'] = sys::buttons($id, 'working', $server['game'], $server['unit']);
+ $out['players'] = '';
- if($players_get)
- {
- foreach($players as $index => $player)
- {
- $html->get($server['game'], 'sections/servers/players');
+ if($players_get)
+ {
+ foreach($players as $index => $player)
+ {
+ $html->get($server['game'], 'sections/servers/players');
- $html->set('i', $player['i']);
- $html->set('name', $player['name']);
- $html->set('score', $player['score']);
- $html->set('time', $player['time']);
+ $html->set('i', $player['i']);
+ $html->set('name', $player['name']);
+ $html->set('score', $player['score']);
+ $html->set('time', $player['time']);
- $html->pack('list');
- }
+ $html->pack('list');
+ }
- $out['players'] = isset($html->arr['list']) ? $html->arr['list'] : '';
- }
+ $out['players'] = isset($html->arr['list']) ? $html->arr['list'] : '';
+ }
- $sql->query('UPDATE `control_servers` set '
- .'`name`="'.$out['name'].'", '
- .'`online`="'.$out['online'].'", '
- .'`map`="'.$info['map'].'", '
- .'`status`="working" WHERE `id`="'.$id.'" LIMIT 1');
+ $sql->query('UPDATE `control_servers` set '
+ .'`name`="'.$out['name'].'", '
+ .'`online`="'.$out['online'].'", '
+ .'`map`="'.$info['map'].'", '
+ .'`status`="working" WHERE `id`="'.$id.'" LIMIT 1');
- if($players_get)
- $sql->query('UPDATE `control_servers` set `players`="'.base64_encode($out['players']).'" WHERE `id`="'.$id.'" LIMIT 1');
+ if($players_get)
+ $sql->query('UPDATE `control_servers` set `players`="'.base64_encode($out['players']).'" WHERE `id`="'.$id.'" LIMIT 1');
- $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
+ $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
- return $out;
- }
+ return $out;
+ }
- public static function info($sq, $id, $pl = false)
- {
- global $sql;
+ public static function info($sq, $id, $pl = false)
+ {
+ global $sql;
- $sql->query('SELECT `address` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `address` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- list($ip, $port) = explode(':', $server['address']);
+ list($ip, $port) = explode(':', $server['address']);
- $sq->Connect($ip, $port, 1, SourceQuery::GOLDSOURCE);
+ $sq->Connect($ip, $port, 1, SourceQuery::GOLDSOURCE);
- if($pl)
- {
- $players = $sq->GetPlayers();
+ if($pl)
+ {
+ $players = $sq->GetPlayers();
- $i = 1;
- $data = array();
+ $i = 1;
+ $data = array();
- foreach($players as $n => $player)
- {
- $data[$i]['i'] = $i;
- $data[$i]['name'] = $player['Name'] == '' ? 'Подключается' : $player['Name'];
- $data[$i]['score'] = $player['Frags'];
- $data[$i]['time'] = $player['TimeF'];
+ foreach($players as $n => $player)
+ {
+ $data[$i]['i'] = $i;
+ $data[$i]['name'] = $player['Name'] == '' ? 'Подключается' : $player['Name'];
+ $data[$i]['score'] = $player['Frags'];
+ $data[$i]['time'] = $player['TimeF'];
- $i+=1;
- }
+ $i+=1;
+ }
- return $data;
- }
+ return $data;
+ }
- $data = $sq->GetInfo();
+ $data = $sq->GetInfo();
- $server['name'] = $data['HostName'];
- $server['map'] = $data['Map'];
- $server['online'] = $data['Players'];
- $server['status'] = strlen($server['map']) > 3 ? true : false;
+ $server['name'] = $data['HostName'];
+ $server['map'] = $data['Map'];
+ $server['online'] = $data['Players'];
+ $server['status'] = strlen($server['map']) > 3 ? true : false;
- return $server;
- }
- }
+ return $server;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/control/csgo/action.php b/system/library/control/csgo/action.php
index 0232e54..5e3d51b 100644
--- a/system/library/control/csgo/action.php
+++ b/system/library/control/csgo/action.php
@@ -1,282 +1,282 @@
query('SELECT `uid`, `unit`, `game`, `address`, `slots`, `name`, `tickrate`, `map_start`, `vac`, `time_start`, `core_fix`, `pingboost` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `uid`, `unit`, `game`, `address`, `slots`, `name`, `tickrate`, `map_start`, `vac`, `time_start`, `core_fix`, `pingboost` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- $sql->query('SELECT `address`, `passwd`, `fcpu` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd`, `fcpu` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return array('e' => sys::text('error', 'ssh'));
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return array('e' => sys::text('error', 'ssh'));
- list($ip, $port) = explode(':', $server['address']);
+ list($ip, $port) = explode(':', $server['address']);
- // Убить процессы
- $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
- .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
+ // Убить процессы
+ $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
+ .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
- $taskset = '';
+ $taskset = '';
- // Если включена система автораспределения и не установлен фиксированный поток
- if(!$server['core_fix'])
- {
- $proc_stat = array();
+ // Если включена система автораспределения и не установлен фиксированный поток
+ if(!$server['core_fix'])
+ {
+ $proc_stat = array();
- $proc_stat[0] = $ssh->get('cat /proc/stat');
- }
+ $proc_stat[0] = $ssh->get('cat /proc/stat');
+ }
- // Проверка наличия стартовой карты
- $ssh->set('cd /servers/'.$server['uid'].'/csgo/maps/ && du -ah | grep -e "\.bsp$" | awk \'{print $2}\'');
+ // Проверка наличия стартовой карты
+ $ssh->set('cd /servers/'.$server['uid'].'/csgo/maps/ && du -ah | grep -e "\.bsp$" | awk \'{print $2}\'');
- include_once(LIB.'games/games.php');
+ include_once(LIB.'games/games.php');
- if(games::map($server['map_start'], $ssh->get()))
- return array('e' => sys::updtext(sys::text('servers', 'nomap'), array('map' => $server['map_start'].'.bsp')));
+ if(games::map($server['map_start'], $ssh->get()))
+ return array('e' => sys::updtext(sys::text('servers', 'nomap'), array('map' => $server['map_start'].'.bsp')));
- // Если система автораспределения продолжить парсинг загрузки процессора
- if(isset($proc_stat))
- {
- $proc_stat[1] = $ssh->get('cat /proc/stat');
+ // Если система автораспределения продолжить парсинг загрузки процессора
+ if(isset($proc_stat))
+ {
+ $proc_stat[1] = $ssh->get('cat /proc/stat');
- // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
- $core = sys::cpu_idle($proc_stat, $server['unit'], $unit['fcpu'], true); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
+ // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
+ $core = sys::cpu_idle($proc_stat, $server['unit'], $unit['fcpu'], true); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
- if(!is_numeric($core))
- return array('e' => sys::text('error', 'cpu'));
+ if(!is_numeric($core))
+ return array('e' => sys::text('error', 'cpu'));
- $taskset = 'taskset -c '.$core;
- }
+ $taskset = 'taskset -c '.$core;
+ }
- if($server['core_fix'])
- {
- $core = $server['core_fix']-1;
- $taskset = 'taskset -c '.$core;
- }
+ if($server['core_fix'])
+ {
+ $core = $server['core_fix']-1;
+ $taskset = 'taskset -c '.$core;
+ }
- // Античит VAC
- $vac = $server['vac'] == 0 ? '-insecure' : '-secure';
+ // Античит VAC
+ $vac = $server['vac'] == 0 ? '-insecure' : '-secure';
- // TV
- $tv = $server['tv'] ? '+tv_enable 1 +tv_maxclients 30 +tv_port '.($port+10000) : '-nohltv';
+ // TV
+ $tv = $server['tv'] ? '+tv_enable 1 +tv_maxclients 30 +tv_port '.($port+10000) : '-nohltv';
- $check = explode('/', $server['map_start']);
+ $check = explode('/', $server['map_start']);
- // Стартовая карта
- $map = $check[0] == 'workshop' ? '+workshop_start_map '.$check[1] : '+map \''.$server['map_start'].'\'';
+ // Стартовая карта
+ $map = $check[0] == 'workshop' ? '+workshop_start_map '.$check[1] : '+map \''.$server['map_start'].'\'';
- // Игровой режим
- $mods = array(
- 1 => '+game_type 0 +game_mode 0',
- 2 => '+game_type 0 +game_mode 1',
- 3 => '+game_type 1 +game_mode 0',
- 4 => '+game_type 1 +game_mode 1',
- 5 => '+game_type 1 +game_mode 2'
- );
+ // Игровой режим
+ $mods = array(
+ 1 => '+game_type 0 +game_mode 0',
+ 2 => '+game_type 0 +game_mode 1',
+ 3 => '+game_type 1 +game_mode 0',
+ 4 => '+game_type 1 +game_mode 1',
+ 5 => '+game_type 1 +game_mode 2'
+ );
- $mod = !$server['pingboost'] ? $mods[2] : $mods[$server['pingboost']];
+ $mod = !$server['pingboost'] ? $mods[2] : $mods[$server['pingboost']];
- // Параметры запуска
- $bash = './srcds_run -debug -game csgo -norestart -condebug console.log -usercon -tickrate '.$server['tickrate'].' '.$mod.' +servercfgfile server.cfg '.$map.' -maxplayers_override '.$server['slots'].' +ip '.$ip.' +net_public_adr '.$ip.' +port '.$port.' -sv_lan 0 '.$vac.' '.$tv;
+ // Параметры запуска
+ $bash = './srcds_run -debug -game csgo -norestart -condebug console.log -usercon -tickrate '.$server['tickrate'].' '.$mod.' +servercfgfile server.cfg '.$map.' -maxplayers_override '.$server['slots'].' +ip '.$ip.' +net_public_adr '.$ip.' +port '.$port.' -sv_lan 0 '.$vac.' '.$tv;
- // Временный файл
- $temp = sys::temp($bash);
+ // Временный файл
+ $temp = sys::temp($bash);
- // Обновление файла start.sh
- $ssh->setfile($temp, '/servers/'.$server['uid'].'/start.sh', 0500);
+ // Обновление файла start.sh
+ $ssh->setfile($temp, '/servers/'.$server['uid'].'/start.sh', 0500);
- // Строка запуска
- $ssh->set('cd /servers/'.$server['uid'].';' // переход в директорию игрового сервера
- .'rm *.pid;' // Удаление *.pid файлов
- .'sudo -u server'.$server['uid'].' mkdir -p csgo/oldstart;' // Создание папки логов
- .'cat csgo/console.log >> csgo/oldstart/'.date('d.m.Y_H:i:s', $server['time_start']).'.log; rm csgo/console.log; rm csgo/oldstart/01.01.1970_03:00:00.log;' // Перемещение лога предыдущего запуска
- .'chown server'.$server['uid'].':1000 start.sh;' // Обновление владельца файла start.sh
- .'sudo -u server'.$server['uid'].' screen -dmS s_'.$server['uid'].' '.$taskset.' sh -c "./start.sh"'); // Запуск игровго сервера
+ // Строка запуска
+ $ssh->set('cd /servers/'.$server['uid'].';' // переход в директорию игрового сервера
+ .'rm *.pid;' // Удаление *.pid файлов
+ .'sudo -u server'.$server['uid'].' mkdir -p csgo/oldstart;' // Создание папки логов
+ .'cat csgo/console.log >> csgo/oldstart/'.date('d.m.Y_H:i:s', $server['time_start']).'.log; rm csgo/console.log; rm csgo/oldstart/01.01.1970_03:00:00.log;' // Перемещение лога предыдущего запуска
+ .'chown server'.$server['uid'].':1000 start.sh;' // Обновление владельца файла start.sh
+ .'sudo -u server'.$server['uid'].' screen -dmS s_'.$server['uid'].' '.$taskset.' sh -c "./start.sh"'); // Запуск игровго сервера
- $core = !isset($core) ? 0 : $core+1;
+ $core = !isset($core) ? 0 : $core+1;
- // Обновление информации в базе
- $sql->query('UPDATE `control_servers` set `status`="'.$type.'", `online`="0", `players`="", `core_use`="'.$core.'", `time_start`="'.$start_point.'", `stop`="1" WHERE `id`="'.$id.'" LIMIT 1');
+ // Обновление информации в базе
+ $sql->query('UPDATE `control_servers` set `status`="'.$type.'", `online`="0", `players`="", `core_use`="'.$core.'", `time_start`="'.$start_point.'", `stop`="1" WHERE `id`="'.$id.'" LIMIT 1');
- unlink($temp);
+ unlink($temp);
- // Сброс кеша
- actions::clmcache($id);
+ // Сброс кеша
+ actions::clmcache($id);
- sys::reset_mcache('ctrl_server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0, 'players' => ''));
- sys::reset_mcache('ctrl_server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0));
+ sys::reset_mcache('ctrl_server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0, 'players' => ''));
+ sys::reset_mcache('ctrl_server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0));
- return array('s' => 'ok');
- }
+ return array('s' => 'ok');
+ }
public static function change($id, $map = false)
{
- global $cfg, $sql, $html, $user, $mcache;
+ global $cfg, $sql, $html, $user, $mcache;
- // Если в кеше есть карты
- if($mcache->get('ctrl_server_maps_change_'.$id) != '' AND !$map)
- return array('maps' => $mcache->get('ctrl_server_maps_change_'.$id));
+ // Если в кеше есть карты
+ if($mcache->get('ctrl_server_maps_change_'.$id) != '' AND !$map)
+ return array('maps' => $mcache->get('ctrl_server_maps_change_'.$id));
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- include(LIB.'games/games.php');
+ include(LIB.'games/games.php');
- $sql->query('SELECT `uid`, `unit`, `game`, `online`, `players`, `name` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `uid`, `unit`, `game`, `online`, `players`, `name` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `address`, `passwd` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $sql->query('SELECT `address`, `passwd` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
$unit = $sql->get();
- // Проверка ssh соедниения пу с локацией
+ // Проверка ssh соедниения пу с локацией
if(!$ssh->auth($unit['passwd'], $unit['address']))
return array('e' => sys::text('error', 'ssh'));
- // Массив карт игрового сервера (папка "maps")
- $aMaps = explode("\n", $ssh->get('cd /servers/'.$server['uid'].'/csgo/maps/ && du -ah | grep -e "\.bsp$" | awk \'{print $2}\''));
+ // Массив карт игрового сервера (папка "maps")
+ $aMaps = explode("\n", $ssh->get('cd /servers/'.$server['uid'].'/csgo/maps/ && du -ah | grep -e "\.bsp$" | awk \'{print $2}\''));
- // Удаление пустого элемента
- unset($aMaps[count($aMaps)-1]);
+ // Удаление пустого элемента
+ unset($aMaps[count($aMaps)-1]);
- // Удаление ".bsp"
- $aMaps = str_ireplace(array('./', '.bsp'), '', $aMaps);
+ // Удаление ".bsp"
+ $aMaps = str_ireplace(array('./', '.bsp'), '', $aMaps);
- // Если выбрана карта
- if($map)
- {
- $map = str_replace('|', '/', $map);
+ // Если выбрана карта
+ if($map)
+ {
+ $map = str_replace('|', '/', $map);
- // Проверка наличия выбранной карты
- if(games::map($map, $aMaps))
- return array('e' => sys::updtext(sys::text('servers', 'change'), array('map' => $map.'.bsp')));
+ // Проверка наличия выбранной карты
+ if(games::map($map, $aMaps))
+ return array('e' => sys::updtext(sys::text('servers', 'change'), array('map' => $map.'.bsp')));
- // Отправка команды changelevel
- $ssh->set('sudo -u server'.$server['uid'].' screen -p 0 -S s_'.$server['uid'].' -X eval '."'stuff \"changelevel ".sys::cmd($map)."\"\015'");
+ // Отправка команды changelevel
+ $ssh->set('sudo -u server'.$server['uid'].' screen -p 0 -S s_'.$server['uid'].' -X eval '."'stuff \"changelevel ".sys::cmd($map)."\"\015'");
- // Обновление информации в базе
- $sql->query('UPDATE `control_servers` set `status`="change" WHERE `id`="'.$id.'" LIMIT 1');
+ // Обновление информации в базе
+ $sql->query('UPDATE `control_servers` set `status`="change" WHERE `id`="'.$id.'" LIMIT 1');
- // Сброс кеша
- actions::clmcache($id);
+ // Сброс кеша
+ actions::clmcache($id);
- sys::reset_mcache('ctrl_server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'change', 'online' => $server['online'], 'players' => base64_decode($server['players'])));
- sys::reset_mcache('ctrl_server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'change', 'online' => $server['online']));
+ sys::reset_mcache('ctrl_server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'change', 'online' => $server['online'], 'players' => base64_decode($server['players'])));
+ sys::reset_mcache('ctrl_server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'change', 'online' => $server['online']));
- return array('s' => 'ok');
- }
+ return array('s' => 'ok');
+ }
- // Сортировка списка карт
- sort($aMaps);
- reset($aMaps);
+ // Сортировка списка карт
+ sort($aMaps);
+ reset($aMaps);
- // Генерация списка карт для выбора
- foreach($aMaps as $map)
- {
- $aName = explode('/', $map);
- $name = end($aName);
+ // Генерация списка карт для выбора
+ foreach($aMaps as $map)
+ {
+ $aName = explode('/', $map);
+ $name = end($aName);
- $html->get('change_list', 'sections/control/servers/csgo');
+ $html->get('change_list', 'sections/control/servers/csgo');
- $html->set('img', file_exists(DIR.'/maps/'.$server['game'].'/'.$name.'.jpg') ? $cfg['http'].'maps/'.$server['game'].'/'.$name.'.jpg' : $cfg['http'].'template/images/status/none.jpg');
- $html->set('map', str_replace('/', '|', $map));
- $html->set('name', $name);
- $html->set('id', $server['unit']);
- $html->set('server', $id);
+ $html->set('img', file_exists(DIR.'/maps/'.$server['game'].'/'.$name.'.jpg') ? $cfg['http'].'maps/'.$server['game'].'/'.$name.'.jpg' : $cfg['http'].'template/images/status/none.jpg');
+ $html->set('map', str_replace('/', '|', $map));
+ $html->set('name', $name);
+ $html->set('id', $server['unit']);
+ $html->set('server', $id);
- if(count($aName) > 1)
- $html->unit('workshop', true);
- else
- $html->unit('workshop');
+ if(count($aName) > 1)
+ $html->unit('workshop', true);
+ else
+ $html->unit('workshop');
- $html->pack('maps');
- }
+ $html->pack('maps');
+ }
- // Запись карт в кеш
- $mcache->set('ctrl_server_maps_change_'.$id, $html->arr['maps'], false, 60);
+ // Запись карт в кеш
+ $mcache->set('ctrl_server_maps_change_'.$id, $html->arr['maps'], false, 60);
- return array('maps' => $html->arr['maps']);
- }
+ return array('maps' => $html->arr['maps']);
+ }
public static function update($id)
{
- global $cfg, $sql, $user, $start_point;
+ global $cfg, $sql, $user, $start_point;
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- $sql->query('SELECT `uid`, `unit`, `game`, `name`, `ftp`, `core_fix` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `uid`, `unit`, `game`, `name`, `ftp`, `core_fix` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `address`, `passwd`, `sql_login`, `sql_passwd`, `sql_port`, `sql_ftp`, `fcpu` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $sql->query('SELECT `address`, `passwd`, `sql_login`, `sql_passwd`, `sql_port`, `sql_ftp`, `fcpu` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
$unit = $sql->get();
- // Проверка ssh соедниения пу с локацией
+ // Проверка ssh соедниения пу с локацией
if(!$ssh->auth($unit['passwd'], $unit['address']))
return array('e' => sys::text('error', 'ssh'));
- $taskset = '';
+ $taskset = '';
- // Если включена система автораспределения и не установлен фиксированный поток
- if(!$server['core_fix'])
- {
- $proc_stat = array();
+ // Если включена система автораспределения и не установлен фиксированный поток
+ if(!$server['core_fix'])
+ {
+ $proc_stat = array();
- $proc_stat[0] = $ssh->get('cat /proc/stat');
- }
+ $proc_stat[0] = $ssh->get('cat /proc/stat');
+ }
- // Директория игрового сервера
- $install = '/servers/'.$server['uid'];
+ // Директория игрового сервера
+ $install = '/servers/'.$server['uid'];
- // Если система автораспределения продолжить парсинг загрузки процессора
- if(isset($proc_stat))
- {
- $proc_stat[1] = $ssh->get('cat /proc/stat');
+ // Если система автораспределения продолжить парсинг загрузки процессора
+ if(isset($proc_stat))
+ {
+ $proc_stat[1] = $ssh->get('cat /proc/stat');
- // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
- $core = sys::cpu_idle($proc_stat, $server['unit'], $unit['fcpu'], true); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
+ // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
+ $core = sys::cpu_idle($proc_stat, $server['unit'], $unit['fcpu'], true); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
- if(!is_numeric($core))
- return array('e' => 'Не удается выполнить операцию, нет свободного потока.');
+ if(!is_numeric($core))
+ return array('e' => 'Не удается выполнить операцию, нет свободного потока.');
- $taskset = 'taskset -c '.$core;
- }
+ $taskset = 'taskset -c '.$core;
+ }
- if($server['core_fix'])
- {
- $core = $server['core_fix']-1;
- $taskset = 'taskset -c '.$core;
- }
+ if($server['core_fix'])
+ {
+ $core = $server['core_fix']-1;
+ $taskset = 'taskset -c '.$core;
+ }
- $ssh->set('cd '.$cfg['steamcmd'].' && '.$taskset.' screen -dmS u_'.$server['uid'].' sh -c "'
- .'./steamcmd.sh +login anonymous +force_install_dir "'.$install.'" +app_update 740 +quit;'
- .'cd '.$install.';'
- .'chown -R server'.$server['uid'].':servers .;'
- .'find . -type d -exec chmod 700 {} \;;'
- .'find . -type f -exec chmod 600 {} \;;'
- .'chmod 500 '.params::$aFileGame[$server['game']].'"');
+ $ssh->set('cd '.$cfg['steamcmd'].' && '.$taskset.' screen -dmS u_'.$server['uid'].' sh -c "'
+ .'./steamcmd.sh +login anonymous +force_install_dir "'.$install.'" +app_update 740 +quit;'
+ .'cd '.$install.';'
+ .'chown -R server'.$server['uid'].':servers .;'
+ .'find . -type d -exec chmod 700 {} \;;'
+ .'find . -type f -exec chmod 600 {} \;;'
+ .'chmod 500 '.params::$aFileGame[$server['game']].'"');
- $core = !isset($core) ? 0 : $core+1;
+ $core = !isset($core) ? 0 : $core+1;
- // Обновление информации в базе
- $sql->query('UPDATE `control_servers` set `status`="update", `core_use`="'.$core.'" WHERE `id`="'.$id.'" LIMIT 1');
+ // Обновление информации в базе
+ $sql->query('UPDATE `control_servers` set `status`="update", `core_use`="'.$core.'" WHERE `id`="'.$id.'" LIMIT 1');
- // Сброс кеша
- actions::clmcache($id);
+ // Сброс кеша
+ actions::clmcache($id);
- sys::reset_mcache('ctrl_server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'update', 'online' => 0, 'players' => ''));
- sys::reset_mcache('ctrl_server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'update', 'online' => 0));
+ sys::reset_mcache('ctrl_server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'update', 'online' => 0, 'players' => ''));
+ sys::reset_mcache('ctrl_server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'update', 'online' => 0));
- return array('s' => 'ok');
- }
+ return array('s' => 'ok');
+ }
}
?>
\ No newline at end of file
diff --git a/system/library/control/csgo/rcon.php b/system/library/control/csgo/rcon.php
index cfaf75c..d783736 100644
--- a/system/library/control/csgo/rcon.php
+++ b/system/library/control/csgo/rcon.php
@@ -1,109 +1,109 @@
Connect($ip, $port, 3, SourceQuery::SOURCE);
+ $sq->Connect($ip, $port, 3, SourceQuery::SOURCE);
- $sq->SetRconPassword(rcon::rcon_passwd($server));
+ $sq->SetRconPassword(rcon::rcon_passwd($server));
- $out = $sq->Rcon($cmd);
+ $out = $sq->Rcon($cmd);
- $sq->Disconnect();
+ $sq->Disconnect();
- return $out;
- }
+ return $out;
+ }
- public static function players($data)
- {
- $aPlayers = array();
- $n = 1;
+ public static function players($data)
+ {
+ $aPlayers = array();
+ $n = 1;
- $lines = explode("\n", $data);
+ $lines = explode("\n", $data);
- foreach($lines as $line)
- {
- if(strpos($line, '#') === FALSE)
- continue;
+ foreach($lines as $line)
+ {
+ if(strpos($line, '#') === FALSE)
+ continue;
- $start = strpos($line, '"')+1;
- $end = strrpos($line, '"');
+ $start = strpos($line, '"')+1;
+ $end = strrpos($line, '"');
- $userid = sys::int(substr($line, 0, $start));
+ $userid = sys::int(substr($line, 0, $start));
- $name = htmlspecialchars(substr($line, $start, $end-$start));
+ $name = htmlspecialchars(substr($line, $start, $end-$start));
- $line = trim(substr($line, $end + 1));
+ $line = trim(substr($line, $end + 1));
- $aData = array_values(array_diff(explode(' ', $line), array('', ' ')));
+ $aData = array_values(array_diff(explode(' ', $line), array('', ' ')));
- $steamid = trim($aData[0]);
- $ip = trim(sys::first(explode(':', $aData[5])));
+ $steamid = trim($aData[0]);
+ $ip = trim(sys::first(explode(':', $aData[5])));
- if((sys::valid($steamid, 'steamid') AND sys::valid($steamid, 'steamid3')) || sys::valid($ip, 'ip'))
- continue;
+ if((sys::valid($steamid, 'steamid') AND sys::valid($steamid, 'steamid3')) || sys::valid($ip, 'ip'))
+ continue;
- $aPlayers[$n]['userid'] = $userid;
- $aPlayers[$n]['name'] = $name;
- $aPlayers[$n]['steamid'] = $steamid;
- $aPlayers[$n]['time'] = trim($aData[1]);
- $aPlayers[$n]['ping'] = trim($aData[2]);
- $aPlayers[$n]['ip'] = $ip;
+ $aPlayers[$n]['userid'] = $userid;
+ $aPlayers[$n]['name'] = $name;
+ $aPlayers[$n]['steamid'] = $steamid;
+ $aPlayers[$n]['time'] = trim($aData[1]);
+ $aPlayers[$n]['ping'] = trim($aData[2]);
+ $aPlayers[$n]['ip'] = $ip;
- $whois = rcon::country($ip);
+ $whois = rcon::country($ip);
- $aPlayers[$n]['ico'] = $whois['ico'];
- $aPlayers[$n]['country'] = $whois['name'];
+ $aPlayers[$n]['ico'] = $whois['ico'];
+ $aPlayers[$n]['country'] = $whois['name'];
- $n+=1;
- }
+ $n+=1;
+ }
- return $aPlayers;
- }
+ return $aPlayers;
+ }
- public static function rcon_passwd($server)
- {
- global $cfg, $sql, $user;
+ public static function rcon_passwd($server)
+ {
+ global $cfg, $sql, $user;
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- $sql->query('SELECT `address`, `passwd` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $sql->query('SELECT `address`, `passwd` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
$unit = $sql->get();
- if(!$ssh->auth($unit['passwd'], $unit['address']))
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
sys::outjs(array('e' => sys::text('error', 'ssh')));
- $ssh->set('cat /servers/'.$server['uid'].'/csgo/cfg/server.cfg | grep rcon_password');
- $get = explode(' ', str_replace('"', '', trim($ssh->get())));
- $rcon = trim(end($get));
+ $ssh->set('cat /servers/'.$server['uid'].'/csgo/cfg/server.cfg | grep rcon_password');
+ $get = explode(' ', str_replace('"', '', trim($ssh->get())));
+ $rcon = trim(end($get));
- if(!isset($rcon{0}))
- sys::outjs(array('r' => 'Необходимо установить rcon пароль (rcon_password).', 'url' => $cfg['http'].'control/id/'.$server['unit'].'/server/'.$server['unit'].'/section/settings/subsection/server'), $nmch);
+ if(!isset($rcon{0}))
+ sys::outjs(array('r' => 'Необходимо установить rcon пароль (rcon_password).', 'url' => $cfg['http'].'control/id/'.$server['unit'].'/server/'.$server['unit'].'/section/settings/subsection/server'), $nmch);
- return $rcon;
- }
+ return $rcon;
+ }
- public static function country($ip)
- {
- global $SxGeo;
+ public static function country($ip)
+ {
+ global $SxGeo;
- $cData = $SxGeo->getCityFull($ip);
- $ico = sys::country($cData['country']['iso']);
+ $cData = $SxGeo->getCityFull($ip);
+ $ico = sys::country($cData['country']['iso']);
- return array('ico' => $ico, 'name' => empty($cData['country']['name_ru']) ? 'Не определена' : $cData['country']['name_ru']);
- }
- }
+ return array('ico' => $ico, 'name' => empty($cData['country']['name_ru']) ? 'Не определена' : $cData['country']['name_ru']);
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/control/csgo/scan.php b/system/library/control/csgo/scan.php
index 3c89854..ab68e56 100644
--- a/system/library/control/csgo/scan.php
+++ b/system/library/control/csgo/scan.php
@@ -1,135 +1,135 @@
get($nmch)))
- return $mcache->get($nmch);
+ if(is_array($mcache->get($nmch)))
+ return $mcache->get($nmch);
- $out = array();
+ $out = array();
- $info = scan::info($sq, $id);
+ $info = scan::info($sq, $id);
- $sql->query('SELECT `unit`, `game`, `name`, `map`, `online`, `players`, `status` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `unit`, `game`, `name`, `map`, `online`, `players`, `status` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- if(!$info['status'])
- {
- $out['name'] = $server['name'];
- $out['status'] = sys::status($server['status'], $server['game'], $server['map']);
- $out['online'] = $server['online'];
- $out['image'] = ' ';
- $out['buttons'] = sys::buttons($id, $server['status'], $server['game'], $server['unit']);
+ if(!$info['status'])
+ {
+ $out['name'] = $server['name'];
+ $out['status'] = sys::status($server['status'], $server['game'], $server['map']);
+ $out['online'] = $server['online'];
+ $out['image'] = ' ';
+ $out['buttons'] = sys::buttons($id, $server['status'], $server['game'], $server['unit']);
- if($players_get)
- $out['players'] = base64_decode($server['players']);
+ if($players_get)
+ $out['players'] = base64_decode($server['players']);
- $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
+ $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
- return $out;
- }
+ return $out;
+ }
- if($players_get)
- $players = scan::info($sq, $id, true);
+ if($players_get)
+ $players = scan::info($sq, $id, true);
- $out['name'] = htmlspecialchars($info['name']);
- $out['status'] = sys::status('working', $server['game'], $info['map']);
- $out['online'] = $info['online'];
- $out['image'] = ' ';
- $out['buttons'] = sys::buttons($id, 'working', $server['game'], $server['unit']);
- $out['players'] = '';
+ $out['name'] = htmlspecialchars($info['name']);
+ $out['status'] = sys::status('working', $server['game'], $info['map']);
+ $out['online'] = $info['online'];
+ $out['image'] = ' ';
+ $out['buttons'] = sys::buttons($id, 'working', $server['game'], $server['unit']);
+ $out['players'] = '';
- if($players_get)
- {
- foreach($players as $index => $player)
- {
- $html->get($server['game'], 'sections/servers/players');
+ if($players_get)
+ {
+ foreach($players as $index => $player)
+ {
+ $html->get($server['game'], 'sections/servers/players');
- $html->set('i', $player['i']);
- $html->set('name', $player['name']);
- $html->set('score', $player['score']);
- $html->set('time', $player['time']);
+ $html->set('i', $player['i']);
+ $html->set('name', $player['name']);
+ $html->set('score', $player['score']);
+ $html->set('time', $player['time']);
- $html->pack('list');
- }
+ $html->pack('list');
+ }
- $out['players'] = isset($html->arr['list']) ? $html->arr['list'] : '';
- }
+ $out['players'] = isset($html->arr['list']) ? $html->arr['list'] : '';
+ }
- $sql->query('UPDATE `control_servers` set '
- .'`name`="'.$out['name'].'", '
- .'`online`="'.$out['online'].'", '
- .'`map`="'.$info['map'].'", '
- .'`status`="working" WHERE `id`="'.$id.'" LIMIT 1');
+ $sql->query('UPDATE `control_servers` set '
+ .'`name`="'.$out['name'].'", '
+ .'`online`="'.$out['online'].'", '
+ .'`map`="'.$info['map'].'", '
+ .'`status`="working" WHERE `id`="'.$id.'" LIMIT 1');
- if($players_get)
- $sql->query('UPDATE `control_servers` set `players`="'.base64_encode($out['players']).'" WHERE `id`="'.$id.'" LIMIT 1');
+ if($players_get)
+ $sql->query('UPDATE `control_servers` set `players`="'.base64_encode($out['players']).'" WHERE `id`="'.$id.'" LIMIT 1');
- $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
+ $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
- return $out;
- }
+ return $out;
+ }
- public static function info($sq, $id, $pl = false)
- {
- global $sql;
+ public static function info($sq, $id, $pl = false)
+ {
+ global $sql;
- $sql->query('SELECT `address` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `address` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- list($ip, $port) = explode(':', $server['address']);
+ list($ip, $port) = explode(':', $server['address']);
- $sq->Connect($ip, $port, 1, SourceQuery::SOURCE);
+ $sq->Connect($ip, $port, 1, SourceQuery::SOURCE);
- if($pl)
- {
- $players = $sq->GetPlayers();
+ if($pl)
+ {
+ $players = $sq->GetPlayers();
- $i = 1;
- $data = array();
+ $i = 1;
+ $data = array();
- foreach($players as $n => $player)
- {
- $data[$i]['i'] = $i;
- $data[$i]['name'] = $player['Name'] == '' ? 'Подключается' : $player['Name'];
- $data[$i]['score'] = $player['Frags'];
- $data[$i]['time'] = $player['TimeF'];
+ foreach($players as $n => $player)
+ {
+ $data[$i]['i'] = $i;
+ $data[$i]['name'] = $player['Name'] == '' ? 'Подключается' : $player['Name'];
+ $data[$i]['score'] = $player['Frags'];
+ $data[$i]['time'] = $player['TimeF'];
- $i+=1;
- }
+ $i+=1;
+ }
- return $data;
- }
+ return $data;
+ }
- $data = $sq->GetInfo();
+ $data = $sq->GetInfo();
- $map = explode('/', $data['Map']);
+ $map = explode('/', $data['Map']);
- $server['name'] = $data['HostName'];
- $server['map'] = end($map);
- $server['online'] = $data['Players'];
- $server['status'] = strlen($server['map']) > 3 ? true : false;
+ $server['name'] = $data['HostName'];
+ $server['map'] = end($map);
+ $server['online'] = $data['Players'];
+ $server['status'] = strlen($server['map']) > 3 ? true : false;
- return $server;
- }
- }
+ return $server;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/control/css/action.php b/system/library/control/css/action.php
index 638b854..87f4de8 100644
--- a/system/library/control/css/action.php
+++ b/system/library/control/css/action.php
@@ -1,177 +1,177 @@
query('SELECT `uid`, `unit`, `game`, `address`, `slots`, `name`, `tickrate`, `map_start`, `vac`, `time_start`, `core_fix` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `uid`, `unit`, `game`, `address`, `slots`, `name`, `tickrate`, `map_start`, `vac`, `time_start`, `core_fix` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- $sql->query('SELECT `address`, `passwd`, `fcpu` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
-
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return array('e' => sys::text('error', 'ssh'));
-
- list($ip, $port) = explode(':', $server['address']);
-
- // Убить процессы
- $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
- .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
-
- $taskset = '';
-
- // Если включена система автораспределения и не установлен фиксированный поток
- if(!$server['core_fix'])
- {
- $proc_stat = array();
-
- $proc_stat[0] = $ssh->get('cat /proc/stat');
- }
-
- // Проверка наличия стартовой карты
- $ssh->set('cd /servers/'.$server['uid'].'/cstrike/maps/ && ls | grep .bsp | grep -v .bsp.');
-
- if($server['map_start'] != '' AND !in_array($server['map_start'], str_replace('.bsp', '', explode("\n", $ssh->get()))))
- return array('e' => sys::updtext(sys::text('servers', 'nomap'), array('map' => $server['map_start'].'.bsp')));
-
- // Если система автораспределения продолжить парсинг загрузки процессора
- if(isset($proc_stat))
- {
- $proc_stat[1] = $ssh->get('cat /proc/stat');
-
- // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
- $core = sys::cpu_idle($proc_stat, $server['unit'], $unit['fcpu'], true); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
-
- if(!is_numeric($core))
- return array('e' => sys::text('error', 'cpu'));
-
- $taskset = 'taskset -c '.$core;
- }
-
- if($server['core_fix'])
- {
- $core = $server['core_fix']-1;
- $taskset = 'taskset -c '.$core;
- }
-
- // Античит VAC
- $vac = $server['vac'] == 0 ? '-insecure' : '-secure';
-
- // TV
- $tv = $server['tv'] ? '+tv_enable 1 +tv_maxclients 255 +tv_port '.($port+10000) : '-nohltv';
-
- // Параметры запуска
- $bash = './srcds_run -debug -game cstrike -norestart -condebug console.log -tickrate '.$server['tickrate'].' +servercfgfile server.cfg +map \''.$server['map_start'].'\' +maxplayers '.$server['slots'].' +ip '.$ip.' +port '.$port.' -sv_lan 0 '.$vac.' '.$tv;
-
- // Временный файл
- $temp = sys::temp($bash);
-
- // Обновление файла start.sh
- $ssh->setfile($temp, '/servers/'.$server['uid'].'/start.sh', 0500);
-
- // Строка запуска
- $ssh->set('cd /servers/'.$server['uid'].';' // переход в директорию игрового сервера
- .'rm *.pid;' // Удаление *.pid файлов
- .'sudo -u server'.$server['uid'].' mkdir -p cstrike/oldstart;' // Создание папки логов
- .'cat cstrike/console.log >> cstrike/oldstart/'.date('d.m.Y_H:i:s', $server['time_start']).'.log; rm cstrike/console.log; rm cstrike/oldstart/01.01.1970_03:00:00.log;' // Перемещение лога предыдущего запуска
- .'chown server'.$server['uid'].':1000 start.sh;' // Обновление владельца файла start.sh
- .'sudo -u server'.$server['uid'].' screen -dmS s_'.$server['uid'].' '.$taskset.' sh -c "./start.sh"'); // Запуск игровго сервера
-
- $core = !isset($core) ? 0 : $core+1;
-
- // Обновление информации в базе
- $sql->query('UPDATE `control_servers` set `status`="'.$type.'", `online`="0", `players`="", `core_use`="'.$core.'", `time_start`="'.$start_point.'", `stop`="1" WHERE `id`="'.$id.'" LIMIT 1');
-
- unlink($temp);
-
- // Сброс кеша
- actions::clmcache($id);
-
- sys::reset_mcache('ctrl_server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0, 'players' => ''));
- sys::reset_mcache('ctrl_server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0));
-
- return array('s' => 'ok');
- }
-
- public static function update($id)
- {
- global $cfg, $sql, $user, $start_point;
-
- include(LIB.'ssh.php');
-
- $sql->query('SELECT `uid`, `unit`, `game`, `name`, `ftp`, `core_fix` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
-
- $sql->query('SELECT `address`, `passwd`, `sql_login`, `sql_passwd`, `sql_port`, `sql_ftp`, `fcpu` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $sql->query('SELECT `address`, `passwd`, `fcpu` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
$unit = $sql->get();
- // Проверка ssh соедниения пу с локацией
+ // Проверка ssh соедниения пу с локацией
if(!$ssh->auth($unit['passwd'], $unit['address']))
return array('e' => sys::text('error', 'ssh'));
- $taskset = '';
+ list($ip, $port) = explode(':', $server['address']);
- // Если включена система автораспределения и не установлен фиксированный поток
- if(!$server['core_fix'])
- {
- $proc_stat = array();
+ // Убить процессы
+ $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
+ .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
- $proc_stat[0] = $ssh->get('cat /proc/stat');
- }
+ $taskset = '';
- // Директория игрового сервера
- $install = '/servers/'.$server['uid'];
+ // Если включена система автораспределения и не установлен фиксированный поток
+ if(!$server['core_fix'])
+ {
+ $proc_stat = array();
- // Если система автораспределения продолжить парсинг загрузки процессора
- if(isset($proc_stat))
- {
- $proc_stat[1] = $ssh->get('cat /proc/stat');
+ $proc_stat[0] = $ssh->get('cat /proc/stat');
+ }
- // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
- $core = sys::cpu_idle($proc_stat, $server['unit'], $unit['fcpu'], true); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
+ // Проверка наличия стартовой карты
+ $ssh->set('cd /servers/'.$server['uid'].'/cstrike/maps/ && ls | grep .bsp | grep -v .bsp.');
- if(!is_numeric($core))
- return array('e' => 'Не удается выполнить операцию, нет свободного потока.');
+ if($server['map_start'] != '' AND !in_array($server['map_start'], str_replace('.bsp', '', explode("\n", $ssh->get()))))
+ return array('e' => sys::updtext(sys::text('servers', 'nomap'), array('map' => $server['map_start'].'.bsp')));
- $taskset = 'taskset -c '.$core;
- }
+ // Если система автораспределения продолжить парсинг загрузки процессора
+ if(isset($proc_stat))
+ {
+ $proc_stat[1] = $ssh->get('cat /proc/stat');
- if($server['core_fix'])
- {
- $core = $server['core_fix']-1;
- $taskset = 'taskset -c '.$core;
- }
+ // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
+ $core = sys::cpu_idle($proc_stat, $server['unit'], $unit['fcpu'], true); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
- $ssh->set('cd '.$cfg['steamcmd'].' && '.$taskset.' screen -dmS u_'.$server['uid'].' sh -c "'
- .'./steamcmd.sh +login anonymous +force_install_dir "'.$install.'" +app_update 232330 +quit;'
- .'cd '.$install.';'
- .'chown -R server'.$server['uid'].':servers .;'
- .'find . -type d -exec chmod 700 {} \;;'
- .'find . -type f -exec chmod 600 {} \;;'
- .'chmod 500 '.params::$aFileGame[$server['game']].'"');
+ if(!is_numeric($core))
+ return array('e' => sys::text('error', 'cpu'));
- $core = !isset($core) ? 0 : $core+1;
+ $taskset = 'taskset -c '.$core;
+ }
- // Обновление информации в базе
- $sql->query('UPDATE `control_servers` set `status`="update", `core_use`="'.$core.'" WHERE `id`="'.$id.'" LIMIT 1');
+ if($server['core_fix'])
+ {
+ $core = $server['core_fix']-1;
+ $taskset = 'taskset -c '.$core;
+ }
- // Сброс кеша
- actions::clmcache($id);
+ // Античит VAC
+ $vac = $server['vac'] == 0 ? '-insecure' : '-secure';
- sys::reset_mcache('ctrl_server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'update', 'online' => 0, 'players' => ''));
- sys::reset_mcache('ctrl_server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'update', 'online' => 0));
+ // TV
+ $tv = $server['tv'] ? '+tv_enable 1 +tv_maxclients 255 +tv_port '.($port+10000) : '-nohltv';
- return array('s' => 'ok');
- }
+ // Параметры запуска
+ $bash = './srcds_run -debug -game cstrike -norestart -condebug console.log -tickrate '.$server['tickrate'].' +servercfgfile server.cfg +map \''.$server['map_start'].'\' +maxplayers '.$server['slots'].' +ip '.$ip.' +port '.$port.' -sv_lan 0 '.$vac.' '.$tv;
+
+ // Временный файл
+ $temp = sys::temp($bash);
+
+ // Обновление файла start.sh
+ $ssh->setfile($temp, '/servers/'.$server['uid'].'/start.sh', 0500);
+
+ // Строка запуска
+ $ssh->set('cd /servers/'.$server['uid'].';' // переход в директорию игрового сервера
+ .'rm *.pid;' // Удаление *.pid файлов
+ .'sudo -u server'.$server['uid'].' mkdir -p cstrike/oldstart;' // Создание папки логов
+ .'cat cstrike/console.log >> cstrike/oldstart/'.date('d.m.Y_H:i:s', $server['time_start']).'.log; rm cstrike/console.log; rm cstrike/oldstart/01.01.1970_03:00:00.log;' // Перемещение лога предыдущего запуска
+ .'chown server'.$server['uid'].':1000 start.sh;' // Обновление владельца файла start.sh
+ .'sudo -u server'.$server['uid'].' screen -dmS s_'.$server['uid'].' '.$taskset.' sh -c "./start.sh"'); // Запуск игровго сервера
+
+ $core = !isset($core) ? 0 : $core+1;
+
+ // Обновление информации в базе
+ $sql->query('UPDATE `control_servers` set `status`="'.$type.'", `online`="0", `players`="", `core_use`="'.$core.'", `time_start`="'.$start_point.'", `stop`="1" WHERE `id`="'.$id.'" LIMIT 1');
+
+ unlink($temp);
+
+ // Сброс кеша
+ actions::clmcache($id);
+
+ sys::reset_mcache('ctrl_server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0, 'players' => ''));
+ sys::reset_mcache('ctrl_server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0));
+
+ return array('s' => 'ok');
+ }
+
+ public static function update($id)
+ {
+ global $cfg, $sql, $user, $start_point;
+
+ include(LIB.'ssh.php');
+
+ $sql->query('SELECT `uid`, `unit`, `game`, `name`, `ftp`, `core_fix` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
+
+ $sql->query('SELECT `address`, `passwd`, `sql_login`, `sql_passwd`, `sql_port`, `sql_ftp`, `fcpu` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
+
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return array('e' => sys::text('error', 'ssh'));
+
+ $taskset = '';
+
+ // Если включена система автораспределения и не установлен фиксированный поток
+ if(!$server['core_fix'])
+ {
+ $proc_stat = array();
+
+ $proc_stat[0] = $ssh->get('cat /proc/stat');
+ }
+
+ // Директория игрового сервера
+ $install = '/servers/'.$server['uid'];
+
+ // Если система автораспределения продолжить парсинг загрузки процессора
+ if(isset($proc_stat))
+ {
+ $proc_stat[1] = $ssh->get('cat /proc/stat');
+
+ // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
+ $core = sys::cpu_idle($proc_stat, $server['unit'], $unit['fcpu'], true); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
+
+ if(!is_numeric($core))
+ return array('e' => 'Не удается выполнить операцию, нет свободного потока.');
+
+ $taskset = 'taskset -c '.$core;
+ }
+
+ if($server['core_fix'])
+ {
+ $core = $server['core_fix']-1;
+ $taskset = 'taskset -c '.$core;
+ }
+
+ $ssh->set('cd '.$cfg['steamcmd'].' && '.$taskset.' screen -dmS u_'.$server['uid'].' sh -c "'
+ .'./steamcmd.sh +login anonymous +force_install_dir "'.$install.'" +app_update 232330 +quit;'
+ .'cd '.$install.';'
+ .'chown -R server'.$server['uid'].':servers .;'
+ .'find . -type d -exec chmod 700 {} \;;'
+ .'find . -type f -exec chmod 600 {} \;;'
+ .'chmod 500 '.params::$aFileGame[$server['game']].'"');
+
+ $core = !isset($core) ? 0 : $core+1;
+
+ // Обновление информации в базе
+ $sql->query('UPDATE `control_servers` set `status`="update", `core_use`="'.$core.'" WHERE `id`="'.$id.'" LIMIT 1');
+
+ // Сброс кеша
+ actions::clmcache($id);
+
+ sys::reset_mcache('ctrl_server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'update', 'online' => 0, 'players' => ''));
+ sys::reset_mcache('ctrl_server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'update', 'online' => 0));
+
+ return array('s' => 'ok');
+ }
}
?>
\ No newline at end of file
diff --git a/system/library/control/css/rcon.php b/system/library/control/css/rcon.php
index 1dff675..5cca4f4 100644
--- a/system/library/control/css/rcon.php
+++ b/system/library/control/css/rcon.php
@@ -1,109 +1,109 @@
Connect($ip, $port, 3, SourceQuery::SOURCE);
+ $sq->Connect($ip, $port, 3, SourceQuery::SOURCE);
- $sq->SetRconPassword(rcon::rcon_passwd($server));
+ $sq->SetRconPassword(rcon::rcon_passwd($server));
- $out = $sq->Rcon($cmd);
+ $out = $sq->Rcon($cmd);
- $sq->Disconnect();
+ $sq->Disconnect();
- return $out;
- }
+ return $out;
+ }
- public static function players($data)
- {
- $aPlayers = array();
- $n = 1;
+ public static function players($data)
+ {
+ $aPlayers = array();
+ $n = 1;
- $lines = explode("\n", $data);
+ $lines = explode("\n", $data);
- foreach($lines as $line)
- {
- if(strpos($line, '#') === FALSE)
- continue;
+ foreach($lines as $line)
+ {
+ if(strpos($line, '#') === FALSE)
+ continue;
- $start = strpos($line, '"')+1;
- $end = strrpos($line, '"');
+ $start = strpos($line, '"')+1;
+ $end = strrpos($line, '"');
- $userid = sys::int(substr($line, 0, $start));
+ $userid = sys::int(substr($line, 0, $start));
- $name = htmlspecialchars(substr($line, $start, $end-$start));
+ $name = htmlspecialchars(substr($line, $start, $end-$start));
- $line = trim(substr($line, $end + 1));
+ $line = trim(substr($line, $end + 1));
- $aData = array_values(array_diff(explode(' ', $line), array('', ' ')));
+ $aData = array_values(array_diff(explode(' ', $line), array('', ' ')));
- $steamid = trim($aData[0]);
- $ip = trim(sys::first(explode(':', $aData[5])));
+ $steamid = trim($aData[0]);
+ $ip = trim(sys::first(explode(':', $aData[5])));
- if((sys::valid($steamid, 'steamid') AND sys::valid($steamid, 'steamid3')) || sys::valid($ip, 'ip'))
- continue;
+ if((sys::valid($steamid, 'steamid') AND sys::valid($steamid, 'steamid3')) || sys::valid($ip, 'ip'))
+ continue;
- $aPlayers[$n]['userid'] = $userid;
- $aPlayers[$n]['name'] = $name;
- $aPlayers[$n]['steamid'] = $steamid;
- $aPlayers[$n]['time'] = trim($aData[1]);
- $aPlayers[$n]['ping'] = trim($aData[2]);
- $aPlayers[$n]['ip'] = $ip;
+ $aPlayers[$n]['userid'] = $userid;
+ $aPlayers[$n]['name'] = $name;
+ $aPlayers[$n]['steamid'] = $steamid;
+ $aPlayers[$n]['time'] = trim($aData[1]);
+ $aPlayers[$n]['ping'] = trim($aData[2]);
+ $aPlayers[$n]['ip'] = $ip;
- $whois = rcon::country($ip);
+ $whois = rcon::country($ip);
- $aPlayers[$n]['ico'] = $whois['ico'];
- $aPlayers[$n]['country'] = $whois['name'];
+ $aPlayers[$n]['ico'] = $whois['ico'];
+ $aPlayers[$n]['country'] = $whois['name'];
- $n+=1;
- }
+ $n+=1;
+ }
- return $aPlayers;
- }
+ return $aPlayers;
+ }
- public static function rcon_passwd($server)
- {
- global $cfg, $sql, $user;
+ public static function rcon_passwd($server)
+ {
+ global $cfg, $sql, $user;
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- $sql->query('SELECT `address`, `passwd` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $sql->query('SELECT `address`, `passwd` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
$unit = $sql->get();
- if(!$ssh->auth($unit['passwd'], $unit['address']))
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
sys::outjs(array('e' => sys::text('error', 'ssh')));
- $ssh->set('cat /servers/'.$server['uid'].'/cstrike/cfg/server.cfg | grep rcon_password');
- $get = explode(' ', str_replace('"', '', trim($ssh->get())));
- $rcon = trim(end($get));
+ $ssh->set('cat /servers/'.$server['uid'].'/cstrike/cfg/server.cfg | grep rcon_password');
+ $get = explode(' ', str_replace('"', '', trim($ssh->get())));
+ $rcon = trim(end($get));
- if(!isset($rcon{0}))
- sys::outjs(array('r' => 'Необходимо установить rcon пароль (rcon_password).', 'url' => $cfg['http'].'control/id/'.$server['unit'].'/server/'.$server['unit'].'/section/settings/subsection/server'), $nmch);
+ if(!isset($rcon{0}))
+ sys::outjs(array('r' => 'Необходимо установить rcon пароль (rcon_password).', 'url' => $cfg['http'].'control/id/'.$server['unit'].'/server/'.$server['unit'].'/section/settings/subsection/server'), $nmch);
- return $rcon;
- }
+ return $rcon;
+ }
- public static function country($ip)
- {
- global $SxGeo;
+ public static function country($ip)
+ {
+ global $SxGeo;
- $cData = $SxGeo->getCityFull($ip);
- $ico = sys::country($cData['country']['iso']);
+ $cData = $SxGeo->getCityFull($ip);
+ $ico = sys::country($cData['country']['iso']);
- return array('ico' => $ico, 'name' => empty($cData['country']['name_ru']) ? 'Не определена' : $cData['country']['name_ru']);
- }
- }
+ return array('ico' => $ico, 'name' => empty($cData['country']['name_ru']) ? 'Не определена' : $cData['country']['name_ru']);
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/control/css/scan.php b/system/library/control/css/scan.php
index f736d83..14ce945 100644
--- a/system/library/control/css/scan.php
+++ b/system/library/control/css/scan.php
@@ -1,133 +1,133 @@
get($nmch)))
- return $mcache->get($nmch);
+ if(is_array($mcache->get($nmch)))
+ return $mcache->get($nmch);
- $out = array();
+ $out = array();
- $info = scan::info($sq, $id);
+ $info = scan::info($sq, $id);
- $sql->query('SELECT `unit`, `game`, `name`, `map`, `online`, `players`, `status` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `unit`, `game`, `name`, `map`, `online`, `players`, `status` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- if(!$info['status'])
- {
- $out['name'] = $server['name'];
- $out['status'] = sys::status($server['status'], $server['game'], $server['map']);
- $out['online'] = $server['online'];
- $out['image'] = ' ';
- $out['buttons'] = sys::buttons($id, $server['status'], $server['game'], $server['unit']);
+ if(!$info['status'])
+ {
+ $out['name'] = $server['name'];
+ $out['status'] = sys::status($server['status'], $server['game'], $server['map']);
+ $out['online'] = $server['online'];
+ $out['image'] = ' ';
+ $out['buttons'] = sys::buttons($id, $server['status'], $server['game'], $server['unit']);
- if($players_get)
- $out['players'] = base64_decode($server['players']);
+ if($players_get)
+ $out['players'] = base64_decode($server['players']);
- $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
+ $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
- return $out;
- }
+ return $out;
+ }
- if($players_get)
- $players = scan::info($sq, $id, true);
+ if($players_get)
+ $players = scan::info($sq, $id, true);
- $out['name'] = htmlspecialchars($info['name']);
- $out['status'] = sys::status('working', $server['game'], $info['map']);
- $out['online'] = $info['online'];
- $out['image'] = ' ';
- $out['buttons'] = sys::buttons($id, 'working', $server['game'], $server['unit']);
- $out['players'] = '';
+ $out['name'] = htmlspecialchars($info['name']);
+ $out['status'] = sys::status('working', $server['game'], $info['map']);
+ $out['online'] = $info['online'];
+ $out['image'] = ' ';
+ $out['buttons'] = sys::buttons($id, 'working', $server['game'], $server['unit']);
+ $out['players'] = '';
- if($players_get)
- {
- foreach($players as $index => $player)
- {
- $html->get($server['game'], 'sections/servers/players');
+ if($players_get)
+ {
+ foreach($players as $index => $player)
+ {
+ $html->get($server['game'], 'sections/servers/players');
- $html->set('i', $player['i']);
- $html->set('name', $player['name']);
- $html->set('score', $player['score']);
- $html->set('time', $player['time']);
+ $html->set('i', $player['i']);
+ $html->set('name', $player['name']);
+ $html->set('score', $player['score']);
+ $html->set('time', $player['time']);
- $html->pack('list');
- }
+ $html->pack('list');
+ }
- $out['players'] = isset($html->arr['list']) ? $html->arr['list'] : '';
- }
+ $out['players'] = isset($html->arr['list']) ? $html->arr['list'] : '';
+ }
- $sql->query('UPDATE `control_servers` set '
- .'`name`="'.$out['name'].'", '
- .'`online`="'.$out['online'].'", '
- .'`map`="'.$info['map'].'", '
- .'`status`="working" WHERE `id`="'.$id.'" LIMIT 1');
+ $sql->query('UPDATE `control_servers` set '
+ .'`name`="'.$out['name'].'", '
+ .'`online`="'.$out['online'].'", '
+ .'`map`="'.$info['map'].'", '
+ .'`status`="working" WHERE `id`="'.$id.'" LIMIT 1');
- if($players_get)
- $sql->query('UPDATE `control_servers` set `players`="'.base64_encode($out['players']).'" WHERE `id`="'.$id.'" LIMIT 1');
+ if($players_get)
+ $sql->query('UPDATE `control_servers` set `players`="'.base64_encode($out['players']).'" WHERE `id`="'.$id.'" LIMIT 1');
- $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
+ $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
- return $out;
- }
+ return $out;
+ }
- public static function info($sq, $id, $pl = false)
- {
- global $sql;
+ public static function info($sq, $id, $pl = false)
+ {
+ global $sql;
- $sql->query('SELECT `address` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `address` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- list($ip, $port) = explode(':', $server['address']);
+ list($ip, $port) = explode(':', $server['address']);
- $sq->Connect($ip, $port, 1, SourceQuery::SOURCE);
+ $sq->Connect($ip, $port, 1, SourceQuery::SOURCE);
- if($pl)
- {
- $players = $sq->GetPlayers();
+ if($pl)
+ {
+ $players = $sq->GetPlayers();
- $i = 1;
- $data = array();
+ $i = 1;
+ $data = array();
- foreach($players as $n => $player)
- {
- $data[$i]['i'] = $i;
- $data[$i]['name'] = $player['Name'] == '' ? 'Подключается' : $player['Name'];
- $data[$i]['score'] = $player['Frags'];
- $data[$i]['time'] = $player['TimeF'];
+ foreach($players as $n => $player)
+ {
+ $data[$i]['i'] = $i;
+ $data[$i]['name'] = $player['Name'] == '' ? 'Подключается' : $player['Name'];
+ $data[$i]['score'] = $player['Frags'];
+ $data[$i]['time'] = $player['TimeF'];
- $i+=1;
- }
+ $i+=1;
+ }
- return $data;
- }
+ return $data;
+ }
- $data = $sq->GetInfo();
+ $data = $sq->GetInfo();
- $server['name'] = $data['HostName'];
- $server['map'] = $data['Map'];
- $server['online'] = $data['Players'];
- $server['status'] = strlen($server['map']) > 3 ? true : false;
+ $server['name'] = $data['HostName'];
+ $server['map'] = $data['Map'];
+ $server['online'] = $data['Players'];
+ $server['status'] = strlen($server['map']) > 3 ? true : false;
- return $server;
- }
- }
+ return $server;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/control/cssold/action.php b/system/library/control/cssold/action.php
index 392f4f2..692ca32 100644
--- a/system/library/control/cssold/action.php
+++ b/system/library/control/cssold/action.php
@@ -1,110 +1,110 @@
query('SELECT `uid`, `unit`, `game`, `address`, `slots`, `name`, `tickrate`, `fps`, `map_start`, `vac`, `time_start`, `core_fix` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `uid`, `unit`, `game`, `address`, `slots`, `name`, `tickrate`, `fps`, `map_start`, `vac`, `time_start`, `core_fix` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- $sql->query('SELECT `address`, `passwd`, `fcpu` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd`, `fcpu` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return array('e' => sys::text('error', 'ssh'));
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return array('e' => sys::text('error', 'ssh'));
- list($ip, $port) = explode(':', $server['address']);
+ list($ip, $port) = explode(':', $server['address']);
- // Убить процессы
- $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
- .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
+ // Убить процессы
+ $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
+ .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
- $taskset = '';
+ $taskset = '';
- // Если включена система автораспределения и не установлен фиксированный поток
- if(!$server['core_fix'])
- {
- $proc_stat = array();
+ // Если включена система автораспределения и не установлен фиксированный поток
+ if(!$server['core_fix'])
+ {
+ $proc_stat = array();
- $proc_stat[0] = $ssh->get('cat /proc/stat');
- }
+ $proc_stat[0] = $ssh->get('cat /proc/stat');
+ }
- // Проверка наличия стартовой карты
- $ssh->set('cd /servers/'.$server['uid'].'/cstrike/maps/ && ls | grep .bsp | grep -v .bsp.');
+ // Проверка наличия стартовой карты
+ $ssh->set('cd /servers/'.$server['uid'].'/cstrike/maps/ && ls | grep .bsp | grep -v .bsp.');
- if($server['map_start'] != '' AND !in_array($server['map_start'], str_replace('.bsp', '', explode("\n", $ssh->get()))))
- return array('e' => sys::updtext(sys::text('servers', 'nomap'), array('map' => $server['map_start'].'.bsp')));
+ if($server['map_start'] != '' AND !in_array($server['map_start'], str_replace('.bsp', '', explode("\n", $ssh->get()))))
+ return array('e' => sys::updtext(sys::text('servers', 'nomap'), array('map' => $server['map_start'].'.bsp')));
- // Если система автораспределения продолжить парсинг загрузки процессора
- if(isset($proc_stat))
- {
- $proc_stat[1] = $ssh->get('cat /proc/stat');
+ // Если система автораспределения продолжить парсинг загрузки процессора
+ if(isset($proc_stat))
+ {
+ $proc_stat[1] = $ssh->get('cat /proc/stat');
- // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
- $core = sys::cpu_idle($proc_stat, $server['unit'], $unit['fcpu'], true); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
+ // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
+ $core = sys::cpu_idle($proc_stat, $server['unit'], $unit['fcpu'], true); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
- if(!is_numeric($core))
- return array('e' => sys::text('error', 'cpu'));
+ if(!is_numeric($core))
+ return array('e' => sys::text('error', 'cpu'));
- $taskset = 'taskset -c '.$core;
- }
+ $taskset = 'taskset -c '.$core;
+ }
- if($server['core_fix'])
- {
- $core = $server['core_fix']-1;
- $taskset = 'taskset -c '.$core;
- }
+ if($server['core_fix'])
+ {
+ $core = $server['core_fix']-1;
+ $taskset = 'taskset -c '.$core;
+ }
- // Античит VAC
- $vac = $server['vac'] == 0 ? '-insecure' : '-secure';
+ // Античит VAC
+ $vac = $server['vac'] == 0 ? '-insecure' : '-secure';
- // TV
- $tv = $server['tv'] ? '+tv_enable 1 +tv_maxclients 255 +tv_port '.($port+10000) : '-nohltv';
+ // TV
+ $tv = $server['tv'] ? '+tv_enable 1 +tv_maxclients 255 +tv_port '.($port+10000) : '-nohltv';
- // FPS
- $fps = $server['fps'];
+ // FPS
+ $fps = $server['fps'];
- // Параметры запуска
- $bash = './srcds_run -debug -game cstrike -norestart -condebug console.log -tickrate '.$server['tickrate'].' +fps_egp '.$fps.' +servercfgfile server.cfg +map \''.$server['map_start'].'\' +maxplayers '.$server['slots'].' +ip '.$ip.' +port '.$port.' +sv_lan 0 -nomaster -localcser '.$vac.' '.$tv;
+ // Параметры запуска
+ $bash = './srcds_run -debug -game cstrike -norestart -condebug console.log -tickrate '.$server['tickrate'].' +fps_egp '.$fps.' +servercfgfile server.cfg +map \''.$server['map_start'].'\' +maxplayers '.$server['slots'].' +ip '.$ip.' +port '.$port.' +sv_lan 0 -nomaster -localcser '.$vac.' '.$tv;
- // Временный файл
- $temp = sys::temp($bash);
+ // Временный файл
+ $temp = sys::temp($bash);
- // Обновление файла start.sh
- $ssh->setfile($temp, '/servers/'.$server['uid'].'/start.sh', 0500);
+ // Обновление файла start.sh
+ $ssh->setfile($temp, '/servers/'.$server['uid'].'/start.sh', 0500);
- // Строка запуска
- $ssh->set('cd /servers/'.$server['uid'].';' // переход в директорию игрового сервера
- .'rm *.pid;' // Удаление *.pid файлов
- .'mv console.log oldstart.log;' // Перемещение лога предыдущего запуска в файл oldstart.log
- .'sudo -u server'.$server['uid'].' mkdir -p cstrike/oldstart;' // Создание папки логов
- .'cat cstrike/console.log >> cstrike/oldstart/'.date('d.m.Y_H:i:s', $server['time_start']).'.log; rm cstrike/console.log; rm cstrike/oldstart/01.01.1970_03:00:00.log;' // Перемещение лога предыдущего запуска
- .'chown server'.$server['uid'].':1000 start.sh;' // Обновление владельца файла start.sh
- .'sudo -u server'.$server['uid'].' screen -dmS s_'.$server['uid'].' '.$taskset.' sh -c "./start.sh"'); // Запуск игровго сервера
+ // Строка запуска
+ $ssh->set('cd /servers/'.$server['uid'].';' // переход в директорию игрового сервера
+ .'rm *.pid;' // Удаление *.pid файлов
+ .'mv console.log oldstart.log;' // Перемещение лога предыдущего запуска в файл oldstart.log
+ .'sudo -u server'.$server['uid'].' mkdir -p cstrike/oldstart;' // Создание папки логов
+ .'cat cstrike/console.log >> cstrike/oldstart/'.date('d.m.Y_H:i:s', $server['time_start']).'.log; rm cstrike/console.log; rm cstrike/oldstart/01.01.1970_03:00:00.log;' // Перемещение лога предыдущего запуска
+ .'chown server'.$server['uid'].':1000 start.sh;' // Обновление владельца файла start.sh
+ .'sudo -u server'.$server['uid'].' screen -dmS s_'.$server['uid'].' '.$taskset.' sh -c "./start.sh"'); // Запуск игровго сервера
- $core = !isset($core) ? 0 : $core+1;
+ $core = !isset($core) ? 0 : $core+1;
- // Обновление информации в базе
- $sql->query('UPDATE `control_servers` set `status`="'.$type.'", `online`="0", `players`="", `core_use`="'.$core.'", `time_start`="'.$start_point.'", `stop`="1" WHERE `id`="'.$id.'" LIMIT 1');
+ // Обновление информации в базе
+ $sql->query('UPDATE `control_servers` set `status`="'.$type.'", `online`="0", `players`="", `core_use`="'.$core.'", `time_start`="'.$start_point.'", `stop`="1" WHERE `id`="'.$id.'" LIMIT 1');
- unlink($temp);
+ unlink($temp);
- // Сброс кеша
- actions::clmcache($id);
+ // Сброс кеша
+ actions::clmcache($id);
- sys::reset_mcache('ctrl_server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0, 'players' => ''));
- sys::reset_mcache('ctrl_server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0));
+ sys::reset_mcache('ctrl_server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0, 'players' => ''));
+ sys::reset_mcache('ctrl_server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0));
- return array('s' => 'ok');
- }
- }
+ return array('s' => 'ok');
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/control/cssold/rcon.php b/system/library/control/cssold/rcon.php
index 97607e6..c92583e 100644
--- a/system/library/control/cssold/rcon.php
+++ b/system/library/control/cssold/rcon.php
@@ -1,109 +1,109 @@
Connect($ip, $port, 3, SourceQuery::SOURCE);
+ $sq->Connect($ip, $port, 3, SourceQuery::SOURCE);
- $sq->SetRconPassword(rcon::rcon_passwd($server));
+ $sq->SetRconPassword(rcon::rcon_passwd($server));
- $out = $sq->Rcon($cmd);
+ $out = $sq->Rcon($cmd);
- $sq->Disconnect();
+ $sq->Disconnect();
- return $out;
- }
+ return $out;
+ }
- public static function players($data)
- {
- $aPlayers = array();
- $n = 1;
+ public static function players($data)
+ {
+ $aPlayers = array();
+ $n = 1;
- $lines = explode("\n", $data);
+ $lines = explode("\n", $data);
- foreach($lines as $line)
- {
- if(strpos($line, '#') === FALSE)
- continue;
+ foreach($lines as $line)
+ {
+ if(strpos($line, '#') === FALSE)
+ continue;
- $start = strpos($line, '"')+1;
- $end = strrpos($line, '"');
+ $start = strpos($line, '"')+1;
+ $end = strrpos($line, '"');
- $userid = sys::int(substr($line, 0, $start));
+ $userid = sys::int(substr($line, 0, $start));
- $name = htmlspecialchars(substr($line, $start, $end-$start));
+ $name = htmlspecialchars(substr($line, $start, $end-$start));
- $line = trim(substr($line, $end + 1));
+ $line = trim(substr($line, $end + 1));
- $aData = array_values(array_diff(explode(' ', $line), array('', ' ')));
+ $aData = array_values(array_diff(explode(' ', $line), array('', ' ')));
- $steamid = trim($aData[0]);
- $ip = trim(sys::first(explode(':', $aData[5])));
+ $steamid = trim($aData[0]);
+ $ip = trim(sys::first(explode(':', $aData[5])));
- if(sys::valid($steamid, 'steamid') || sys::valid($ip, 'ip'))
- continue;
+ if(sys::valid($steamid, 'steamid') || sys::valid($ip, 'ip'))
+ continue;
- $aPlayers[$n]['userid'] = $userid;
- $aPlayers[$n]['name'] = $name;
- $aPlayers[$n]['steamid'] = $steamid;
- $aPlayers[$n]['time'] = trim($aData[1]);
- $aPlayers[$n]['ping'] = trim($aData[2]);
- $aPlayers[$n]['ip'] = $ip;
+ $aPlayers[$n]['userid'] = $userid;
+ $aPlayers[$n]['name'] = $name;
+ $aPlayers[$n]['steamid'] = $steamid;
+ $aPlayers[$n]['time'] = trim($aData[1]);
+ $aPlayers[$n]['ping'] = trim($aData[2]);
+ $aPlayers[$n]['ip'] = $ip;
- $whois = rcon::country($ip);
+ $whois = rcon::country($ip);
- $aPlayers[$n]['ico'] = $whois['ico'];
- $aPlayers[$n]['country'] = $whois['name'];
+ $aPlayers[$n]['ico'] = $whois['ico'];
+ $aPlayers[$n]['country'] = $whois['name'];
- $n+=1;
- }
+ $n+=1;
+ }
- return $aPlayers;
- }
+ return $aPlayers;
+ }
- public static function rcon_passwd($server)
- {
- global $cfg, $sql, $user;
+ public static function rcon_passwd($server)
+ {
+ global $cfg, $sql, $user;
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- $sql->query('SELECT `address`, `passwd` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $sql->query('SELECT `address`, `passwd` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
$unit = $sql->get();
- if(!$ssh->auth($unit['passwd'], $unit['address']))
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
sys::outjs(array('e' => sys::text('error', 'ssh')));
- $ssh->set('cat /servers/'.$server['uid'].'/cstrike/cfg/server.cfg | grep rcon_password');
- $get = explode(' ', str_replace('"', '', trim($ssh->get())));
- $rcon = trim(end($get));
+ $ssh->set('cat /servers/'.$server['uid'].'/cstrike/cfg/server.cfg | grep rcon_password');
+ $get = explode(' ', str_replace('"', '', trim($ssh->get())));
+ $rcon = trim(end($get));
- if(!isset($rcon{0}))
- sys::outjs(array('r' => 'Необходимо установить rcon пароль (rcon_password).', 'url' => $cfg['http'].'control/id/'.$server['unit'].'/server/'.$server['unit'].'/section/settings/subsection/server'), $nmch);
+ if(!isset($rcon{0}))
+ sys::outjs(array('r' => 'Необходимо установить rcon пароль (rcon_password).', 'url' => $cfg['http'].'control/id/'.$server['unit'].'/server/'.$server['unit'].'/section/settings/subsection/server'), $nmch);
- return $rcon;
- }
+ return $rcon;
+ }
- public static function country($ip)
- {
- global $SxGeo;
+ public static function country($ip)
+ {
+ global $SxGeo;
- $cData = $SxGeo->getCityFull($ip);
- $ico = sys::country($cData['country']['iso']);
+ $cData = $SxGeo->getCityFull($ip);
+ $ico = sys::country($cData['country']['iso']);
- return array('ico' => $ico, 'name' => empty($cData['country']['name_ru']) ? 'Не определена' : $cData['country']['name_ru']);
- }
- }
+ return array('ico' => $ico, 'name' => empty($cData['country']['name_ru']) ? 'Не определена' : $cData['country']['name_ru']);
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/control/cssold/scan.php b/system/library/control/cssold/scan.php
index f736d83..14ce945 100644
--- a/system/library/control/cssold/scan.php
+++ b/system/library/control/cssold/scan.php
@@ -1,133 +1,133 @@
get($nmch)))
- return $mcache->get($nmch);
+ if(is_array($mcache->get($nmch)))
+ return $mcache->get($nmch);
- $out = array();
+ $out = array();
- $info = scan::info($sq, $id);
+ $info = scan::info($sq, $id);
- $sql->query('SELECT `unit`, `game`, `name`, `map`, `online`, `players`, `status` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `unit`, `game`, `name`, `map`, `online`, `players`, `status` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- if(!$info['status'])
- {
- $out['name'] = $server['name'];
- $out['status'] = sys::status($server['status'], $server['game'], $server['map']);
- $out['online'] = $server['online'];
- $out['image'] = ' ';
- $out['buttons'] = sys::buttons($id, $server['status'], $server['game'], $server['unit']);
+ if(!$info['status'])
+ {
+ $out['name'] = $server['name'];
+ $out['status'] = sys::status($server['status'], $server['game'], $server['map']);
+ $out['online'] = $server['online'];
+ $out['image'] = ' ';
+ $out['buttons'] = sys::buttons($id, $server['status'], $server['game'], $server['unit']);
- if($players_get)
- $out['players'] = base64_decode($server['players']);
+ if($players_get)
+ $out['players'] = base64_decode($server['players']);
- $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
+ $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
- return $out;
- }
+ return $out;
+ }
- if($players_get)
- $players = scan::info($sq, $id, true);
+ if($players_get)
+ $players = scan::info($sq, $id, true);
- $out['name'] = htmlspecialchars($info['name']);
- $out['status'] = sys::status('working', $server['game'], $info['map']);
- $out['online'] = $info['online'];
- $out['image'] = ' ';
- $out['buttons'] = sys::buttons($id, 'working', $server['game'], $server['unit']);
- $out['players'] = '';
+ $out['name'] = htmlspecialchars($info['name']);
+ $out['status'] = sys::status('working', $server['game'], $info['map']);
+ $out['online'] = $info['online'];
+ $out['image'] = ' ';
+ $out['buttons'] = sys::buttons($id, 'working', $server['game'], $server['unit']);
+ $out['players'] = '';
- if($players_get)
- {
- foreach($players as $index => $player)
- {
- $html->get($server['game'], 'sections/servers/players');
+ if($players_get)
+ {
+ foreach($players as $index => $player)
+ {
+ $html->get($server['game'], 'sections/servers/players');
- $html->set('i', $player['i']);
- $html->set('name', $player['name']);
- $html->set('score', $player['score']);
- $html->set('time', $player['time']);
+ $html->set('i', $player['i']);
+ $html->set('name', $player['name']);
+ $html->set('score', $player['score']);
+ $html->set('time', $player['time']);
- $html->pack('list');
- }
+ $html->pack('list');
+ }
- $out['players'] = isset($html->arr['list']) ? $html->arr['list'] : '';
- }
+ $out['players'] = isset($html->arr['list']) ? $html->arr['list'] : '';
+ }
- $sql->query('UPDATE `control_servers` set '
- .'`name`="'.$out['name'].'", '
- .'`online`="'.$out['online'].'", '
- .'`map`="'.$info['map'].'", '
- .'`status`="working" WHERE `id`="'.$id.'" LIMIT 1');
+ $sql->query('UPDATE `control_servers` set '
+ .'`name`="'.$out['name'].'", '
+ .'`online`="'.$out['online'].'", '
+ .'`map`="'.$info['map'].'", '
+ .'`status`="working" WHERE `id`="'.$id.'" LIMIT 1');
- if($players_get)
- $sql->query('UPDATE `control_servers` set `players`="'.base64_encode($out['players']).'" WHERE `id`="'.$id.'" LIMIT 1');
+ if($players_get)
+ $sql->query('UPDATE `control_servers` set `players`="'.base64_encode($out['players']).'" WHERE `id`="'.$id.'" LIMIT 1');
- $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
+ $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
- return $out;
- }
+ return $out;
+ }
- public static function info($sq, $id, $pl = false)
- {
- global $sql;
+ public static function info($sq, $id, $pl = false)
+ {
+ global $sql;
- $sql->query('SELECT `address` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `address` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- list($ip, $port) = explode(':', $server['address']);
+ list($ip, $port) = explode(':', $server['address']);
- $sq->Connect($ip, $port, 1, SourceQuery::SOURCE);
+ $sq->Connect($ip, $port, 1, SourceQuery::SOURCE);
- if($pl)
- {
- $players = $sq->GetPlayers();
+ if($pl)
+ {
+ $players = $sq->GetPlayers();
- $i = 1;
- $data = array();
+ $i = 1;
+ $data = array();
- foreach($players as $n => $player)
- {
- $data[$i]['i'] = $i;
- $data[$i]['name'] = $player['Name'] == '' ? 'Подключается' : $player['Name'];
- $data[$i]['score'] = $player['Frags'];
- $data[$i]['time'] = $player['TimeF'];
+ foreach($players as $n => $player)
+ {
+ $data[$i]['i'] = $i;
+ $data[$i]['name'] = $player['Name'] == '' ? 'Подключается' : $player['Name'];
+ $data[$i]['score'] = $player['Frags'];
+ $data[$i]['time'] = $player['TimeF'];
- $i+=1;
- }
+ $i+=1;
+ }
- return $data;
- }
+ return $data;
+ }
- $data = $sq->GetInfo();
+ $data = $sq->GetInfo();
- $server['name'] = $data['HostName'];
- $server['map'] = $data['Map'];
- $server['online'] = $data['Players'];
- $server['status'] = strlen($server['map']) > 3 ? true : false;
+ $server['name'] = $data['HostName'];
+ $server['map'] = $data['Map'];
+ $server['online'] = $data['Players'];
+ $server['status'] = strlen($server['map']) > 3 ? true : false;
- return $server;
- }
- }
+ return $server;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/control/plugins.php b/system/library/control/plugins.php
index 96700cd..2951608 100644
--- a/system/library/control/plugins.php
+++ b/system/library/control/plugins.php
@@ -1,181 +1,181 @@
arr['images']))
- unset($html->arr['images']);
+ if(isset($html->arr['images']))
+ unset($html->arr['images']);
- $aImg = explode("\n", $images);
+ $aImg = explode("\n", $images);
- foreach($aImg as $img)
- {
- $html->get('plugin_images', 'sections/control/servers/games/plugins');
+ foreach($aImg as $img)
+ {
+ $html->get('plugin_images', 'sections/control/servers/games/plugins');
- $html->set('id', $plugin);
- $html->set('img', $img);
+ $html->set('id', $plugin);
+ $html->set('img', $img);
- $html->pack('images');
- }
+ $html->pack('images');
+ }
- return isset($html->arr['images']) ? $html->arr['images'] : '';
- }
+ return isset($html->arr['images']) ? $html->arr['images'] : '';
+ }
- public static function status($status)
- {
- global $html;
+ public static function status($status)
+ {
+ global $html;
- if(!$status)
- {
- $html->unit('unstable');
- $html->unit('stable', 1);
- $html->unit('testing');
- }elseif($status == 2){
- $html->unit('unstable');
- $html->unit('stable');
- $html->unit('testing', 1);
- }else{
- $html->unit('unstable', 1);
- $html->unit('stable');
- $html->unit('testing');
- }
+ if(!$status)
+ {
+ $html->unit('unstable');
+ $html->unit('stable', 1);
+ $html->unit('testing');
+ }elseif($status == 2){
+ $html->unit('unstable');
+ $html->unit('stable');
+ $html->unit('testing', 1);
+ }else{
+ $html->unit('unstable', 1);
+ $html->unit('stable');
+ $html->unit('testing');
+ }
- return NULL;
- }
+ return NULL;
+ }
- public static function required($id, $required, $choice, $mcache)
- {
- global $sql;
+ public static function required($id, $required, $choice, $mcache)
+ {
+ global $sql;
- if($required == '')
- return NULL;
+ if($required == '')
+ return NULL;
- $aRequi = explode(':', $required);
+ $aRequi = explode(':', $required);
- foreach($aRequi as $pl)
- {
- $sql->query('SELECT `id` FROM `control_plugins_install` WHERE `server`="'.$sid.'" AND `plugin`="'.$pl.'" LIMIT 1');
- if(!$sql->num())
- {
- $sql->query('SELECT `name` FROM `plugins` WHERE `id`="'.$pl.'" LIMIT 1');
- $plRequi = $sql->get();
+ foreach($aRequi as $pl)
+ {
+ $sql->query('SELECT `id` FROM `control_plugins_install` WHERE `server`="'.$sid.'" AND `plugin`="'.$pl.'" LIMIT 1');
+ if(!$sql->num())
+ {
+ $sql->query('SELECT `name` FROM `plugins` WHERE `id`="'.$pl.'" LIMIT 1');
+ $plRequi = $sql->get();
- if($choice != '')
- {
- $aChoice = explode(' ', $choice);
+ if($choice != '')
+ {
+ $aChoice = explode(' ', $choice);
- foreach($aChoice as $plugins)
- {
- $aPlugins = explode(':', $plugins);
+ foreach($aChoice as $plugins)
+ {
+ $aPlugins = explode(':', $plugins);
- if(in_array($pl, $aPlugins))
- {
- $options = '';
- foreach($aPlugins as $plugin)
- {
- $sql->query('SELECT `name`, `upd` FROM `plugins` WHERE `id`="'.$plugin.'" LIMIT 1');
- $data = $sql->get();
+ if(in_array($pl, $aPlugins))
+ {
+ $options = '';
+ foreach($aPlugins as $plugin)
+ {
+ $sql->query('SELECT `name`, `upd` FROM `plugins` WHERE `id`="'.$plugin.'" LIMIT 1');
+ $data = $sql->get();
- if($data['upd'])
- {
- $sql->query('SELECT `name` FROM `plugins_update` WHERE `plugin`="'.$plugin.'" ORDER BY `id` DESC LIMIT 1');
- $data = $sql->get();
- }
+ if($data['upd'])
+ {
+ $sql->query('SELECT `name` FROM `plugins_update` WHERE `plugin`="'.$plugin.'" ORDER BY `id` DESC LIMIT 1');
+ $data = $sql->get();
+ }
- $options .= ''.strip_tags($data['name']).' ';
- }
+ $options .= ''.strip_tags($data['name']).' ';
+ }
- if($options != '')
- sys::outjs(array('e' => 'Для данного плагина требуется установка одного из родителя', 'required' => true, 'pid' => $pl, 'select' => $options), $mcache);
- }
- }
- }
+ if($options != '')
+ sys::outjs(array('e' => 'Для данного плагина требуется установка одного из родителя', 'required' => true, 'pid' => $pl, 'select' => $options), $mcache);
+ }
+ }
+ }
- sys::outjs(array('e' => 'Для данного плагина требуется установка родителя', 'required' => true, 'pid' => $pl, 'pname' => htmlspecialchars_decode($plRequi['name'])), $mcache);
- }
- }
+ sys::outjs(array('e' => 'Для данного плагина требуется установка родителя', 'required' => true, 'pid' => $pl, 'pname' => htmlspecialchars_decode($plRequi['name'])), $mcache);
+ }
+ }
- return NULL;
- }
+ return NULL;
+ }
- public static function incompatible($id, $incompatible, $mcache)
- {
- global $sql;
+ public static function incompatible($id, $incompatible, $mcache)
+ {
+ global $sql;
- if($incompatible == '')
- return NULL;
+ if($incompatible == '')
+ return NULL;
- $aIncomp = explode(':', $incompatible);
+ $aIncomp = explode(':', $incompatible);
- foreach($aIncomp as $pl)
- {
- $sql->query('SELECT `id` FROM `control_plugins_install` WHERE `server`="'.$sid.'" AND `plugin`="'.$pl.'" LIMIT 1');
- if($sql->num())
- {
- $sql->query('SELECT `name` FROM `plugins` WHERE `id`="'.$pl.'" LIMIT 1');
- $plIncomp = $sql->get();
+ foreach($aIncomp as $pl)
+ {
+ $sql->query('SELECT `id` FROM `control_plugins_install` WHERE `server`="'.$sid.'" AND `plugin`="'.$pl.'" LIMIT 1');
+ if($sql->num())
+ {
+ $sql->query('SELECT `name` FROM `plugins` WHERE `id`="'.$pl.'" LIMIT 1');
+ $plIncomp = $sql->get();
- sys::outjs(array('e' => 'Данный плагин несовместим с уже установленным плагином', 'pid' => $pl, 'pname' => htmlspecialchars_decode($plIncomp['name'])), $mcache);
- }
- }
+ sys::outjs(array('e' => 'Данный плагин несовместим с уже установленным плагином', 'pid' => $pl, 'pname' => htmlspecialchars_decode($plIncomp['name'])), $mcache);
+ }
+ }
- return NULL;
- }
+ return NULL;
+ }
- public static function clear($clear, $uid, $dir)
- {
- global $ssh;
+ public static function clear($clear, $uid, $dir)
+ {
+ global $ssh;
- // Если регулярное выражение
- if(isset($clear['regex']) AND $clear['regex'])
- {
- $file = preg_replace($clear['text'], '', $ssh->get('sudo -u server'.$uid.' cat '.$dir.$clear['file']));
+ // Если регулярное выражение
+ if(isset($clear['regex']) AND $clear['regex'])
+ {
+ $file = preg_replace($clear['text'], '', $ssh->get('sudo -u server'.$uid.' cat '.$dir.$clear['file']));
- // Временный файл
- $temp = sys::temp($file);
+ // Временный файл
+ $temp = sys::temp($file);
- $ssh->setfile($temp, $dir.$clear['file'], 0644);
+ $ssh->setfile($temp, $dir.$clear['file'], 0644);
- unlink($temp);
+ unlink($temp);
- $query = 'chown server'.$uid.':servers '.$dir.$clear['file'].';';
+ $query = 'chown server'.$uid.':servers '.$dir.$clear['file'].';';
- }else
- // Удаление текста из файла
- $query = 'sudo -u server'.$uid.' sed -i '."'s/".str_replace('/', '\/', htmlspecialchars_decode($clear['text']))."//g'".' '.$dir.$clear['file'].';';
+ }else
+ // Удаление текста из файла
+ $query = 'sudo -u server'.$uid.' sed -i '."'s/".str_replace('/', '\/', htmlspecialchars_decode($clear['text']))."//g'".' '.$dir.$clear['file'].';';
- $ssh->set($query.'sudo -u server'.$uid.' sed -i '."'/./!d'".' '.$dir.$clear['file']);
+ $ssh->set($query.'sudo -u server'.$uid.' sed -i '."'/./!d'".' '.$dir.$clear['file']);
- return NULL;
- }
+ return NULL;
+ }
- public static function write($write, $uid, $dir)
- {
- global $ssh;
+ public static function write($write, $uid, $dir)
+ {
+ global $ssh;
- // Костыль (добавить пустую строку на всякий случай)
- $query = 'sudo -u server'.$uid.' echo "" >> '.$dir.$write['file'].';';
+ // Костыль (добавить пустую строку на всякий случай)
+ $query = 'sudo -u server'.$uid.' echo "" >> '.$dir.$write['file'].';';
- // Исключить дублирование, путем удаления добавляемого текста
- $query .= 'sudo -u server'.$uid.' sed -i '."'s/".str_replace('/', '\/', htmlspecialchars_decode($write['text']))."//g'".' '.$dir.$write['file'].';';
+ // Исключить дублирование, путем удаления добавляемого текста
+ $query .= 'sudo -u server'.$uid.' sed -i '."'s/".str_replace('/', '\/', htmlspecialchars_decode($write['text']))."//g'".' '.$dir.$write['file'].';';
- // Добавление текста в начало файла
- if($write['top'])
- $query .= 'sudo -u server'.$uid.' touch '.$dir.$write['file'].'; sudo -u server'.$uid.' sed -i '."'1i ".str_replace(array('/', "'", '\"'), array('\/', "\'", '"'), htmlspecialchars_decode($write['text']))."'".' '.$dir.$write['file'].';';
- else
- // Добавление текста в конец файла
- $query .= 'sudo -u server'.$uid.' touch '.$dir.$write['file'].'; sudo -u server'.$uid.' echo "'.str_replace('"', '\"', htmlspecialchars_decode($write['text'])).'" >> '.$dir.$write['file'].';';
+ // Добавление текста в начало файла
+ if($write['top'])
+ $query .= 'sudo -u server'.$uid.' touch '.$dir.$write['file'].'; sudo -u server'.$uid.' sed -i '."'1i ".str_replace(array('/', "'", '\"'), array('\/', "\'", '"'), htmlspecialchars_decode($write['text']))."'".' '.$dir.$write['file'].';';
+ else
+ // Добавление текста в конец файла
+ $query .= 'sudo -u server'.$uid.' touch '.$dir.$write['file'].'; sudo -u server'.$uid.' echo "'.str_replace('"', '\"', htmlspecialchars_decode($write['text'])).'" >> '.$dir.$write['file'].';';
- $ssh->set($query.'sudo -u server'.$uid.' sed -i '."'/./!d'".' '.$dir.$clear['file']);
+ $ssh->set($query.'sudo -u server'.$uid.' sed -i '."'/./!d'".' '.$dir.$clear['file']);
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/control/scans.php b/system/library/control/scans.php
index 9b94376..47549c2 100644
--- a/system/library/control/scans.php
+++ b/system/library/control/scans.php
@@ -1,186 +1,186 @@
'hlds_',
- 'cssold' => 'srcds_i686',
- 'css' => 'srcds_',
- 'csgo' => 'srcds_',
- 'samp' => 'samp',
- 'crmp' => 'samp',
- 'mta' => 'mta',
- 'mc' => 'java'
- );
+ class scans
+ {
+ private static $process = array(
+ 'cs' => 'hlds_',
+ 'cssold' => 'srcds_i686',
+ 'css' => 'srcds_',
+ 'csgo' => 'srcds_',
+ 'samp' => 'samp',
+ 'crmp' => 'samp',
+ 'mta' => 'mta',
+ 'mc' => 'java'
+ );
- public static function resources($id)
- {
- global $cfg, $sql, $mcache;
+ public static function resources($id)
+ {
+ global $cfg, $sql, $mcache;
- $nmch = 'ctrl_server_resources_'.$id;
+ $nmch = 'ctrl_server_resources_'.$id;
- if(is_array($mcache->get($nmch)))
- return $mcache->get($nmch);
+ if(is_array($mcache->get($nmch)))
+ return $mcache->get($nmch);
- $sql->query('SELECT `uid`, `unit`, `game`, `slots`, `status`, `online`, `hdd_use` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $sql->query('SELECT `uid`, `unit`, `game`, `slots`, `status`, `online`, `hdd_use` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
- if(!$sql->num())
- return NULL;
+ if(!$sql->num())
+ return NULL;
- $server = $sql->get();
+ $server = $sql->get();
- $resources = array(
- 'usr' => 0,
- 'cpu' => 0,
- 'ram' => 0,
- 'hdd' => $server['hdd_use']
- );
+ $resources = array(
+ 'usr' => 0,
+ 'cpu' => 0,
+ 'ram' => 0,
+ 'hdd' => $server['hdd_use']
+ );
- $sql->query('SELECT `address`, `passwd`, `ram`, `hdd` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd`, `ram`, `hdd` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return $resources;
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return $resources;
- if(!in_array($server['status'], array('working', 'start', 'restart', 'change')))
- return $resources;
+ if(!in_array($server['status'], array('working', 'start', 'restart', 'change')))
+ return $resources;
- $resources['usr'] = ceil(100/$server['slots']*$server['online']);
- $resources['usr'] = $resources['usr'] > 100 ? 100 : $resources['usr'];
+ $resources['usr'] = ceil(100/$server['slots']*$server['online']);
+ $resources['usr'] = $resources['usr'] > 100 ? 100 : $resources['usr'];
- $cr = explode('|', $ssh->get('top -u '.$server['uid'].' -b -n 1 | grep '.(scans::$process[$server['game']]).' | sort | tail -1 | awk \'{print $9"|"$10}\''));
+ $cr = explode('|', $ssh->get('top -u '.$server['uid'].' -b -n 1 | grep '.(scans::$process[$server['game']]).' | sort | tail -1 | awk \'{print $9"|"$10}\''));
- if(isset($cr[0]))
- $resources['cpu'] = str_replace(',', '.', $cr[0]);
+ if(isset($cr[0]))
+ $resources['cpu'] = str_replace(',', '.', $cr[0]);
- $resources['cpu'] = $resources['cpu'] > 100 ? 100 : round($resources['cpu']);
+ $resources['cpu'] = $resources['cpu'] > 100 ? 100 : round($resources['cpu']);
- if(isset($cr[1]))
- $resources['ram'] = str_replace(',', '.', $cr[1]);
+ if(isset($cr[1]))
+ $resources['ram'] = str_replace(',', '.', $cr[1]);
- // ram на сервер
- $ram = $server['ram'] ? $server['ram'] : $server['slots']*$cfg['ram'][$server['game']];
+ // ram на сервер
+ $ram = $server['ram'] ? $server['ram'] : $server['slots']*$cfg['ram'][$server['game']];
- $resources['ram'] = $unit['ram']/100*$resources['ram']/($ram/100);
+ $resources['ram'] = $unit['ram']/100*$resources['ram']/($ram/100);
- $resources['ram'] = $resources['ram'] > 100 ? 100 : round($resources['ram']);
+ $resources['ram'] = $resources['ram'] > 100 ? 100 : round($resources['ram']);
- $resources['hdd'] = ceil(sys::int($ssh->get('cd /servers/'.$server['uid'].' && du -ms'))/($unit['hdd']/100));
- $resources['hdd'] = $resources['hdd'] > 100 ? 100 : $resources['hdd'];
+ $resources['hdd'] = ceil(sys::int($ssh->get('cd /servers/'.$server['uid'].' && du -ms'))/($unit['hdd']/100));
+ $resources['hdd'] = $resources['hdd'] > 100 ? 100 : $resources['hdd'];
- $sql->query('UPDATE `control_servers` set `ram_use`="'.$resources['ram'].'", `cpu_use`="'.$resources['cpu'].'", `hdd_use`="'.$resources['hdd'].'" WHERE `id`="'.$id.'" LIMIT 1');
+ $sql->query('UPDATE `control_servers` set `ram_use`="'.$resources['ram'].'", `cpu_use`="'.$resources['cpu'].'", `hdd_use`="'.$resources['hdd'].'" WHERE `id`="'.$id.'" LIMIT 1');
- $mcache->set($nmch, $resources, false, $cfg['mcache_server_resources']);
+ $mcache->set($nmch, $resources, false, $cfg['mcache_server_resources']);
- return $resources;
- }
+ return $resources;
+ }
- public static function status($id)
- {
- global $start_point, $cfg, $sql, $mcache;
+ public static function status($id)
+ {
+ global $start_point, $cfg, $sql, $mcache;
- $nmch = 'ctrl_server_status_'.$id;
+ $nmch = 'ctrl_server_status_'.$id;
- if($mcache->get($nmch))
- return 'mcache -> system_block_operation';
+ if($mcache->get($nmch))
+ return 'mcache -> system_block_operation';
- $mcache->set($nmch, true, false, $cfg['mcache_server_status']);
+ $mcache->set($nmch, true, false, $cfg['mcache_server_status']);
- $sql->query('SELECT `uid`, `unit`, `game`, `address`, `status`, `name`, `online`, `players` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `uid`, `unit`, `game`, `address`, `status`, `name`, `online`, `players` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `address`, `passwd` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return 'unit error connect';
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return 'unit error connect';
- switch($server['status'])
- {
- case 'working': case 'change': case 'start': case 'restart':
- if(!sys::int($ssh->get('ps aux | grep s_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
- {
- $sql->query('UPDATE `control_servers` set `status`="off", `online`="0", `players`="0" WHERE `id`="'.$id.'" LIMIT 1');
+ switch($server['status'])
+ {
+ case 'working': case 'change': case 'start': case 'restart':
+ if(!sys::int($ssh->get('ps aux | grep s_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
+ {
+ $sql->query('UPDATE `control_servers` set `status`="off", `online`="0", `players`="0" WHERE `id`="'.$id.'" LIMIT 1');
- sys::reset_mcache('ctrl_server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0, 'players' => ''));
- sys::reset_mcache('ctrl_server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0));
+ sys::reset_mcache('ctrl_server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0, 'players' => ''));
+ sys::reset_mcache('ctrl_server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0));
- return 'server -> working -> off';
- }
+ return 'server -> working -> off';
+ }
- break;
+ break;
- case 'off':
- if(sys::int($ssh->get('ps aux | grep s_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
- {
- $sql->query('UPDATE `control_servers` set `status`="working" WHERE `id`="'.$id.'" LIMIT 1');
+ case 'off':
+ if(sys::int($ssh->get('ps aux | grep s_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
+ {
+ $sql->query('UPDATE `control_servers` set `status`="working" WHERE `id`="'.$id.'" LIMIT 1');
- sys::reset_mcache('ctrl_server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'working', 'online' => $server['online'], 'players' => $server['players']));
- sys::reset_mcache('ctrl_server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'working', 'online' => $server['online']));
+ sys::reset_mcache('ctrl_server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'working', 'online' => $server['online'], 'players' => $server['players']));
+ sys::reset_mcache('ctrl_server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'working', 'online' => $server['online']));
- return 'server -> off -> working';
- }
+ return 'server -> off -> working';
+ }
- break;
+ break;
- case 'reinstall':
- if(!sys::int($ssh->get('ps aux | grep r_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
- {
- $sql->query('UPDATE `control_servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
+ case 'reinstall':
+ if(!sys::int($ssh->get('ps aux | grep r_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
+ {
+ $sql->query('UPDATE `control_servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
- sys::reset_mcache('ctrl_server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0, 'players' => ''));
- sys::reset_mcache('ctrl_server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0));
+ sys::reset_mcache('ctrl_server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0, 'players' => ''));
+ sys::reset_mcache('ctrl_server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0));
- return 'server -> reinstall -> end';
- }
+ return 'server -> reinstall -> end';
+ }
- break;
+ break;
- case 'update':
- if(!sys::int($ssh->get('ps aux | grep u_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
- {
- $sql->query('UPDATE `control_servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
+ case 'update':
+ if(!sys::int($ssh->get('ps aux | grep u_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
+ {
+ $sql->query('UPDATE `control_servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
- sys::reset_mcache('ctrl_server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0, 'players' => ''));
- sys::reset_mcache('ctrl_server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0));
+ sys::reset_mcache('ctrl_server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0, 'players' => ''));
+ sys::reset_mcache('ctrl_server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0));
- return 'server -> update -> end';
- }
+ return 'server -> update -> end';
+ }
- break;
+ break;
- case 'install':
- if(!sys::int($ssh->get('ps aux | grep i_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
- {
- $sql->query('UPDATE `control_servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
+ case 'install':
+ if(!sys::int($ssh->get('ps aux | grep i_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
+ {
+ $sql->query('UPDATE `control_servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
- sys::reset_mcache('ctrl_server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0, 'players' => ''));
- sys::reset_mcache('ctrl_server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0));
+ sys::reset_mcache('ctrl_server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0, 'players' => ''));
+ sys::reset_mcache('ctrl_server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0));
- return 'server -> install -> end';
- }
+ return 'server -> install -> end';
+ }
- break;
+ break;
- case 'recovery':
- if(!sys::int($ssh->get('ps aux | grep rec_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
- {
- $sql->query('UPDATE `control_servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
+ case 'recovery':
+ if(!sys::int($ssh->get('ps aux | grep rec_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
+ {
+ $sql->query('UPDATE `control_servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
- sys::reset_mcache('ctrl_server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0, 'players' => ''));
- sys::reset_mcache('ctrl_server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0));
+ sys::reset_mcache('ctrl_server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0, 'players' => ''));
+ sys::reset_mcache('ctrl_server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0));
- return 'server -> recovery -> end';
- }
- }
+ return 'server -> recovery -> end';
+ }
+ }
- return 'server -> no change -> end scan';
- }
- }
+ return 'server -> no change -> end scan';
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/cron.php b/system/library/cron.php
index cac5f93..406c5d2 100644
--- a/system/library/cron.php
+++ b/system/library/cron.php
@@ -1,77 +1,77 @@
0, 'group' => 'admin');
+ $device = '!mobile';
+ $user = array('id' => 0, 'group' => 'admin');
- class cron
- {
- public static $seping = 5;
+ class cron
+ {
+ public static $seping = 5;
- public static $process = array(
- 'cs' => 'hlds_',
- 'cssold' => 'srcds_i686',
- 'css' => 'srcds_',
- 'csgo' => 'srcds_',
- 'samp' => 'samp',
- 'crmp' => 'samp',
- 'mta' => 'mta',
- 'mc' => 'java'
- );
+ public static $process = array(
+ 'cs' => 'hlds_',
+ 'cssold' => 'srcds_i686',
+ 'css' => 'srcds_',
+ 'csgo' => 'srcds_',
+ 'samp' => 'samp',
+ 'crmp' => 'samp',
+ 'mta' => 'mta',
+ 'mc' => 'java'
+ );
- public static $quakestat = array(
- 'cs' => 'a2s',
- 'cssold' => 'a2s',
- 'css' => 'a2s',
- 'csgo' => 'a2s',
- 'mta' => 'eye'
- );
+ public static $quakestat = array(
+ 'cs' => 'a2s',
+ 'cssold' => 'a2s',
+ 'css' => 'a2s',
+ 'csgo' => 'a2s',
+ 'mta' => 'eye'
+ );
- public static $admins_file = array(
- 'cs' => 'cstrike/addons/amxmodx/configs/users.ini',
- 'cssold' => 'cstrike/addons/sourcemod/configs/admins_simple.ini',
- 'css' => 'cstrike/addons/sourcemod/configs/admins_simple.ini',
- 'csgo' => 'csgo/addons/sourcemod/configs/admins_simple.ini'
- );
+ public static $admins_file = array(
+ 'cs' => 'cstrike/addons/amxmodx/configs/users.ini',
+ 'cssold' => 'cstrike/addons/sourcemod/configs/admins_simple.ini',
+ 'css' => 'cstrike/addons/sourcemod/configs/admins_simple.ini',
+ 'csgo' => 'csgo/addons/sourcemod/configs/admins_simple.ini'
+ );
- public static function thread($num, $type, $aData)
- {
- $threads = array();
+ public static function thread($num, $type, $aData)
+ {
+ $threads = array();
- for($n = 1; $n <= $num; $n+=1)
- {
- $data = '';
+ for($n = 1; $n <= $num; $n+=1)
+ {
+ $data = '';
- $i = 0;
+ $i = 0;
- foreach($aData as $key => $val)
- {
- if($i == cron::$seping)
- break;
+ foreach($aData as $key => $val)
+ {
+ if($i == cron::$seping)
+ break;
- $data .= $val.' ';
+ $data .= $val.' ';
- unset($aData[$key]);
+ unset($aData[$key]);
- $i+=1;
- }
+ $i+=1;
+ }
- $aData = array_values($aData);
+ $aData = array_values($aData);
- $threads[] = $type.' '.substr($data, 0, -1);
- }
+ $threads[] = $type.' '.substr($data, 0, -1);
+ }
- return $threads;
- }
- }
+ return $threads;
+ }
+ }
- include(CRON.$task.'.php');
+ include(CRON.$task.'.php');
- new $task();
+ new $task();
?>
\ No newline at end of file
diff --git a/system/library/cron/control_delete.php b/system/library/cron/control_delete.php
index 3adc903..a8b7d23 100644
--- a/system/library/cron/control_delete.php
+++ b/system/library/cron/control_delete.php
@@ -1,36 +1,36 @@
query('SELECT `id` FROM `control` WHERE `user`="-1" LIMIT 1');
+ $sql->query('SELECT `id` FROM `control` WHERE `user`="-1" LIMIT 1');
- if(!$sql->num())
- return NULL;
+ if(!$sql->num())
+ return NULL;
- $unit = $sql->get();
+ $unit = $sql->get();
- $servers = $sql->query('SELECT `id` FROM `control_servers` WHERE `unit`="'.$unit['id'].'"');
- while($server = $sql->get($servers))
- {
- $sql->query('DELETE FROM `control_admins_'.$server['game'].'` WHERE `server`="'.$server['id'].'"');
- $sql->query('DELETE FROM `control_copy` WHERE `server`="'.$server['id'].'"');
- $sql->query('DELETE FROM `control_firewall` WHERE `server`="'.$server['id'].'"');
- $sql->query('DELETE FROM `control_plugins_install` WHERE `server`="'.$server['id'].'"');
- }
+ $servers = $sql->query('SELECT `id` FROM `control_servers` WHERE `unit`="'.$unit['id'].'"');
+ while($server = $sql->get($servers))
+ {
+ $sql->query('DELETE FROM `control_admins_'.$server['game'].'` WHERE `server`="'.$server['id'].'"');
+ $sql->query('DELETE FROM `control_copy` WHERE `server`="'.$server['id'].'"');
+ $sql->query('DELETE FROM `control_firewall` WHERE `server`="'.$server['id'].'"');
+ $sql->query('DELETE FROM `control_plugins_install` WHERE `server`="'.$server['id'].'"');
+ }
- // Удаление различной информации игрового сервера
- $sql->query('DELETE FROM `control_servers` WHERE `unit`="'.$unit['id'].'"');
- $sql->query('DELETE FROM `control` WHERE `id`="'.$unit['id'].'"');
+ // Удаление различной информации игрового сервера
+ $sql->query('DELETE FROM `control_servers` WHERE `unit`="'.$unit['id'].'"');
+ $sql->query('DELETE FROM `control` WHERE `id`="'.$unit['id'].'"');
- $sql->query('INSERT INTO `logs_sys` set `user`="0", `control`="'.$unit['id'].'", `text`="Удаление подключенного сервера #'.$unit['id'].' ('.$unit['address'].') passwd: #'.$unit['passwd'].'", `time`="'.$start_point.'"');
+ $sql->query('INSERT INTO `logs_sys` set `user`="0", `control`="'.$unit['id'].'", `text`="Удаление подключенного сервера #'.$unit['id'].' ('.$unit['address'].') passwd: #'.$unit['passwd'].'", `time`="'.$start_point.'"');
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/cron/control_install.php b/system/library/cron/control_install.php
index ee0f604..9d07735 100644
--- a/system/library/cron/control_install.php
+++ b/system/library/cron/control_install.php
@@ -1,35 +1,35 @@
query('SELECT `id`, `address`, `passwd` FROM `control` WHERE `status`="install" AND `install`="0" LIMIT 1');
+ $sql->query('SELECT `id`, `address`, `passwd` FROM `control` WHERE `status`="install" AND `install`="0" LIMIT 1');
- if(!$sql->num())
- exit('not found');
+ if(!$sql->num())
+ exit('not found');
- $unit = $sql->get();
+ $unit = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- exit('error connect');
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ exit('error connect');
- $ssh->set('apt-get update; apt-get install -y wget screen');
+ $ssh->set('apt-get update; apt-get install -y wget screen');
- sleep(20);
+ sleep(20);
- $ssh->set('screen -dmS install bash -c "cd /tmp; rm script.sh; wget -O script.sh [home]autocontrol/action/script --no-check-certificate; chmod 500 script.sh;./script.sh"');
+ $ssh->set('screen -dmS install bash -c "cd /tmp; rm script.sh; wget -O script.sh [home]autocontrol/action/script --no-check-certificate; chmod 500 script.sh;./script.sh"');
- $sql->query('UPDATE `control` set install="1" WHERE `id`="'.$unit['id'].'" LIMIT 1');
+ $sql->query('UPDATE `control` set install="1" WHERE `id`="'.$unit['id'].'" LIMIT 1');
- exit('install');
- }
- }
+ exit('install');
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/cron/control_scan_servers.php b/system/library/cron/control_scan_servers.php
index 5657515..9a391d5 100644
--- a/system/library/cron/control_scan_servers.php
+++ b/system/library/cron/control_scan_servers.php
@@ -1,105 +1,105 @@
query('SELECT `address` FROM `control` WHERE `id`="'.$servers[4].'" LIMIT 1');
- if(!$sql->num())
- return NULL;
+ $sql->query('SELECT `address` FROM `control` WHERE `id`="'.$servers[4].'" LIMIT 1');
+ if(!$sql->num())
+ return NULL;
- $unit = $sql->get();
+ $unit = $sql->get();
- $game = $servers[3];
+ $game = $servers[3];
- unset($servers[3], $servers[4]);
+ unset($servers[3], $servers[4]);
- $sql->query('SELECT `unit` FROM `control_servers` WHERE `id`="'.$servers[5].'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `unit` FROM `control_servers` WHERE `id`="'.$servers[5].'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `address`, `passwd` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return NULL;
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return NULL;
- foreach($servers as $id)
- {
- $sql->query('SELECT `uid`, `address`, `status`, `stop` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ foreach($servers as $id)
+ {
+ $sql->query('SELECT `uid`, `address`, `status`, `stop` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- switch($server['status'])
- {
- case 'working': case 'change': case 'start': case 'restart':
- if(!sys::int($ssh->get('ps aux | grep s_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
- {
- $sql->query('UPDATE `control_servers` set `status`="off", `online`="0", `players`="0" WHERE `id`="'.$id.'" LIMIT 1');
+ switch($server['status'])
+ {
+ case 'working': case 'change': case 'start': case 'restart':
+ if(!sys::int($ssh->get('ps aux | grep s_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
+ {
+ $sql->query('UPDATE `control_servers` set `status`="off", `online`="0", `players`="0" WHERE `id`="'.$id.'" LIMIT 1');
- // Запуск сервера (если он был выключен не через панель)
- if($server['stop'])
- {
- exec('sh -c "cd /var/enginegp; php cron.php '.$cfg['cron_key'].' control_server_action start '.$game.' '.$id.'"');
+ // Запуск сервера (если он был выключен не через панель)
+ if($server['stop'])
+ {
+ exec('sh -c "cd /var/enginegp; php cron.php '.$cfg['cron_key'].' control_server_action start '.$game.' '.$id.'"');
- $sql->query('INSERT INTO `logs_sys` set `user`="0", `server`="'.$id.'", `text`="[Контроль] Включение сервера: сервер выключен не через панель", `time`="'.$start_point.'"');
- }
- }else
- exec('sh -c "cd /var/enginegp; php cron.php '.$cfg['cron_key'].' control_server_scan '.$game.' '.$id.'"');
+ $sql->query('INSERT INTO `logs_sys` set `user`="0", `server`="'.$id.'", `text`="[Контроль] Включение сервера: сервер выключен не через панель", `time`="'.$start_point.'"');
+ }
+ }else
+ exec('sh -c "cd /var/enginegp; php cron.php '.$cfg['cron_key'].' control_server_scan '.$game.' '.$id.'"');
- break;
+ break;
- case 'off':
- if(sys::int($ssh->get('ps aux | grep s_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
- $sql->query('UPDATE `control_servers` set `status`="working" WHERE `id`="'.$id.'" LIMIT 1');
- else{
- // Запуск сервера (если он был выключен не через панель)
- if($server['stop'])
- {
- exec('sh -c "cd /var/enginegp; php cron.php '.$cfg['cron_key'].' control_server_action start '.$game.' '.$id.'"');
+ case 'off':
+ if(sys::int($ssh->get('ps aux | grep s_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
+ $sql->query('UPDATE `control_servers` set `status`="working" WHERE `id`="'.$id.'" LIMIT 1');
+ else{
+ // Запуск сервера (если он был выключен не через панель)
+ if($server['stop'])
+ {
+ exec('sh -c "cd /var/enginegp; php cron.php '.$cfg['cron_key'].' control_server_action start '.$game.' '.$id.'"');
- $sql->query('INSERT INTO `logs_sys` set `user`="0", `server`="'.$id.'", `text`="[Контроль] Включение сервера: сервер выключен не через панель", `time`="'.$start_point.'"');
+ $sql->query('INSERT INTO `logs_sys` set `user`="0", `server`="'.$id.'", `text`="[Контроль] Включение сервера: сервер выключен не через панель", `time`="'.$start_point.'"');
- continue;
- }
- }
+ continue;
+ }
+ }
- break;
+ break;
- case 'reinstall':
- if(!sys::int($ssh->get('ps aux | grep r_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
- $sql->query('UPDATE `control_servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
+ case 'reinstall':
+ if(!sys::int($ssh->get('ps aux | grep r_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
+ $sql->query('UPDATE `control_servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
- break;
+ break;
- case 'update':
- if(!sys::int($ssh->get('ps aux | grep u_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
- $sql->query('UPDATE `control_servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
+ case 'update':
+ if(!sys::int($ssh->get('ps aux | grep u_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
+ $sql->query('UPDATE `control_servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
- break;
+ break;
- case 'install':
- if(!sys::int($ssh->get('ps aux | grep i_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
- $sql->query('UPDATE `control_servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
+ case 'install':
+ if(!sys::int($ssh->get('ps aux | grep i_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
+ $sql->query('UPDATE `control_servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
- break;
+ break;
- case 'recovery':
- if(!sys::int($ssh->get('ps aux | grep rec_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
- $sql->query('UPDATE `control_servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
- }
- }
+ case 'recovery':
+ if(!sys::int($ssh->get('ps aux | grep rec_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
+ $sql->query('UPDATE `control_servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
+ }
+ }
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/cron/control_scan_servers_admins.php b/system/library/cron/control_scan_servers_admins.php
index a9c64ed..1f76e19 100644
--- a/system/library/cron/control_scan_servers_admins.php
+++ b/system/library/cron/control_scan_servers_admins.php
@@ -1,68 +1,68 @@
query('SELECT `address` FROM `control` WHERE `id`="'.$servers[4].'" LIMIT 1');
- if(!$sql->num())
- return NULL;
+ $sql->query('SELECT `address` FROM `control` WHERE `id`="'.$servers[4].'" LIMIT 1');
+ if(!$sql->num())
+ return NULL;
- $unit = $sql->get();
+ $unit = $sql->get();
- unset($servers[3], $servers[4]);
+ unset($servers[3], $servers[4]);
- $sql->query('SELECT `unit` FROM `control_servers` WHERE `id`="'.$servers[5].'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `unit` FROM `control_servers` WHERE `id`="'.$servers[5].'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `address`, `passwd` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return NULL;
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return NULL;
- foreach($servers as $id)
- {
- $sql->query('SELECT `uid` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ foreach($servers as $id)
+ {
+ $sql->query('SELECT `uid` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- $admins = $sql->query('SELECT `id`, `text` FROM `control_admins_'.$game.'` WHERE `server`="'.$id.'" AND `active`="1" AND `time`<"'.$start_point.'"');
+ $admins = $sql->query('SELECT `id`, `text` FROM `control_admins_'.$game.'` WHERE `server`="'.$id.'" AND `active`="1" AND `time`<"'.$start_point.'"');
- if(!$sql->num($admins))
- continue;
+ if(!$sql->num($admins))
+ continue;
- $cmd = 'cd /servers/'.$server['uid'].';';
+ $cmd = 'cd /servers/'.$server['uid'].';';
- while($admin = $sql->get($admins))
- {
- $cmd .= 'sed -i -e \'s/'.escapeshellcmd(htmlspecialchars_decode($admin['text'])).'//g\' '.cron::$admins_file[$game].';';
+ while($admin = $sql->get($admins))
+ {
+ $cmd .= 'sed -i -e \'s/'.escapeshellcmd(htmlspecialchars_decode($admin['text'])).'//g\' '.cron::$admins_file[$game].';';
- $sql->query('UPDATE `admins_'.$game.'` set `active`="0" WHERE `id`="'.$admin['id'].'" LIMIT 1');
- }
+ $sql->query('UPDATE `admins_'.$game.'` set `active`="0" WHERE `id`="'.$admin['id'].'" LIMIT 1');
+ }
- $cmd .= 'sed -i '."'/./!d'".' '.cron::$admins_file[$game].'; echo -e "\n" >> '.cron::$admins_file[$game].';';
- $cmd .= 'chown server'.$server['uid'].':1000 '.cron::$admins_file[$game];
+ $cmd .= 'sed -i '."'/./!d'".' '.cron::$admins_file[$game].'; echo -e "\n" >> '.cron::$admins_file[$game].';';
+ $cmd .= 'chown server'.$server['uid'].':1000 '.cron::$admins_file[$game];
- $ssh->set($cmd);
- }
+ $ssh->set($cmd);
+ }
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/cron/control_scan_servers_copy.php b/system/library/cron/control_scan_servers_copy.php
index 9a643e3..423ad74 100644
--- a/system/library/cron/control_scan_servers_copy.php
+++ b/system/library/cron/control_scan_servers_copy.php
@@ -1,53 +1,53 @@
query('SELECT `address` FROM `control` WHERE `id`="'.$servers[4].'" LIMIT 1');
- if(!$sql->num())
- return NULL;
+ $sql->query('SELECT `address` FROM `control` WHERE `id`="'.$servers[4].'" LIMIT 1');
+ if(!$sql->num())
+ return NULL;
- $unit = $sql->get();
+ $unit = $sql->get();
- $game = $servers[3];
+ $game = $servers[3];
- unset($servers[3], $servers[4]);
+ unset($servers[3], $servers[4]);
- $sql->query('SELECT `unit` FROM `control_servers` WHERE `id`="'.$servers[5].'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `unit` FROM `control_servers` WHERE `id`="'.$servers[5].'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `address`, `passwd` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return NULL;
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return NULL;
- foreach($servers as $id)
- {
- $copys = $sql->query('SELECT `id` FROM `control_copy` WHERE `status`="0"');
- while($copy = $sql->get($copys))
- {
- $sql->query('SELECT `uid` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ foreach($servers as $id)
+ {
+ $copys = $sql->query('SELECT `id` FROM `control_copy` WHERE `status`="0"');
+ while($copy = $sql->get($copys))
+ {
+ $sql->query('SELECT `uid` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- if(!sys::int($ssh->get('ps aux | grep copy_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
- $sql->query('UPDATE `control_copy` set `status`="1" WHERE `id`="'.$copy['id'].'" LIMIT 1');
- }
- }
+ if(!sys::int($ssh->get('ps aux | grep copy_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
+ $sql->query('UPDATE `control_copy` set `status`="1" WHERE `id`="'.$copy['id'].'" LIMIT 1');
+ }
+ }
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/cron/control_scan_servers_down.php b/system/library/cron/control_scan_servers_down.php
index 6cdd074..d0b01fb 100644
--- a/system/library/cron/control_scan_servers_down.php
+++ b/system/library/cron/control_scan_servers_down.php
@@ -1,62 +1,62 @@
query('SELECT `address` FROM `control` WHERE `id`="'.$servers[4].'" LIMIT 1');
- if(!$sql->num())
- return NULL;
+ $sql->query('SELECT `address` FROM `control` WHERE `id`="'.$servers[4].'" LIMIT 1');
+ if(!$sql->num())
+ return NULL;
- $unit = $sql->get();
+ $unit = $sql->get();
- $game = $servers[3];
+ $game = $servers[3];
- if(!array_key_exists($game, cron::$quakestat))
- return NULL;
+ if(!array_key_exists($game, cron::$quakestat))
+ return NULL;
- unset($servers[3], $servers[4]);
+ unset($servers[3], $servers[4]);
- $sql->query('SELECT `unit` FROM `control_servers` WHERE `id`="'.$servers[5].'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `unit` FROM `control_servers` WHERE `id`="'.$servers[5].'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `address`, `passwd`, `ram` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd`, `ram` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return NULL;
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return NULL;
- foreach($servers as $id)
- {
- $sql->query('SELECT `uid`, `address`, `status`, `autorestart` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ foreach($servers as $id)
+ {
+ $sql->query('SELECT `uid`, `address`, `status`, `autorestart` FROM `control_servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- if(!$server['autorestart'])
- continue;
+ if(!$server['autorestart'])
+ continue;
- if($server['status'] != 'working')
- continue;
+ if($server['status'] != 'working')
+ continue;
- if(!in_array(trim($ssh->get('quakestat -'.(cron::$quakestat[$game]).' '.$server['address'].' -retry 5 -interval 2 | grep -v frags | tail -1 | awk \'{print $2}\'')), array('DOWN', 'no')))
- continue;
+ if(!in_array(trim($ssh->get('quakestat -'.(cron::$quakestat[$game]).' '.$server['address'].' -retry 5 -interval 2 | grep -v frags | tail -1 | awk \'{print $2}\'')), array('DOWN', 'no')))
+ continue;
- exec('sh -c "cd /var/enginegp; php cron.php '.$cfg['cron_key'].' control_server_action restart '.$game.' '.$id.'"');
+ exec('sh -c "cd /var/enginegp; php cron.php '.$cfg['cron_key'].' control_server_action restart '.$game.' '.$id.'"');
- $sql->query('INSERT INTO `logs_sys` set `user`="0", `server`="'.$id.'", `text`="[Контроль] Перезагрука сервера: сервер завис", `time`="'.$start_point.'"');
- }
+ $sql->query('INSERT INTO `logs_sys` set `user`="0", `server`="'.$id.'", `text`="[Контроль] Перезагрука сервера: сервер завис", `time`="'.$start_point.'"');
+ }
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/cron/control_scan_servers_route.php b/system/library/cron/control_scan_servers_route.php
index 2822cfa..6f7e7e5 100644
--- a/system/library/cron/control_scan_servers_route.php
+++ b/system/library/cron/control_scan_servers_route.php
@@ -1,104 +1,104 @@
query('SELECT `address` FROM `control` WHERE `id`="'.$servers[4].'" LIMIT 1');
- if(!$sql->num())
- return NULL;
+ $sql->query('SELECT `address` FROM `control` WHERE `id`="'.$servers[4].'" LIMIT 1');
+ if(!$sql->num())
+ return NULL;
- $unit = $sql->get();
+ $unit = $sql->get();
- $game = $servers[3];
+ $game = $servers[3];
- unset($servers[3], $servers[4]);
+ unset($servers[3], $servers[4]);
- $sql->query('SELECT `unit` FROM `control_servers` WHERE `id`="'.$servers[5].'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `unit` FROM `control_servers` WHERE `id`="'.$servers[5].'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `address`, `passwd`, `fcpu` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd`, `fcpu` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return NULL;
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return NULL;
- $first = $ssh->get('cat /proc/stat');
+ $first = $ssh->get('cat /proc/stat');
- sleep(1);
+ sleep(1);
- $aCpu = sys::cpu_idle(array($first, $ssh->get('cat /proc/stat')), $unit['fcpu'], true);
+ $aCpu = sys::cpu_idle(array($first, $ssh->get('cat /proc/stat')), $unit['fcpu'], true);
- array_shift($aCpu);
+ array_shift($aCpu);
- $idle = array();
- $uses = array();
+ $idle = array();
+ $uses = array();
- foreach($aCpu as $cpu => $data)
- {
- $core = sys::int($cpu)+1;
+ foreach($aCpu as $cpu => $data)
+ {
+ $core = sys::int($cpu)+1;
- $sql->query('SELECT `id` FROM `control_servers` WHERE `unit`="'.$server['unit'].'" AND `core_fix`="'.$core.'" AND `core_fix`="1" LIMIT 1');
- if($sql->num())
- {
- unset($aCpu[$cpu]);
+ $sql->query('SELECT `id` FROM `control_servers` WHERE `unit`="'.$server['unit'].'" AND `core_fix`="'.$core.'" AND `core_fix`="1" LIMIT 1');
+ if($sql->num())
+ {
+ unset($aCpu[$cpu]);
- continue;
- }
+ continue;
+ }
- if($data['idle'] > 50)
- $idle[$core] = $data['idle'];
- else
- $uses[$core] = 100-$data['idle'];
- }
+ if($data['idle'] > 50)
+ $idle[$core] = $data['idle'];
+ else
+ $uses[$core] = 100-$data['idle'];
+ }
- if(!count($idle))
- return NULL;
+ if(!count($idle))
+ return NULL;
- foreach($uses as $use_core => $use)
- {
- if(!count($idle))
- break;
+ foreach($uses as $use_core => $use)
+ {
+ if(!count($idle))
+ break;
- $sql->query('SELECT `id`, `uid` FROM `control_servers` WHERE `unit`="'.$server['unit'].'" AND `game`="'.$game.'" AND `core_use`="'.$use_core.'" AND `status`="working" AND `core_fix`="0" ORDER BY `slots_start` DESC, `online` DESC LIMIT 3');
- if($sql->num() > 1)
- {
- $server = $sql->get();
+ $sql->query('SELECT `id`, `uid` FROM `control_servers` WHERE `unit`="'.$server['unit'].'" AND `game`="'.$game.'" AND `core_use`="'.$use_core.'" AND `status`="working" AND `core_fix`="0" ORDER BY `slots_start` DESC, `online` DESC LIMIT 3');
+ if($sql->num() > 1)
+ {
+ $server = $sql->get();
- $core = array_search(max($idle), $idle);
+ $core = array_search(max($idle), $idle);
- $aPid = explode("\n", $ssh->get('ps aux | grep -v grep | grep '.$server['uid'].' | awk \'{print $2}\''));
+ $aPid = explode("\n", $ssh->get('ps aux | grep -v grep | grep '.$server['uid'].' | awk \'{print $2}\''));
- if(count($aPid) < 2)
- continue;
+ if(count($aPid) < 2)
+ continue;
- array_pop($aPid);
+ array_pop($aPid);
- $taskset = '';
+ $taskset = '';
- foreach($aPid as $pid)
- $taskset .= 'taskset -cp '.($core-1).' '.$pid.';';
+ foreach($aPid as $pid)
+ $taskset .= 'taskset -cp '.($core-1).' '.$pid.';';
- $ssh->set($taskset);
+ $ssh->set($taskset);
- unset($idle[$core]);
+ unset($idle[$core]);
- $sql->query('UPDATE `control_servers` set `core_use`="'.$core.'" WHERE `id`="'.$server['id'].'" LIMIT 1');
- }
- }
+ $sql->query('UPDATE `control_servers` set `core_use`="'.$core.'" WHERE `id`="'.$server['id'].'" LIMIT 1');
+ }
+ }
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/cron/control_server_action.php b/system/library/cron/control_server_action.php
index 4582fdc..748cd95 100644
--- a/system/library/cron/control_server_action.php
+++ b/system/library/cron/control_server_action.php
@@ -1,55 +1,55 @@
get($nmch))
- return NULL;
+ if($mcache->get($nmch))
+ return NULL;
- $mcache->set($nmch, true, false, 10);
+ $mcache->set($nmch, true, false, 10);
- if($argv[3] == 'console')
- {
- global $sql;
+ if($argv[3] == 'console')
+ {
+ global $sql;
- $sql->query('SELECT `uid`, `unit` FROM `control_servers` WHERE `id`="'.$argv[5].'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `uid`, `unit` FROM `control_servers` WHERE `id`="'.$argv[5].'" LIMIT 1');
+ $server = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- $sql->query('SELECT `address`, `passwd` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd` FROM `control` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return NULL;
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return NULL;
- $sql->query('SELECT `commands` FROM `control_crontab` WHERE `id`="'.$argv[6].'" LIMIT 1');
- $cron = $sql->get();
+ $sql->query('SELECT `commands` FROM `control_crontab` WHERE `id`="'.$argv[6].'" LIMIT 1');
+ $cron = $sql->get();
- $aCmd = explode("\n", base64_decode($cron['commands']));
+ $aCmd = explode("\n", base64_decode($cron['commands']));
- foreach($aCmd as $cmd)
- $ssh->set('sudo -u server'.$server['uid'].' screen -p 0 -S s_'.$server['uid'].' -X eval \'stuff "'.sys::cmd($cmd).'"\015\'; sudo -u server'.$server['uid'].' screen -p 0 -S s_'.$server['uid'].' -X eval \'stuff \015\'');
+ foreach($aCmd as $cmd)
+ $ssh->set('sudo -u server'.$server['uid'].' screen -p 0 -S s_'.$server['uid'].' -X eval \'stuff "'.sys::cmd($cmd).'"\015\'; sudo -u server'.$server['uid'].' screen -p 0 -S s_'.$server['uid'].' -X eval \'stuff \015\'');
- return NULL;
- }
+ return NULL;
+ }
- include(LIB.'control/'.$argv[4].'/action.php');
+ include(LIB.'control/'.$argv[4].'/action.php');
- if($argv[3] == 'restart')
- action::start($argv[5], 'restart');
- else
- action::$argv[3]($argv[5]);
+ if($argv[3] == 'restart')
+ action::start($argv[5], 'restart');
+ else
+ action::$argv[3]($argv[5]);
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/cron/control_server_cron.php b/system/library/cron/control_server_cron.php
index 89aa18a..cc48c45 100644
--- a/system/library/cron/control_server_cron.php
+++ b/system/library/cron/control_server_cron.php
@@ -1,24 +1,24 @@
query('SELECT `game` FROM `control_servers` WHERE `id`="'.$argv[3].'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `game` FROM `control_servers` WHERE `id`="'.$argv[3].'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `task` FROM `control_crontab` WHERE `id`="'.$argv[4].'" LIMIT 1');
- $cron = $sql->get();
+ $sql->query('SELECT `task` FROM `control_crontab` WHERE `id`="'.$argv[4].'" LIMIT 1');
+ $cron = $sql->get();
- $cmd = $cron['task'] == 'console' ? ' '.$argv[4] : '';
+ $cmd = $cron['task'] == 'console' ? ' '.$argv[4] : '';
- exec('sh -c "cd /var/enginegp; php cron.php '.$cfg['cron_key'].' control_server_action '.$cron['task'].' '.$server['game'].' '.$argv[3].$cmd.'"');
+ exec('sh -c "cd /var/enginegp; php cron.php '.$cfg['cron_key'].' control_server_action '.$cron['task'].' '.$server['game'].' '.$argv[3].$cmd.'"');
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/cron/control_server_scan.php b/system/library/cron/control_server_scan.php
index 9dd6439..7d3efa0 100644
--- a/system/library/cron/control_server_scan.php
+++ b/system/library/cron/control_server_scan.php
@@ -1,19 +1,19 @@
\ No newline at end of file
diff --git a/system/library/cron/control_threads.php b/system/library/cron/control_threads.php
index 24fce18..9af8c7a 100644
--- a/system/library/cron/control_threads.php
+++ b/system/library/cron/control_threads.php
@@ -1,63 +1,63 @@
query('SELECT `id` FROM `control` ORDER BY `id` ASC');
+ $aUnit = array();
+ $sql->query('SELECT `id` FROM `control` ORDER BY `id` ASC');
- if(!$sql->num())
- return NULL;
+ if(!$sql->num())
+ return NULL;
- while($unit = $sql->get())
- $aUnit[$unit['id']] = '';
+ while($unit = $sql->get())
+ $aUnit[$unit['id']] = '';
- $sql->query('SELECT `id` FROM `control_servers` LIMIT 1');
+ $sql->query('SELECT `id` FROM `control_servers` LIMIT 1');
- if(!$sql->num())
- return NULL;
+ if(!$sql->num())
+ return NULL;
- $sql->query('SELECT `id`, `unit`, `game` FROM `control_servers` ORDER BY `unit` DESC');
+ $sql->query('SELECT `id`, `unit`, `game` FROM `control_servers` ORDER BY `unit` DESC');
- $all = $sql->num();
+ $all = $sql->num();
- while($server = $sql->get())
- $aUnit[$server['unit']][$server['game']] .= $server['id'].' ';
+ while($server = $sql->get())
+ $aUnit[$server['unit']][$server['game']] .= $server['id'].' ';
- if($argv[3] == 'control_scan_servers_route')
- cron::$seping = 50;
+ if($argv[3] == 'control_scan_servers_route')
+ cron::$seping = 50;
- foreach($aUnit as $unit => $aGame)
- {
- foreach($aGame as $game => $servers)
- {
- $aData = explode(' ', $servers);
+ foreach($aUnit as $unit => $aGame)
+ {
+ foreach($aGame as $game => $servers)
+ {
+ $aData = explode(' ', $servers);
- $num = count($aData)-1;
- $sep = $num > 0 ? ceil($num/cron::$seping) : 1;
+ $num = count($aData)-1;
+ $sep = $num > 0 ? ceil($num/cron::$seping) : 1;
- unset($aData[end($aData)]);
+ unset($aData[end($aData)]);
- $threads[] = cron::thread($sep, $game.' '.$unit, $aData);
- }
- }
+ $threads[] = cron::thread($sep, $game.' '.$unit, $aData);
+ }
+ }
- $cmd = '';
+ $cmd = '';
- foreach($threads as $thread)
- {
- foreach($thread as $screen => $servers)
- $cmd .= 'sudo -u www-data screen -dmS scan_'.(sys::first(explode(' ', $servers))).'_'.$screen.' taskset -c '.$cfg['cron_taskset'].' sh -c \"cd /var/enginegp; php cron.php '.$cfg['cron_key'].' '.$argv[3].' '.$servers.'\"; sleep 1;';
- }
+ foreach($threads as $thread)
+ {
+ foreach($thread as $screen => $servers)
+ $cmd .= 'sudo -u www-data screen -dmS scan_'.(sys::first(explode(' ', $servers))).'_'.$screen.' taskset -c '.$cfg['cron_taskset'].' sh -c \"cd /var/enginegp; php cron.php '.$cfg['cron_key'].' '.$argv[3].' '.$servers.'\"; sleep 1;';
+ }
- exec('screen -dmS control_threads_'.date('His', $start_point).' sh -c "'.$cmd.'"');
+ exec('screen -dmS control_threads_'.date('His', $start_point).' sh -c "'.$cmd.'"');
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/cron/graph_servers_day.php b/system/library/cron/graph_servers_day.php
index edf1fe6..1058036 100644
--- a/system/library/cron/graph_servers_day.php
+++ b/system/library/cron/graph_servers_day.php
@@ -1,50 +1,50 @@
query('SELECT `id`, `date` FROM `servers` ORDER BY `id` ASC');
+ $servers = $sql->query('SELECT `id`, `date` FROM `servers` ORDER BY `id` ASC');
- while($server = $sql->get($servers))
- {
- if($server['date']+86400 > $start_point)
- continue;
+ while($server = $sql->get($servers))
+ {
+ if($server['date']+86400 > $start_point)
+ continue;
- $aGraph = array('online' => 0, 'cpu' => 0, 'ram' => 0, 'hdd' => 0, 'time' => 0);
+ $aGraph = array('online' => 0, 'cpu' => 0, 'ram' => 0, 'hdd' => 0, 'time' => 0);
- $sql->query('SELECT `online`, `cpu`, `ram`, `hdd` FROM `graph_hour` WHERE `server`="'.$server['id'].'" AND `time`>"'.($start_point-86400).'" ORDER BY `id` DESC LIMIT 24');
+ $sql->query('SELECT `online`, `cpu`, `ram`, `hdd` FROM `graph_hour` WHERE `server`="'.$server['id'].'" AND `time`>"'.($start_point-86400).'" ORDER BY `id` DESC LIMIT 24');
- $n = $sql->num();
+ $n = $sql->num();
- if(!$n)
- continue;
+ if(!$n)
+ continue;
- while($graph = $sql->get())
- {
- $aGraph['online'] += $graph['online'];
- $aGraph['cpu'] += $graph['cpu'];
- $aGraph['ram'] += $graph['ram'];
- $aGraph['hdd'] += $graph['hdd'];
- }
+ while($graph = $sql->get())
+ {
+ $aGraph['online'] += $graph['online'];
+ $aGraph['cpu'] += $graph['cpu'];
+ $aGraph['ram'] += $graph['ram'];
+ $aGraph['hdd'] += $graph['hdd'];
+ }
- $aGraph['online'] = $aGraph['online']/$n;
- $aGraph['cpu'] = $aGraph['cpu']/$n;
- $aGraph['ram'] = $aGraph['ram']/$n;
- $aGraph['hdd'] = $aGraph['hdd']/$n;
+ $aGraph['online'] = $aGraph['online']/$n;
+ $aGraph['cpu'] = $aGraph['cpu']/$n;
+ $aGraph['ram'] = $aGraph['ram']/$n;
+ $aGraph['hdd'] = $aGraph['hdd']/$n;
- $sql->query('INSERT INTO `graph_day` set `server`="'.$server['id'].'",'
- .'`online`="'.$aGraph['online'].'",'
- .'`cpu`="'.$aGraph['cpu'].'",'
- .'`ram`="'.$aGraph['ram'].'",'
- .'`hdd`="'.$aGraph['hdd'].'", `time`="'.$start_point.'"');
- }
+ $sql->query('INSERT INTO `graph_day` set `server`="'.$server['id'].'",'
+ .'`online`="'.$aGraph['online'].'",'
+ .'`cpu`="'.$aGraph['cpu'].'",'
+ .'`ram`="'.$aGraph['ram'].'",'
+ .'`hdd`="'.$aGraph['hdd'].'", `time`="'.$start_point.'"');
+ }
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/cron/graph_servers_hour.php b/system/library/cron/graph_servers_hour.php
index 06cc145..3c07b56 100644
--- a/system/library/cron/graph_servers_hour.php
+++ b/system/library/cron/graph_servers_hour.php
@@ -1,28 +1,28 @@
query('SELECT `id`, `online`, `ram_use`, `cpu_use`, `hdd_use`, `date` FROM `servers` ORDER BY `id` ASC');
+ $servers = $sql->query('SELECT `id`, `online`, `ram_use`, `cpu_use`, `hdd_use`, `date` FROM `servers` ORDER BY `id` ASC');
- while($server = $sql->get($servers))
- {
- if($server['date']+3600 > $start_point)
- continue;
+ while($server = $sql->get($servers))
+ {
+ if($server['date']+3600 > $start_point)
+ continue;
- $sql->query('INSERT INTO `graph_hour` set `server`="'.$server['id'].'",'
- .'`online`="'.$server['online'].'",'
- .'`cpu`="'.$server['cpu_use'].'",'
- .'`ram`="'.$server['ram_use'].'",'
- .'`hdd`="'.$server['hdd_use'].'", `time`="'.$start_point.'"');
- }
+ $sql->query('INSERT INTO `graph_hour` set `server`="'.$server['id'].'",'
+ .'`online`="'.$server['online'].'",'
+ .'`cpu`="'.$server['cpu_use'].'",'
+ .'`ram`="'.$server['ram_use'].'",'
+ .'`hdd`="'.$server['hdd_use'].'", `time`="'.$start_point.'"');
+ }
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/cron/notice_help.php b/system/library/cron/notice_help.php
index 6b5065f..f1457db 100644
--- a/system/library/cron/notice_help.php
+++ b/system/library/cron/notice_help.php
@@ -1,32 +1,32 @@
query('SELECT `id`, `user`, `time` FROM `help` WHERE `status`="0" AND `time`<"'.$time.'" AND `notice`="0" AND `close`="0"');
- while($help = $sql->get($helps))
- {
- $sql->query('SELECT `mail` FROM `users` WHERE `id`="'.$help['user'].'" AND `time`<"'.$help['time'].'" AND `notice_help`="1" LIMIT 1');
+ $helps = $sql->query('SELECT `id`, `user`, `time` FROM `help` WHERE `status`="0" AND `time`<"'.$time.'" AND `notice`="0" AND `close`="0"');
+ while($help = $sql->get($helps))
+ {
+ $sql->query('SELECT `mail` FROM `users` WHERE `id`="'.$help['user'].'" AND `time`<"'.$help['time'].'" AND `notice_help`="1" LIMIT 1');
- if(!$sql->num())
- continue;
+ if(!$sql->num())
+ continue;
- $user = $sql->get();
+ $user = $sql->get();
- if(!sys::mail('Техническая поддержка', sys::updtext(sys::text('mail', 'notice_help'), array('site' => $cfg['name'], 'url' => $cfg['http'].'help/section/dialog/id/'.$help['id'])), $user['mail']))
- continue;
+ if(!sys::mail('Техническая поддержка', sys::updtext(sys::text('mail', 'notice_help'), array('site' => $cfg['name'], 'url' => $cfg['http'].'help/section/dialog/id/'.$help['id'])), $user['mail']))
+ continue;
- $sql->query('UPDATE `help` set `notice`="1" WHERE `id`="'.$help['id'].'" LIMIT 1');
- }
+ $sql->query('UPDATE `help` set `notice`="1" WHERE `id`="'.$help['id'].'" LIMIT 1');
+ }
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/cron/notice_help_admin.php b/system/library/cron/notice_help_admin.php
index 26e391c..581b06c 100644
--- a/system/library/cron/notice_help_admin.php
+++ b/system/library/cron/notice_help_admin.php
@@ -1,37 +1,37 @@
query('SELECT `id`, `time`, `notice_admin` FROM `help` WHERE (`notice_admin`="0" OR `notice_admin`="2") AND `close`="0" LIMIT 1');
- if(!$sql->num())
- return NULL;
+ $sql->query('SELECT `id`, `time`, `notice_admin` FROM `help` WHERE (`notice_admin`="0" OR `notice_admin`="2") AND `close`="0" LIMIT 1');
+ if(!$sql->num())
+ return NULL;
- $help = $sql->get();
+ $help = $sql->get();
- foreach($cfg['notice_admin'] as $id)
- {
- $sql->query('SELECT `mail` FROM `users` WHERE `id`="'.$id.'" LIMIT 1');
- $admin = $sql->get();
+ foreach($cfg['notice_admin'] as $id)
+ {
+ $sql->query('SELECT `mail` FROM `users` WHERE `id`="'.$id.'" LIMIT 1');
+ $admin = $sql->get();
- if($help['notice_admin'] != 2)
- {
- if(!sys::mail('Техническая поддержка', sys::updtext(sys::text('mail', 'notice_help_admin_new'), array('url' => $cfg['http'].'help/section/dialog/id/'.$help['id'])), $admin['mail']))
- continue;
- }else{
- if(!sys::mail('Техническая поддержка', sys::updtext(sys::text('mail', 'notice_help_admin'), array('url' => $cfg['http'].'help/section/dialog/id/'.$help['id'])), $admin['mail']))
- continue;
- }
- }
+ if($help['notice_admin'] != 2)
+ {
+ if(!sys::mail('Техническая поддержка', sys::updtext(sys::text('mail', 'notice_help_admin_new'), array('url' => $cfg['http'].'help/section/dialog/id/'.$help['id'])), $admin['mail']))
+ continue;
+ }else{
+ if(!sys::mail('Техническая поддержка', sys::updtext(sys::text('mail', 'notice_help_admin'), array('url' => $cfg['http'].'help/section/dialog/id/'.$help['id'])), $admin['mail']))
+ continue;
+ }
+ }
- $sql->query('UPDATE `help` set `notice_admin`="1" WHERE `id`="'.$help['id'].'" LIMIT 1');
+ $sql->query('UPDATE `help` set `notice_admin`="1" WHERE `id`="'.$help['id'].'" LIMIT 1');
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/cron/notice_server_overdue.php b/system/library/cron/notice_server_overdue.php
index ca3e4c0..ba0407f 100644
--- a/system/library/cron/notice_server_overdue.php
+++ b/system/library/cron/notice_server_overdue.php
@@ -1,30 +1,30 @@
query('SELECT `id`, `user`, `address` FROM `servers` WHERE `time`<"'.$start_point.'" AND `mail`="0"');
- while($server = $sql->get($servers))
- {
- $sql->query('SELECT `mail` FROM `users` WHERE `id`="'.$server['user'].'" LIMIT 1');
- $user = $sql->get();
+ $servers = $sql->query('SELECT `id`, `user`, `address` FROM `servers` WHERE `time`<"'.$start_point.'" AND `mail`="0"');
+ while($server = $sql->get($servers))
+ {
+ $sql->query('SELECT `mail` FROM `users` WHERE `id`="'.$server['user'].'" LIMIT 1');
+ $user = $sql->get();
- if(!sys::mail('Аренда сервера', sys::updtext(sys::text('mail', 'notice_server_overdue'), array('site' => $cfg['name'], 'id' => $server['id'], 'address' => $server['address'])), $user['mail']))
- continue;
+ if(!sys::mail('Аренда сервера', sys::updtext(sys::text('mail', 'notice_server_overdue'), array('site' => $cfg['name'], 'id' => $server['id'], 'address' => $server['address'])), $user['mail']))
+ continue;
- $sql->query('UPDATE `servers` set `mail`="1" WHERE `id`="'.$server['id'].'" LIMIT 1');
- }
+ $sql->query('UPDATE `servers` set `mail`="1" WHERE `id`="'.$server['id'].'" LIMIT 1');
+ }
- $servers = $sql->query('SELECT `id` FROM `servers` WHERE `time`>"'.$start_point.'" AND `mail`="1"');
- while($server = $sql->get($servers))
- $sql->query('UPDATE `servers` set `mail`="0" WHERE `id`="'.$server['id'].'" LIMIT 1');
+ $servers = $sql->query('SELECT `id` FROM `servers` WHERE `time`>"'.$start_point.'" AND `mail`="1"');
+ while($server = $sql->get($servers))
+ $sql->query('UPDATE `servers` set `mail`="0" WHERE `id`="'.$server['id'].'" LIMIT 1');
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/cron/preparing_web_delete.php b/system/library/cron/preparing_web_delete.php
index 73e240f..e7b8d1d 100644
--- a/system/library/cron/preparing_web_delete.php
+++ b/system/library/cron/preparing_web_delete.php
@@ -1,18 +1,18 @@
query('SELECT `id` FROM `web` WHERE `user`="0"');
- while($web = $sql->get())
- exec('sh -c "cd /var/enginegp; php cron.php '.$cfg['cron_key'].' web_delete '.$web['id'].'"');
+ $sql->query('SELECT `id` FROM `web` WHERE `user`="0"');
+ while($web = $sql->get())
+ exec('sh -c "cd /var/enginegp; php cron.php '.$cfg['cron_key'].' web_delete '.$web['id'].'"');
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/cron/privileges.php b/system/library/cron/privileges.php
index df716cc..5348300 100644
--- a/system/library/cron/privileges.php
+++ b/system/library/cron/privileges.php
@@ -1,99 +1,99 @@
query('SELECT `address` FROM `units` WHERE `id`="'.$servers[4].'" LIMIT 1');
- if(!$sql->num())
- return ': UNIT#'.$servers[4].' .';
+ $sql->query('SELECT `address` FROM `units` WHERE `id`="'.$servers[4].'" LIMIT 1');
+ if(!$sql->num())
+ return ': UNIT#'.$servers[4].' .';
- $unit = $sql->get();
+ $unit = $sql->get();
- unset($servers[3], $servers[4]);
+ unset($servers[3], $servers[4]);
- foreach($servers as $i => $id)
- {
- $sql->query('SELECT `id` FROM `privileges_buy` WHERE `server`="'.$id.'" AND `status`="1" LIMIT 1');
- if(!$sql->num())
- unset($servers[$i]);
- }
+ foreach($servers as $i => $id)
+ {
+ $sql->query('SELECT `id` FROM `privileges_buy` WHERE `server`="'.$id.'" AND `status`="1" LIMIT 1');
+ if(!$sql->num())
+ unset($servers[$i]);
+ }
- if(!count($servers))
- return NULL;
+ if(!count($servers))
+ return NULL;
- $sql->query('SELECT `unit` FROM `servers` WHERE `id`="'.end($servers).'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `unit` FROM `servers` WHERE `id`="'.end($servers).'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- // ssh
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return ': UNIT#'.$server['unit'].' .';
+ // ssh
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return ': UNIT#'.$server['unit'].' .';
- $time = $start_point-172800;
+ $time = $start_point-172800;
- foreach($servers as $id)
- {
- $sql->query('DELETE FROM `privileges_buy` WHERE `date`<"'.$time.'" AND status`="0" LIMIT 5');
+ foreach($servers as $id)
+ {
+ $sql->query('DELETE FROM `privileges_buy` WHERE `date`<"'.$time.'" AND status`="0" LIMIT 5');
- $aMail = array();
+ $aMail = array();
- $sql->query('SELECT `uid`, `tarif` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `uid`, `tarif` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
- $tarif = $sql->get();
+ $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
+ $tarif = $sql->get();
- $file = $tarif['install'].$server['uid'].'/'.cron::$admins_file[$game];
+ $file = $tarif['install'].$server['uid'].'/'.cron::$admins_file[$game];
- $text = $ssh->get('cat '.$file);
+ $text = $ssh->get('cat '.$file);
- $privileges = $sql->query('SELECT `id`, `text`, `sql`, `mail` FROM `privileges_buy` WHERE `server`="'.$id.'" AND `status`="1" LIMIT 3');
- while($privilege = $sql->get($privileges))
- {
- $text .= base64_decode($privilege['text']).PHP_EOL;
+ $privileges = $sql->query('SELECT `id`, `text`, `sql`, `mail` FROM `privileges_buy` WHERE `server`="'.$id.'" AND `status`="1" LIMIT 3');
+ while($privilege = $sql->get($privileges))
+ {
+ $text .= base64_decode($privilege['text']).PHP_EOL;
- $sql->query(base64_decode($privilege['sql']));
- $sql->query('DELETE FROM `privileges_buy` WHERE `id`="'.$privilege['id'].'" LIMIT 1');
+ $sql->query(base64_decode($privilege['sql']));
+ $sql->query('DELETE FROM `privileges_buy` WHERE `id`="'.$privilege['id'].'" LIMIT 1');
- $aMail[] = $privilege['mail'];
- }
+ $aMail[] = $privilege['mail'];
+ }
- $temp = sys::temp($text);
+ $temp = sys::temp($text);
- $ssh->setfile($temp, $file, 0644);
+ $ssh->setfile($temp, $file, 0644);
- unlink($temp);
+ unlink($temp);
- $cmd = $game == 'cs' ? 'amx_reloadadmins' : 'sm_reloadadmins';
+ $cmd = $game == 'cs' ? 'amx_reloadadmins' : 'sm_reloadadmins';
- $ssh->set('chown server'.$server['uid'].':servers '.$file);
- $ssh->set("sudo -u server".$server['uid']." screen -p 0 -S s_".$server['uid']." -X eval 'stuff \"".$cmd."\"\015'");
+ $ssh->set('chown server'.$server['uid'].':servers '.$file);
+ $ssh->set("sudo -u server".$server['uid']." screen -p 0 -S s_".$server['uid']." -X eval 'stuff \"".$cmd."\"\015'");
- foreach($aMail as $mail)
- sys::mail(' ', sys::text('mail', 'success_privilege'), $mail);
+ foreach($aMail as $mail)
+ sys::mail(' ', sys::text('mail', 'success_privilege'), $mail);
- echo 'server#'.$id.' ('.$game.') -> add privileges '.PHP_EOL;
- }
+ echo 'server#'.$id.' ('.$game.') -> add privileges '.PHP_EOL;
+ }
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/cron/scan_control.php b/system/library/cron/scan_control.php
index 583a21c..e588827 100644
--- a/system/library/cron/scan_control.php
+++ b/system/library/cron/scan_control.php
@@ -1,21 +1,21 @@
query('SELECT `id` FROM `control` ORDER BY `id` ASC');
- while($ctrl = $sql->get())
- ctrl::update_status($ctrl['id'], $ssh);
+ $sql->query('SELECT `id` FROM `control` ORDER BY `id` ASC');
+ while($ctrl = $sql->get())
+ ctrl::update_status($ctrl['id'], $ssh);
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/cron/scan_servers.php b/system/library/cron/scan_servers.php
index 3836246..8d2346e 100644
--- a/system/library/cron/scan_servers.php
+++ b/system/library/cron/scan_servers.php
@@ -1,145 +1,145 @@
query('SELECT `address`, `sql_login`, `sql_passwd`, `sql_port`, `sql_ftp` FROM `units` WHERE `id`="'.$servers[4].'" LIMIT 1');
- if(!$sql->num())
- return NULL;
+ $sql->query('SELECT `address`, `sql_login`, `sql_passwd`, `sql_port`, `sql_ftp` FROM `units` WHERE `id`="'.$servers[4].'" LIMIT 1');
+ if(!$sql->num())
+ return NULL;
- $unit = $sql->get();
+ $unit = $sql->get();
- $game = $servers[3];
+ $game = $servers[3];
- unset($servers[3], $servers[4]);
+ unset($servers[3], $servers[4]);
- $sql->query('SELECT `unit` FROM `servers` WHERE `id`="'.$servers[5].'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `unit` FROM `servers` WHERE `id`="'.$servers[5].'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return NULL;
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return NULL;
- foreach($servers as $id)
- {
- $sql->query('SELECT `user`, `uid`, `address`, `status`, `time`, `overdue`, `ftp`, `stop`, `block` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ foreach($servers as $id)
+ {
+ $sql->query('SELECT `user`, `uid`, `address`, `status`, `time`, `overdue`, `ftp`, `stop`, `block` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- // Если аренда не закончилась, а сервер просрочен
- if($server['time'] > $start_point && $server['status'] == 'overdue')
- {
- $sql->query('UPDATE `servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
+ // Если аренда не закончилась, а сервер просрочен
+ if($server['time'] > $start_point && $server['status'] == 'overdue')
+ {
+ $sql->query('UPDATE `servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
- continue;
- }
+ continue;
+ }
- // Если аренда закончилась, а сервер не просрочен (и не заблокирован)
- if($server['time'] < $start_point && !in_array($server['status'], array('overdue', 'blocked')))
- {
- // Убить процессы
- $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
- .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
+ // Если аренда закончилась, а сервер не просрочен (и не заблокирован)
+ if($server['time'] < $start_point && !in_array($server['status'], array('overdue', 'blocked')))
+ {
+ // Убить процессы
+ $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
+ .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
- if($server['ftp'])
- $ssh->set("mysql -P ".$unit['sql_port']." -u".$unit['sql_login']." -p".$unit['sql_passwd']." --database ".$unit['sql_ftp']." -e \"DELETE FROM ftp WHERE user='".$server['uid']."'\"");
+ if($server['ftp'])
+ $ssh->set("mysql -P ".$unit['sql_port']." -u".$unit['sql_login']." -p".$unit['sql_passwd']." --database ".$unit['sql_ftp']." -e \"DELETE FROM ftp WHERE user='".$server['uid']."'\"");
- $sql->query('UPDATE `servers` set `status`="overdue", `online`="0", `players`="", `ftp`="0", `overdue`="'.$start_point.'" WHERE `id`="'.$id.'" LIMIT 1');
+ $sql->query('UPDATE `servers` set `status`="overdue", `online`="0", `players`="", `ftp`="0", `overdue`="'.$start_point.'" WHERE `id`="'.$id.'" LIMIT 1');
- continue;
- }
+ continue;
+ }
- // Если аренда закончилась и сервер просрочен длительное время или поставлен на удаление
- if($server['user'] == -1 || ($server['time'] < $start_point && ($server['overdue']+$cfg['server_delete']*86400) < $start_point))
- {
- if($server['user'] != -1)
- $sql->query('UPDATE `servers` set `user`="-1" WHERE `id`="'.$id.'" LIMIT 1');
+ // Если аренда закончилась и сервер просрочен длительное время или поставлен на удаление
+ if($server['user'] == -1 || ($server['time'] < $start_point && ($server['overdue']+$cfg['server_delete']*86400) < $start_point))
+ {
+ if($server['user'] != -1)
+ $sql->query('UPDATE `servers` set `user`="-1" WHERE `id`="'.$id.'" LIMIT 1');
- exec('sh -c "cd /var/enginegp; php cron.php '.$cfg['cron_key'].' server_delete '.$id.'"');
+ exec('sh -c "cd /var/enginegp; php cron.php '.$cfg['cron_key'].' server_delete '.$id.'"');
- continue;
- }
+ continue;
+ }
- switch($server['status'])
- {
- case 'working': case 'change': case 'start': case 'restart':
- if(!sys::int($ssh->get('ps aux | grep s_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
- {
- $sql->query('UPDATE `servers` set `status`="off", `online`="0", `players`="0" WHERE `id`="'.$id.'" LIMIT 1');
+ switch($server['status'])
+ {
+ case 'working': case 'change': case 'start': case 'restart':
+ if(!sys::int($ssh->get('ps aux | grep s_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
+ {
+ $sql->query('UPDATE `servers` set `status`="off", `online`="0", `players`="0" WHERE `id`="'.$id.'" LIMIT 1');
- // Запуск сервера (если он был выключен не через панель)
- if($server['stop'])
- {
- exec('sh -c "cd /var/enginegp; php cron.php '.$cfg['cron_key'].' server_action start '.$game.' '.$id.'"');
+ // Запуск сервера (если он был выключен не через панель)
+ if($server['stop'])
+ {
+ exec('sh -c "cd /var/enginegp; php cron.php '.$cfg['cron_key'].' server_action start '.$game.' '.$id.'"');
- $sql->query('INSERT INTO `logs_sys` set `user`="0", `server`="'.$id.'", `text`="Включение сервера: сервер выключен не через панель", `time`="'.$start_point.'"');
- }
- }else
- exec('sh -c "cd /var/enginegp; php cron.php '.$cfg['cron_key'].' server_scan '.$game.' '.$id.'"');
+ $sql->query('INSERT INTO `logs_sys` set `user`="0", `server`="'.$id.'", `text`="Включение сервера: сервер выключен не через панель", `time`="'.$start_point.'"');
+ }
+ }else
+ exec('sh -c "cd /var/enginegp; php cron.php '.$cfg['cron_key'].' server_scan '.$game.' '.$id.'"');
- break;
+ break;
- case 'off':
- if(sys::int($ssh->get('ps aux | grep s_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
- $sql->query('UPDATE `servers` set `status`="working" WHERE `id`="'.$id.'" LIMIT 1');
- else{
- // Запуск сервера (если он был выключен не через панель)
- if($server['stop'])
- {
- exec('sh -c "cd /var/enginegp; php cron.php '.$cfg['cron_key'].' server_action start '.$game.' '.$id.'"');
+ case 'off':
+ if(sys::int($ssh->get('ps aux | grep s_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
+ $sql->query('UPDATE `servers` set `status`="working" WHERE `id`="'.$id.'" LIMIT 1');
+ else{
+ // Запуск сервера (если он был выключен не через панель)
+ if($server['stop'])
+ {
+ exec('sh -c "cd /var/enginegp; php cron.php '.$cfg['cron_key'].' server_action start '.$game.' '.$id.'"');
- $sql->query('INSERT INTO `logs_sys` set `user`="0", `server`="'.$id.'", `text`="Включение сервера: сервер выключен не через панель", `time`="'.$start_point.'"');
+ $sql->query('INSERT INTO `logs_sys` set `user`="0", `server`="'.$id.'", `text`="Включение сервера: сервер выключен не через панель", `time`="'.$start_point.'"');
- continue;
- }
- }
+ continue;
+ }
+ }
- break;
+ break;
- case 'reinstall':
- if(!sys::int($ssh->get('ps aux | grep r_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
- $sql->query('UPDATE `servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
+ case 'reinstall':
+ if(!sys::int($ssh->get('ps aux | grep r_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
+ $sql->query('UPDATE `servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
- break;
+ break;
- case 'update':
- if(!sys::int($ssh->get('ps aux | grep u_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
- $sql->query('UPDATE `servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
+ case 'update':
+ if(!sys::int($ssh->get('ps aux | grep u_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
+ $sql->query('UPDATE `servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
- break;
+ break;
- case 'install':
- if(!sys::int($ssh->get('ps aux | grep i_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
- $sql->query('UPDATE `servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
+ case 'install':
+ if(!sys::int($ssh->get('ps aux | grep i_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
+ $sql->query('UPDATE `servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
- break;
+ break;
- case 'recovery':
- if(!sys::int($ssh->get('ps aux | grep rec_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
- $sql->query('UPDATE `servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
+ case 'recovery':
+ if(!sys::int($ssh->get('ps aux | grep rec_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
+ $sql->query('UPDATE `servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
- break;
+ break;
- case 'blocked':
- if($server['block'] < $start_point)
- $sql->query('UPDATE `servers` set `status`="off", `block`="0" WHERE `id`="'.$id.'" LIMIT 1');
- }
- }
+ case 'blocked':
+ if($server['block'] < $start_point)
+ $sql->query('UPDATE `servers` set `status`="off", `block`="0" WHERE `id`="'.$id.'" LIMIT 1');
+ }
+ }
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/cron/scan_servers_admins.php b/system/library/cron/scan_servers_admins.php
index 7034e07..40578ad 100644
--- a/system/library/cron/scan_servers_admins.php
+++ b/system/library/cron/scan_servers_admins.php
@@ -1,71 +1,71 @@
query('SELECT `address` FROM `units` WHERE `id`="'.$servers[4].'" LIMIT 1');
- if(!$sql->num())
- return NULL;
+ $sql->query('SELECT `address` FROM `units` WHERE `id`="'.$servers[4].'" LIMIT 1');
+ if(!$sql->num())
+ return NULL;
- $unit = $sql->get();
+ $unit = $sql->get();
- unset($servers[3], $servers[4]);
+ unset($servers[3], $servers[4]);
- $sql->query('SELECT `unit` FROM `servers` WHERE `id`="'.$servers[5].'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `unit` FROM `servers` WHERE `id`="'.$servers[5].'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return NULL;
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return NULL;
- foreach($servers as $id)
- {
- $sql->query('SELECT `uid`, `tarif` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ foreach($servers as $id)
+ {
+ $sql->query('SELECT `uid`, `tarif` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
- $tarif = $sql->get();
+ $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
+ $tarif = $sql->get();
- $admins = $sql->query('SELECT `id`, `text` FROM `admins_'.$game.'` WHERE `server`="'.$id.'" AND `active`="1" AND `time`<"'.$start_point.'"');
+ $admins = $sql->query('SELECT `id`, `text` FROM `admins_'.$game.'` WHERE `server`="'.$id.'" AND `active`="1" AND `time`<"'.$start_point.'"');
- if(!$sql->num($admins))
- continue;
+ if(!$sql->num($admins))
+ continue;
- $cmd = 'cd '.$tarif['install'].$server['uid'].';';
+ $cmd = 'cd '.$tarif['install'].$server['uid'].';';
- while($admin = $sql->get($admins))
- {
- $cmd .= 'sed -i -e \'s/'.escapeshellcmd(htmlspecialchars_decode($admin['text'])).'//g\' '.cron::$admins_file[$game].';';
+ while($admin = $sql->get($admins))
+ {
+ $cmd .= 'sed -i -e \'s/'.escapeshellcmd(htmlspecialchars_decode($admin['text'])).'//g\' '.cron::$admins_file[$game].';';
- $sql->query('UPDATE `admins_'.$game.'` set `active`="0" WHERE `id`="'.$admin['id'].'" LIMIT 1');
- }
+ $sql->query('UPDATE `admins_'.$game.'` set `active`="0" WHERE `id`="'.$admin['id'].'" LIMIT 1');
+ }
- $cmd .= 'sed -i '."'/./!d'".' '.cron::$admins_file[$game].'; echo -e "\n" >> '.cron::$admins_file[$game].';';
- $cmd .= 'chown server'.$server['uid'].':1000 '.cron::$admins_file[$game];
+ $cmd .= 'sed -i '."'/./!d'".' '.cron::$admins_file[$game].'; echo -e "\n" >> '.cron::$admins_file[$game].';';
+ $cmd .= 'chown server'.$server['uid'].':1000 '.cron::$admins_file[$game];
- $ssh->set($cmd);
- }
+ $ssh->set($cmd);
+ }
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/cron/scan_servers_copy.php b/system/library/cron/scan_servers_copy.php
index f7259a7..ff03a8a 100644
--- a/system/library/cron/scan_servers_copy.php
+++ b/system/library/cron/scan_servers_copy.php
@@ -1,53 +1,53 @@
query('SELECT `address` FROM `units` WHERE `id`="'.$servers[4].'" LIMIT 1');
- if(!$sql->num())
- return NULL;
+ $sql->query('SELECT `address` FROM `units` WHERE `id`="'.$servers[4].'" LIMIT 1');
+ if(!$sql->num())
+ return NULL;
- $unit = $sql->get();
+ $unit = $sql->get();
- $game = $servers[3];
+ $game = $servers[3];
- unset($servers[3], $servers[4]);
+ unset($servers[3], $servers[4]);
- $sql->query('SELECT `unit` FROM `servers` WHERE `id`="'.$servers[5].'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `unit` FROM `servers` WHERE `id`="'.$servers[5].'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return NULL;
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return NULL;
- foreach($servers as $id)
- {
- $copys = $sql->query('SELECT `id` FROM `copy` WHERE `status`="0"');
- while($copy = $sql->get($copys))
- {
- $sql->query('SELECT `uid` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ foreach($servers as $id)
+ {
+ $copys = $sql->query('SELECT `id` FROM `copy` WHERE `status`="0"');
+ while($copy = $sql->get($copys))
+ {
+ $sql->query('SELECT `uid` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- if(!sys::int($ssh->get('ps aux | grep copy_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
- $sql->query('UPDATE `copy` set `status`="1" WHERE `id`="'.$copy['id'].'" LIMIT 1');
- }
- }
+ if(!sys::int($ssh->get('ps aux | grep copy_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
+ $sql->query('UPDATE `copy` set `status`="1" WHERE `id`="'.$copy['id'].'" LIMIT 1');
+ }
+ }
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/cron/scan_servers_down.php b/system/library/cron/scan_servers_down.php
index 043956c..293ac5c 100644
--- a/system/library/cron/scan_servers_down.php
+++ b/system/library/cron/scan_servers_down.php
@@ -1,62 +1,62 @@
query('SELECT `address` FROM `units` WHERE `id`="'.$servers[4].'" LIMIT 1');
- if(!$sql->num())
- return NULL;
+ $sql->query('SELECT `address` FROM `units` WHERE `id`="'.$servers[4].'" LIMIT 1');
+ if(!$sql->num())
+ return NULL;
- $unit = $sql->get();
+ $unit = $sql->get();
- $game = $servers[3];
+ $game = $servers[3];
- if(!array_key_exists($game, cron::$quakestat))
- return NULL;
+ if(!array_key_exists($game, cron::$quakestat))
+ return NULL;
- unset($servers[3], $servers[4]);
+ unset($servers[3], $servers[4]);
- $sql->query('SELECT `unit` FROM `servers` WHERE `id`="'.$servers[5].'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `unit` FROM `servers` WHERE `id`="'.$servers[5].'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `address`, `passwd`, `ram` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd`, `ram` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return NULL;
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return NULL;
- foreach($servers as $id)
- {
- $sql->query('SELECT `uid`, `address`, `status`, `autorestart` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ foreach($servers as $id)
+ {
+ $sql->query('SELECT `uid`, `address`, `status`, `autorestart` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- if(!$server['autorestart'])
- continue;
+ if(!$server['autorestart'])
+ continue;
- if($server['status'] != 'working')
- continue;
+ if($server['status'] != 'working')
+ continue;
- if(!in_array(trim($ssh->get('quakestat -'.(cron::$quakestat[$game]).' '.$server['address'].' -retry 5 -interval 2 | grep -v frags | tail -1 | awk \'{print $2}\'')), array('DOWN', 'no')))
- continue;
+ if(!in_array(trim($ssh->get('quakestat -'.(cron::$quakestat[$game]).' '.$server['address'].' -retry 5 -interval 2 | grep -v frags | tail -1 | awk \'{print $2}\'')), array('DOWN', 'no')))
+ continue;
- exec('sh -c "cd /var/enginegp; php cron.php '.$cfg['cron_key'].' server_action restart '.$game.' '.$id.'"');
+ exec('sh -c "cd /var/enginegp; php cron.php '.$cfg['cron_key'].' server_action restart '.$game.' '.$id.'"');
- $sql->query('INSERT INTO `logs_sys` set `user`="0", `server`="'.$id.'", `text`="Перезагрука сервера: сервер завис", `time`="'.$start_point.'"');
- }
+ $sql->query('INSERT INTO `logs_sys` set `user`="0", `server`="'.$id.'", `text`="Перезагрука сервера: сервер завис", `time`="'.$start_point.'"');
+ }
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/cron/scan_servers_load.php b/system/library/cron/scan_servers_load.php
index a58e925..9ecd804 100644
--- a/system/library/cron/scan_servers_load.php
+++ b/system/library/cron/scan_servers_load.php
@@ -1,96 +1,96 @@
query('SELECT `address` FROM `units` WHERE `id`="'.$servers[4].'" LIMIT 1');
- if(!$sql->num())
- return NULL;
+ $sql->query('SELECT `address` FROM `units` WHERE `id`="'.$servers[4].'" LIMIT 1');
+ if(!$sql->num())
+ return NULL;
- $unit = $sql->get();
+ $unit = $sql->get();
- $game = $servers[3];
+ $game = $servers[3];
- unset($servers[3], $servers[4]);
+ unset($servers[3], $servers[4]);
- $sql->query('SELECT `unit` FROM `servers` WHERE `id`="'.$servers[5].'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `unit` FROM `servers` WHERE `id`="'.$servers[5].'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `address`, `passwd`, `ram` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd`, `ram` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return NULL;
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return NULL;
- foreach($servers as $id)
- {
- $sql->query('SELECT `uid`, `slots`, `hdd`, `ram`, `ram_use_max`, `cpu_use_max`, `core_fix`, `core_fix_one` `status` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ foreach($servers as $id)
+ {
+ $sql->query('SELECT `uid`, `slots`, `hdd`, `ram`, `ram_use_max`, `cpu_use_max`, `core_fix`, `core_fix_one` `status` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- if($server['core_fix'] AND $server['core_fix_one'])
- continue;
+ if($server['core_fix'] AND $server['core_fix_one'])
+ continue;
- if(!in_array($server['status'], array('working', 'start', 'restart', 'change')))
- {
- echo 'server#'.$id.' ('.$game.') -> load average: cpu = 0% / ram = 0% (no working)'.PHP_EOL;
+ if(!in_array($server['status'], array('working', 'start', 'restart', 'change')))
+ {
+ echo 'server#'.$id.' ('.$game.') -> load average: cpu = 0% / ram = 0% (no working)'.PHP_EOL;
- continue;
- }
+ continue;
+ }
- $resources = array();
+ $resources = array();
- for($n = 0; $n <= 2; $n+=1)
- {
- $cr = explode('|', $ssh->get('top -u '.$server['uid'].' -b -n 1 | grep '.(cron::$process[$game]).' | awk \'{print $9"|"$10}\''));
+ for($n = 0; $n <= 2; $n+=1)
+ {
+ $cr = explode('|', $ssh->get('top -u '.$server['uid'].' -b -n 1 | grep '.(cron::$process[$game]).' | awk \'{print $9"|"$10}\''));
- $resources[$n]['cpu'] = isset($cr[0]) ? round(str_replace(',', '.', $cr[0])) : 0;
+ $resources[$n]['cpu'] = isset($cr[0]) ? round(str_replace(',', '.', $cr[0])) : 0;
- $resources[$n]['ram'] = isset($cr[1]) ? str_replace(',', '.', $cr[1]) : 0;
- $ram = $server['ram'] ? $server['ram'] : $server['slots']*$cfg['ram'][$game];
- $resources[$n]['ram'] = round($unit['ram']/100*$resources[$n]['ram']/($ram/100));
+ $resources[$n]['ram'] = isset($cr[1]) ? str_replace(',', '.', $cr[1]) : 0;
+ $ram = $server['ram'] ? $server['ram'] : $server['slots']*$cfg['ram'][$game];
+ $resources[$n]['ram'] = round($unit['ram']/100*$resources[$n]['ram']/($ram/100));
- sleep(1);
- }
+ sleep(1);
+ }
- $loads = array();
+ $loads = array();
- foreach($resources as $n => $load)
- {
- foreach($load as $type => $val)
- $loads[$type] += $val;
- }
+ foreach($resources as $n => $load)
+ {
+ foreach($load as $type => $val)
+ $loads[$type] += $val;
+ }
- $average_cpu = isset($loads['cpu']) ? $loads['cpu']/2 : 0;
- $average_ram = isset($loads['ram']) ? $loads['ram']/2 : 0;
+ $average_cpu = isset($loads['cpu']) ? $loads['cpu']/2 : 0;
+ $average_ram = isset($loads['ram']) ? $loads['ram']/2 : 0;
- $max_cpu = $server['cpu_use_max'] ? $server['cpu_use_max'] : $cfg['cpu_use_max'][$game];
- $max_ram = $server['ram_use_max'] ? $server['ram_use_max'] : $cfg['ram_use_max'][$game];
+ $max_cpu = $server['cpu_use_max'] ? $server['cpu_use_max'] : $cfg['cpu_use_max'][$game];
+ $max_ram = $server['ram_use_max'] ? $server['ram_use_max'] : $cfg['ram_use_max'][$game];
- if($average_cpu > $max_cpu)
- {
- exec('sh -c "cd /var/enginegp; php cron.php '.$cfg['cron_key'].' server_action restart '.$game.' '.$id.'"');
+ if($average_cpu > $max_cpu)
+ {
+ exec('sh -c "cd /var/enginegp; php cron.php '.$cfg['cron_key'].' server_action restart '.$game.' '.$id.'"');
- $sql->query('INSERT INTO `logs_sys` set `user`="0", `server`="'.$id.'", `text`="Перезагрука сервера: OVERLOAD^cpu = '.$average_cpu.'%", `time`="'.$start_point.'"');
- }elseif($average_ram > $max_ram){
- exec('sh -c "cd /var/enginegp; php cron.php '.$cfg['cron_key'].' server_action restart '.$game.' '.$id.'"');
+ $sql->query('INSERT INTO `logs_sys` set `user`="0", `server`="'.$id.'", `text`="Перезагрука сервера: OVERLOAD^cpu = '.$average_cpu.'%", `time`="'.$start_point.'"');
+ }elseif($average_ram > $max_ram){
+ exec('sh -c "cd /var/enginegp; php cron.php '.$cfg['cron_key'].' server_action restart '.$game.' '.$id.'"');
- $sql->query('INSERT INTO `logs_sys` set `user`="0", `server`="'.$id.'", `text`="Перезагрука сервера: OVERLOAD^ram = '.$average_ram.'%", `time`="'.$start_point.'"');
- }
- }
+ $sql->query('INSERT INTO `logs_sys` set `user`="0", `server`="'.$id.'", `text`="Перезагрука сервера: OVERLOAD^ram = '.$average_ram.'%", `time`="'.$start_point.'"');
+ }
+ }
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/cron/scan_servers_route.php b/system/library/cron/scan_servers_route.php
index 0c830e6..0c4d105 100644
--- a/system/library/cron/scan_servers_route.php
+++ b/system/library/cron/scan_servers_route.php
@@ -1,104 +1,104 @@
query('SELECT `address` FROM `units` WHERE `id`="'.$servers[4].'" LIMIT 1');
- if(!$sql->num())
- return NULL;
+ $sql->query('SELECT `address` FROM `units` WHERE `id`="'.$servers[4].'" LIMIT 1');
+ if(!$sql->num())
+ return NULL;
- $unit = $sql->get();
+ $unit = $sql->get();
- $game = $servers[3];
+ $game = $servers[3];
- unset($servers[3], $servers[4]);
+ unset($servers[3], $servers[4]);
- $sql->query('SELECT `unit` FROM `servers` WHERE `id`="'.$servers[5].'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `unit` FROM `servers` WHERE `id`="'.$servers[5].'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `address`, `passwd`, `ram` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd`, `ram` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return NULL;
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return NULL;
- $first = $ssh->get('cat /proc/stat');
+ $first = $ssh->get('cat /proc/stat');
- sleep(1);
+ sleep(1);
- $aCpu = sys::cpu_idle(array($first, $ssh->get('cat /proc/stat')), false, true);
+ $aCpu = sys::cpu_idle(array($first, $ssh->get('cat /proc/stat')), false, true);
- array_shift($aCpu);
+ array_shift($aCpu);
- $idle = array();
- $uses = array();
+ $idle = array();
+ $uses = array();
- foreach($aCpu as $cpu => $data)
- {
- $core = sys::int($cpu)+1;
+ foreach($aCpu as $cpu => $data)
+ {
+ $core = sys::int($cpu)+1;
- $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$server['unit'].'" AND `core_fix`="'.$core.'" AND `core_fix`="1" LIMIT 1');
- if($sql->num())
- {
- unset($aCpu[$cpu]);
+ $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$server['unit'].'" AND `core_fix`="'.$core.'" AND `core_fix`="1" LIMIT 1');
+ if($sql->num())
+ {
+ unset($aCpu[$cpu]);
- continue;
- }
+ continue;
+ }
- if($data['idle'] > 50)
- $idle[$core] = $data['idle'];
- else
- $uses[$core] = 100-$data['idle'];
- }
+ if($data['idle'] > 50)
+ $idle[$core] = $data['idle'];
+ else
+ $uses[$core] = 100-$data['idle'];
+ }
- if(!count($idle))
- return NULL;
+ if(!count($idle))
+ return NULL;
- foreach($uses as $use_core => $use)
- {
- if(!count($idle))
- break;
+ foreach($uses as $use_core => $use)
+ {
+ if(!count($idle))
+ break;
- $sql->query('SELECT `id`, `uid` FROM `servers` WHERE `unit`="'.$server['unit'].'" AND `game`="'.$game.'" AND `core_use`="'.$use_core.'" AND `status`="working" AND `core_fix`="0" ORDER BY `slots_start` DESC, `online` DESC LIMIT 3');
- if($sql->num() > 1)
- {
- $server = $sql->get();
+ $sql->query('SELECT `id`, `uid` FROM `servers` WHERE `unit`="'.$server['unit'].'" AND `game`="'.$game.'" AND `core_use`="'.$use_core.'" AND `status`="working" AND `core_fix`="0" ORDER BY `slots_start` DESC, `online` DESC LIMIT 3');
+ if($sql->num() > 1)
+ {
+ $server = $sql->get();
- $core = array_search(max($idle), $idle);
+ $core = array_search(max($idle), $idle);
- $aPid = explode("\n", $ssh->get('ps aux | grep -v grep | grep '.$server['uid'].' | awk \'{print $2}\''));
+ $aPid = explode("\n", $ssh->get('ps aux | grep -v grep | grep '.$server['uid'].' | awk \'{print $2}\''));
- if(count($aPid) < 2)
- continue;
+ if(count($aPid) < 2)
+ continue;
- array_pop($aPid);
+ array_pop($aPid);
- $taskset = '';
+ $taskset = '';
- foreach($aPid as $pid)
- $taskset .= 'taskset -cp '.($core-1).' '.$pid.';';
+ foreach($aPid as $pid)
+ $taskset .= 'taskset -cp '.($core-1).' '.$pid.';';
- $ssh->set($taskset);
+ $ssh->set($taskset);
- unset($idle[$core]);
+ unset($idle[$core]);
- $sql->query('UPDATE `servers` set `core_use`="'.$core.'" WHERE `id`="'.$server['id'].'" LIMIT 1');
- }
- }
+ $sql->query('UPDATE `servers` set `core_use`="'.$core.'" WHERE `id`="'.$server['id'].'" LIMIT 1');
+ }
+ }
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/cron/scan_servers_stop.php b/system/library/cron/scan_servers_stop.php
index 89b68c2..1f071f3 100644
--- a/system/library/cron/scan_servers_stop.php
+++ b/system/library/cron/scan_servers_stop.php
@@ -1,57 +1,57 @@
query('SELECT `address` FROM `units` WHERE `id`="'.$servers[4].'" LIMIT 1');
- if(!$sql->num())
- return NULL;
+ $sql->query('SELECT `address` FROM `units` WHERE `id`="'.$servers[4].'" LIMIT 1');
+ if(!$sql->num())
+ return NULL;
- $unit = $sql->get();
+ $unit = $sql->get();
- $game = $servers[3];
+ $game = $servers[3];
- unset($servers[3], $servers[4]);
+ unset($servers[3], $servers[4]);
- $sql->query('SELECT `unit` FROM `servers` WHERE `id`="'.$servers[5].'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `unit` FROM `servers` WHERE `id`="'.$servers[5].'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return NULL;
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return NULL;
- $autostop = $start_point-$cfg['autostop']*60;
- $teststop = $start_point-$cfg['teststop']*60;
+ $autostop = $start_point-$cfg['autostop']*60;
+ $teststop = $start_point-$cfg['teststop']*60;
- $sqlq = '(`test`="1" AND `time_start`<"'.$teststop.'" OR `autostop`="1" AND `time_start`<"'.$autostop.'")';
+ $sqlq = '(`test`="1" AND `time_start`<"'.$teststop.'" OR `autostop`="1" AND `time_start`<"'.$autostop.'")';
- foreach($servers as $id)
- {
- $sql->query('SELECT `id` FROM `servers` WHERE `id`="'.$id.'" AND `status`="working" AND `online`="0" AND '.$sqlq.' LIMIT 1');
+ foreach($servers as $id)
+ {
+ $sql->query('SELECT `id` FROM `servers` WHERE `id`="'.$id.'" AND `status`="working" AND `online`="0" AND '.$sqlq.' LIMIT 1');
- if(!$sql->num())
- continue;
+ if(!$sql->num())
+ continue;
- exec('sh -c "cd /var/enginegp; php cron.php '.$cfg['cron_key'].' server_action stop '.$game.' '.$id.'"');
+ exec('sh -c "cd /var/enginegp; php cron.php '.$cfg['cron_key'].' server_action stop '.$game.' '.$id.'"');
- $sql->query('INSERT INTO `logs_sys` set `user`="0", `server`="'.$id.'", `text`="Выключение сервера: на сервере нет игроков", `time`="'.$start_point.'"');
- }
+ $sql->query('INSERT INTO `logs_sys` set `user`="0", `server`="'.$id.'", `text`="Выключение сервера: на сервере нет игроков", `time`="'.$start_point.'"');
+ }
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/cron/server_action.php b/system/library/cron/server_action.php
index 325aa71..dda1c5e 100644
--- a/system/library/cron/server_action.php
+++ b/system/library/cron/server_action.php
@@ -1,55 +1,55 @@
get($nmch))
- return NULL;
+ if($mcache->get($nmch))
+ return NULL;
- $mcache->set($nmch, true, false, 10);
+ $mcache->set($nmch, true, false, 10);
- if($argv[3] == 'console')
- {
- global $sql;
+ if($argv[3] == 'console')
+ {
+ global $sql;
- $sql->query('SELECT `uid`, `unit` FROM `servers` WHERE `id`="'.$argv[5].'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `uid`, `unit` FROM `servers` WHERE `id`="'.$argv[5].'" LIMIT 1');
+ $server = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return NULL;
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return NULL;
- $sql->query('SELECT `commands` FROM `crontab` WHERE `id`="'.$argv[6].'" LIMIT 1');
- $cron = $sql->get();
+ $sql->query('SELECT `commands` FROM `crontab` WHERE `id`="'.$argv[6].'" LIMIT 1');
+ $cron = $sql->get();
- $aCmd = explode("\n", base64_decode($cron['commands']));
+ $aCmd = explode("\n", base64_decode($cron['commands']));
- foreach($aCmd as $cmd)
- $ssh->set('sudo -u server'.$server['uid'].' screen -p 0 -S s_'.$server['uid'].' -X eval \'stuff "'.sys::cmd($cmd).'"\015\'; sudo -u server'.$server['uid'].' screen -p 0 -S s_'.$server['uid'].' -X eval \'stuff \015\'');
+ foreach($aCmd as $cmd)
+ $ssh->set('sudo -u server'.$server['uid'].' screen -p 0 -S s_'.$server['uid'].' -X eval \'stuff "'.sys::cmd($cmd).'"\015\'; sudo -u server'.$server['uid'].' screen -p 0 -S s_'.$server['uid'].' -X eval \'stuff \015\'');
- return NULL;
- }
+ return NULL;
+ }
- include(LIB.'games/'.$argv[4].'/action.php');
+ include(LIB.'games/'.$argv[4].'/action.php');
- if($argv[3] == 'restart')
- action::start($argv[5], 'restart');
- else
- action::$argv[3]($argv[5]);
+ if($argv[3] == 'restart')
+ action::start($argv[5], 'restart');
+ else
+ action::$argv[3]($argv[5]);
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/cron/server_cron.php b/system/library/cron/server_cron.php
index 5825e83..5b4f77f 100644
--- a/system/library/cron/server_cron.php
+++ b/system/library/cron/server_cron.php
@@ -1,24 +1,24 @@
query('SELECT `game` FROM `servers` WHERE `id`="'.$argv[3].'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `game` FROM `servers` WHERE `id`="'.$argv[3].'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `task` FROM `crontab` WHERE `id`="'.$argv[4].'" LIMIT 1');
- $cron = $sql->get();
+ $sql->query('SELECT `task` FROM `crontab` WHERE `id`="'.$argv[4].'" LIMIT 1');
+ $cron = $sql->get();
- $cmd = $cron['task'] == 'console' ? ' '.$argv[4] : '';
+ $cmd = $cron['task'] == 'console' ? ' '.$argv[4] : '';
- exec('sh -c "cd /var/enginegp; php cron.php '.$cfg['cron_key'].' server_action '.$cron['task'].' '.$server['game'].' '.$argv[3].$cmd.'"');
+ exec('sh -c "cd /var/enginegp; php cron.php '.$cfg['cron_key'].' server_action '.$cron['task'].' '.$server['game'].' '.$argv[3].$cmd.'"');
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/cron/server_delete.php b/system/library/cron/server_delete.php
index fdac0c4..fb5a47d 100644
--- a/system/library/cron/server_delete.php
+++ b/system/library/cron/server_delete.php
@@ -1,148 +1,148 @@
query('SELECT `id`, `uid`, `user`, `unit`, `tarif`, `game`, `slots`, `address`, `ddos` FROM `servers` WHERE `id`="'.$argv[3].'" AND `user`="-1" LIMIT 1');
+ $sql->query('SELECT `id`, `uid`, `user`, `unit`, `tarif`, `game`, `slots`, `address`, `ddos` FROM `servers` WHERE `id`="'.$argv[3].'" AND `user`="-1" LIMIT 1');
- if(!$sql->num())
- return NULL;
+ if(!$sql->num())
+ return NULL;
- $server = $sql->get();
+ $server = $sql->get();
- if(!$server['uid'])
- return NULL;
+ if(!$server['uid'])
+ return NULL;
- $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
- $tarif = $sql->get();
+ $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
+ $tarif = $sql->get();
- $sql->query('SELECT `address`, `passwd`, `sql_login`, `sql_passwd`, `sql_port`, `sql_ftp` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd`, `sql_login`, `sql_passwd`, `sql_port`, `sql_ftp` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- // Проверка ssh соединения с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return NULL;
+ // Проверка ssh соединения с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return NULL;
- // Убить процессы
- $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
- .'lsof -i@:'.$server['address'].' | awk '."'{print $2}'".' | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
+ // Убить процессы
+ $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
+ .'lsof -i@:'.$server['address'].' | awk '."'{print $2}'".' | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
- // Директория игрового сервера
- $install = $tarif['install'].$server['uid'];
+ // Директория игрового сервера
+ $install = $tarif['install'].$server['uid'];
- $copys = 'screen -dmS r_copy_'.$server['uid'].' sh -c "';
+ $copys = 'screen -dmS r_copy_'.$server['uid'].' sh -c "';
- $scopy = $sql->query('SELECT `id`, `name` FROM `copy` WHERE `server`="'.$server['id'].'"');
- while($copy = $sql->get($scopy))
- {
- $copys .= 'rm /copy/'.$copy['name'].'.tar;';
+ $scopy = $sql->query('SELECT `id`, `name` FROM `copy` WHERE `server`="'.$server['id'].'"');
+ while($copy = $sql->get($scopy))
+ {
+ $copys .= 'rm /copy/'.$copy['name'].'.tar;';
- $sql->query('DELETE FROM `copy` WHERE `id`="'.$copy['id'].'" LIMIT 1');
- }
+ $sql->query('DELETE FROM `copy` WHERE `id`="'.$copy['id'].'" LIMIT 1');
+ }
- $copys .= '";';
+ $copys .= '";';
- $ssh->set($copys // Удаление резервных копий
- .'screen -dmS r_'.$server['uid'].' sh -c "rm -r '.$install.';' // Удаление директории сервера
- .'userdel server'.$server['uid'].'"'); // Удаление пользователя сервера c локации
+ $ssh->set($copys // Удаление резервных копий
+ .'screen -dmS r_'.$server['uid'].' sh -c "rm -r '.$install.';' // Удаление директории сервера
+ .'userdel server'.$server['uid'].'"'); // Удаление пользователя сервера c локации
- // Удаление ftp доступа
- $qSql = 'DELETE FROM users WHERE username=\''.$server['uid'].'\';'
+ // Удаление ftp доступа
+ $qSql = 'DELETE FROM users WHERE username=\''.$server['uid'].'\';'
.'DELETE FROM quotalimits WHERE name=\''.$server['uid'].'\';'
.'DELETE FROM quotatallies WHERE name=\''.$server['uid'].'\'';
$ssh->set('screen -dmS ftp'.$server['uid'].' mysql -P '.$unit['sql_port'].' -u'.$unit['sql_login'].' -p'.$unit['sql_passwd'].' --database '.$unit['sql_ftp'].' -e "'.$qSql.'"');
- include(LIB.'games/games.php');
+ include(LIB.'games/games.php');
- // Очистка правил FireWall
- games::iptables($server['id'], 'remove', NULL, NULL, NULL, false, $ssh);
+ // Очистка правил FireWall
+ games::iptables($server['id'], 'remove', NULL, NULL, NULL, false, $ssh);
- // Очистка правил FireWall GEO
- if($server['ddos'])
- {
- $geo = $cfg['iptables'].'_geo';
+ // Очистка правил FireWall GEO
+ if($server['ddos'])
+ {
+ $geo = $cfg['iptables'].'_geo';
- $country = $server['ddos'] == 2 ? 'AM,BY,UA,RU,KZ' : 'UA,RU';
+ $country = $server['ddos'] == 2 ? 'AM,BY,UA,RU,KZ' : 'UA,RU';
- $ssh->set('iptables -D INPUT -p udp -d '.$ip.' --dport '.$port.' -m geoip ! --source-country '.$country.' -j DROP;'
- .'sed "`nl '.$geo.' | grep \"#'.$id.'\" | awk \'{print $1","$1+1}\'`d" '.$geo.' > '.$geo.'_temp; cat '.$geo.'_temp > '.$geo.'; rm '.$geo.'_temp;');
- }
+ $ssh->set('iptables -D INPUT -p udp -d '.$ip.' --dport '.$port.' -m geoip ! --source-country '.$country.' -j DROP;'
+ .'sed "`nl '.$geo.' | grep \"#'.$id.'\" | awk \'{print $1","$1+1}\'`d" '.$geo.' > '.$geo.'_temp; cat '.$geo.'_temp > '.$geo.'; rm '.$geo.'_temp;');
+ }
- // Удаление заданий из crontab
- $sql->query('SELECT `address`, `passwd` FROM `panel` LIMIT 1');
- $panel = $sql->get();
+ // Удаление заданий из crontab
+ $sql->query('SELECT `address`, `passwd` FROM `panel` LIMIT 1');
+ $panel = $sql->get();
- if(!$ssh->auth($panel['passwd'], $panel['address']))
- return NULL;
+ if(!$ssh->auth($panel['passwd'], $panel['address']))
+ return NULL;
- $crons = $sql->query('SELECT `id`, `cron` FROM `crontab` WHERE `server`="'.$server['id'].'"');
- while($cron = $sql->get($crons))
- {
- $ssh->set('echo "" >> /etc/crontab && cat /etc/crontab');
- $crontab = str_replace($cron['cron'], '', $ssh->get());
+ $crons = $sql->query('SELECT `id`, `cron` FROM `crontab` WHERE `server`="'.$server['id'].'"');
+ while($cron = $sql->get($crons))
+ {
+ $ssh->set('echo "" >> /etc/crontab && cat /etc/crontab');
+ $crontab = str_replace($cron['cron'], '', $ssh->get());
- // Временный файл
- $temp = sys::temp($crontab);
+ // Временный файл
+ $temp = sys::temp($crontab);
- $ssh->setfile($temp, '/etc/crontab', 0644);
+ $ssh->setfile($temp, '/etc/crontab', 0644);
- $ssh->set("sed -i '/^$/d' /etc/crontab");
- $ssh->set('crontab -u root /etc/crontab');
+ $ssh->set("sed -i '/^$/d' /etc/crontab");
+ $ssh->set('crontab -u root /etc/crontab');
- unlink($temp);
+ unlink($temp);
- $sql->query('DELETE FROM `crontab` WHERE `id`="'.$cron['id'].'" LIMIT 1');
- }
+ $sql->query('DELETE FROM `crontab` WHERE `id`="'.$cron['id'].'" LIMIT 1');
+ }
- // Обновление данных выделенного адреса
- $sql->query('SELECT `id`, `aid` FROM `address_buy` WHERE `server`="'.$server['id'].'" LIMIT 1');
- if($sql->num())
- {
- $add = $sql->get();
+ // Обновление данных выделенного адреса
+ $sql->query('SELECT `id`, `aid` FROM `address_buy` WHERE `server`="'.$server['id'].'" LIMIT 1');
+ if($sql->num())
+ {
+ $add = $sql->get();
- $sql->query('UPDATE `address` set `buy`="0" WHERE `id`="'.$add['aid'].'" LIMIT 1');
- $sql->query('DELETE FROM `address_buy` WHERE `id`="'.$add['id'].'" LIMIT 1');
- }
+ $sql->query('UPDATE `address` set `buy`="0" WHERE `id`="'.$add['aid'].'" LIMIT 1');
+ $sql->query('DELETE FROM `address_buy` WHERE `id`="'.$add['id'].'" LIMIT 1');
+ }
- include(DATA.'web.php');
+ include(DATA.'web.php');
- $sql->query('SELECT `id` FROM `servers` WHERE `id`!="'.$server['id'].'" AND `user`="'.$server['user'].'" AND `unit`="'.$server['unit'].'" LIMIT 1');
- if($sql->num())
- {
- $server_sec = $sql->get();
+ $sql->query('SELECT `id` FROM `servers` WHERE `id`!="'.$server['id'].'" AND `user`="'.$server['user'].'" AND `unit`="'.$server['unit'].'" LIMIT 1');
+ if($sql->num())
+ {
+ $server_sec = $sql->get();
- // Подготовка к удалению доп. услуги или обновление данных
- $webs = $sql->query('SELECT `id`, `type` FROM `web` WHERE `server`="'.$server['id'].'"');
- while($web = $sql->get($webs))
- {
- if($aWebInstall[$server['game']][$web['type']] == ('unit' || 'user'))
- $sql->query('UPDATE `web` set `server`="'.$server_sec['id'].'" WHERE `id`="'.$web['id'].'" LIMIT 1');
- else
- $sql->query('UPDATE `web` set `user`="0" WHERE `id`="'.$web['id'].'" LIMIT 1');
- }
- }else
- $sql->query('UPDATE `web` set `user`="0" WHERE `server`="'.$server['id'].'"');
+ // Подготовка к удалению доп. услуги или обновление данных
+ $webs = $sql->query('SELECT `id`, `type` FROM `web` WHERE `server`="'.$server['id'].'"');
+ while($web = $sql->get($webs))
+ {
+ if($aWebInstall[$server['game']][$web['type']] == ('unit' || 'user'))
+ $sql->query('UPDATE `web` set `server`="'.$server_sec['id'].'" WHERE `id`="'.$web['id'].'" LIMIT 1');
+ else
+ $sql->query('UPDATE `web` set `user`="0" WHERE `id`="'.$web['id'].'" LIMIT 1');
+ }
+ }else
+ $sql->query('UPDATE `web` set `user`="0" WHERE `server`="'.$server['id'].'"');
- // Удаление различной информации игрового сервера
- $sql->query('DELETE FROM `admins_'.$server['game'].'` WHERE `server`="'.$server['id'].'"');
- $sql->query('DELETE FROM `plugins_install` WHERE `server`="'.$server['id'].'"');
- $sql->query('DELETE FROM `owners` WHERE `server`="'.$server['id'].'"');
- $sql->query('DELETE FROM `graph` WHERE `server`="'.$server['id'].'"');
- $sql->query('DELETE FROM `graph_day` WHERE `server`="'.$server['id'].'"');
- $sql->query('DELETE FROM `graph_hour` WHERE `server`="'.$server['id'].'"');
- $sql->query('DELETE FROM `servers` WHERE `id`="'.$server['id'].'" LIMIT 1');
+ // Удаление различной информации игрового сервера
+ $sql->query('DELETE FROM `admins_'.$server['game'].'` WHERE `server`="'.$server['id'].'"');
+ $sql->query('DELETE FROM `plugins_install` WHERE `server`="'.$server['id'].'"');
+ $sql->query('DELETE FROM `owners` WHERE `server`="'.$server['id'].'"');
+ $sql->query('DELETE FROM `graph` WHERE `server`="'.$server['id'].'"');
+ $sql->query('DELETE FROM `graph_day` WHERE `server`="'.$server['id'].'"');
+ $sql->query('DELETE FROM `graph_hour` WHERE `server`="'.$server['id'].'"');
+ $sql->query('DELETE FROM `servers` WHERE `id`="'.$server['id'].'" LIMIT 1');
- $sql->query('INSERT INTO `logs_sys` set `user`="0", `server`="'.$argv[3].'", `text`="Удаление игрового сервера #'.$argv[3].' ('.$server['game'].') unit: #'.$server['unit'].', tarif: #'.$server['tarif'].', slots: #'.$server['slots'].'", `time`="'.$start_point.'"');
+ $sql->query('INSERT INTO `logs_sys` set `user`="0", `server`="'.$argv[3].'", `text`="Удаление игрового сервера #'.$argv[3].' ('.$server['game'].') unit: #'.$server['unit'].', tarif: #'.$server['tarif'].', slots: #'.$server['slots'].'", `time`="'.$start_point.'"');
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/cron/server_scan.php b/system/library/cron/server_scan.php
index d00e14c..04e0ce9 100644
--- a/system/library/cron/server_scan.php
+++ b/system/library/cron/server_scan.php
@@ -1,19 +1,19 @@
\ No newline at end of file
diff --git a/system/library/cron/threads.php b/system/library/cron/threads.php
index e656b66..8ab696e 100644
--- a/system/library/cron/threads.php
+++ b/system/library/cron/threads.php
@@ -1,63 +1,63 @@
query('SELECT `id` FROM `units` ORDER BY `id` ASC');
+ $aUnit = array();
+ $sql->query('SELECT `id` FROM `units` ORDER BY `id` ASC');
- if(!$sql->num())
- return NULL;
+ if(!$sql->num())
+ return NULL;
- while($unit = $sql->get())
- $aUnit[$unit['id']] = '';
+ while($unit = $sql->get())
+ $aUnit[$unit['id']] = '';
- $sql->query('SELECT `id` FROM `servers` LIMIT 1');
+ $sql->query('SELECT `id` FROM `servers` LIMIT 1');
- if(!$sql->num())
- return NULL;
+ if(!$sql->num())
+ return NULL;
- $sql->query('SELECT `id`, `unit`, `game` FROM `servers` ORDER BY `unit` DESC');
+ $sql->query('SELECT `id`, `unit`, `game` FROM `servers` ORDER BY `unit` DESC');
- $all = $sql->num();
+ $all = $sql->num();
- while($server = $sql->get())
- $aUnit[$server['unit']][$server['game']] .= $server['id'].' ';
+ while($server = $sql->get())
+ $aUnit[$server['unit']][$server['game']] .= $server['id'].' ';
- if($argv[3] == 'scan_servers_route')
- cron::$seping = 50;
+ if($argv[3] == 'scan_servers_route')
+ cron::$seping = 50;
- foreach($aUnit as $unit => $aGame)
- {
- foreach($aGame as $game => $servers)
- {
- $aData = explode(' ', $servers);
+ foreach($aUnit as $unit => $aGame)
+ {
+ foreach($aGame as $game => $servers)
+ {
+ $aData = explode(' ', $servers);
- $num = count($aData)-1;
- $sep = $num > 0 ? ceil($num/cron::$seping) : 1;
+ $num = count($aData)-1;
+ $sep = $num > 0 ? ceil($num/cron::$seping) : 1;
- unset($aData[end($aData)]);
+ unset($aData[end($aData)]);
- $threads[] = cron::thread($sep, $game.' '.$unit, $aData);
- }
- }
+ $threads[] = cron::thread($sep, $game.' '.$unit, $aData);
+ }
+ }
- $cmd = '';
+ $cmd = '';
- foreach($threads as $thread)
- {
- foreach($thread as $screen => $servers)
- $cmd .= 'sudo -u www-data screen -dmS scan_'.(sys::first(explode(' ', $servers))).'_'.$screen.' taskset -c '.$cfg['cron_taskset'].' sh -c \"cd /var/enginegp; php cron.php '.$cfg['cron_key'].' '.$argv[3].' '.$servers.'\"; sleep 1;';
- }
+ foreach($threads as $thread)
+ {
+ foreach($thread as $screen => $servers)
+ $cmd .= 'sudo -u www-data screen -dmS scan_'.(sys::first(explode(' ', $servers))).'_'.$screen.' taskset -c '.$cfg['cron_taskset'].' sh -c \"cd /var/enginegp; php cron.php '.$cfg['cron_key'].' '.$argv[3].' '.$servers.'\"; sleep 1;';
+ }
- exec('screen -dmS threads_'.date('His', $start_point).' sh -c "'.$cmd.'"');
+ exec('screen -dmS threads_'.date('His', $start_point).' sh -c "'.$cmd.'"');
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/cron/update_address.php b/system/library/cron/update_address.php
index 7d8366b..c815957 100644
--- a/system/library/cron/update_address.php
+++ b/system/library/cron/update_address.php
@@ -1,44 +1,44 @@
query('SELECT `id`, `aid`, `server` FROM `address_buy` WHERE `time`<"'.$start_point.'"');
+ $add_buys = $sql->query('SELECT `id`, `aid`, `server` FROM `address_buy` WHERE `time`<"'.$start_point.'"');
- while($add_buy = $sql->get($add_buys))
- {
- $sql->query('SELECT `unit`, `port`, `game`, `status` FROM `servers` WHERE `id`="'.$add_buy['server'].'" LIMIT 1');
- if($sql->num())
- {
- $server = $sql->get();
+ while($add_buy = $sql->get($add_buys))
+ {
+ $sql->query('SELECT `unit`, `port`, `game`, `status` FROM `servers` WHERE `id`="'.$add_buy['server'].'" LIMIT 1');
+ if($sql->num())
+ {
+ $server = $sql->get();
- if(!$cfg['buy_address'][$server['game']])
- continue;
+ if(!$cfg['buy_address'][$server['game']])
+ continue;
- $sql->query('SELECT `address` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- include(LIB.'games/games.php');
+ include(LIB.'games/games.php');
- // Очистка правил FireWall
- games::iptables($add_buy['server'], 'remove', NULL, NULL, $server['unit'], false);
+ // Очистка правил FireWall
+ games::iptables($add_buy['server'], 'remove', NULL, NULL, $server['unit'], false);
- $sql->query('UPDATE `servers` set `address`="'.(sys::first(explode(':', $unit['address']))).':'.$server['port'].'" WHERE `id`="'.$add_buy['server'].'" LIMIT 1');
+ $sql->query('UPDATE `servers` set `address`="'.(sys::first(explode(':', $unit['address']))).':'.$server['port'].'" WHERE `id`="'.$add_buy['server'].'" LIMIT 1');
- if(in_array($server['status'], array('working', 'start', 'restart', 'change')))
- exec('sh -c "cd /var/enginegp; php cron.php '.$cfg['cron_key'].' server_action restart '.$server['game'].' '.$add_buy['server'].'"');
- }
+ if(in_array($server['status'], array('working', 'start', 'restart', 'change')))
+ exec('sh -c "cd /var/enginegp; php cron.php '.$cfg['cron_key'].' server_action restart '.$server['game'].' '.$add_buy['server'].'"');
+ }
- $sql->query('UPDATE `address` set `buy`="0" WHERE `id`="'.$add_buy['aid'].'" LIMIT 1');
- $sql->query('DELETE FROM `address_buy` WHERE `id`="'.$add_buy['id'].'" LIMIT 1');
- }
+ $sql->query('UPDATE `address` set `buy`="0" WHERE `id`="'.$add_buy['aid'].'" LIMIT 1');
+ $sql->query('DELETE FROM `address_buy` WHERE `id`="'.$add_buy['id'].'" LIMIT 1');
+ }
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/cron/users_recovery_signup.php b/system/library/cron/users_recovery_signup.php
index bc29f13..072a0b8 100644
--- a/system/library/cron/users_recovery_signup.php
+++ b/system/library/cron/users_recovery_signup.php
@@ -1,19 +1,19 @@
query('DELETE FROM `signup` WHERE `date`<"'.$time.'"');
- $sql->query('DELETE FROM `recovery` WHERE `date`<"'.$time.'"');
+ $sql->query('DELETE FROM `signup` WHERE `date`<"'.$time.'"');
+ $sql->query('DELETE FROM `recovery` WHERE `date`<"'.$time.'"');
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/cron/web_delete.php b/system/library/cron/web_delete.php
index d2386f9..970582b 100644
--- a/system/library/cron/web_delete.php
+++ b/system/library/cron/web_delete.php
@@ -1,36 +1,36 @@
query('SELECT `id`, `login`, `type`, `server`, `unit` FROM `web` WHERE `id`="'.$argv[3].'" LIMIT 1');
- $web = $sql->get();
+ $sql->query('SELECT `id`, `login`, `type`, `server`, `unit` FROM `web` WHERE `id`="'.$argv[3].'" LIMIT 1');
+ $web = $sql->get();
- if($web['type'] == 'hosting')
- {
- include(DATA.'web.php');
+ if($web['type'] == 'hosting')
+ {
+ include(DATA.'web.php');
- $result = json_decode(file_get_contents(sys::updtext($aWebUnit['isp']['account']['delete'], array('login' => $web['login']))), true);
+ $result = json_decode(file_get_contents(sys::updtext($aWebUnit['isp']['account']['delete'], array('login' => $web['login']))), true);
- if(!isset($result['result']) || strtolower($result['result']) != 'ok')
- continue;
+ if(!isset($result['result']) || strtolower($result['result']) != 'ok')
+ continue;
- $sql->query('DELETE FROM `web` WHERE `id`="'.$web['id'].'" LIMIT 1');
- }
+ $sql->query('DELETE FROM `web` WHERE `id`="'.$web['id'].'" LIMIT 1');
+ }
- include(LIB.'web/free.php');
+ include(LIB.'web/free.php');
- $aData = array(
- 'type' => $web['type'],
- 'server' => array('id' => $web['server'], 'unit' => $web['unit'], 'user' => 0, 'game' => 'system')
- );
+ $aData = array(
+ 'type' => $web['type'],
+ 'server' => array('id' => $web['server'], 'unit' => $web['unit'], 'user' => 0, 'game' => 'system')
+ );
- web::delete($aData, false);
- }
- }
+ web::delete($aData, false);
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/ftp.php b/system/library/ftp.php
index 2778dac..bb30b6c 100644
--- a/system/library/ftp.php
+++ b/system/library/ftp.php
@@ -1,516 +1,516 @@
'Понедельник',
- 'Tue' => 'Вторник',
- 'Wed' => 'Среда',
- 'Thu' => 'Четверг',
- 'Fri' => 'Пятница',
- 'Sat' => 'Суббота',
- 'Sun' => 'Воскресенье'
- );
-
- var $mounthint = array(
- 'Jan' => '01',
- 'Feb' => '02',
- 'Mar' => '03',
- 'Apr' => '04',
- 'May' => '05',
- 'Jun' => '06',
- 'Jul' => '07',
- 'Aug' => '08',
- 'Sep' => '09',
- 'Oct' => '10',
- 'Nov' => '11',
- 'Dec' => '12'
- );
-
- var $mounthru = array(
- 'Jan' => 'Янв',
- 'Feb' => 'Фев',
- 'Mar' => 'Мар',
- 'Apr' => 'Апр',
- 'May' => 'Май',
- 'Jun' => 'Июн',
- 'Jul' => 'Июл',
- 'Aug' => 'Авг',
- 'Sep' => 'Сен',
- 'Oct' => 'Окт',
- 'Nov' => 'Ноя',
- 'Dec' => 'Дек'
- );
-
- var $aEdits = array(
- 'txt',
- 'cfg',
- 'conf',
- 'json',
- 'xml',
- 'ini',
- 'gam',
- 'php',
- 'html',
- 'inf',
- 'js',
- 'css',
- 'sma',
- 'log'
- );
-
- public function auth($host, $user, $password, $port = 21)
- {
- $ftp_connect = @ftp_connect($host, $port);
-
- if(!$ftp_connect)
- return false;
-
- if(!@ftp_login($ftp_connect, $user, $password))
- return false;
-
- @ftp_pasv($ftp_connect, true);
-
- $this->steck = $ftp_connect;
-
- return true;
- }
-
- public function read($path)
- {
- $path = ($path == '') ? '/' : $path;
-
- $path = str_replace('//', '/', $path);
-
- $aDir = array();
- $aFile = array();
- $aInfo = array();
-
- $rawlist = array();
-
- $data = ftp_rawlist($this->steck, $path);
-
- if(is_array($data))
- foreach($data as $index)
- {
- $vinfo = preg_split('/[\s]+/', $index, 9);
-
- if($vinfo[0] !== 'total')
- {
- $aInfo['chmod'] = $vinfo[0];
- $aInfo['num'] = $vinfo[1];
- $aInfo['owner'] = $vinfo[2];
- $aInfo['group'] = $vinfo[3];
- $aInfo['size'] = $vinfo[4];
- $aInfo['month'] = $vinfo[5];
- $aInfo['day'] = $vinfo[6];
- $aInfo['time'] = $vinfo[7];
- $aInfo['name'] = $vinfo[8];
-
- $rawlist[$aInfo['name']] = $aInfo;
- }
- }
-
- foreach($rawlist as $name => $data)
- {
- if($data['chmod']{0} == 'd')
- $aDir[$name] = $data;
-
- elseif($data['chmod']{0} == '-')
- $aFile[$name] = $data;
- }
-
- $aData = array(
- 'folder' => $aDir,
- 'file' => $aFile,
- 'path' => $path
- );
-
- return $aData;
- }
-
- public function view($view, $server)
- {
- global $html;
-
- if($view['path'] != '/')
- {
- $html->get('filetp_back', 'sections/servers/games/filetp');
-
- $html->set('back', $this->path($view['path']));
-
- $html->pack('list');
- }
+ exit(header('Refresh: 0; URL=http://'.$_SERVER['SERVER_NAME'].'/404'));
+
+ class ftp
+ {
+ var $steck = false;
+
+ var $dayru = array(
+ 'Mon' => 'Понедельник',
+ 'Tue' => 'Вторник',
+ 'Wed' => 'Среда',
+ 'Thu' => 'Четверг',
+ 'Fri' => 'Пятница',
+ 'Sat' => 'Суббота',
+ 'Sun' => 'Воскресенье'
+ );
+
+ var $mounthint = array(
+ 'Jan' => '01',
+ 'Feb' => '02',
+ 'Mar' => '03',
+ 'Apr' => '04',
+ 'May' => '05',
+ 'Jun' => '06',
+ 'Jul' => '07',
+ 'Aug' => '08',
+ 'Sep' => '09',
+ 'Oct' => '10',
+ 'Nov' => '11',
+ 'Dec' => '12'
+ );
+
+ var $mounthru = array(
+ 'Jan' => 'Янв',
+ 'Feb' => 'Фев',
+ 'Mar' => 'Мар',
+ 'Apr' => 'Апр',
+ 'May' => 'Май',
+ 'Jun' => 'Июн',
+ 'Jul' => 'Июл',
+ 'Aug' => 'Авг',
+ 'Sep' => 'Сен',
+ 'Oct' => 'Окт',
+ 'Nov' => 'Ноя',
+ 'Dec' => 'Дек'
+ );
+
+ var $aEdits = array(
+ 'txt',
+ 'cfg',
+ 'conf',
+ 'json',
+ 'xml',
+ 'ini',
+ 'gam',
+ 'php',
+ 'html',
+ 'inf',
+ 'js',
+ 'css',
+ 'sma',
+ 'log'
+ );
+
+ public function auth($host, $user, $password, $port = 21)
+ {
+ $ftp_connect = @ftp_connect($host, $port);
+
+ if(!$ftp_connect)
+ return false;
+
+ if(!@ftp_login($ftp_connect, $user, $password))
+ return false;
+
+ @ftp_pasv($ftp_connect, true);
+
+ $this->steck = $ftp_connect;
+
+ return true;
+ }
+
+ public function read($path)
+ {
+ $path = ($path == '') ? '/' : $path;
+
+ $path = str_replace('//', '/', $path);
+
+ $aDir = array();
+ $aFile = array();
+ $aInfo = array();
+
+ $rawlist = array();
+
+ $data = ftp_rawlist($this->steck, $path);
+
+ if(is_array($data))
+ foreach($data as $index)
+ {
+ $vinfo = preg_split('/[\s]+/', $index, 9);
+
+ if($vinfo[0] !== 'total')
+ {
+ $aInfo['chmod'] = $vinfo[0];
+ $aInfo['num'] = $vinfo[1];
+ $aInfo['owner'] = $vinfo[2];
+ $aInfo['group'] = $vinfo[3];
+ $aInfo['size'] = $vinfo[4];
+ $aInfo['month'] = $vinfo[5];
+ $aInfo['day'] = $vinfo[6];
+ $aInfo['time'] = $vinfo[7];
+ $aInfo['name'] = $vinfo[8];
+
+ $rawlist[$aInfo['name']] = $aInfo;
+ }
+ }
+
+ foreach($rawlist as $name => $data)
+ {
+ if($data['chmod']{0} == 'd')
+ $aDir[$name] = $data;
+
+ elseif($data['chmod']{0} == '-')
+ $aFile[$name] = $data;
+ }
+
+ $aData = array(
+ 'folder' => $aDir,
+ 'file' => $aFile,
+ 'path' => $path
+ );
+
+ return $aData;
+ }
+
+ public function view($view, $server)
+ {
+ global $html;
+
+ if($view['path'] != '/')
+ {
+ $html->get('filetp_back', 'sections/servers/games/filetp');
+
+ $html->set('back', $this->path($view['path']));
+
+ $html->pack('list');
+ }
- foreach($view as $type => $aVal)
- {
- if(!is_array($aVal))
- continue;
+ foreach($view as $type => $aVal)
+ {
+ if(!is_array($aVal))
+ continue;
- foreach($aVal as $name => $info)
- {
- $html->get('filetp_list', 'sections/servers/games/filetp');
+ foreach($aVal as $name => $info)
+ {
+ $html->get('filetp_list', 'sections/servers/games/filetp');
- $html->set('id', $server);
- $html->set('name', $name);
+ $html->set('id', $server);
+ $html->set('name', $name);
- $path = $view['path'];
+ $path = $view['path'];
- if($path{0} != '/') $path = '/'.$path;
+ if($path{0} != '/') $path = '/'.$path;
- if($path != '/') $path = $path.'/';
+ if($path != '/') $path = $path.'/';
- $html->set('path', $path);
- $html->set('chmod', $this->cti($info['chmod']).' '.$info['chmod']);
- $html->set('owner', $info['owner']);
- $html->set('group', $info['group']);
+ $html->set('path', $path);
+ $html->set('chmod', $this->cti($info['chmod']).' '.$info['chmod']);
+ $html->set('owner', $info['owner']);
+ $html->set('group', $info['group']);
- if($type == 'folder')
- {
- $html->unit('folder', 1);
- $html->unit('file');
- $html->set('size', '');
- }else{
- $type = explode('.', $name);
+ if($type == 'folder')
+ {
+ $html->unit('folder', 1);
+ $html->unit('file');
+ $html->set('size', '');
+ }else{
+ $type = explode('.', $name);
- if(in_array(end($type), $this->aEdits))
- $html->unit('edit', 1);
- else
- $html->unit('edit');
+ if(in_array(end($type), $this->aEdits))
+ $html->unit('edit', 1);
+ else
+ $html->unit('edit');
- $html->unit('file', 1);
- $html->unit('folder');
- $html->set('size', sys::size($info['size']));
- }
+ $html->unit('file', 1);
+ $html->unit('folder');
+ $html->set('size', sys::size($info['size']));
+ }
- $html->set('month', $this->mounthru[$info['month']]);
- $html->set('day', $info['day']);
- $html->set('time', $info['time']);
+ $html->set('month', $this->mounthru[$info['month']]);
+ $html->set('day', $info['day']);
+ $html->set('time', $info['time']);
- $html->pack('list');
- }
- }
+ $html->pack('list');
+ }
+ }
- return isset($html->arr['list']) ? $html->arr['list'] : '';
- }
+ return isset($html->arr['list']) ? $html->arr['list'] : '';
+ }
- public function mkdir($path, $folders)
- {
- if(!@ftp_chdir($this->steck, $path))
- sys::outjs(array('e' => 'Ошибка: не удалось создать папку'));
+ public function mkdir($path, $folders)
+ {
+ if(!@ftp_chdir($this->steck, $path))
+ sys::outjs(array('e' => 'Ошибка: не удалось создать папку'));
- $aFolder = explode('/', $folders);
+ $aFolder = explode('/', $folders);
- foreach($aFolder as $folder)
- {
- if($folder == '')
- continue;
+ foreach($aFolder as $folder)
+ {
+ if($folder == '')
+ continue;
- if(!@ftp_chdir($this->steck, $folder))
- {
- if(!@ftp_mkdir($this->steck, $folder))
- sys::outjs(array('e' => 'Ошибка: не удалось создать папку '.$folder));
+ if(!@ftp_chdir($this->steck, $folder))
+ {
+ if(!@ftp_mkdir($this->steck, $folder))
+ sys::outjs(array('e' => 'Ошибка: не удалось создать папку '.$folder));
- @ftp_chdir($this->steck, $folder);
- }
- }
+ @ftp_chdir($this->steck, $folder);
+ }
+ }
- sys::outjs(array('s' => 'ok'));
- }
+ sys::outjs(array('s' => 'ok'));
+ }
- public function touch($path, $file, $text)
- {
- $aData = explode('/', $file);
+ public function touch($path, $file, $text)
+ {
+ $aData = explode('/', $file);
- $path_file = '';
+ $path_file = '';
- if(count($aData))
- {
- $file = end($aData);
+ if(count($aData))
+ {
+ $file = end($aData);
- unset($aData[count($aData)-1]);
+ unset($aData[count($aData)-1]);
- foreach($aData as $val)
- $path_file .= $val.'/';
- }
+ foreach($aData as $val)
+ $path_file .= $val.'/';
+ }
- $dir = str_replace('//', '', $path.'/'.$path_file);
+ $dir = str_replace('//', '', $path.'/'.$path_file);
- $dir = ($dir == '') ? '/' : $dir;
+ $dir = ($dir == '') ? '/' : $dir;
- if(!@ftp_chdir($this->steck, $dir))
- sys::outjs(array('e' => 'Ошибка: не удалось создать файл'));
+ if(!@ftp_chdir($this->steck, $dir))
+ sys::outjs(array('e' => 'Ошибка: не удалось создать файл'));
- $temp = sys::temp($text);
+ $temp = sys::temp($text);
- if(@ftp_put($this->steck, $file, $temp, FTP_BINARY))
- {
- unlink($temp);
+ if(@ftp_put($this->steck, $file, $temp, FTP_BINARY))
+ {
+ unlink($temp);
- sys::outjs(array('s' => 'ok'));
- }
+ sys::outjs(array('s' => 'ok'));
+ }
- unlink($temp);
+ unlink($temp);
- sys::outjs(array('e' => 'Ошибка: не удалось создать файл'));
- }
+ sys::outjs(array('e' => 'Ошибка: не удалось создать файл'));
+ }
- public function edit_file($path, $file)
- {
- $name = md5(time().$file.'ftp');
+ public function edit_file($path, $file)
+ {
+ $name = md5(time().$file.'ftp');
- if(@ftp_get($this->steck, TEMP.$name, $path.'/'.$file, FTP_BINARY))
- {
- $data = file_get_contents(TEMP.$name);
+ if(@ftp_get($this->steck, TEMP.$name, $path.'/'.$file, FTP_BINARY))
+ {
+ $data = file_get_contents(TEMP.$name);
- unlink(TEMP.$name);
+ unlink(TEMP.$name);
- sys::outjs(array('s' => $data));
- }
+ sys::outjs(array('s' => $data));
+ }
- sys::outjs(array('e' => 'Не удалось открыть файл'));
- }
+ sys::outjs(array('e' => 'Не удалось открыть файл'));
+ }
- public function rename($path, $oldname, $newname)
- {
- if(@ftp_rename($this->steck, $path.'/'.$oldname, $path.'/'.$newname))
- sys::outjs(array('s' => 'ok'));
+ public function rename($path, $oldname, $newname)
+ {
+ if(@ftp_rename($this->steck, $path.'/'.$oldname, $path.'/'.$newname))
+ sys::outjs(array('s' => 'ok'));
- sys::outjs(array('e' => 'Не удалось сменить имя'));
- }
+ sys::outjs(array('e' => 'Не удалось сменить имя'));
+ }
- public function rmdir($path, $folder)
- {
- if(@ftp_rmdir($this->steck, $path.'/'.$folder))
- sys::outjs(array('s' => 'ok'));
+ public function rmdir($path, $folder)
+ {
+ if(@ftp_rmdir($this->steck, $path.'/'.$folder))
+ sys::outjs(array('s' => 'ok'));
- sys::outjs(array('e' => 'Ошибка: не удалось удалить папку.'));
- }
+ sys::outjs(array('e' => 'Ошибка: не удалось удалить папку.'));
+ }
- public function rmfile($file)
- {
- if(@ftp_delete($this->steck, $file))
- sys::outjs(array('s' => 'ok'));
+ public function rmfile($file)
+ {
+ if(@ftp_delete($this->steck, $file))
+ sys::outjs(array('s' => 'ok'));
- sys::outjs(array('e' => 'Ошибка: не удалось удалить файл'));
- }
+ sys::outjs(array('e' => 'Ошибка: не удалось удалить файл'));
+ }
- public function chmod($path, $name, $chmod)
- {
- if(ftp_site($this->steck, 'CHMOD 0'.$chmod.' '.$path.'/'.$name))
- sys::outjs(array('s' => 'ok'));
+ public function chmod($path, $name, $chmod)
+ {
+ if(ftp_site($this->steck, 'CHMOD 0'.$chmod.' '.$path.'/'.$name))
+ sys::outjs(array('s' => 'ok'));
- sys::outjs(array('e' => 'Ошибка: не удалось изменить права.'));
- }
+ sys::outjs(array('e' => 'Ошибка: не удалось изменить права.'));
+ }
- public function search($str, $server)
- {
- global $html, $mcache;
+ public function search($str, $server)
+ {
+ global $html, $mcache;
- $nmch = md5($str.$server);
+ $nmch = md5($str.$server);
- $cache = $mcache->get($nmch);
+ $cache = $mcache->get($nmch);
- if(!is_array($cache))
- {
- $aData = ftp_rawlist($this->steck, '/', true);
+ if(!is_array($cache))
+ {
+ $aData = ftp_rawlist($this->steck, '/', true);
- if(!is_array($aData))
- sys::out('Ничего не найдено');
+ if(!is_array($aData))
+ sys::out('Ничего не найдено');
- // Файлы
- $aFile = array();
+ // Файлы
+ $aFile = array();
- // Файлы в корне
- $end = array_search('', $aData);
+ // Файлы в корне
+ $end = array_search('', $aData);
- for($i = 0; $i < $end; $i+=1)
- {
- $aInfo = preg_split('/[\s]+/', $aData[$i], 9);
+ for($i = 0; $i < $end; $i+=1)
+ {
+ $aInfo = preg_split('/[\s]+/', $aData[$i], 9);
- $info = '';
+ $info = '';
- for($n = 0; $n < 8; $n+=1)
- $info .= $aInfo[$n].' ';
+ for($n = 0; $n < 8; $n+=1)
+ $info .= $aInfo[$n].' ';
- $aFile['/'][] = array('info' => $info, 'name' => $aInfo[8]);
- }
+ $aFile['/'][] = array('info' => $info, 'name' => $aInfo[8]);
+ }
- // Перебор директорий и файлов в них
- foreach($aData as $index)
- {
- $begin = array_search('', $aData);
- unset($aData[$begin]);
+ // Перебор директорий и файлов в них
+ foreach($aData as $index)
+ {
+ $begin = array_search('', $aData);
+ unset($aData[$begin]);
- $end = array_search('', $aData);
+ $end = array_search('', $aData);
- if(!$begin)
- break;
+ if(!$begin)
+ break;
- $dir = substr($aData[$begin+1], 0, -1);
+ $dir = substr($aData[$begin+1], 0, -1);
- for($i = $begin+2; $i < $end; $i+=1)
- {
- $aInfo = preg_split('/[\s]+/', $aData[$i], 9);
+ for($i = $begin+2; $i < $end; $i+=1)
+ {
+ $aInfo = preg_split('/[\s]+/', $aData[$i], 9);
- $info = '';
+ $info = '';
- for($n = 0; $n < 8; $n+=1)
- $info .= $aInfo[$n].' ';
+ for($n = 0; $n < 8; $n+=1)
+ $info .= $aInfo[$n].' ';
- $aFile[$dir][] = array('info' => $info, 'name' => $aInfo[8]);
- }
- }
+ $aFile[$dir][] = array('info' => $info, 'name' => $aInfo[8]);
+ }
+ }
- $mcache->set($nmch, $aFile, false, 20);
- }else
- $aFile = $cache;
+ $mcache->set($nmch, $aFile, false, 20);
+ }else
+ $aFile = $cache;
- $aFind = array();
+ $aFind = array();
- // Поиск
- foreach($aFile as $dir => $files)
- {
- foreach($files as $file)
- {
- $find = sys::first(explode('.', $file['name']));
+ // Поиск
+ foreach($aFile as $dir => $files)
+ {
+ foreach($files as $file)
+ {
+ $find = sys::first(explode('.', $file['name']));
- if(preg_match('/'.$str.'/i', $find))
- $aFind[] = array('dir' => $dir, 'info' => $file['info'], 'file' => $file['name'], 'find' => sys::find($file['name'], $str));
- }
- }
+ if(preg_match('/'.$str.'/i', $find))
+ $aFind[] = array('dir' => $dir, 'info' => $file['info'], 'file' => $file['name'], 'find' => sys::find($file['name'], $str));
+ }
+ }
- unset($aFile);
+ unset($aFile);
- foreach($aFind as $data)
- {
- $info = preg_split('/[\s]+/', trim($data['info']), 8);
+ foreach($aFind as $data)
+ {
+ $info = preg_split('/[\s]+/', trim($data['info']), 8);
- $html->get('filetp_find', 'sections/servers/games/filetp');
+ $html->get('filetp_find', 'sections/servers/games/filetp');
- $html->set('id', $server);
- $html->set('find', $data['find']);
- $html->set('name', $data['file']);
+ $html->set('id', $server);
+ $html->set('find', $data['find']);
+ $html->set('name', $data['file']);
- $path = $data['dir'];
+ $path = $data['dir'];
- if($path{0} != '/') $path = '/'.$path;
+ if($path{0} != '/') $path = '/'.$path;
- if($path != '/') $path = $path.'/';
+ if($path != '/') $path = $path.'/';
- $html->set('path', $path);
- $html->set('chmod', $this->cti($info[0]).' '.$info[0]);
- $html->set('owner', $info[2]);
- $html->set('group', $info[3]);
+ $html->set('path', $path);
+ $html->set('chmod', $this->cti($info[0]).' '.$info[0]);
+ $html->set('owner', $info[2]);
+ $html->set('group', $info[3]);
- if($info[0]{0} == 'd')
- {
- $html->unit('folder', 1);
- $html->unit('file');
- $html->set('size', '');
- }else{
- $type = explode('.', $data['file']);
+ if($info[0]{0} == 'd')
+ {
+ $html->unit('folder', 1);
+ $html->unit('file');
+ $html->set('size', '');
+ }else{
+ $type = explode('.', $data['file']);
- if(in_array(end($type), $this->aEdits))
- $html->unit('edit', 1);
- else
- $html->unit('edit');
+ if(in_array(end($type), $this->aEdits))
+ $html->unit('edit', 1);
+ else
+ $html->unit('edit');
- $html->unit('file', 1);
- $html->unit('folder');
- $html->set('size', sys::size($info[4]));
- }
+ $html->unit('file', 1);
+ $html->unit('folder');
+ $html->set('size', sys::size($info[4]));
+ }
- $html->set('month', $this->mounthru[$info[5]]);
- $html->set('day', $info[6]);
- $html->set('time', $info[7]);
+ $html->set('month', $this->mounthru[$info[5]]);
+ $html->set('day', $info[6]);
+ $html->set('time', $info[7]);
- $html->pack('list');
- }
+ $html->pack('list');
+ }
- if(isset($html->arr['list']))
- sys::out($html->arr['list']);
+ if(isset($html->arr['list']))
+ sys::out($html->arr['list']);
- sys::out('Ничего не найдено');
- }
+ sys::out('Ничего не найдено');
+ }
- public function logs($data, $uid)
- {
- global $html;
+ public function logs($data, $uid)
+ {
+ global $html;
- $aLine = explode("\n", $data);
+ $aLine = explode("\n", $data);
- $actions = array('i' => 'загрузка', 'o' => 'скачивание', 'd' => 'удаление');
- $acticon = array('i' => ' ', 'o' => ' ', 'd' => ' ');
+ $actions = array('i' => 'загрузка', 'o' => 'скачивание', 'd' => 'удаление');
+ $acticon = array('i' => ' ', 'o' => ' ', 'd' => ' ');
- unset($aLine[count($aLine)-1]);
+ unset($aLine[count($aLine)-1]);
- rsort($aLine);
+ rsort($aLine);
- foreach($aLine as $line)
- {
- $aData = explode('\\', $line);
+ foreach($aLine as $line)
+ {
+ $aData = explode('\\', $line);
- $html->get('filetp_logs', 'sections/servers/games/filetp');
+ $html->get('filetp_logs', 'sections/servers/games/filetp');
- $html->set('month', $this->mounthint[$aData[0]]);
- $html->set('day', $aData[1]);
- $html->set('time', $aData[2]);
- $html->set('year', $aData[3]);
- $html->set('who', $this->who($aData[4]));
- $html->set('size', sys::size($aData[5]));
- $html->set('file', str_replace('/servers/'.$uid.'/', '', $aData[6]));
- $html->set('action', $actions[$aData[7]]);
- $html->set('acticon', $acticon[$aData[7]]);
+ $html->set('month', $this->mounthint[$aData[0]]);
+ $html->set('day', $aData[1]);
+ $html->set('time', $aData[2]);
+ $html->set('year', $aData[3]);
+ $html->set('who', $this->who($aData[4]));
+ $html->set('size', sys::size($aData[5]));
+ $html->set('file', str_replace('/servers/'.$uid.'/', '', $aData[6]));
+ $html->set('action', $actions[$aData[7]]);
+ $html->set('acticon', $acticon[$aData[7]]);
- $html->pack('logs');
- }
+ $html->pack('logs');
+ }
- return isset($html->arr['logs']) ? $html->arr['logs'] : 'Список логов отсутствует';
- }
+ return isset($html->arr['logs']) ? $html->arr['logs'] : 'Список логов отсутствует';
+ }
- private function path($path)
- {
- $path = str_replace('//', '/', $path);
+ private function path($path)
+ {
+ $path = str_replace('//', '/', $path);
- $path = explode('/', $path);
+ $path = explode('/', $path);
- unset($path[count($path)-1]);
+ unset($path[count($path)-1]);
- $newpath = '/';
+ $newpath = '/';
- foreach($path as $index => $val)
- if(count($path)-1 == $index) $newpath .= $val; else $newpath .= $val.'/';
+ foreach($path as $index => $val)
+ if(count($path)-1 == $index) $newpath .= $val; else $newpath .= $val.'/';
- return str_replace('//', '/', $newpath);
- }
+ return str_replace('//', '/', $newpath);
+ }
- private function cti($chmod)
- {
- $intchmod = array('-' => '0', 'r' => '4', 'w' => '2', 'x' => '1');
+ private function cti($chmod)
+ {
+ $intchmod = array('-' => '0', 'r' => '4', 'w' => '2', 'x' => '1');
- $chmod = substr(strtr($chmod, $intchmod), 1);
+ $chmod = substr(strtr($chmod, $intchmod), 1);
- $split = str_split($chmod, 3);
+ $split = str_split($chmod, 3);
- return array_sum(str_split($split[0])).array_sum(str_split($split[1])).array_sum(str_split($split[2]));
- }
+ return array_sum(str_split($split[0])).array_sum(str_split($split[1])).array_sum(str_split($split[2]));
+ }
- private function who($address)
- {
- global $cfg, $uip;
+ private function who($address)
+ {
+ global $cfg, $uip;
- if($address == $cfg['ip'])
- return 'панель управления';
+ if($address == $cfg['ip'])
+ return 'панель управления';
- if($address == $uip)
- return 'вы';
+ if($address == $uip)
+ return 'вы';
- return $address;
- }
- }
+ return $address;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/games/actions.php b/system/library/games/actions.php
index aa1a7b8..7a4537d 100644
--- a/system/library/games/actions.php
+++ b/system/library/games/actions.php
@@ -1,316 +1,316 @@
query('SELECT `uid`, `unit`, `game`, `address`, `name` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `uid`, `unit`, `game`, `address`, `name` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return array('e' => sys::text('error', 'ssh'));
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return array('e' => sys::text('error', 'ssh'));
- $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
- .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
+ $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
+ .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
- // Обновление информации в базе
- $sql->query('UPDATE `servers` set `status`="off", `online`="0", `players`="", `stop`="0" WHERE `id`="'.$id.'" LIMIT 1');
+ // Обновление информации в базе
+ $sql->query('UPDATE `servers` set `status`="off", `online`="0", `players`="", `stop`="0" WHERE `id`="'.$id.'" LIMIT 1');
- // Сброс кеша
- actions::clmcache($id);
+ // Сброс кеша
+ actions::clmcache($id);
- sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0, 'players' => ''));
- sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0));
+ sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0, 'players' => ''));
+ sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0));
- return array('s' => 'ok');
- }
+ return array('s' => 'ok');
+ }
- public static function change($id, $map = false)
- {
- global $cfg, $sql, $html, $user, $mcache;
+ public static function change($id, $map = false)
+ {
+ global $cfg, $sql, $html, $user, $mcache;
- // Если в кеше есть карты
- if($mcache->get('server_maps_change_'.$id) != '' && !$map)
- return array('maps' => $mcache->get('server_maps_change_'.$id));
+ // Если в кеше есть карты
+ if($mcache->get('server_maps_change_'.$id) != '' && !$map)
+ return array('maps' => $mcache->get('server_maps_change_'.$id));
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- $sql->query('SELECT `uid`, `unit`, `game`, `tarif`, `online`, `players`, `name` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `uid`, `unit`, `game`, `tarif`, `online`, `players`, `name` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
- $tarif = $sql->get();
+ $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
+ $tarif = $sql->get();
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return array('e' => sys::text('error', 'ssh'));
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return array('e' => sys::text('error', 'ssh'));
- // Массив карт игрового сервера (папка "maps")
- $aMaps = explode("\n", $ssh->get('cd '.$tarif['install'].$server['uid'].'/cstrike/maps/ && ls | grep .bsp | grep -v .bsp.'));
+ // Массив карт игрового сервера (папка "maps")
+ $aMaps = explode("\n", $ssh->get('cd '.$tarif['install'].$server['uid'].'/cstrike/maps/ && ls | grep .bsp | grep -v .bsp.'));
- // Удаление пустого элемента
- unset($aMaps[count($aMaps)-1]);
+ // Удаление пустого элемента
+ unset($aMaps[count($aMaps)-1]);
- // Удаление ".bsp"
- $aMaps = str_replace('.bsp', '', $aMaps);
+ // Удаление ".bsp"
+ $aMaps = str_replace('.bsp', '', $aMaps);
- // Если выбрана карта
- if($map)
- {
- // Проверка наличия выбранной карты
- if(!in_array($map, $aMaps))
- return array('e' => sys::updtext(sys::text('servers', 'change'), array('map' => $map.'.bsp')));
+ // Если выбрана карта
+ if($map)
+ {
+ // Проверка наличия выбранной карты
+ if(!in_array($map, $aMaps))
+ return array('e' => sys::updtext(sys::text('servers', 'change'), array('map' => $map.'.bsp')));
- // Отправка команды changelevel
- $ssh->set('sudo -u server'.$server['uid'].' screen -p 0 -S s_'.$server['uid'].' -X eval '."'stuff \"changelevel ".sys::cmd($map)."\"\015'");
+ // Отправка команды changelevel
+ $ssh->set('sudo -u server'.$server['uid'].' screen -p 0 -S s_'.$server['uid'].' -X eval '."'stuff \"changelevel ".sys::cmd($map)."\"\015'");
- // Обновление информации в базе
- $sql->query('UPDATE `servers` set `status`="change" WHERE `id`="'.$id.'" LIMIT 1');
+ // Обновление информации в базе
+ $sql->query('UPDATE `servers` set `status`="change" WHERE `id`="'.$id.'" LIMIT 1');
- // Сброс кеша
- actions::clmcache($id);
+ // Сброс кеша
+ actions::clmcache($id);
- sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'change', 'online' => $server['online'], 'players' => base64_decode($server['players'])));
- sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'change', 'online' => $server['online']));
+ sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'change', 'online' => $server['online'], 'players' => base64_decode($server['players'])));
+ sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'change', 'online' => $server['online']));
- return array('s' => 'ok');
- }
+ return array('s' => 'ok');
+ }
- // Сортировка списка карт
- sort($aMaps);
- reset($aMaps);
+ // Сортировка списка карт
+ sort($aMaps);
+ reset($aMaps);
- // Генерация списка карт для выбора
- foreach($aMaps as $map)
- {
- $html->get('change_list', 'sections/servers/games');
- $html->set('img', sys::img($map, $server['game']));
- $html->set('name', $map);
- $html->set('id', $id);
- $html->pack('maps');
- }
+ // Генерация списка карт для выбора
+ foreach($aMaps as $map)
+ {
+ $html->get('change_list', 'sections/servers/games');
+ $html->set('img', sys::img($map, $server['game']));
+ $html->set('name', $map);
+ $html->set('id', $id);
+ $html->pack('maps');
+ }
- // Запись карт в кеш
- $mcache->set('server_maps_change_'.$id, $html->arr['maps'], false, 30);
+ // Запись карт в кеш
+ $mcache->set('server_maps_change_'.$id, $html->arr['maps'], false, 30);
- return array('maps' => $html->arr['maps']);
- }
+ return array('maps' => $html->arr['maps']);
+ }
- public static function reinstall($id)
- {
- global $cfg, $sql, $user, $start_point;
+ public static function reinstall($id)
+ {
+ global $cfg, $sql, $user, $start_point;
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- $sql->query('SELECT `uid`, `unit`, `tarif`, `address`, `game`, `name`, `pack`, `plugins_use`, `ftp`, `reinstall`, `core_fix` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `uid`, `unit`, `tarif`, `address`, `game`, `name`, `pack`, `plugins_use`, `ftp`, `reinstall`, `core_fix` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- // Проверка времени переустановки
- $reinstall = $server['reinstall']+$cfg['reinstall'][$server['game']]*60;
+ // Проверка времени переустановки
+ $reinstall = $server['reinstall']+$cfg['reinstall'][$server['game']]*60;
- if($reinstall > $start_point && $user['group'] != 'admin')
- return array('e' => sys::updtext(sys::text('servers', 'reinstall'), array('time' => sys::date('max', $reinstall))));
+ if($reinstall > $start_point && $user['group'] != 'admin')
+ return array('e' => sys::updtext(sys::text('servers', 'reinstall'), array('time' => sys::date('max', $reinstall))));
- $sql->query('SELECT `address`, `passwd`, `sql_login`, `sql_passwd`, `sql_port`, `sql_ftp` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd`, `sql_login`, `sql_passwd`, `sql_port`, `sql_ftp` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- $sql->query('SELECT `path`, `install`, `plugins_install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
- $tarif = $sql->get();
+ $sql->query('SELECT `path`, `install`, `plugins_install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
+ $tarif = $sql->get();
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return array('e' => sys::text('error', 'ssh'));
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return array('e' => sys::text('error', 'ssh'));
- $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
- .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
+ $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
+ .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
- $taskset = '';
+ $taskset = '';
- // Если включена система автораспределения и не установлен фиксированный поток
- if($cfg['cpu_route'] && !$server['core_fix'])
- {
- $proc_stat = array();
+ // Если включена система автораспределения и не установлен фиксированный поток
+ if($cfg['cpu_route'] && !$server['core_fix'])
+ {
+ $proc_stat = array();
- $proc_stat[0] = $ssh->get('cat /proc/stat');
- }
+ $proc_stat[0] = $ssh->get('cat /proc/stat');
+ }
- // Директория сборки
- $path = $tarif['path'].$server['pack'];
+ // Директория сборки
+ $path = $tarif['path'].$server['pack'];
- // Директория игрового сервера
- $install = $tarif['install'].$server['uid'];
+ // Директория игрового сервера
+ $install = $tarif['install'].$server['uid'];
- // Если система автораспределения продолжить парсинг загрузки процессора
- if(isset($proc_stat))
- {
- $proc_stat[1] = $ssh->get('cat /proc/stat');
+ // Если система автораспределения продолжить парсинг загрузки процессора
+ if(isset($proc_stat))
+ {
+ $proc_stat[1] = $ssh->get('cat /proc/stat');
- // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
- $core = sys::cpu_idle($proc_stat, $server['unit'], false); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
+ // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
+ $core = sys::cpu_idle($proc_stat, $server['unit'], false); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
- if(!is_numeric($core))
- return array('e' => 'Не удается выполнить операцию, нет свободного потока.');
+ if(!is_numeric($core))
+ return array('e' => 'Не удается выполнить операцию, нет свободного потока.');
- $taskset = 'taskset -c '.$core;
- }
+ $taskset = 'taskset -c '.$core;
+ }
- if($server['core_fix'])
- {
- $core = $server['core_fix']-1;
- $taskset = 'taskset -c '.$core;
- }
+ if($server['core_fix'])
+ {
+ $core = $server['core_fix']-1;
+ $taskset = 'taskset -c '.$core;
+ }
- $ssh->set('rm -r '.$install.';' // Удаление директории игрового сервера
- .'mkdir '.$install.';' // Создание директории
- .'chown server'.$server['uid'].':1000 '.$install.';' // Изменение владельца и группы директории
- .'cd '.$install.' && sudo -u server'.$server['uid'].' '.$taskset.' screen -dmS r_'.$server['uid'].' sh -c "'
- .'cp -r '.$path.'/. .;' // Копирование файлов сборки для сервера
- .'find . -type d -exec chmod 700 {} \;;'
- .'find . -type f -exec chmod 600 {} \;;'
- .'chmod 500 '.params::$aFileGame[$server['game']].'"');
+ $ssh->set('rm -r '.$install.';' // Удаление директории игрового сервера
+ .'mkdir '.$install.';' // Создание директории
+ .'chown server'.$server['uid'].':1000 '.$install.';' // Изменение владельца и группы директории
+ .'cd '.$install.' && sudo -u server'.$server['uid'].' '.$taskset.' screen -dmS r_'.$server['uid'].' sh -c "'
+ .'cp -r '.$path.'/. .;' // Копирование файлов сборки для сервера
+ .'find . -type d -exec chmod 700 {} \;;'
+ .'find . -type f -exec chmod 600 {} \;;'
+ .'chmod 500 '.params::$aFileGame[$server['game']].'"');
- // Очистка записей в базе
- $sql->query('DELETE FROM `admins_'.$server['game'].'` WHERE `server`="'.$id.'"'); // Список админов на сервере
- $sql->query('DELETE FROM `plugins_install` WHERE `server`="'.$id.'"'); // Список установленных плагинов на сервере
+ // Очистка записей в базе
+ $sql->query('DELETE FROM `admins_'.$server['game'].'` WHERE `server`="'.$id.'"'); // Список админов на сервере
+ $sql->query('DELETE FROM `plugins_install` WHERE `server`="'.$id.'"'); // Список установленных плагинов на сервере
- // Запись установленных плагинов
- if($server['plugins_use'])
- {
- // Массив идентификаторов плагинов
- $aPlugins = sys::b64djs($tarif['plugins_install']);
+ // Запись установленных плагинов
+ if($server['plugins_use'])
+ {
+ // Массив идентификаторов плагинов
+ $aPlugins = sys::b64djs($tarif['plugins_install']);
- if(isset($aPlugins[$server['pack']]))
- {
- $plugins = explode(',', $aPlugins[$server['pack']]);
+ if(isset($aPlugins[$server['pack']]))
+ {
+ $plugins = explode(',', $aPlugins[$server['pack']]);
- foreach($plugins as $plugin)
- if($plugin)
- $sql->query('INSERT INTO `plugins_install` set `server`="'.$id.'", `plugin`="'.$plugin.'", `time`="'.$start_point.'"');
- }
- }
+ foreach($plugins as $plugin)
+ if($plugin)
+ $sql->query('INSERT INTO `plugins_install` set `server`="'.$id.'", `plugin`="'.$plugin.'", `time`="'.$start_point.'"');
+ }
+ }
- $core = !isset($core) ? 0 : $core+1;
+ $core = !isset($core) ? 0 : $core+1;
- // Обновление информации в базе
- $sql->query('UPDATE `servers` set `status`="reinstall", `reinstall`="'.$start_point.'", `core_use`="'.$core.'", `fastdl`="0" WHERE `id`="'.$id.'" LIMIT 1');
+ // Обновление информации в базе
+ $sql->query('UPDATE `servers` set `status`="reinstall", `reinstall`="'.$start_point.'", `core_use`="'.$core.'", `fastdl`="0" WHERE `id`="'.$id.'" LIMIT 1');
- // Логирование
- $sql->query('INSERT INTO `logs_sys` set `user`="'.$user['id'].'", `server`="'.$id.'", `text`="'.sys::text('syslogs', 'reinstall').'", `time`="'.$start_point.'"');
+ // Логирование
+ $sql->query('INSERT INTO `logs_sys` set `user`="'.$user['id'].'", `server`="'.$id.'", `text`="'.sys::text('syslogs', 'reinstall').'", `time`="'.$start_point.'"');
- // Сброс кеша
- actions::clmcache($id);
+ // Сброс кеша
+ actions::clmcache($id);
- sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'reinstall', 'online' => 0, 'players' => ''));
- sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'reinstall', 'online' => 0));
+ sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'reinstall', 'online' => 0, 'players' => ''));
+ sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'reinstall', 'online' => 0));
- return array('s' => 'ok');
- }
+ return array('s' => 'ok');
+ }
- public static function update($id)
- {
- global $cfg, $sql, $user, $start_point;
+ public static function update($id)
+ {
+ global $cfg, $sql, $user, $start_point;
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- $sql->query('SELECT `uid`, `unit`, `tarif`, `address`, `game`, `name`, `pack`, `plugins_use`, `ftp`, `update` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `uid`, `unit`, `tarif`, `address`, `game`, `name`, `pack`, `plugins_use`, `ftp`, `update` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- // Проверка времени обновления
- $update = $server['update']+$cfg['update'][$server['game']]*60;
+ // Проверка времени обновления
+ $update = $server['update']+$cfg['update'][$server['game']]*60;
- if($update > $start_point && $user['group'] != 'admin')
- return array('e' => sys::updtext(sys::text('servers', 'update'), array('time' => sys::date('max', $update))));
+ if($update > $start_point && $user['group'] != 'admin')
+ return array('e' => sys::updtext(sys::text('servers', 'update'), array('time' => sys::date('max', $update))));
- $sql->query('SELECT `address`, `passwd`, `sql_login`, `sql_passwd`, `sql_port`, `sql_ftp` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd`, `sql_login`, `sql_passwd`, `sql_port`, `sql_ftp` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- $sql->query('SELECT `update`, `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
- $tarif = $sql->get();
+ $sql->query('SELECT `update`, `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
+ $tarif = $sql->get();
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return array('e' => sys::text('error', 'ssh'));
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return array('e' => sys::text('error', 'ssh'));
- $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
- .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
+ $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
+ .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
- $taskset = '';
+ $taskset = '';
- // Если включена система автораспределения и не установлен фиксированный поток
- if($cfg['cpu_route'] && !$server['core_fix'])
- {
- $proc_stat = array();
+ // Если включена система автораспределения и не установлен фиксированный поток
+ if($cfg['cpu_route'] && !$server['core_fix'])
+ {
+ $proc_stat = array();
- $proc_stat[0] = $ssh->get('cat /proc/stat');
- }
+ $proc_stat[0] = $ssh->get('cat /proc/stat');
+ }
- // Директория обновлений сборки
- $path = $tarif['update'].$server['pack'];
+ // Директория обновлений сборки
+ $path = $tarif['update'].$server['pack'];
- // Директория игрового сервера
- $install = $tarif['install'].$server['uid'];
+ // Директория игрового сервера
+ $install = $tarif['install'].$server['uid'];
- // Если система автораспределения продолжить парсинг загрузки процессора
- if(isset($proc_stat))
- {
- $proc_stat[1] = $ssh->get('cat /proc/stat');
+ // Если система автораспределения продолжить парсинг загрузки процессора
+ if(isset($proc_stat))
+ {
+ $proc_stat[1] = $ssh->get('cat /proc/stat');
- // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
- $core = sys::cpu_idle($proc_stat, $server['unit'], false); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
+ // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
+ $core = sys::cpu_idle($proc_stat, $server['unit'], false); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
- if(!is_numeric($core))
- return array('e' => 'Не удается выполнить операцию, нет свободного потока.');
+ if(!is_numeric($core))
+ return array('e' => 'Не удается выполнить операцию, нет свободного потока.');
- $taskset = 'taskset -c '.$core;
- }
+ $taskset = 'taskset -c '.$core;
+ }
- if($server['core_fix'])
- {
- $core = $server['core_fix']-1;
- $taskset = 'taskset -c '.$core;
- }
+ if($server['core_fix'])
+ {
+ $core = $server['core_fix']-1;
+ $taskset = 'taskset -c '.$core;
+ }
- $ssh->set('cd '.$install.' && sudo -u server'.$server['uid'].' '.$taskset.' screen -dmS u_'.$server['uid'].' sh -c "cp -rv '.$path.'/. .;' // Копирование файлов обвновления сборки для сервера
- .'find . -type d -exec chmod 700 {} \;;'
- .'find . -type f -exec chmod 600 {} \;;'
- .'chmod 500 '.params::$aFileGame[$server['game']].'"');
+ $ssh->set('cd '.$install.' && sudo -u server'.$server['uid'].' '.$taskset.' screen -dmS u_'.$server['uid'].' sh -c "cp -rv '.$path.'/. .;' // Копирование файлов обвновления сборки для сервера
+ .'find . -type d -exec chmod 700 {} \;;'
+ .'find . -type f -exec chmod 600 {} \;;'
+ .'chmod 500 '.params::$aFileGame[$server['game']].'"');
- $core = !isset($core) ? 0 : $core+1;
+ $core = !isset($core) ? 0 : $core+1;
- // Обновление информации в базе
- $sql->query('UPDATE `servers` set `status`="update", `update`="'.$start_point.'", `core_use`="'.$core.'" WHERE `id`="'.$id.'" LIMIT 1');
+ // Обновление информации в базе
+ $sql->query('UPDATE `servers` set `status`="update", `update`="'.$start_point.'", `core_use`="'.$core.'" WHERE `id`="'.$id.'" LIMIT 1');
- // Логирование
- $sql->query('INSERT INTO `logs_sys` set `user`="'.$user['id'].'", `server`="'.$id.'", `text`="'.sys::text('syslogs', 'update').'", `time`="'.$start_point.'"');
+ // Логирование
+ $sql->query('INSERT INTO `logs_sys` set `user`="'.$user['id'].'", `server`="'.$id.'", `text`="'.sys::text('syslogs', 'update').'", `time`="'.$start_point.'"');
- // Сброс кеша
- actions::clmcache($id);
+ // Сброс кеша
+ actions::clmcache($id);
- sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'update', 'online' => 0, 'players' => ''));
- sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'update', 'online' => 0));
+ sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'update', 'online' => 0, 'players' => ''));
+ sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'update', 'online' => 0));
- return array('s' => 'ok');
- }
+ return array('s' => 'ok');
+ }
- public static function clmcache($id)
- {
- global $mcache;
+ public static function clmcache($id)
+ {
+ global $mcache;
- $mcache->delete('server_index_'.$id);
- $mcache->delete('server_resources_'.$id);
- $mcache->delete('server_status_'.$id);
- }
- }
\ No newline at end of file
+ $mcache->delete('server_index_'.$id);
+ $mcache->delete('server_resources_'.$id);
+ $mcache->delete('server_status_'.$id);
+ }
+ }
\ No newline at end of file
diff --git a/system/library/games/boost.php b/system/library/games/boost.php
index 0d96409..43b71fd 100644
--- a/system/library/games/boost.php
+++ b/system/library/games/boost.php
@@ -1,113 +1,113 @@
partner_key = $key;
- $this->service_url = $url;
- }
+ function __construct($key, $url)
+ {
+ $this->partner_key = $key;
+ $this->service_url = $url;
+ }
- public function def($data)
- {
- $aData = array(
- 'service' => 'boost',
- 'period' => $data['period'],
- 'address' => $data['address'],
- 'game' => 'cs16'
- );
+ public function def($data)
+ {
+ $aData = array(
+ 'service' => 'boost',
+ 'period' => $data['period'],
+ 'address' => $data['address'],
+ 'game' => 'cs16'
+ );
- $out = json_decode($this->defaultcurl(json_encode($aData)), true);
+ $out = json_decode($this->defaultcurl(json_encode($aData)), true);
- if($out['message'] == 'Услуга уже присутствует')
- $out = json_decode($this->defaultcurl(json_encode($aData), 'prolong'), true);
+ if($out['message'] == 'Услуга уже присутствует')
+ $out = json_decode($this->defaultcurl(json_encode($aData), 'prolong'), true);
- if(!array_key_exists('status', $out))
- array('error' => 'Не удалось приобрести услугу, повторите запрос позже.');
+ if(!array_key_exists('status', $out))
+ array('error' => 'Не удалось приобрести услугу, повторите запрос позже.');
- if(!$out['status'])
- return true;
+ if(!$out['status'])
+ return true;
- return array('error' => $out['message']);
- }
+ return array('error' => $out['message']);
+ }
- private function defaultcurl($data, $action = 'buy')
- {
- if(!($curl = curl_init()))
- array('error' => 'FAIL: curl_init().');
+ private function defaultcurl($data, $action = 'buy')
+ {
+ if(!($curl = curl_init()))
+ array('error' => 'FAIL: curl_init().');
- curl_setopt($curl, CURLOPT_URL, $this->service_url);
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($curl, CURLOPT_POST, true);
- curl_setopt($curl, CURLOPT_POSTFIELDS, 'key='.$this->partner_key.'&action='.$action.'&data='.$data);
+ curl_setopt($curl, CURLOPT_URL, $this->service_url);
+ curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
+ curl_setopt($curl, CURLOPT_POST, true);
+ curl_setopt($curl, CURLOPT_POSTFIELDS, 'key='.$this->partner_key.'&action='.$action.'&data='.$data);
- $out = curl_exec($curl);
+ $out = curl_exec($curl);
- curl_close($curl);
+ curl_close($curl);
- return $out;
- }
+ return $out;
+ }
- public function vipms($data)
- {
- $aData = array(
- 'format' => 'POST',
- 'country' => 'RU',
- 'hoster_id' => 1,
- 'key' => $this->partner_key,
- 'full_address' => $data['address'],
- 'service_id' => $data['period']
- );
+ public function vipms($data)
+ {
+ $aData = array(
+ 'format' => 'POST',
+ 'country' => 'RU',
+ 'hoster_id' => 1,
+ 'key' => $this->partner_key,
+ 'full_address' => $data['address'],
+ 'service_id' => $data['period']
+ );
- return $this->othercurl($aData);
- }
+ return $this->othercurl($aData);
+ }
- public function fulls($data)
- {
- $aData = array(
- 'format' => 'POST',
- 'country' => 'RU',
- 'hoster_id' => 1,
- 'key' => $this->partner_key,
- 'full_address' => $data['address'],
- 'service_id' => $data['period']
- );
+ public function fulls($data)
+ {
+ $aData = array(
+ 'format' => 'POST',
+ 'country' => 'RU',
+ 'hoster_id' => 1,
+ 'key' => $this->partner_key,
+ 'full_address' => $data['address'],
+ 'service_id' => $data['period']
+ );
- return $this->othercurl($aData);
- }
+ return $this->othercurl($aData);
+ }
- private function othercurl($aData)
- {
- if(!($curl = curl_init()))
- array('error' => 'FAIL: curl_init().');
+ private function othercurl($aData)
+ {
+ if(!($curl = curl_init()))
+ array('error' => 'FAIL: curl_init().');
- curl_setopt($curl, CURLOPT_URL, $this->service_url.'?'.urldecode(http_build_query($aData)));
- curl_setopt($curl, CURLOPT_POST, true);
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($curl, CURLOPT_POSTFIELDS, urldecode(http_build_query($aData)));
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
+ curl_setopt($curl, CURLOPT_URL, $this->service_url.'?'.urldecode(http_build_query($aData)));
+ curl_setopt($curl, CURLOPT_POST, true);
+ curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
+ curl_setopt($curl, CURLOPT_POSTFIELDS, urldecode(http_build_query($aData)));
+ curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
- $result = curl_exec($curl);
+ $result = curl_exec($curl);
- curl_close($curl);
+ curl_close($curl);
- if($result == 'OK')
- return true;
+ if($result == 'OK')
+ return true;
- $aErr = array(
- 1 => 'BAD_HOSTER_ID',
- 2 => 'HOSTER_NOT_FOUND',
- 3 => 'BAD_HOSTER_IP',
- 4 => 'FORM_INVALID',
- 5 => 'BAD_SERVICE_ID'
- );
+ $aErr = array(
+ 1 => 'BAD_HOSTER_ID',
+ 2 => 'HOSTER_NOT_FOUND',
+ 3 => 'BAD_HOSTER_IP',
+ 4 => 'FORM_INVALID',
+ 5 => 'BAD_SERVICE_ID'
+ );
- return array('error' => $aErr[$result]);
- }
- }
+ return array('error' => $aErr[$result]);
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/games/crmp/action.php b/system/library/games/crmp/action.php
index 9398e77..b8533a3 100644
--- a/system/library/games/crmp/action.php
+++ b/system/library/games/crmp/action.php
@@ -1,130 +1,130 @@
query('SELECT `uid`, `unit`, `tarif`, `game`, `address`, `slots_start`, `name`, `map_start`, `time_start`, `core_fix` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `uid`, `unit`, `tarif`, `game`, `address`, `slots_start`, `name`, `map_start`, `time_start`, `core_fix` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
+ $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
$tarif = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return array('e' => sys::text('error', 'ssh'));
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return array('e' => sys::text('error', 'ssh'));
- list($ip, $port) = explode(':', $server['address']);
+ list($ip, $port) = explode(':', $server['address']);
- // Убить процессы
- $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
- .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe;');
+ // Убить процессы
+ $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
+ .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe;');
- // Временный файл
- $temp = sys::temp(action::config($ip, $port, $server['slots_start'], $ssh->get('cat '.$tarif['install'].'/'.$server['uid'].'/server.cfg')));
+ // Временный файл
+ $temp = sys::temp(action::config($ip, $port, $server['slots_start'], $ssh->get('cat '.$tarif['install'].'/'.$server['uid'].'/server.cfg')));
- // Обновление файла server.cfg
- $ssh->setfile($temp, $tarif['install'].$server['uid'].'/server.cfg', 0644);
+ // Обновление файла server.cfg
+ $ssh->setfile($temp, $tarif['install'].$server['uid'].'/server.cfg', 0644);
- unlink($temp);
+ unlink($temp);
- $taskset = '';
+ $taskset = '';
- // Если включена система автораспределения и не установлен фиксированный поток
- if($cfg['cpu_route'] AND !$server['core_fix'])
- {
- $proc_stat = array();
+ // Если включена система автораспределения и не установлен фиксированный поток
+ if($cfg['cpu_route'] AND !$server['core_fix'])
+ {
+ $proc_stat = array();
- $proc_stat[0] = $ssh->get('cat /proc/stat');
- }
+ $proc_stat[0] = $ssh->get('cat /proc/stat');
+ }
- // Если система автораспределения продолжить парсинг загрузки процессора
- if(isset($proc_stat))
- {
- $ssh->set('cat /proc/stat');
- $proc_stat[1] = $ssh->get();
+ // Если система автораспределения продолжить парсинг загрузки процессора
+ if(isset($proc_stat))
+ {
+ $ssh->set('cat /proc/stat');
+ $proc_stat[1] = $ssh->get();
- // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
- $core = sys::cpu_idle($proc_stat, $server['unit'], false); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
+ // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
+ $core = sys::cpu_idle($proc_stat, $server['unit'], false); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
- if(!is_numeric($core))
- return array('e' => sys::text('error', 'cpu'));
+ if(!is_numeric($core))
+ return array('e' => sys::text('error', 'cpu'));
- $taskset = 'taskset -c '.$core;
- }
+ $taskset = 'taskset -c '.$core;
+ }
- if($server['core_fix'])
- {
- $core = $server['core_fix']-1;
- $taskset = 'taskset -c '.$core;
- }
+ if($server['core_fix'])
+ {
+ $core = $server['core_fix']-1;
+ $taskset = 'taskset -c '.$core;
+ }
- // Параметры запуска
- $bash = './samp03svr-cr';
+ // Параметры запуска
+ $bash = './samp03svr-cr';
- // Временный файл
- $temp = sys::temp($bash);
+ // Временный файл
+ $temp = sys::temp($bash);
- // Обновление файла start.sh
- $ssh->setfile($temp, $tarif['install'].$server['uid'].'/start.sh', 0500);
+ // Обновление файла start.sh
+ $ssh->setfile($temp, $tarif['install'].$server['uid'].'/start.sh', 0500);
- // Строка запуска
- $ssh->set('cd '.$tarif['install'].$server['uid'].';' // переход в директорию игрового сервера
- .'rm *.pid;' // Удаление *.pid файлов
- .'sudo -u server'.$server['uid'].' mkdir -p oldstart;' // Создание папки логов
- .'cat server_log.txt >> oldstart/'.date('d.m.Y_H:i:s', $server['time_start']).'.log; rm server_log.txt; rm oldstart/01.01.1970_03:00:00.log;' // Перемещение лога предыдущего запуска
- .'chown server'.$server['uid'].':1000 server.cfg start.sh;' // Обновление владельца файлов server.cfg start.sh
- .'sudo -u server'.$server['uid'].' screen -dmS s_'.$server['uid'].' '.$taskset.' sh -c "./start.sh"'); // Запуск игровго сервера
+ // Строка запуска
+ $ssh->set('cd '.$tarif['install'].$server['uid'].';' // переход в директорию игрового сервера
+ .'rm *.pid;' // Удаление *.pid файлов
+ .'sudo -u server'.$server['uid'].' mkdir -p oldstart;' // Создание папки логов
+ .'cat server_log.txt >> oldstart/'.date('d.m.Y_H:i:s', $server['time_start']).'.log; rm server_log.txt; rm oldstart/01.01.1970_03:00:00.log;' // Перемещение лога предыдущего запуска
+ .'chown server'.$server['uid'].':1000 server.cfg start.sh;' // Обновление владельца файлов server.cfg start.sh
+ .'sudo -u server'.$server['uid'].' screen -dmS s_'.$server['uid'].' '.$taskset.' sh -c "./start.sh"'); // Запуск игровго сервера
- $core = !isset($core) ? 0 : $core+1;
+ $core = !isset($core) ? 0 : $core+1;
- // Обновление информации в базе
- $sql->query('UPDATE `servers` set `status`="'.$type.'", `online`="0", `players`="", `core_use`="'.$core.'", `time_start`="'.$start_point.'", `stop`="1" WHERE `id`="'.$id.'" LIMIT 1');
+ // Обновление информации в базе
+ $sql->query('UPDATE `servers` set `status`="'.$type.'", `online`="0", `players`="", `core_use`="'.$core.'", `time_start`="'.$start_point.'", `stop`="1" WHERE `id`="'.$id.'" LIMIT 1');
- unlink($temp);
+ unlink($temp);
- // Сброс кеша
- actions::clmcache($id);
+ // Сброс кеша
+ actions::clmcache($id);
- sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0, 'players' => ''));
- sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0));
+ sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0, 'players' => ''));
+ sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0));
- return array('s' => 'ok');
- }
+ return array('s' => 'ok');
+ }
- public static function config($ip, $port, $slots, $config)
- {
- $aLine = explode("\n", $config);
+ public static function config($ip, $port, $slots, $config)
+ {
+ $aLine = explode("\n", $config);
- $eConfig = '';
+ $eConfig = '';
- foreach($aLine as $line)
- {
- $param = explode(' ', trim($line));
+ foreach($aLine as $line)
+ {
+ $param = explode(' ', trim($line));
- if(in_array(trim($param[0]), array('bind', 'port', 'maxplayers', 'query')))
- continue;
+ if(in_array(trim($param[0]), array('bind', 'port', 'maxplayers', 'query')))
+ continue;
- $eConfig .= $line.PHP_EOL;
- }
+ $eConfig .= $line.PHP_EOL;
+ }
- $eConfig .= 'bind '.$ip.PHP_EOL
- .'port '.$port.PHP_EOL
- .'maxplayers '.$slots.PHP_EOL
- .'query 1';
+ $eConfig .= 'bind '.$ip.PHP_EOL
+ .'port '.$port.PHP_EOL
+ .'maxplayers '.$slots.PHP_EOL
+ .'query 1';
- return $eConfig;
- }
+ return $eConfig;
+ }
}
?>
\ No newline at end of file
diff --git a/system/library/games/crmp/scan.php b/system/library/games/crmp/scan.php
index 5545de9..e79dade 100644
--- a/system/library/games/crmp/scan.php
+++ b/system/library/games/crmp/scan.php
@@ -1,115 +1,115 @@
query('SELECT `address`, `game`, `name`, `map`, `online`, `players`, `status`, `time`, `overdue` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `address`, `game`, `name`, `map`, `online`, `players`, `status`, `time`, `overdue` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- list($ip, $port) = explode(':', $server['address']);
+ list($ip, $port) = explode(':', $server['address']);
- include(LIB.'games/query/SampQuery.php');
+ include(LIB.'games/query/SampQuery.php');
- $sq = new SampQuery($ip, $port);
+ $sq = new SampQuery($ip, $port);
- if($players_get)
- $nmch = 'server_scan_mon_pl_'.$id;
- else
- $nmch = 'server_scan_mon_'.$id;
+ if($players_get)
+ $nmch = 'server_scan_mon_pl_'.$id;
+ else
+ $nmch = 'server_scan_mon_'.$id;
- if(is_array($mcache->get($nmch)))
- return $mcache->get($nmch);
+ if(is_array($mcache->get($nmch)))
+ return $mcache->get($nmch);
- $out = array();
+ $out = array();
- $out['time'] = 'Арендован до: '.date('d.m.Y - H:i', $server['time']);
+ $out['time'] = 'Арендован до: '.date('d.m.Y - H:i', $server['time']);
- if($server['status'] == 'overdue')
- $out['time_end'] = 'Удаление через: '.sys::date('min', $server['overdue']+$cfg['server_delete']*86400);
- else
- $out['time_end'] = 'Осталось: '.sys::date('min', $server['time']);
+ if($server['status'] == 'overdue')
+ $out['time_end'] = 'Удаление через: '.sys::date('min', $server['overdue']+$cfg['server_delete']*86400);
+ else
+ $out['time_end'] = 'Осталось: '.sys::date('min', $server['time']);
- if(!$sq->connect())
- {
- $out['name'] = $server['name'];
- $out['status'] = sys::status($server['status'], $server['game'], $server['map']);
- $out['online'] = $server['online'];
- $out['image'] = ' ';
- $out['buttons'] = sys::buttons($id, $server['status'], $server['game']);
+ if(!$sq->connect())
+ {
+ $out['name'] = $server['name'];
+ $out['status'] = sys::status($server['status'], $server['game'], $server['map']);
+ $out['online'] = $server['online'];
+ $out['image'] = ' ';
+ $out['buttons'] = sys::buttons($id, $server['status'], $server['game']);
- if($players_get)
- $out['players'] = base64_decode($server['players']);
+ if($players_get)
+ $out['players'] = base64_decode($server['players']);
- $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
+ $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
- return $out;
- }
+ return $out;
+ }
- $info = $sq->getInfo();
+ $info = $sq->getInfo();
- if($players_get)
- $players = scan::players($sq->getDetailedPlayers());
+ if($players_get)
+ $players = scan::players($sq->getDetailedPlayers());
- $info['map'] = htmlspecialchars(mb_convert_encoding($info['map'], 'UTF-8', 'WINDOWS-1251'));
- $out['name'] = htmlspecialchars(mb_convert_encoding($info['hostname'], 'UTF-8', 'WINDOWS-1251'));
- $out['status'] = sys::status('working', $server['game'], $info['map']);
- $out['online'] = sys::int($info['players']);
- $out['image'] = ' ';
- $out['buttons'] = sys::buttons($id, 'working', $server['game']);
- $out['players'] = '';
+ $info['map'] = htmlspecialchars(mb_convert_encoding($info['map'], 'UTF-8', 'WINDOWS-1251'));
+ $out['name'] = htmlspecialchars(mb_convert_encoding($info['hostname'], 'UTF-8', 'WINDOWS-1251'));
+ $out['status'] = sys::status('working', $server['game'], $info['map']);
+ $out['online'] = sys::int($info['players']);
+ $out['image'] = ' ';
+ $out['buttons'] = sys::buttons($id, 'working', $server['game']);
+ $out['players'] = '';
- if($players_get)
- {
- foreach($players as $index => $player)
- {
- $html->get($server['game'], 'sections/servers/players');
+ if($players_get)
+ {
+ foreach($players as $index => $player)
+ {
+ $html->get($server['game'], 'sections/servers/players');
- $html->set('i', $player['i']);
- $html->set('name', htmlspecialchars($player['name']));
- $html->set('ping', sys::int($player['ping']));
+ $html->set('i', $player['i']);
+ $html->set('name', htmlspecialchars($player['name']));
+ $html->set('ping', sys::int($player['ping']));
- $html->pack('list');
- }
+ $html->pack('list');
+ }
- $out['players'] = isset($html->arr['list']) ? $html->arr['list'] : '';
- }
+ $out['players'] = isset($html->arr['list']) ? $html->arr['list'] : '';
+ }
- $sql->query('UPDATE `servers` set '
- .'`name`="'.$out['name'].'", '
- .'`online`="'.$out['online'].'", '
- .'`map`="'.$info['map'].'", '
- .'`status`="working" WHERE `id`="'.$id.'" LIMIT 1');
+ $sql->query('UPDATE `servers` set '
+ .'`name`="'.$out['name'].'", '
+ .'`online`="'.$out['online'].'", '
+ .'`map`="'.$info['map'].'", '
+ .'`status`="working" WHERE `id`="'.$id.'" LIMIT 1');
- if($players_get)
- $sql->query('UPDATE `servers` set `players`="'.base64_encode($out['players']).'" WHERE `id`="'.$id.'" LIMIT 1');
+ if($players_get)
+ $sql->query('UPDATE `servers` set `players`="'.base64_encode($out['players']).'" WHERE `id`="'.$id.'" LIMIT 1');
- $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
+ $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
- return $out;
- }
+ return $out;
+ }
- public static function players($aPlayrs)
- {
- $i = 1;
- $aData = array();
+ public static function players($aPlayrs)
+ {
+ $i = 1;
+ $aData = array();
- foreach($aPlayrs as $n => $player)
- {
- $aData[$i]['i'] = $i;
- $aData[$i]['name'] = $player['nickname'] == '' ? 'Подключается' : htmlspecialchars($player['nickname']);
- $aData[$i]['ping'] = sys::int($player['ping']);
+ foreach($aPlayrs as $n => $player)
+ {
+ $aData[$i]['i'] = $i;
+ $aData[$i]['name'] = $player['nickname'] == '' ? 'Подключается' : htmlspecialchars($player['nickname']);
+ $aData[$i]['ping'] = sys::int($player['ping']);
- $i+=1;
- }
+ $i+=1;
+ }
- return $aData;
- }
- }
+ return $aData;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/games/crmp/service.php b/system/library/games/crmp/service.php
index 32e2531..46c862f 100644
--- a/system/library/games/crmp/service.php
+++ b/system/library/games/crmp/service.php
@@ -1,355 +1,355 @@
query('SELECT `address`, `test` FROM `units` WHERE `id`="'.$aData['unit'].'" AND `crmp`="1" AND `show`="1" LIMIT 1');
- if(!$sql->num())
- sys::outjs(array('e' => 'Локация не найдена.'));
+ // Проверка локации
+ $sql->query('SELECT `address`, `test` FROM `units` WHERE `id`="'.$aData['unit'].'" AND `crmp`="1" AND `show`="1" LIMIT 1');
+ if(!$sql->num())
+ sys::outjs(array('e' => 'Локация не найдена.'));
- $unit = $sql->get();
+ $unit = $sql->get();
- // Проверка тарифа
- $sql->query('SELECT `id` FROM `tarifs` WHERE `id`="'.$aData['tarif'].'" AND `unit`="'.$aData['unit'].'" AND `show`="1" LIMIT 1');
- if(!$sql->num())
- sys::outjs(array('e' => 'Тариф не найден.'));
+ // Проверка тарифа
+ $sql->query('SELECT `id` FROM `tarifs` WHERE `id`="'.$aData['tarif'].'" AND `unit`="'.$aData['unit'].'" AND `show`="1" LIMIT 1');
+ if(!$sql->num())
+ sys::outjs(array('e' => 'Тариф не найден.'));
- $sql->query('SELECT '
- .'`slots_min`,'
- .'`slots_max`,'
- .'`port_min`,'
- .'`port_max`,'
- .'`hostname`,'
- .'`packs`,'
- .'`time`,'
- .'`test`,'
- .'`tests`,'
- .'`discount`,'
- .'`ftp`,'
- .'`plugins`,'
- .'`console`,'
- .'`stats`,'
- .'`copy`,'
- .'`web`,'
- .'`plugins_install`,'
- .'`hdd`,'
- .'`autostop`,'
- .'`core_fix`,'
- .'`ip`,'
- .'`price`'
- .' FROM `tarifs` WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
+ $sql->query('SELECT '
+ .'`slots_min`,'
+ .'`slots_max`,'
+ .'`port_min`,'
+ .'`port_max`,'
+ .'`hostname`,'
+ .'`packs`,'
+ .'`time`,'
+ .'`test`,'
+ .'`tests`,'
+ .'`discount`,'
+ .'`ftp`,'
+ .'`plugins`,'
+ .'`console`,'
+ .'`stats`,'
+ .'`copy`,'
+ .'`web`,'
+ .'`plugins_install`,'
+ .'`hdd`,'
+ .'`autostop`,'
+ .'`core_fix`,'
+ .'`ip`,'
+ .'`price`'
+ .' FROM `tarifs` WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
- $tarif = $sql->get();
+ $tarif = $sql->get();
- // Проверка сборки
- if(!array_key_exists($aData['pack'], sys::b64djs($tarif['packs'], true)))
- sys::outjs(array('e' => 'Сборка не найдена.'));
+ // Проверка сборки
+ if(!array_key_exists($aData['pack'], sys::b64djs($tarif['packs'], true)))
+ sys::outjs(array('e' => 'Сборка не найдена.'));
- $test = 0;
+ $test = 0;
- // Проверка периода на тест
- if($aData['test'])
- {
- if(!$tarif['test'] || !$unit['test'])
- sys::outjs(array('e' => 'Тестовый период недоступен.'));
+ // Проверка периода на тест
+ if($aData['test'])
+ {
+ if(!$tarif['test'] || !$unit['test'])
+ sys::outjs(array('e' => 'Тестовый период недоступен.'));
- // Проверка на повторный запрос
- $sql->query('SELECT `id`, `game` FROM `tests` WHERE `user`="'.$user['id'].'" LIMIT 1');
- if($sql->num())
- {
- $test_info = $sql->get();
+ // Проверка на повторный запрос
+ $sql->query('SELECT `id`, `game` FROM `tests` WHERE `user`="'.$user['id'].'" LIMIT 1');
+ if($sql->num())
+ {
+ $test_info = $sql->get();
- if(!$cfg['tests']['game'] || $test_info['game'] == 'crmp')
- sys::outjs(array('e' => 'Тестовый период предоставляется один раз.'));
+ if(!$cfg['tests']['game'] || $test_info['game'] == 'crmp')
+ sys::outjs(array('e' => 'Тестовый период предоставляется один раз.'));
- $sql->query('SELECT `id` FROM `servers` WHERE `user`="'.$user['id'].'" AND `test`="1" LIMIT 1');
- if($sql->num() AND !$cfg['tests']['sametime'])
- sys::outjs(array('e' => 'Чтобы получить тестовый период другой игры, дождитесь окончания текущего.'));
- }
+ $sql->query('SELECT `id` FROM `servers` WHERE `user`="'.$user['id'].'" AND `test`="1" LIMIT 1');
+ if($sql->num() AND !$cfg['tests']['sametime'])
+ sys::outjs(array('e' => 'Чтобы получить тестовый период другой игры, дождитесь окончания текущего.'));
+ }
- // Проверка наличия мест на локации
- $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `test`="1" AND `time`>"'.$start_point.'" LIMIT '.$unit['test']);
- if($sql->num() == $unit['test'])
- sys::outjs(array('e' => 'Свободного места для тестового периода нет.'));
+ // Проверка наличия мест на локации
+ $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `test`="1" AND `time`>"'.$start_point.'" LIMIT '.$unit['test']);
+ if($sql->num() == $unit['test'])
+ sys::outjs(array('e' => 'Свободного места для тестового периода нет.'));
- // Проверка наличия мест для выбранного тарифа
- $sql->query('SELECT `id` FROM `servers` WHERE `tarif`="'.$aData['tarif'].'" AND `test`="1" AND `time`>"'.$start_point.'" LIMIT '.$tarif['tests']);
- if($sql->num() == $tarif['tests'])
- sys::outjs(array('e' => 'Свободного места для тестового периода выбранного тарифа нет.'));
+ // Проверка наличия мест для выбранного тарифа
+ $sql->query('SELECT `id` FROM `servers` WHERE `tarif`="'.$aData['tarif'].'" AND `test`="1" AND `time`>"'.$start_point.'" LIMIT '.$tarif['tests']);
+ if($sql->num() == $tarif['tests'])
+ sys::outjs(array('e' => 'Свободного места для тестового периода выбранного тарифа нет.'));
- $test = 1;
- }else
- // Проверка периода
- if(!$cfg['settlement_period'] AND !in_array($aData['time'], explode(':', $tarif['time'])))
- sys::outjs(array('e' => 'Переданные данные периода неверны.'));
+ $test = 1;
+ }else
+ // Проверка периода
+ if(!$cfg['settlement_period'] AND !in_array($aData['time'], explode(':', $tarif['time'])))
+ sys::outjs(array('e' => 'Переданные данные периода неверны.'));
- // Проверка слот
- if($aData['slots'] < $tarif['slots_min'] || $aData['slots'] > $tarif['slots_max'])
- sys::outjs(array('e' => 'Переданные данные слот неверны.'));
+ // Проверка слот
+ if($aData['slots'] < $tarif['slots_min'] || $aData['slots'] > $tarif['slots_max'])
+ sys::outjs(array('e' => 'Переданные данные слот неверны.'));
- // Определение суммы
- if($cfg['settlement_period'])
- {
- // Цена аренды за расчетный период
- $sum = games::define_sum($tarif['discount'], $tarif['price'], $aData['slots'], $start_point);
+ // Определение суммы
+ if($cfg['settlement_period'])
+ {
+ // Цена аренды за расчетный период
+ $sum = games::define_sum($tarif['discount'], $tarif['price'], $aData['slots'], $start_point);
- $aData['time'] = games::define_period('buy', params::$aDayMonth);
- }else
- $sum = games::define_sum($tarif['discount'], $tarif['price'], $aData['slots'], $aData['time']);
+ $aData['time'] = games::define_period('buy', params::$aDayMonth);
+ }else
+ $sum = games::define_sum($tarif['discount'], $tarif['price'], $aData['slots'], $aData['time']);
- // Проверка промо-кода
- $promo = games::define_promo(
- $aData['promo'],
- array(
- 'tarif' => $aData['tarif'],
- 'slots' => $aData['slots'],
- 'time' => $aData['time'],
- 'user' => $user['id']
- ),
- $tarif['discount'],
- $sum
- );
+ // Проверка промо-кода
+ $promo = games::define_promo(
+ $aData['promo'],
+ array(
+ 'tarif' => $aData['tarif'],
+ 'slots' => $aData['slots'],
+ 'time' => $aData['time'],
+ 'user' => $user['id']
+ ),
+ $tarif['discount'],
+ $sum
+ );
- $days = $aData['time']; // Кол-во дней аренды
+ $days = $aData['time']; // Кол-во дней аренды
- // Использование промо-кода
- if(is_array($promo))
- {
- if(array_key_exists('sum', $promo))
- $sum = $promo['sum'];
- else
- $days += $promo['days']; // Кол-во дней аренды с учетом подарочных (промо-код)
- }
+ // Использование промо-кода
+ if(is_array($promo))
+ {
+ if(array_key_exists('sum', $promo))
+ $sum = $promo['sum'];
+ else
+ $days += $promo['days']; // Кол-во дней аренды с учетом подарочных (промо-код)
+ }
- // Проверка баланса
- if($user['balance'] < $sum)
- sys::outjs(array('e' => 'У вас не хватает '.(round($sum-$user['balance'], 2)).' '.$cfg['currency']));
+ // Проверка баланса
+ if($user['balance'] < $sum)
+ sys::outjs(array('e' => 'У вас не хватает '.(round($sum-$user['balance'], 2)).' '.$cfg['currency']));
- // Выделенный адрес игрового сервера
- if(!empty($tarif['ip']))
- {
- $aIp = explode(':', $tarif['ip']);
+ // Выделенный адрес игрового сервера
+ if(!empty($tarif['ip']))
+ {
+ $aIp = explode(':', $tarif['ip']);
- $ip = false;
- $port = params::$aDefPort['crmp'];
+ $ip = false;
+ $port = params::$aDefPort['crmp'];
- // Проверка наличия свободного адреса
- foreach($aIp as $adr)
- {
- $adr = trim($adr);
+ // Проверка наличия свободного адреса
+ foreach($aIp as $adr)
+ {
+ $adr = trim($adr);
- $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `address` LIKE "'.$adr.':%" LIMIT 1');
- if(!$sql->num())
- {
- $ip = $adr;
+ $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `address` LIKE "'.$adr.':%" LIMIT 1');
+ if(!$sql->num())
+ {
+ $ip = $adr;
- break;
- }
- }
- }else{
- $ip = sys::first(explode(':', $unit['address']));
- $port = false;
+ break;
+ }
+ }
+ }else{
+ $ip = sys::first(explode(':', $unit['address']));
+ $port = false;
- // Проверка наличия свободного порта
- for($tarif['port_min']; $tarif['port_min'] <= $tarif['port_max']; $tarif['port_min']+=1)
- {
- $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND (`address`="'.$ip.':'.$tarif['port_min'].'" OR `port`="'.$tarif['port_min'].'") LIMIT 1');
- if(!$sql->num())
- {
- $port = $tarif['port_min'];
+ // Проверка наличия свободного порта
+ for($tarif['port_min']; $tarif['port_min'] <= $tarif['port_max']; $tarif['port_min']+=1)
+ {
+ $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND (`address`="'.$ip.':'.$tarif['port_min'].'" OR `port`="'.$tarif['port_min'].'") LIMIT 1');
+ if(!$sql->num())
+ {
+ $port = $tarif['port_min'];
- break;
- }
- }
- }
+ break;
+ }
+ }
+ }
- if(!$ip || !$port)
- {
- $sql->query('UPDATE `tarifs` set `show`="0" WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
+ if(!$ip || !$port)
+ {
+ $sql->query('UPDATE `tarifs` set `show`="0" WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
- sys::outjs(array('e' => 'К сожалению нет доступных мест, обратитесь в тех.поддержку.'));
- }
+ sys::outjs(array('e' => 'К сожалению нет доступных мест, обратитесь в тех.поддержку.'));
+ }
- if($test)
- $aData['time'] = games::time($start_point, $tarif['test']);
- else
- $aData['time'] = games::time($start_point, $days);
+ if($test)
+ $aData['time'] = games::time($start_point, $tarif['test']);
+ else
+ $aData['time'] = games::time($start_point, $days);
- $fix_one = 0;
- $core = 0;
+ $fix_one = 0;
+ $core = 0;
- if($tarif['core_fix'] != '')
- {
- $aCore = explode(',', $tarif['core_fix']);
+ if($tarif['core_fix'] != '')
+ {
+ $aCore = explode(',', $tarif['core_fix']);
- foreach($aCore as $cpu)
- {
- $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `tarif`="'.$aData['tarif'].'" AND `core_fix`="'.$cpu.'" AND `core_fix_one`="1" LIMIT 1');
+ foreach($aCore as $cpu)
+ {
+ $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `tarif`="'.$aData['tarif'].'" AND `core_fix`="'.$cpu.'" AND `core_fix_one`="1" LIMIT 1');
- if($sql->num())
- continue;
+ if($sql->num())
+ continue;
- $fix_one = 1;
- $core = $cpu;
+ $fix_one = 1;
+ $core = $cpu;
- break;
- }
+ break;
+ }
- if(!$core)
- {
- $sql->query('UPDATE `tarifs` set `show`="0" WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
+ if(!$core)
+ {
+ $sql->query('UPDATE `tarifs` set `show`="0" WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
- sys::outjs(array('e' => 'К сожалению нет доступных мест, обратитесь в тех.поддержку.'));
- }
- }
+ sys::outjs(array('e' => 'К сожалению нет доступных мест, обратитесь в тех.поддержку.'));
+ }
+ }
- $ram = $tarif['param_fix'] ? $aData['ram'] : $cfg['ram']['crmp']*$aSDATA['slots'];
+ $ram = $tarif['param_fix'] ? $aData['ram'] : $cfg['ram']['crmp']*$aSDATA['slots'];
- // Массив данных
- $aSDATA = array(
- 'unit' => $aData['unit'], // идентификатор локации
- 'tarif' => $aData['tarif'], // идентификатор тарифа
- 'ram' => $ram, // значение ram
- 'param_fix' => $tarif['param_fix'], // фиксированные параметры
- 'pack' => $aData['pack'], // Выбранная сборка для установки
- 'time' => $aData['time'], // Время аренды
- 'days' => $days, // Число дней
- 'sum' => $sum, // Сумма списания
- 'test' => $test, // тестовый период
- 'address' => $ip.':'.$port, // адрес игрового сервера
- 'port' => $port, // порт игрового сервера
- 'slots' => $aData['slots'], // Кол-во слот
- 'autostop' => $tarif['autostop'], // Выключение при 0 онлайне
- 'ftp' => $tarif['ftp'], // Использование ftp
- 'plugins' => $tarif['plugins'], // Использование плагинов
- 'console' => $tarif['console'], // Использование консоли
- 'stats' => $tarif['stats'], // Использование графиков (ведение статистики)
- 'copy' => $tarif['copy'], // Использование резервных копий
- 'web' => $tarif['web'], // Использование доп услуг
- 'plugins_install' => $tarif['plugins_install'], // Список установленных плагинов
- 'hdd' => $tarif['hdd'], // Дисковое пространство
- 'core_fix' => $core, // Выделенный поток
- 'core_fix_one' => $fix_one, // Выделенный поток
- 'promo' => $promo // Использование промо-кода
- );
+ // Массив данных
+ $aSDATA = array(
+ 'unit' => $aData['unit'], // идентификатор локации
+ 'tarif' => $aData['tarif'], // идентификатор тарифа
+ 'ram' => $ram, // значение ram
+ 'param_fix' => $tarif['param_fix'], // фиксированные параметры
+ 'pack' => $aData['pack'], // Выбранная сборка для установки
+ 'time' => $aData['time'], // Время аренды
+ 'days' => $days, // Число дней
+ 'sum' => $sum, // Сумма списания
+ 'test' => $test, // тестовый период
+ 'address' => $ip.':'.$port, // адрес игрового сервера
+ 'port' => $port, // порт игрового сервера
+ 'slots' => $aData['slots'], // Кол-во слот
+ 'autostop' => $tarif['autostop'], // Выключение при 0 онлайне
+ 'ftp' => $tarif['ftp'], // Использование ftp
+ 'plugins' => $tarif['plugins'], // Использование плагинов
+ 'console' => $tarif['console'], // Использование консоли
+ 'stats' => $tarif['stats'], // Использование графиков (ведение статистики)
+ 'copy' => $tarif['copy'], // Использование резервных копий
+ 'web' => $tarif['web'], // Использование доп услуг
+ 'plugins_install' => $tarif['plugins_install'], // Список установленных плагинов
+ 'hdd' => $tarif['hdd'], // Дисковое пространство
+ 'core_fix' => $core, // Выделенный поток
+ 'core_fix_one' => $fix_one, // Выделенный поток
+ 'promo' => $promo // Использование промо-кода
+ );
- return $aSDATA;
- }
+ return $aSDATA;
+ }
- public static function install($aSDATA = array())
- {
- global $cfg, $sql, $user, $start_point;
+ public static function install($aSDATA = array())
+ {
+ global $cfg, $sql, $user, $start_point;
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- // Массив данных локации (адрес,пароль)
- $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$aSDATA['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ // Массив данных локации (адрес,пароль)
+ $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$aSDATA['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- // Проверка ssh соединения с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- sys::outjs(array('e' => sys::text('error', 'ssh')));
+ // Проверка ssh соединения с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ sys::outjs(array('e' => sys::text('error', 'ssh')));
- // Массив данных тарифа (путь сборки,путь установки)
- $sql->query('SELECT `path`, `install`, `hostname` FROM `tarifs` WHERE `id`="'.$aSDATA['tarif'].'" LIMIT 1');
- $tarif = $sql->get();
+ // Массив данных тарифа (путь сборки,путь установки)
+ $sql->query('SELECT `path`, `install`, `hostname` FROM `tarifs` WHERE `id`="'.$aSDATA['tarif'].'" LIMIT 1');
+ $tarif = $sql->get();
- // Получение идентификаторов игрового сервера
- $sql->query('INSERT INTO `servers` set uid="1"');
- $id = $sql->id();
- $uid = $id+1000;
+ // Получение идентификаторов игрового сервера
+ $sql->query('INSERT INTO `servers` set uid="1"');
+ $id = $sql->id();
+ $uid = $id+1000;
- // Директория сборки
- $path = $tarif['path'].$aSDATA['pack'];
+ // Директория сборки
+ $path = $tarif['path'].$aSDATA['pack'];
- // Директория игрового сервера
- $install = $tarif['install'].$uid;
+ // Директория игрового сервера
+ $install = $tarif['install'].$uid;
- $ssh->set('mkdir '.$install.';' // Создание директории
- .'useradd -s /bin/false -d '.$install.' -g servers -u '.$uid.' server'.$uid.';' // Создание пользователя сервера на локации
- .'chown server'.$uid.':1000 '.$install.';' // Изменение владельца и группы директории
- .'cd '.$install.' && sudo -u server'.$uid.' screen -dmS i_'.$uid.' sh -c "cp -r '.$path.'/. .;' // Копирование файлов сборки для сервера
- .'find . -type d -exec chmod 700 {} \;;'
- .'find . -type f -exec chmod 777 {} \;;'
- .'chmod 500 '.params::$aFileGame['crmp'].'"');
+ $ssh->set('mkdir '.$install.';' // Создание директории
+ .'useradd -s /bin/false -d '.$install.' -g servers -u '.$uid.' server'.$uid.';' // Создание пользователя сервера на локации
+ .'chown server'.$uid.':1000 '.$install.';' // Изменение владельца и группы директории
+ .'cd '.$install.' && sudo -u server'.$uid.' screen -dmS i_'.$uid.' sh -c "cp -r '.$path.'/. .;' // Копирование файлов сборки для сервера
+ .'find . -type d -exec chmod 700 {} \;;'
+ .'find . -type f -exec chmod 777 {} \;;'
+ .'chmod 500 '.params::$aFileGame['crmp'].'"');
- // Запись данных нового сервера
- $sql->query('UPDATE `servers` set
- `uid`="'.$uid.'",
- `unit`="'.$aSDATA['unit'].'",
- `tarif`="'.$aSDATA['tarif'].'",
- `user`="'.$user['id'].'",
- `address`="'.$aSDATA['address'].'",
- `port`="'.$aSDATA['port'].'",
- `game`="crmp",
- `slots`="'.$aSDATA['slots'].'",
- `slots_start`="'.$aSDATA['slots'].'",
- `status`="install",
- `name`="'.$tarif['hostname'].'",
- `pack`="'.$aSDATA['pack'].'",
- `plugins_use`="'.$aSDATA['plugins'].'",
- `ftp_use`="'.$aSDATA['ftp'].'",
- `console_use`="'.$aSDATA['console'].'",
- `stats_use`="'.$aSDATA['stats'].'",
- `copy_use`="'.$aSDATA['copy'].'",
- `web_use`="'.$aSDATA['web'].'",
- `vac`="1",
- `hdd`="'.$aSDATA['hdd'].'",
- `time`="'.$aSDATA['time'].'",
- `date`="'.$start_point.'",
- `test`="'.$aSDATA['test'].'",
- `ram`="'.$aSDATA['ram'].'",
- `map_start`="'.sys::passwd(8).'",
- `core_fix`="'.$aSDATA['core_fix'].'",
- `core_fix_one`="'.$aSDATA['core_fix_one'].'",
- `autostop`="'.$aSDATA['autostop'].'" WHERE `id`="'.$id.'" LIMIT 1');
+ // Запись данных нового сервера
+ $sql->query('UPDATE `servers` set
+ `uid`="'.$uid.'",
+ `unit`="'.$aSDATA['unit'].'",
+ `tarif`="'.$aSDATA['tarif'].'",
+ `user`="'.$user['id'].'",
+ `address`="'.$aSDATA['address'].'",
+ `port`="'.$aSDATA['port'].'",
+ `game`="crmp",
+ `slots`="'.$aSDATA['slots'].'",
+ `slots_start`="'.$aSDATA['slots'].'",
+ `status`="install",
+ `name`="'.$tarif['hostname'].'",
+ `pack`="'.$aSDATA['pack'].'",
+ `plugins_use`="'.$aSDATA['plugins'].'",
+ `ftp_use`="'.$aSDATA['ftp'].'",
+ `console_use`="'.$aSDATA['console'].'",
+ `stats_use`="'.$aSDATA['stats'].'",
+ `copy_use`="'.$aSDATA['copy'].'",
+ `web_use`="'.$aSDATA['web'].'",
+ `vac`="1",
+ `hdd`="'.$aSDATA['hdd'].'",
+ `time`="'.$aSDATA['time'].'",
+ `date`="'.$start_point.'",
+ `test`="'.$aSDATA['test'].'",
+ `ram`="'.$aSDATA['ram'].'",
+ `map_start`="'.sys::passwd(8).'",
+ `core_fix`="'.$aSDATA['core_fix'].'",
+ `core_fix_one`="'.$aSDATA['core_fix_one'].'",
+ `autostop`="'.$aSDATA['autostop'].'" WHERE `id`="'.$id.'" LIMIT 1');
- // Запись установленных плагинов
- if($aSDATA['plugins'])
- {
- // Массив идентификаторов плагинов
- $aPlugins = sys::b64djs($aSDATA['plugins_install']);
+ // Запись установленных плагинов
+ if($aSDATA['plugins'])
+ {
+ // Массив идентификаторов плагинов
+ $aPlugins = sys::b64djs($aSDATA['plugins_install']);
- if(isset($aPlugins[$aSDATA['pack']]))
- {
- $plugins = explode(',', $aPlugins[$aSDATA['pack']]);
+ if(isset($aPlugins[$aSDATA['pack']]))
+ {
+ $plugins = explode(',', $aPlugins[$aSDATA['pack']]);
- foreach($plugins as $plugin)
- if($plugin)
- $sql->query('INSERT INTO `plugins_install` set `server`="'.$id.'", `plugin`="'.$plugin.'", `time`="'.$start_point.'"');
- }
- }
+ foreach($plugins as $plugin)
+ if($plugin)
+ $sql->query('INSERT INTO `plugins_install` set `server`="'.$id.'", `plugin`="'.$plugin.'", `time`="'.$start_point.'"');
+ }
+ }
- // Списание средств с баланса пользователя
- $sql->query('UPDATE `users` set `balance`="'.($user['balance']-$aSDATA['sum']).'" WHERE `id`="'.$user['id'].'" LIMIT 1');
+ // Списание средств с баланса пользователя
+ $sql->query('UPDATE `users` set `balance`="'.($user['balance']-$aSDATA['sum']).'" WHERE `id`="'.$user['id'].'" LIMIT 1');
- // Запись получения тестового периода
- if($aSDATA['test'])
- {
- $sql->query('INSERT INTO `tests` set `server`="'.$id.'", `unit`="'.$aSDATA['unit'].'", `game`="crmp", `user`="'.$user['id'].'", `time`="'.$start_point.'"');
- $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server_test'), array('id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="0"');
- }else{
- // Реф. система
- games::part($user['id'], $aSDATA['sum']);
+ // Запись получения тестового периода
+ if($aSDATA['test'])
+ {
+ $sql->query('INSERT INTO `tests` set `server`="'.$id.'", `unit`="'.$aSDATA['unit'].'", `game`="crmp", `user`="'.$user['id'].'", `time`="'.$start_point.'"');
+ $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server_test'), array('id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="0"');
+ }else{
+ // Реф. система
+ games::part($user['id'], $aSDATA['sum']);
- // Запись логов
- if(!is_array($aSDATA['promo']))
- $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server'), array('days' => games::parse_day($aSDATA['days'], true), 'money' => $aSDATA['sum'], 'id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="'.$aSDATA['sum'].'"');
- else{
- $sql->query('UPDATE `servers` set `benefit`="'.$aSDATA['time'].'" WHERE `id`="'.$id.'" LIMIT 1');
- $sql->query('INSERT INTO `promo_use` set `promo`="'.$aSDATA['promo']['id'].'", `user`="'.$user['id'].'", `time`="'.$start_point.'"');
- $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server_promo'), array('days' => games::parse_day($aSDATA['days'], true), 'money' => $aSDATA['sum'], 'promo' => $aSDATA['promo']['cod'], 'id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="'.$aSDATA['sum'].'"');
- }
- }
+ // Запись логов
+ if(!is_array($aSDATA['promo']))
+ $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server'), array('days' => games::parse_day($aSDATA['days'], true), 'money' => $aSDATA['sum'], 'id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="'.$aSDATA['sum'].'"');
+ else{
+ $sql->query('UPDATE `servers` set `benefit`="'.$aSDATA['time'].'" WHERE `id`="'.$id.'" LIMIT 1');
+ $sql->query('INSERT INTO `promo_use` set `promo`="'.$aSDATA['promo']['id'].'", `user`="'.$user['id'].'", `time`="'.$start_point.'"');
+ $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server_promo'), array('days' => games::parse_day($aSDATA['days'], true), 'money' => $aSDATA['sum'], 'promo' => $aSDATA['promo']['cod'], 'id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="'.$aSDATA['sum'].'"');
+ }
+ }
- return $id;
- }
+ return $id;
+ }
}
?>
\ No newline at end of file
diff --git a/system/library/games/crmp/tarif.php b/system/library/games/crmp/tarif.php
index a65da45..b61e6a3 100644
--- a/system/library/games/crmp/tarif.php
+++ b/system/library/games/crmp/tarif.php
@@ -1,179 +1,179 @@
get('extend', 'sections/servers/games/tarif');
+ $html->get('extend', 'sections/servers/games/tarif');
- if(isset($html->arr['extend_address']))
- {
- $html->unit('extend_address', 1);
- $html->set('extend_address', $html->arr['extend_address']);
- }else
- $html->unit('extend_address');
+ if(isset($html->arr['extend_address']))
+ {
+ $html->unit('extend_address', 1);
+ $html->set('extend_address', $html->arr['extend_address']);
+ }else
+ $html->unit('extend_address');
- $html->set('id', $sid);
- $html->set('time', sys::date('min', $server['time']));
- $html->set('options', 'Выберете период продления '.$options);
- $html->set('slots', $server['slots']);
- $html->set('info', '');
- $html->set('tarif', $tarif_name);
- $html->set('cur', $cfg['currency']);
+ $html->set('id', $sid);
+ $html->set('time', sys::date('min', $server['time']));
+ $html->set('options', 'Выберете период продления '.$options);
+ $html->set('slots', $server['slots']);
+ $html->set('info', '');
+ $html->set('tarif', $tarif_name);
+ $html->set('cur', $cfg['currency']);
- $html->pack('main');
+ $html->pack('main');
- return NULL;
- }
+ return NULL;
+ }
public static function extend_sp($server, $tarif, $sid)
{
- global $cfg, $sql, $html, $start_point;
+ global $cfg, $sql, $html, $start_point;
- tarifs::extend_address($server['game'], $sid);
+ tarifs::extend_address($server['game'], $sid);
- $sum = $tarif['slots'] ? $tarif['price'] : $tarif['price']*$server['slots'];
+ $sum = $tarif['slots'] ? $tarif['price'] : $tarif['price']*$server['slots'];
- $html->get('extend_sp', 'sections/servers/games/tarif');
+ $html->get('extend_sp', 'sections/servers/games/tarif');
- if(isset($html->arr['extend_address']))
- {
- $html->unit('extend_address', 1);
- $html->set('extend_address', $html->arr['extend_address']);
- }else
- $html->unit('extend_address');
+ if(isset($html->arr['extend_address']))
+ {
+ $html->unit('extend_address', 1);
+ $html->set('extend_address', $html->arr['extend_address']);
+ }else
+ $html->unit('extend_address');
- $html->set('id', $sid);
- $html->set('time', sys::date('min', $server['time']));
- $html->set('date', $server['time'] > $start_point ? 'Сервер продлен до: '.date('d.m.Y', $server['time']) : 'Текущая дата: '.date('d.m.Y', $start_point));
- $html->set('options', 'Выберете период продления '.$options);
- $html->set('slots', $server['slots']);
- $html->set('info', '');
- $html->set('tarif', $tarif['name']);
- $html->set('sum', $sum);
- $html->set('cur', $cfg['currency']);
+ $html->set('id', $sid);
+ $html->set('time', sys::date('min', $server['time']));
+ $html->set('date', $server['time'] > $start_point ? 'Сервер продлен до: '.date('d.m.Y', $server['time']) : 'Текущая дата: '.date('d.m.Y', $start_point));
+ $html->set('options', 'Выберете период продления '.$options);
+ $html->set('slots', $server['slots']);
+ $html->set('info', '');
+ $html->set('tarif', $tarif['name']);
+ $html->set('sum', $sum);
+ $html->set('cur', $cfg['currency']);
- $html->pack('main');
+ $html->pack('main');
- return NULL;
- }
+ return NULL;
+ }
public static function plan()
{
- return NULL;
- }
+ return NULL;
+ }
- public static function unit($server, $unit_name, $tarif_name, $sid)
+ public static function unit($server, $unit_name, $tarif_name, $sid)
{
- global $cfg, $sql, $html;
+ global $cfg, $sql, $html;
- if(!$cfg['change_unit'][$server['game']])
- return NULL;
+ if(!$cfg['change_unit'][$server['game']])
+ return NULL;
- $tarifs = $sql->query('SELECT `unit` FROM `tarifs` WHERE `game`="'.$server['game'].'" AND `name`="'.$tarif_name.'" AND `id`!="'.$server['tarif'].'" AND `show`="1" ORDER BY `unit`');
- if(!$sql->num($tarifs))
- return NULL;
+ $tarifs = $sql->query('SELECT `unit` FROM `tarifs` WHERE `game`="'.$server['game'].'" AND `name`="'.$tarif_name.'" AND `id`!="'.$server['tarif'].'" AND `show`="1" ORDER BY `unit`');
+ if(!$sql->num($tarifs))
+ return NULL;
- $units = 0;
+ $units = 0;
- $options = 'Выберете новую локацию ';
+ $options = 'Выберете новую локацию ';
- while($tarif = $sql->get($tarifs))
- {
- $sql->query('SELECT `id`, `name` FROM `units` WHERE `id`="'.$tarif['unit'].'" AND `show`="1" LIMIT 1');
- if(!$sql->num())
- continue;
+ while($tarif = $sql->get($tarifs))
+ {
+ $sql->query('SELECT `id`, `name` FROM `units` WHERE `id`="'.$tarif['unit'].'" AND `show`="1" LIMIT 1');
+ if(!$sql->num())
+ continue;
- $unit = $sql->get();
+ $unit = $sql->get();
- $options .= ''.$unit['name'].' ';
+ $options .= ''.$unit['name'].' ';
- $units+=1;
- }
+ $units+=1;
+ }
- if(!$units)
- return NULL;
+ if(!$units)
+ return NULL;
- $html->get('unit', 'sections/servers/games/tarif');
+ $html->get('unit', 'sections/servers/games/tarif');
- $html->set('id', $sid);
- $html->set('options', $options);
- $html->set('slots', $server['slots']);
- $html->set('info', '');
- $html->set('unit', $unit_name);
- $html->set('tarif', $tarif_name);
+ $html->set('id', $sid);
+ $html->set('options', $options);
+ $html->set('slots', $server['slots']);
+ $html->set('info', '');
+ $html->set('unit', $unit_name);
+ $html->set('tarif', $tarif_name);
- $html->pack('main');
+ $html->pack('main');
- return NULL;
- }
+ return NULL;
+ }
- public static function unit_new($tarif, $unit, $server, $mcache)
- {
- global $ssh, $sql, $user, $start_point;
+ public static function unit_new($tarif, $unit, $server, $mcache)
+ {
+ global $ssh, $sql, $user, $start_point;
- // Проверка ssh соединения с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- sys::outjs(array('e' => sys::text('error', 'ssh')));
+ // Проверка ssh соединения с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ sys::outjs(array('e' => sys::text('error', 'ssh')));
- // Директория сборки
- $path = $tarif['path'].$tarif['pack'];
+ // Директория сборки
+ $path = $tarif['path'].$tarif['pack'];
- // Директория игрового сервера
- $install = $tarif['install'].$server['uid'];
+ // Директория игрового сервера
+ $install = $tarif['install'].$server['uid'];
- // Пользователь сервера
- $uS = 'server'.$server['uid'];
+ // Пользователь сервера
+ $uS = 'server'.$server['uid'];
- $ssh->set('mkdir '.$install.';' // Создание директории
- .'useradd -d '.$install.' -g servers -u '.$server['uid'].' '.$uS.';' // Создание пользователя сервера на локации
- .'chown '.$uS.':1000 '.$install.';' // Изменение владельца и группы директории
- .'cd '.$install.' && sudo -u '.$uS.' screen -dmS i_'.$server['uid'].' cp -r '.$path.'/. .'); // Копирование файлов сборки для сервера
+ $ssh->set('mkdir '.$install.';' // Создание директории
+ .'useradd -d '.$install.' -g servers -u '.$server['uid'].' '.$uS.';' // Создание пользователя сервера на локации
+ .'chown '.$uS.':1000 '.$install.';' // Изменение владельца и группы директории
+ .'cd '.$install.' && sudo -u '.$uS.' screen -dmS i_'.$server['uid'].' cp -r '.$path.'/. .'); // Копирование файлов сборки для сервера
- $address = explode(':', $server['address']);
+ $address = explode(':', $server['address']);
- $fix_one = $tarif['core_fix'] ? 1 : 0;
+ $fix_one = $tarif['core_fix'] ? 1 : 0;
- // Обновление данных нового сервера
- $sql->query('UPDATE `servers` set
- `unit`="'.$tarif['unit'].'",
- `tarif`="'.$tarif['id'].'",
- `address`="'.$server['address'].'",
- `port`="'.$address[1].'",
- `status`="install",
- `name`="'.$tarif['hostname'].'",
- `pack`="'.$tarif['pack'].'",
- `map_start`="'.$tarif['map'].'",
- `hdd`="'.$tarif['hdd'].'",
- `time`="'.$tarif['time'].'",
- `autostop`="'.$tarif['autostop'].'",
- `core_fix`="'.$tarif['core_fix'].'",
- `core_fix_one`="'.$fix_one.'",
- `reinstall`="'.$start_point.'" WHERE `id`="'.$server['id'].'" LIMIT 1');
+ // Обновление данных нового сервера
+ $sql->query('UPDATE `servers` set
+ `unit`="'.$tarif['unit'].'",
+ `tarif`="'.$tarif['id'].'",
+ `address`="'.$server['address'].'",
+ `port`="'.$address[1].'",
+ `status`="install",
+ `name`="'.$tarif['hostname'].'",
+ `pack`="'.$tarif['pack'].'",
+ `map_start`="'.$tarif['map'].'",
+ `hdd`="'.$tarif['hdd'].'",
+ `time`="'.$tarif['time'].'",
+ `autostop`="'.$tarif['autostop'].'",
+ `core_fix`="'.$tarif['core_fix'].'",
+ `core_fix_one`="'.$fix_one.'",
+ `reinstall`="'.$start_point.'" WHERE `id`="'.$server['id'].'" LIMIT 1');
- // Запись установленных плагинов
- if($tarif['plugins'])
- {
- // Массив идентификаторов плагинов
- $aPlugins = sys::b64js($tarif['plugins_install']);
+ // Запись установленных плагинов
+ if($tarif['plugins'])
+ {
+ // Массив идентификаторов плагинов
+ $aPlugins = sys::b64js($tarif['plugins_install']);
- if(isset($aPlugins[$tarif['pack']]))
- {
- $plugins = explode(',', $aPlugins[$tarif['pack']]);
+ if(isset($aPlugins[$tarif['pack']]))
+ {
+ $plugins = explode(',', $aPlugins[$tarif['pack']]);
- foreach($plugins as $plugin)
- if($plugin)
- $sql->query('INSERT INTO `plugins_install` set `server`="'.$server['id'].'", `plugin`="'.$plugin.'", `time`="'.$start_point.'"');
- }
- }
+ foreach($plugins as $plugin)
+ if($plugin)
+ $sql->query('INSERT INTO `plugins_install` set `server`="'.$server['id'].'", `plugin`="'.$plugin.'", `time`="'.$start_point.'"');
+ }
+ }
- return NULL;
- }
+ return NULL;
+ }
}
?>
\ No newline at end of file
diff --git a/system/library/games/cs/action.php b/system/library/games/cs/action.php
index 76ada82..01bd54b 100644
--- a/system/library/games/cs/action.php
+++ b/system/library/games/cs/action.php
@@ -1,117 +1,117 @@
query('SELECT `uid`, `unit`, `tarif`, `game`, `address`, `slots_start`, `name`, `fps`, `map_start`, `vac`, `pingboost`, `time_start`, `core_fix` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `uid`, `unit`, `tarif`, `game`, `address`, `slots_start`, `name`, `fps`, `map_start`, `vac`, `pingboost`, `time_start`, `core_fix` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
- $tarif = $sql->get();
+ $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
+ $tarif = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return array('e' => sys::text('error', 'ssh'));
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return array('e' => sys::text('error', 'ssh'));
- list($ip, $port) = explode(':', $server['address']);
+ list($ip, $port) = explode(':', $server['address']);
- // Убить процессы
- $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
- .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
+ // Убить процессы
+ $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
+ .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
- $taskset = '';
+ $taskset = '';
- // Если включена система автораспределения и не установлен фиксированный поток
- if($cfg['cpu_route'] AND !$server['core_fix'])
- {
- $proc_stat = array();
+ // Если включена система автораспределения и не установлен фиксированный поток
+ if($cfg['cpu_route'] AND !$server['core_fix'])
+ {
+ $proc_stat = array();
- $proc_stat[0] = $ssh->get('cat /proc/stat');
- }
+ $proc_stat[0] = $ssh->get('cat /proc/stat');
+ }
- // Проверка наличия стартовой карты
- $ssh->set('cd '.$tarif['install'].$server['uid'].'/cstrike/maps/ && ls | grep .bsp | grep -v .bsp.');
+ // Проверка наличия стартовой карты
+ $ssh->set('cd '.$tarif['install'].$server['uid'].'/cstrike/maps/ && ls | grep .bsp | grep -v .bsp.');
- if($server['map_start'] != '' AND !in_array($server['map_start'], str_replace('.bsp', '', explode("\n", $ssh->get()))))
- return array('e' => sys::updtext(sys::text('servers', 'nomap'), array('map' => $server['map_start'].'.bsp')));
+ if($server['map_start'] != '' AND !in_array($server['map_start'], str_replace('.bsp', '', explode("\n", $ssh->get()))))
+ return array('e' => sys::updtext(sys::text('servers', 'nomap'), array('map' => $server['map_start'].'.bsp')));
- // Если система автораспределения продолжить парсинг загрузки процессора
- if(isset($proc_stat))
- {
- $proc_stat[1] = $ssh->get('cat /proc/stat');
+ // Если система автораспределения продолжить парсинг загрузки процессора
+ if(isset($proc_stat))
+ {
+ $proc_stat[1] = $ssh->get('cat /proc/stat');
- // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
- $core = sys::cpu_idle($proc_stat, $server['unit'], false); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
+ // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
+ $core = sys::cpu_idle($proc_stat, $server['unit'], false); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
- if(!is_numeric($core))
- return array('e' => sys::text('error', 'cpu'));
+ if(!is_numeric($core))
+ return array('e' => sys::text('error', 'cpu'));
- $taskset = 'taskset -c '.$core;
- }
+ $taskset = 'taskset -c '.$core;
+ }
- if($server['core_fix'])
- {
- $core = $server['core_fix']-1;
- $taskset = 'taskset -c '.$core;
- }
+ if($server['core_fix'])
+ {
+ $core = $server['core_fix']-1;
+ $taskset = 'taskset -c '.$core;
+ }
- // Античит VAC
- $vac = $server['vac'] == 0 ? '-insecure' : '-secure';
+ // Античит VAC
+ $vac = $server['vac'] == 0 ? '-insecure' : '-secure';
- // Значение PingBoost
- $pingboost = $server['pingboost'] == 0 ? $cfg['pingboost'] : $server['pingboost'];
+ // Значение PingBoost
+ $pingboost = $server['pingboost'] == 0 ? $cfg['pingboost'] : $server['pingboost'];
- if(!$pingboost)
- $pingboost = '';
- else
- $pingboost = '-pingboost '.$pingboost;
+ if(!$pingboost)
+ $pingboost = '';
+ else
+ $pingboost = '-pingboost '.$pingboost;
- // Значение sys_ticrate (FPS)
- $fps = $server['fps']+$cfg['fpsplus'];
+ // Значение sys_ticrate (FPS)
+ $fps = $server['fps']+$cfg['fpsplus'];
- // Параметры запуска
- $bash = './hlds_run -debug -game cstrike -norestart -condebug -sys_ticrate '.$fps.' +servercfgfile server.cfg +sys_ticrate '.$fps.' +map \''.$server['map_start'].'\' +maxplayers '.$server['slots_start'].' +ip '.$ip.' +port '.$port.' +sv_lan 0 '.$vac.' '.$pingboost;
+ // Параметры запуска
+ $bash = './hlds_run -debug -game cstrike -norestart -condebug -sys_ticrate '.$fps.' +servercfgfile server.cfg +sys_ticrate '.$fps.' +map \''.$server['map_start'].'\' +maxplayers '.$server['slots_start'].' +ip '.$ip.' +port '.$port.' +sv_lan 0 '.$vac.' '.$pingboost;
- // Временный файл
- $temp = sys::temp($bash);
+ // Временный файл
+ $temp = sys::temp($bash);
- // Обновление файла start.sh
- $ssh->setfile($temp, $tarif['install'].$server['uid'].'/start.sh', 0500);
+ // Обновление файла start.sh
+ $ssh->setfile($temp, $tarif['install'].$server['uid'].'/start.sh', 0500);
- // Строка запуска
- $ssh->set('cd '.$tarif['install'].$server['uid'].';' // переход в директорию игрового сервера
- .'rm *.pid;' // Удаление *.pid файлов
- .'sudo -u server'.$server['uid'].' mkdir -p cstrike/oldstart;' // Создание папки логов
- .'cat cstrike/qconsole.log >> cstrike/oldstart/'.date('d.m.Y_H:i:s', $server['time_start']).'.log; rm cstrike/qconsole.log; rm cstrike/oldstart/01.01.1970_03:00:00.log;' // Перемещение лога предыдущего запуска
- .'chown server'.$server['uid'].':1000 start.sh;' // Обновление владельца файла start.sh
- .'sudo -u server'.$server['uid'].' screen -dmS s_'.$server['uid'].' '.$taskset.' sh -c ./start.sh'); // Запуск игровго сервера
+ // Строка запуска
+ $ssh->set('cd '.$tarif['install'].$server['uid'].';' // переход в директорию игрового сервера
+ .'rm *.pid;' // Удаление *.pid файлов
+ .'sudo -u server'.$server['uid'].' mkdir -p cstrike/oldstart;' // Создание папки логов
+ .'cat cstrike/qconsole.log >> cstrike/oldstart/'.date('d.m.Y_H:i:s', $server['time_start']).'.log; rm cstrike/qconsole.log; rm cstrike/oldstart/01.01.1970_03:00:00.log;' // Перемещение лога предыдущего запуска
+ .'chown server'.$server['uid'].':1000 start.sh;' // Обновление владельца файла start.sh
+ .'sudo -u server'.$server['uid'].' screen -dmS s_'.$server['uid'].' '.$taskset.' sh -c ./start.sh'); // Запуск игровго сервера
- $core = !isset($core) ? 0 : $core+1;
+ $core = !isset($core) ? 0 : $core+1;
- // Обновление информации в базе
- $sql->query('UPDATE `servers` set `status`="'.$type.'", `online`="0", `players`="", `core_use`="'.$core.'", `time_start`="'.$start_point.'", `stop`="1" WHERE `id`="'.$id.'" LIMIT 1');
+ // Обновление информации в базе
+ $sql->query('UPDATE `servers` set `status`="'.$type.'", `online`="0", `players`="", `core_use`="'.$core.'", `time_start`="'.$start_point.'", `stop`="1" WHERE `id`="'.$id.'" LIMIT 1');
- unlink($temp);
+ unlink($temp);
- // Сброс кеша
- actions::clmcache($id);
+ // Сброс кеша
+ actions::clmcache($id);
- sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0, 'players' => ''));
- sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0));
+ sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0, 'players' => ''));
+ sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0));
- return array('s' => 'ok');
- }
- }
+ return array('s' => 'ok');
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/games/cs/rcon.php b/system/library/games/cs/rcon.php
index 0cf116a..0cc957a 100644
--- a/system/library/games/cs/rcon.php
+++ b/system/library/games/cs/rcon.php
@@ -1,110 +1,110 @@
Connect($ip, $port, 3, SourceQuery::GOLDSOURCE);
+ $sq->Connect($ip, $port, 3, SourceQuery::GOLDSOURCE);
- $sq->SetRconPassword(rcon::rcon_passwd($server));
+ $sq->SetRconPassword(rcon::rcon_passwd($server));
- $out = $sq->Rcon($cmd);
+ $out = $sq->Rcon($cmd);
- $sq->Disconnect();
+ $sq->Disconnect();
- return $out;
- }
+ return $out;
+ }
- public static function players($data)
- {
- $aPlayers = array();
- $n = 1;
+ public static function players($data)
+ {
+ $aPlayers = array();
+ $n = 1;
- $lines = explode("\n", $data);
+ $lines = explode("\n", $data);
- foreach($lines as $line)
- {
- if(strpos($line, '#') === FALSE)
- continue;
+ foreach($lines as $line)
+ {
+ if(strpos($line, '#') === FALSE)
+ continue;
- $start = strpos($line, '"')+1;
- $end = strrpos($line, '"');
+ $start = strpos($line, '"')+1;
+ $end = strrpos($line, '"');
- $name = htmlspecialchars(substr($line, $start, $end-$start));
+ $name = htmlspecialchars(substr($line, $start, $end-$start));
- $line = trim(substr($line, $end + 1));
+ $line = trim(substr($line, $end + 1));
- $aData = array_values(array_diff(explode(' ', $line), array('', ' ')));
+ $aData = array_values(array_diff(explode(' ', $line), array('', ' ')));
- $steamid = trim($aData[1]);
- $ip = trim(sys::first(explode(':', $aData[6])));
+ $steamid = trim($aData[1]);
+ $ip = trim(sys::first(explode(':', $aData[6])));
- if(sys::valid($steamid, 'steamid') || sys::valid($ip, 'ip'))
- continue;
+ if(sys::valid($steamid, 'steamid') || sys::valid($ip, 'ip'))
+ continue;
- $aPlayers[$n]['name'] = $name;
- $aPlayers[$n]['steamid'] = $steamid;
- $aPlayers[$n]['frags'] = trim($aData[2]);
- $aPlayers[$n]['time'] = trim($aData[3]);
- $aPlayers[$n]['ping'] = trim($aData[4]);
- $aPlayers[$n]['ip'] = $ip;
+ $aPlayers[$n]['name'] = $name;
+ $aPlayers[$n]['steamid'] = $steamid;
+ $aPlayers[$n]['frags'] = trim($aData[2]);
+ $aPlayers[$n]['time'] = trim($aData[3]);
+ $aPlayers[$n]['ping'] = trim($aData[4]);
+ $aPlayers[$n]['ip'] = $ip;
- $whois = rcon::country($ip);
+ $whois = rcon::country($ip);
- $aPlayers[$n]['ico'] = $whois['ico'];
- $aPlayers[$n]['country'] = $whois['name'];
+ $aPlayers[$n]['ico'] = $whois['ico'];
+ $aPlayers[$n]['country'] = $whois['name'];
- $n+=1;
- }
+ $n+=1;
+ }
- return $aPlayers;
- }
+ return $aPlayers;
+ }
- public static function rcon_passwd($server)
- {
- global $cfg, $sql, $user;
+ public static function rcon_passwd($server)
+ {
+ global $cfg, $sql, $user;
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
$unit = $sql->get();
- if(!$ssh->auth($unit['passwd'], $unit['address']))
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
sys::outjs(array('e' => sys::text('error', 'ssh')));
- $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
- $tarif = $sql->get();
+ $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
+ $tarif = $sql->get();
- $ssh->set('cat '.$tarif['install'].$server['uid'].'/cstrike/server.cfg | grep rcon_password');
- $get = explode(' ', str_replace('"', '', trim($ssh->get())));
- $rcon = trim(end($get));
+ $ssh->set('cat '.$tarif['install'].$server['uid'].'/cstrike/server.cfg | grep rcon_password');
+ $get = explode(' ', str_replace('"', '', trim($ssh->get())));
+ $rcon = trim(end($get));
- if(!isset($rcon{0}))
- sys::outjs(array('r' => 'Необходимо установить rcon пароль (rcon_password).', 'url' => $cfg['http'].'servers/id/'.$server['id'].'/section/settings/subsection/server'), $nmch);
+ if(!isset($rcon{0}))
+ sys::outjs(array('r' => 'Необходимо установить rcon пароль (rcon_password).', 'url' => $cfg['http'].'servers/id/'.$server['id'].'/section/settings/subsection/server'), $nmch);
- return $rcon;
- }
+ return $rcon;
+ }
- public static function country($ip)
- {
- global $SxGeo;
+ public static function country($ip)
+ {
+ global $SxGeo;
- $cData = $SxGeo->getCityFull($ip);
- $ico = sys::country($cData['country']['iso']);
+ $cData = $SxGeo->getCityFull($ip);
+ $ico = sys::country($cData['country']['iso']);
- return array('ico' => $ico, 'name' => empty($cData['country']['name_ru']) ? 'Не определена' : $cData['country']['name_ru']);
- }
- }
+ return array('ico' => $ico, 'name' => empty($cData['country']['name_ru']) ? 'Не определена' : $cData['country']['name_ru']);
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/games/cs/scan.php b/system/library/games/cs/scan.php
index 59b6507..999aae1 100644
--- a/system/library/games/cs/scan.php
+++ b/system/library/games/cs/scan.php
@@ -1,140 +1,140 @@
get($nmch)))
- return $mcache->get($nmch);
+ if(is_array($mcache->get($nmch)))
+ return $mcache->get($nmch);
- $out = array();
+ $out = array();
- $info = scan::info($sq, $id);
+ $info = scan::info($sq, $id);
- $sql->query('SELECT `game`, `name`, `map`, `online`, `players`, `status`, `time`, `overdue` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `game`, `name`, `map`, `online`, `players`, `status`, `time`, `overdue` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- $out['time'] = 'Арендован до: '.date('d.m.Y - H:i', $server['time']);
+ $out['time'] = 'Арендован до: '.date('d.m.Y - H:i', $server['time']);
- if($server['status'] == 'overdue')
- $out['time_end'] = 'Удаление через: '.sys::date('min', $server['overdue']+$cfg['server_delete']*86400);
- else
- $out['time_end'] = 'Осталось: '.sys::date('min', $server['time']);
+ if($server['status'] == 'overdue')
+ $out['time_end'] = 'Удаление через: '.sys::date('min', $server['overdue']+$cfg['server_delete']*86400);
+ else
+ $out['time_end'] = 'Осталось: '.sys::date('min', $server['time']);
- if(!$info['status'])
- {
- $out['name'] = $server['name'];
- $out['status'] = sys::status($server['status'], $server['game'], $server['map']);
- $out['online'] = $server['online'];
- $out['image'] = ' ';
- $out['buttons'] = sys::buttons($id, $server['status']);
+ if(!$info['status'])
+ {
+ $out['name'] = $server['name'];
+ $out['status'] = sys::status($server['status'], $server['game'], $server['map']);
+ $out['online'] = $server['online'];
+ $out['image'] = ' ';
+ $out['buttons'] = sys::buttons($id, $server['status']);
- if($players_get)
- $out['players'] = base64_decode($server['players']);
+ if($players_get)
+ $out['players'] = base64_decode($server['players']);
- $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
+ $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
- return $out;
- }
+ return $out;
+ }
- if($players_get)
- $players = scan::info($sq, $id, true);
+ if($players_get)
+ $players = scan::info($sq, $id, true);
- $out['name'] = htmlspecialchars($info['name']);
- $out['status'] = sys::status('working', $server['game'], $info['map']);
- $out['online'] = $info['online'];
- $out['image'] = ' ';
- $out['buttons'] = sys::buttons($id, 'working');
- $out['players'] = '';
+ $out['name'] = htmlspecialchars($info['name']);
+ $out['status'] = sys::status('working', $server['game'], $info['map']);
+ $out['online'] = $info['online'];
+ $out['image'] = ' ';
+ $out['buttons'] = sys::buttons($id, 'working');
+ $out['players'] = '';
- if($players_get)
- {
- foreach($players as $index => $player)
- {
- $html->get($server['game'], 'sections/servers/players');
+ if($players_get)
+ {
+ foreach($players as $index => $player)
+ {
+ $html->get($server['game'], 'sections/servers/players');
- $html->set('i', $player['i']);
- $html->set('name', $player['name']);
- $html->set('score', $player['score']);
- $html->set('time', $player['time']);
+ $html->set('i', $player['i']);
+ $html->set('name', $player['name']);
+ $html->set('score', $player['score']);
+ $html->set('time', $player['time']);
- $html->pack('list');
- }
+ $html->pack('list');
+ }
- $out['players'] = isset($html->arr['list']) ? $html->arr['list'] : '';
- }
+ $out['players'] = isset($html->arr['list']) ? $html->arr['list'] : '';
+ }
- $sql->query('UPDATE `servers` set '
- .'`name`="'.$out['name'].'", '
- .'`online`="'.$out['online'].'", '
- .'`map`="'.$info['map'].'", '
- .'`status`="working" WHERE `id`="'.$id.'" LIMIT 1');
+ $sql->query('UPDATE `servers` set '
+ .'`name`="'.$out['name'].'", '
+ .'`online`="'.$out['online'].'", '
+ .'`map`="'.$info['map'].'", '
+ .'`status`="working" WHERE `id`="'.$id.'" LIMIT 1');
- if($players_get)
- $sql->query('UPDATE `servers` set `players`="'.base64_encode($out['players']).'" WHERE `id`="'.$id.'" LIMIT 1');
+ if($players_get)
+ $sql->query('UPDATE `servers` set `players`="'.base64_encode($out['players']).'" WHERE `id`="'.$id.'" LIMIT 1');
- $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
+ $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
- return $out;
- }
+ return $out;
+ }
- public static function info($sq, $id, $pl = false)
- {
- global $sql;
+ public static function info($sq, $id, $pl = false)
+ {
+ global $sql;
- $sql->query('SELECT `address` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `address` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- list($ip, $port) = explode(':', $server['address']);
+ list($ip, $port) = explode(':', $server['address']);
- $sq->Connect($ip, $port, 1, SourceQuery::GOLDSOURCE);
+ $sq->Connect($ip, $port, 1, SourceQuery::GOLDSOURCE);
- if($pl)
- {
- $players = $sq->GetPlayers();
+ if($pl)
+ {
+ $players = $sq->GetPlayers();
- $i = 1;
- $data = array();
+ $i = 1;
+ $data = array();
- foreach($players as $n => $player)
- {
- $data[$i]['i'] = $i;
- $data[$i]['name'] = $player['Name'] == '' ? 'Подключается' : $player['Name'];
- $data[$i]['score'] = $player['Frags'];
- $data[$i]['time'] = $player['TimeF'];
+ foreach($players as $n => $player)
+ {
+ $data[$i]['i'] = $i;
+ $data[$i]['name'] = $player['Name'] == '' ? 'Подключается' : $player['Name'];
+ $data[$i]['score'] = $player['Frags'];
+ $data[$i]['time'] = $player['TimeF'];
- $i+=1;
- }
+ $i+=1;
+ }
- return $data;
- }
+ return $data;
+ }
- $data = $sq->GetInfo();
+ $data = $sq->GetInfo();
- $server['name'] = $data['HostName'];
- $server['map'] = $data['Map'];
- $server['online'] = $data['Players'];
- $server['status'] = strlen($server['map']) > 3 ? true : false;
+ $server['name'] = $data['HostName'];
+ $server['map'] = $data['Map'];
+ $server['online'] = $data['Players'];
+ $server['status'] = strlen($server['map']) > 3 ? true : false;
- return $server;
- }
- }
+ return $server;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/games/cs/service.php b/system/library/games/cs/service.php
index 44655e0..952bc0c 100644
--- a/system/library/games/cs/service.php
+++ b/system/library/games/cs/service.php
@@ -1,368 +1,368 @@
query('SELECT `address`, `test` FROM `units` WHERE `id`="'.$aData['unit'].'" AND `cs`="1" AND `show`="1" LIMIT 1');
- if(!$sql->num())
- sys::outjs(array('e' => 'Локация не найдена.'));
+ // Проверка локации
+ $sql->query('SELECT `address`, `test` FROM `units` WHERE `id`="'.$aData['unit'].'" AND `cs`="1" AND `show`="1" LIMIT 1');
+ if(!$sql->num())
+ sys::outjs(array('e' => 'Локация не найдена.'));
- $unit = $sql->get();
+ $unit = $sql->get();
- // Проверка тарифа
- $sql->query('SELECT `id` FROM `tarifs` WHERE `id`="'.$aData['tarif'].'" AND `unit`="'.$aData['unit'].'" AND `show`="1" LIMIT 1');
- if(!$sql->num())
- sys::outjs(array('e' => 'Тариф не найден.'));
+ // Проверка тарифа
+ $sql->query('SELECT `id` FROM `tarifs` WHERE `id`="'.$aData['tarif'].'" AND `unit`="'.$aData['unit'].'" AND `show`="1" LIMIT 1');
+ if(!$sql->num())
+ sys::outjs(array('e' => 'Тариф не найден.'));
- $sql->query('SELECT '
- .'`slots_min`,'
- .'`slots_max`,'
- .'`port_min`,'
- .'`port_max`,'
- .'`hostname`,'
- .'`packs`,'
- .'`fps`,'
- .'`time`,'
- .'`test`,'
- .'`tests`,'
- .'`discount`,'
- .'`map`,'
- .'`ftp`,'
- .'`plugins`,'
- .'`console`,'
- .'`stats`,'
- .'`copy`,'
- .'`web`,'
- .'`plugins_install`,'
- .'`hdd`,'
- .'`autostop`,'
- .'`core_fix`,'
- .'`ip`,'
- .'`price`'
- .' FROM `tarifs` WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
+ $sql->query('SELECT '
+ .'`slots_min`,'
+ .'`slots_max`,'
+ .'`port_min`,'
+ .'`port_max`,'
+ .'`hostname`,'
+ .'`packs`,'
+ .'`fps`,'
+ .'`time`,'
+ .'`test`,'
+ .'`tests`,'
+ .'`discount`,'
+ .'`map`,'
+ .'`ftp`,'
+ .'`plugins`,'
+ .'`console`,'
+ .'`stats`,'
+ .'`copy`,'
+ .'`web`,'
+ .'`plugins_install`,'
+ .'`hdd`,'
+ .'`autostop`,'
+ .'`core_fix`,'
+ .'`ip`,'
+ .'`price`'
+ .' FROM `tarifs` WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
- $tarif = $sql->get();
+ $tarif = $sql->get();
- // Проверка сборки
- if(!array_key_exists($aData['pack'], sys::b64djs($tarif['packs'], true)))
- sys::outjs(array('e' => 'Сборка не найдена.'));
+ // Проверка сборки
+ if(!array_key_exists($aData['pack'], sys::b64djs($tarif['packs'], true)))
+ sys::outjs(array('e' => 'Сборка не найдена.'));
- // Проверка FPS
- if(!in_array($aData['fps'], explode(':', $tarif['fps'])))
- sys::outjs(array('e' => 'Переданные данные fps неверны.'));
+ // Проверка FPS
+ if(!in_array($aData['fps'], explode(':', $tarif['fps'])))
+ sys::outjs(array('e' => 'Переданные данные fps неверны.'));
- $test = 0;
+ $test = 0;
- // Проверка периода на тест
- if($aData['test'])
- {
- if(!$tarif['test'] || !$unit['test'])
- sys::outjs(array('e' => 'Тестовый период недоступен.'));
+ // Проверка периода на тест
+ if($aData['test'])
+ {
+ if(!$tarif['test'] || !$unit['test'])
+ sys::outjs(array('e' => 'Тестовый период недоступен.'));
- // Проверка на повторный запрос
- $sql->query('SELECT `id`, `game` FROM `tests` WHERE `user`="'.$user['id'].'" LIMIT 1');
- if($sql->num())
- {
- $test_info = $sql->get();
+ // Проверка на повторный запрос
+ $sql->query('SELECT `id`, `game` FROM `tests` WHERE `user`="'.$user['id'].'" LIMIT 1');
+ if($sql->num())
+ {
+ $test_info = $sql->get();
- if(!$cfg['tests']['game'] || $test_info['game'] == 'cs')
- sys::outjs(array('e' => 'Тестовый период предоставляется один раз.'));
+ if(!$cfg['tests']['game'] || $test_info['game'] == 'cs')
+ sys::outjs(array('e' => 'Тестовый период предоставляется один раз.'));
- $sql->query('SELECT `id` FROM `servers` WHERE `user`="'.$user['id'].'" AND `test`="1" LIMIT 1');
- if($sql->num() AND !$cfg['tests']['sametime'])
- sys::outjs(array('e' => 'Чтобы получить тестовый период другой игры, дождитесь окончания текущего.'));
- }
+ $sql->query('SELECT `id` FROM `servers` WHERE `user`="'.$user['id'].'" AND `test`="1" LIMIT 1');
+ if($sql->num() AND !$cfg['tests']['sametime'])
+ sys::outjs(array('e' => 'Чтобы получить тестовый период другой игры, дождитесь окончания текущего.'));
+ }
- // Проверка наличия мест на локации
- $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `test`="1" AND `time`>"'.$start_point.'" LIMIT '.$unit['test']);
- if($sql->num() == $unit['test'])
- sys::outjs(array('e' => 'Свободного места для тестового периода нет.'));
+ // Проверка наличия мест на локации
+ $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `test`="1" AND `time`>"'.$start_point.'" LIMIT '.$unit['test']);
+ if($sql->num() == $unit['test'])
+ sys::outjs(array('e' => 'Свободного места для тестового периода нет.'));
- // Проверка наличия мест для выбранного тарифа
- $sql->query('SELECT `id` FROM `servers` WHERE `tarif`="'.$aData['tarif'].'" AND `test`="1" AND `time`>"'.$start_point.'" LIMIT '.$tarif['tests']);
- if($sql->num() == $tarif['tests'])
- sys::outjs(array('e' => 'Свободного места для тестового периода выбранного тарифа нет.'));
+ // Проверка наличия мест для выбранного тарифа
+ $sql->query('SELECT `id` FROM `servers` WHERE `tarif`="'.$aData['tarif'].'" AND `test`="1" AND `time`>"'.$start_point.'" LIMIT '.$tarif['tests']);
+ if($sql->num() == $tarif['tests'])
+ sys::outjs(array('e' => 'Свободного места для тестового периода выбранного тарифа нет.'));
- $test = 1;
- }else
- // Проверка периода
- if(!$cfg['settlement_period'] AND !in_array($aData['time'], explode(':', $tarif['time'])))
- sys::outjs(array('e' => 'Переданные данные периода неверны.'));
+ $test = 1;
+ }else
+ // Проверка периода
+ if(!$cfg['settlement_period'] AND !in_array($aData['time'], explode(':', $tarif['time'])))
+ sys::outjs(array('e' => 'Переданные данные периода неверны.'));
- // Проверка слот
- if($aData['slots'] < $tarif['slots_min'] || $aData['slots'] > $tarif['slots_max'])
- sys::outjs(array('e' => 'Переданные данные слот неверны.'));
+ // Проверка слот
+ if($aData['slots'] < $tarif['slots_min'] || $aData['slots'] > $tarif['slots_max'])
+ sys::outjs(array('e' => 'Переданные данные слот неверны.'));
- // Определение цены
- $aPrice = explode(':', $tarif['price']);
- $price = $aPrice[array_search($aData['fps'], explode(':', $tarif['fps']))];
+ // Определение цены
+ $aPrice = explode(':', $tarif['price']);
+ $price = $aPrice[array_search($aData['fps'], explode(':', $tarif['fps']))];
- // Определение суммы
- if($cfg['settlement_period'])
- {
- // Цена аренды за расчетный период
- $sum = games::define_sum($tarif['discount'], $price, $aData['slots'], $start_point);
+ // Определение суммы
+ if($cfg['settlement_period'])
+ {
+ // Цена аренды за расчетный период
+ $sum = games::define_sum($tarif['discount'], $price, $aData['slots'], $start_point);
- $aData['time'] = games::define_period('buy', params::$aDayMonth);
- }else
- $sum = games::define_sum($tarif['discount'], $price, $aData['slots'], $aData['time']);
+ $aData['time'] = games::define_period('buy', params::$aDayMonth);
+ }else
+ $sum = games::define_sum($tarif['discount'], $price, $aData['slots'], $aData['time']);
- // Проверка промо-кода
- $promo = games::define_promo(
- $aData['promo'],
- array(
- 'tarif' => $aData['tarif'],
- 'fps' => $aData['fps'],
- 'slots' => $aData['slots'],
- 'time' => $aData['time'],
- 'user' => $user['id']
- ),
- $tarif['discount'],
- $sum
- );
+ // Проверка промо-кода
+ $promo = games::define_promo(
+ $aData['promo'],
+ array(
+ 'tarif' => $aData['tarif'],
+ 'fps' => $aData['fps'],
+ 'slots' => $aData['slots'],
+ 'time' => $aData['time'],
+ 'user' => $user['id']
+ ),
+ $tarif['discount'],
+ $sum
+ );
- $days = $aData['time']; // Кол-во дней аренды
+ $days = $aData['time']; // Кол-во дней аренды
- // Использование промо-кода
- if(is_array($promo))
- {
- if(array_key_exists('sum', $promo))
- $sum = $promo['sum'];
- else
- $days += $promo['days']; // Кол-во дней аренды с учетом подарочных (промо-код)
- }
+ // Использование промо-кода
+ if(is_array($promo))
+ {
+ if(array_key_exists('sum', $promo))
+ $sum = $promo['sum'];
+ else
+ $days += $promo['days']; // Кол-во дней аренды с учетом подарочных (промо-код)
+ }
- // Проверка баланса
- if($user['balance'] < $sum)
- sys::outjs(array('e' => 'У вас не хватает '.(round($sum-$user['balance'], 2)).' '.$cfg['currency']));
+ // Проверка баланса
+ if($user['balance'] < $sum)
+ sys::outjs(array('e' => 'У вас не хватает '.(round($sum-$user['balance'], 2)).' '.$cfg['currency']));
- // Выделенный адрес игрового сервера
- if(!empty($tarif['ip']))
- {
- $aIp = explode(':', $tarif['ip']);
+ // Выделенный адрес игрового сервера
+ if(!empty($tarif['ip']))
+ {
+ $aIp = explode(':', $tarif['ip']);
- $ip = false;
- $port = params::$aDefPort['cs'];
+ $ip = false;
+ $port = params::$aDefPort['cs'];
- // Проверка наличия свободного адреса
- foreach($aIp as $adr)
- {
- $adr = trim($adr);
+ // Проверка наличия свободного адреса
+ foreach($aIp as $adr)
+ {
+ $adr = trim($adr);
- $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `address` LIKE "'.$adr.':%" LIMIT 1');
- if(!$sql->num())
- {
- $ip = $adr;
+ $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `address` LIKE "'.$adr.':%" LIMIT 1');
+ if(!$sql->num())
+ {
+ $ip = $adr;
- break;
- }
- }
- }else{
- $ip = sys::first(explode(':', $unit['address']));
- $port = false;
+ break;
+ }
+ }
+ }else{
+ $ip = sys::first(explode(':', $unit['address']));
+ $port = false;
- // Проверка наличия свободного порта
- for($tarif['port_min']; $tarif['port_min'] <= $tarif['port_max']; $tarif['port_min']+=1)
- {
- $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND (`address`="'.$ip.':'.$tarif['port_min'].'" OR `port`="'.$tarif['port_min'].'") LIMIT 1');
- if(!$sql->num())
- {
- $port = $tarif['port_min'];
+ // Проверка наличия свободного порта
+ for($tarif['port_min']; $tarif['port_min'] <= $tarif['port_max']; $tarif['port_min']+=1)
+ {
+ $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND (`address`="'.$ip.':'.$tarif['port_min'].'" OR `port`="'.$tarif['port_min'].'") LIMIT 1');
+ if(!$sql->num())
+ {
+ $port = $tarif['port_min'];
- break;
- }
- }
- }
+ break;
+ }
+ }
+ }
- if(!$ip || !$port)
- {
- $sql->query('UPDATE `tarifs` set `show`="0" WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
+ if(!$ip || !$port)
+ {
+ $sql->query('UPDATE `tarifs` set `show`="0" WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
- sys::outjs(array('e' => 'К сожалению нет доступных мест, обратитесь в тех.поддержку.'));
- }
+ sys::outjs(array('e' => 'К сожалению нет доступных мест, обратитесь в тех.поддержку.'));
+ }
- if($test)
- $aData['time'] = games::time($start_point, $tarif['test']);
- else
- $aData['time'] = games::time($start_point, $days);
+ if($test)
+ $aData['time'] = games::time($start_point, $tarif['test']);
+ else
+ $aData['time'] = games::time($start_point, $days);
- $fix_one = 0;
- $core = 0;
+ $fix_one = 0;
+ $core = 0;
- if($tarif['core_fix'] != '')
- {
- $aCore = explode(',', $tarif['core_fix']);
+ if($tarif['core_fix'] != '')
+ {
+ $aCore = explode(',', $tarif['core_fix']);
- foreach($aCore as $cpu)
- {
- $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `core_fix`="'.$cpu.'" AND `core_fix_one`="1" LIMIT 1');
+ foreach($aCore as $cpu)
+ {
+ $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `core_fix`="'.$cpu.'" AND `core_fix_one`="1" LIMIT 1');
- if($sql->num())
- continue;
+ if($sql->num())
+ continue;
- $fix_one = 1;
- $core = $cpu;
+ $fix_one = 1;
+ $core = $cpu;
- break;
- }
+ break;
+ }
- if(!$core)
- {
- $sql->query('UPDATE `tarifs` set `show`="0" WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
+ if(!$core)
+ {
+ $sql->query('UPDATE `tarifs` set `show`="0" WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
- sys::outjs(array('e' => 'К сожалению нет доступных мест, обратитесь в тех.поддержку.'));
- }
- }
+ sys::outjs(array('e' => 'К сожалению нет доступных мест, обратитесь в тех.поддержку.'));
+ }
+ }
- $ram = $tarif['param_fix'] ? $aData['ram'] : $cfg['ram']['cs']*$aSDATA['slots'];
+ $ram = $tarif['param_fix'] ? $aData['ram'] : $cfg['ram']['cs']*$aSDATA['slots'];
- // Массив данных
- $aSDATA = array(
- 'unit' => $aData['unit'], // идентификатор локации
- 'tarif' => $aData['tarif'], // идентификатор тарифа
- 'ram' => $ram, // значение ram
- 'param_fix' => $tarif['param_fix'], // фиксированные параметры
- 'fps' => $aData['fps'], // значение fps
- 'pack' => $aData['pack'], // Выбранная сборка для установки
- 'time' => $aData['time'], // Время аренды
- 'days' => $days, // Число дней
- 'sum' => $sum, // Сумма списания
- 'test' => $test, // тестовый период
- 'address' => $ip.':'.$port, // адрес игрового сервера
- 'port' => $port, // порт игрового сервера
- 'slots' => $aData['slots'], // Кол-во слот
- 'map' => $tarif['map'], // Фиксированное значение слот
- 'autostop' => $tarif['autostop'], // Выключение при 0 онлайне
- 'ftp' => $tarif['ftp'], // Использование ftp
- 'plugins' => $tarif['plugins'], // Использование плагинов
- 'console' => $tarif['console'], // Использование консоли
- 'stats' => $tarif['stats'], // Использование графиков (ведение статистики)
- 'copy' => $tarif['copy'], // Использование резервных копий
- 'web' => $tarif['web'], // Использование доп услуг
- 'plugins_install' => $tarif['plugins_install'], // Список установленных плагинов
- 'hdd' => $tarif['hdd'], // Дисковое пространство
- 'core_fix' => $core, // Выделенный поток
- 'core_fix_one' => $fix_one, // Выделенный поток
- 'promo' => $promo // Использование промо-кода
- );
+ // Массив данных
+ $aSDATA = array(
+ 'unit' => $aData['unit'], // идентификатор локации
+ 'tarif' => $aData['tarif'], // идентификатор тарифа
+ 'ram' => $ram, // значение ram
+ 'param_fix' => $tarif['param_fix'], // фиксированные параметры
+ 'fps' => $aData['fps'], // значение fps
+ 'pack' => $aData['pack'], // Выбранная сборка для установки
+ 'time' => $aData['time'], // Время аренды
+ 'days' => $days, // Число дней
+ 'sum' => $sum, // Сумма списания
+ 'test' => $test, // тестовый период
+ 'address' => $ip.':'.$port, // адрес игрового сервера
+ 'port' => $port, // порт игрового сервера
+ 'slots' => $aData['slots'], // Кол-во слот
+ 'map' => $tarif['map'], // Фиксированное значение слот
+ 'autostop' => $tarif['autostop'], // Выключение при 0 онлайне
+ 'ftp' => $tarif['ftp'], // Использование ftp
+ 'plugins' => $tarif['plugins'], // Использование плагинов
+ 'console' => $tarif['console'], // Использование консоли
+ 'stats' => $tarif['stats'], // Использование графиков (ведение статистики)
+ 'copy' => $tarif['copy'], // Использование резервных копий
+ 'web' => $tarif['web'], // Использование доп услуг
+ 'plugins_install' => $tarif['plugins_install'], // Список установленных плагинов
+ 'hdd' => $tarif['hdd'], // Дисковое пространство
+ 'core_fix' => $core, // Выделенный поток
+ 'core_fix_one' => $fix_one, // Выделенный поток
+ 'promo' => $promo // Использование промо-кода
+ );
- return $aSDATA;
- }
+ return $aSDATA;
+ }
- public static function install($aSDATA = array())
- {
- global $cfg, $sql, $user, $start_point;
+ public static function install($aSDATA = array())
+ {
+ global $cfg, $sql, $user, $start_point;
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- // Массив данных локации (адрес,пароль)
- $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$aSDATA['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ // Массив данных локации (адрес,пароль)
+ $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$aSDATA['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- // Проверка ssh соединения с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- sys::outjs(array('e' => sys::text('error', 'ssh')));
+ // Проверка ssh соединения с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ sys::outjs(array('e' => sys::text('error', 'ssh')));
- // Массив данных тарифа (путь сборки,путь установки)
- $sql->query('SELECT `path`, `install`, `hostname` FROM `tarifs` WHERE `id`="'.$aSDATA['tarif'].'" LIMIT 1');
- $tarif = $sql->get();
+ // Массив данных тарифа (путь сборки,путь установки)
+ $sql->query('SELECT `path`, `install`, `hostname` FROM `tarifs` WHERE `id`="'.$aSDATA['tarif'].'" LIMIT 1');
+ $tarif = $sql->get();
- // Получение идентификаторов игрового сервера
- $sql->query('INSERT INTO `servers` set uid="1"');
- $id = $sql->id();
- $uid = $id+1000;
+ // Получение идентификаторов игрового сервера
+ $sql->query('INSERT INTO `servers` set uid="1"');
+ $id = $sql->id();
+ $uid = $id+1000;
- // Директория сборки
- $path = $tarif['path'].$aSDATA['pack'];
+ // Директория сборки
+ $path = $tarif['path'].$aSDATA['pack'];
- // Директория игрового сервера
- $install = $tarif['install'].$uid;
+ // Директория игрового сервера
+ $install = $tarif['install'].$uid;
- $ssh->set('mkdir '.$install.';' // Создание директории
- .'useradd -s /bin/false -d '.$install.' -g servers -u '.$uid.' server'.$uid.';' // Создание пользователя сервера на локации
- .'chown server'.$uid.':1000 '.$install.';' // Изменение владельца и группы директории
- .'cd '.$install.' && sudo -u server'.$uid.' screen -dmS i_'.$uid.' sh -c "cp -r '.$path.'/. .;' // Копирование файлов сборки для сервера
- .'find . -type d -exec chmod 700 {} \;;'
- .'find . -type f -exec chmod 600 {} \;;'
- .'chmod 500 '.params::$aFileGame['cs'].'"');
+ $ssh->set('mkdir '.$install.';' // Создание директории
+ .'useradd -s /bin/false -d '.$install.' -g servers -u '.$uid.' server'.$uid.';' // Создание пользователя сервера на локации
+ .'chown server'.$uid.':1000 '.$install.';' // Изменение владельца и группы директории
+ .'cd '.$install.' && sudo -u server'.$uid.' screen -dmS i_'.$uid.' sh -c "cp -r '.$path.'/. .;' // Копирование файлов сборки для сервера
+ .'find . -type d -exec chmod 700 {} \;;'
+ .'find . -type f -exec chmod 600 {} \;;'
+ .'chmod 500 '.params::$aFileGame['cs'].'"');
- // Запись данных нового сервера
- $sql->query('UPDATE `servers` set
- `uid`="'.$uid.'",
- `unit`="'.$aSDATA['unit'].'",
- `tarif`="'.$aSDATA['tarif'].'",
- `user`="'.$user['id'].'",
- `address`="'.$aSDATA['address'].'",
- `port`="'.$aSDATA['port'].'",
- `game`="cs",
- `slots`="'.$aSDATA['slots'].'",
- `slots_start`="'.$aSDATA['slots'].'",
- `status`="install",
- `name`="'.$tarif['hostname'].'",
- `pack`="'.$aSDATA['pack'].'",
- `plugins_use`="'.$aSDATA['plugins'].'",
- `ftp_use`="'.$aSDATA['ftp'].'",
- `console_use`="'.$aSDATA['console'].'",
- `stats_use`="'.$aSDATA['stats'].'",
- `copy_use`="'.$aSDATA['copy'].'",
- `web_use`="'.$aSDATA['web'].'",
- `fps`="'.$aSDATA['fps'].'",
- `map_start`="'.$aSDATA['map'].'",
- `vac`="1",
- `hdd`="'.$aSDATA['hdd'].'",
- `time`="'.$aSDATA['time'].'",
- `date`="'.$start_point.'",
- `test`="'.$aSDATA['test'].'",
- `ram`="'.$aSDATA['ram'].'",
- `core_fix`="'.$aSDATA['core_fix'].'",
- `core_fix_one`="'.$aSDATA['core_fix_one'].'",
- `autostop`="'.$aSDATA['autostop'].'" WHERE `id`="'.$id.'" LIMIT 1');
+ // Запись данных нового сервера
+ $sql->query('UPDATE `servers` set
+ `uid`="'.$uid.'",
+ `unit`="'.$aSDATA['unit'].'",
+ `tarif`="'.$aSDATA['tarif'].'",
+ `user`="'.$user['id'].'",
+ `address`="'.$aSDATA['address'].'",
+ `port`="'.$aSDATA['port'].'",
+ `game`="cs",
+ `slots`="'.$aSDATA['slots'].'",
+ `slots_start`="'.$aSDATA['slots'].'",
+ `status`="install",
+ `name`="'.$tarif['hostname'].'",
+ `pack`="'.$aSDATA['pack'].'",
+ `plugins_use`="'.$aSDATA['plugins'].'",
+ `ftp_use`="'.$aSDATA['ftp'].'",
+ `console_use`="'.$aSDATA['console'].'",
+ `stats_use`="'.$aSDATA['stats'].'",
+ `copy_use`="'.$aSDATA['copy'].'",
+ `web_use`="'.$aSDATA['web'].'",
+ `fps`="'.$aSDATA['fps'].'",
+ `map_start`="'.$aSDATA['map'].'",
+ `vac`="1",
+ `hdd`="'.$aSDATA['hdd'].'",
+ `time`="'.$aSDATA['time'].'",
+ `date`="'.$start_point.'",
+ `test`="'.$aSDATA['test'].'",
+ `ram`="'.$aSDATA['ram'].'",
+ `core_fix`="'.$aSDATA['core_fix'].'",
+ `core_fix_one`="'.$aSDATA['core_fix_one'].'",
+ `autostop`="'.$aSDATA['autostop'].'" WHERE `id`="'.$id.'" LIMIT 1');
- // Запись установленных плагинов
- if($aSDATA['plugins'])
- {
- // Массив идентификаторов плагинов
- $aPlugins = sys::b64djs($aSDATA['plugins_install']);
+ // Запись установленных плагинов
+ if($aSDATA['plugins'])
+ {
+ // Массив идентификаторов плагинов
+ $aPlugins = sys::b64djs($aSDATA['plugins_install']);
- if(isset($aPlugins[$aSDATA['pack']]))
- {
- $plugins = explode(',', $aPlugins[$aSDATA['pack']]);
+ if(isset($aPlugins[$aSDATA['pack']]))
+ {
+ $plugins = explode(',', $aPlugins[$aSDATA['pack']]);
- foreach($plugins as $plugin)
- if($plugin)
- $sql->query('INSERT INTO `plugins_install` set `server`="'.$id.'", `plugin`="'.$plugin.'", `time`="'.$start_point.'"');
- }
- }
+ foreach($plugins as $plugin)
+ if($plugin)
+ $sql->query('INSERT INTO `plugins_install` set `server`="'.$id.'", `plugin`="'.$plugin.'", `time`="'.$start_point.'"');
+ }
+ }
- // Списание средств с баланса пользователя
- $sql->query('UPDATE `users` set `balance`="'.($user['balance']-$aSDATA['sum']).'" WHERE `id`="'.$user['id'].'" LIMIT 1');
+ // Списание средств с баланса пользователя
+ $sql->query('UPDATE `users` set `balance`="'.($user['balance']-$aSDATA['sum']).'" WHERE `id`="'.$user['id'].'" LIMIT 1');
- // Запись получения тестового периода
- if($aSDATA['test'])
- {
- $sql->query('INSERT INTO `tests` set `server`="'.$id.'", `unit`="'.$aSDATA['unit'].'", `game`="cs", `user`="'.$user['id'].'", `time`="'.$start_point.'"');
- $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server_test'), array('id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="0"');
- }else{
- // Реф. система
- games::part($user['id'], $aSDATA['sum']);
+ // Запись получения тестового периода
+ if($aSDATA['test'])
+ {
+ $sql->query('INSERT INTO `tests` set `server`="'.$id.'", `unit`="'.$aSDATA['unit'].'", `game`="cs", `user`="'.$user['id'].'", `time`="'.$start_point.'"');
+ $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server_test'), array('id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="0"');
+ }else{
+ // Реф. система
+ games::part($user['id'], $aSDATA['sum']);
- // Запись логов
- if(!is_array($aSDATA['promo']))
- $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server'), array('days' => games::parse_day($aSDATA['days'], true), 'money' => $aSDATA['sum'], 'id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="'.$aSDATA['sum'].'"');
- else{
- $sql->query('UPDATE `servers` set `benefit`="'.$aSDATA['time'].'" WHERE `id`="'.$id.'" LIMIT 1');
- $sql->query('INSERT INTO `promo_use` set `promo`="'.$aSDATA['promo']['id'].'", `user`="'.$user['id'].'", `time`="'.$start_point.'"');
- $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server_promo'), array('days' => games::parse_day($aSDATA['days'], true), 'money' => $aSDATA['sum'], 'promo' => $aSDATA['promo']['cod'], 'id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="'.$aSDATA['sum'].'"');
- }
- }
+ // Запись логов
+ if(!is_array($aSDATA['promo']))
+ $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server'), array('days' => games::parse_day($aSDATA['days'], true), 'money' => $aSDATA['sum'], 'id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="'.$aSDATA['sum'].'"');
+ else{
+ $sql->query('UPDATE `servers` set `benefit`="'.$aSDATA['time'].'" WHERE `id`="'.$id.'" LIMIT 1');
+ $sql->query('INSERT INTO `promo_use` set `promo`="'.$aSDATA['promo']['id'].'", `user`="'.$user['id'].'", `time`="'.$start_point.'"');
+ $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server_promo'), array('days' => games::parse_day($aSDATA['days'], true), 'money' => $aSDATA['sum'], 'promo' => $aSDATA['promo']['cod'], 'id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="'.$aSDATA['sum'].'"');
+ }
+ }
- return $id;
- }
+ return $id;
+ }
}
?>
\ No newline at end of file
diff --git a/system/library/games/cs/tarif.php b/system/library/games/cs/tarif.php
index c571bc8..f8e5e7f 100644
--- a/system/library/games/cs/tarif.php
+++ b/system/library/games/cs/tarif.php
@@ -1,225 +1,225 @@
get('extend', 'sections/servers/games/tarif');
+ $html->get('extend', 'sections/servers/games/tarif');
- if(isset($html->arr['extend_address']))
- {
- $html->unit('extend_address', 1);
- $html->set('extend_address', $html->arr['extend_address']);
- }else
- $html->unit('extend_address');
+ if(isset($html->arr['extend_address']))
+ {
+ $html->unit('extend_address', 1);
+ $html->set('extend_address', $html->arr['extend_address']);
+ }else
+ $html->unit('extend_address');
- $html->set('id', $sid);
- $html->set('time', sys::date('min', $server['time']));
- $html->set('options', 'Выберете период продления '.$options);
- $html->set('slots', $server['slots']);
- $html->set('info', $server['fps'].' FPS');
- $html->set('tarif', $tarif_name);
- $html->set('cur', $cfg['currency']);
+ $html->set('id', $sid);
+ $html->set('time', sys::date('min', $server['time']));
+ $html->set('options', 'Выберете период продления '.$options);
+ $html->set('slots', $server['slots']);
+ $html->set('info', $server['fps'].' FPS');
+ $html->set('tarif', $tarif_name);
+ $html->set('cur', $cfg['currency']);
- $html->pack('main');
+ $html->pack('main');
- return NULL;
- }
+ return NULL;
+ }
public static function extend_sp($server, $tarif, $sid)
{
- global $cfg, $sql, $html, $start_point;
+ global $cfg, $sql, $html, $start_point;
- tarifs::extend_address($server['game'], $sid);
+ tarifs::extend_address($server['game'], $sid);
- $aPrice = explode(':', $tarif['price']);
- $aFPS = explode(':', $tarif['fps']);
+ $aPrice = explode(':', $tarif['price']);
+ $aFPS = explode(':', $tarif['fps']);
- $sum = $tarif['slots'] ? $aPrice[array_search($server['fps'], $aFPS)] : $aPrice[array_search($server['fps'], $aFPS)]*$server['slots'];
+ $sum = $tarif['slots'] ? $aPrice[array_search($server['fps'], $aFPS)] : $aPrice[array_search($server['fps'], $aFPS)]*$server['slots'];
- $html->get('extend_sp', 'sections/servers/games/tarif');
+ $html->get('extend_sp', 'sections/servers/games/tarif');
- if(isset($html->arr['extend_address']))
- {
- $html->unit('extend_address', 1);
- $html->set('extend_address', $html->arr['extend_address']);
- }else
- $html->unit('extend_address');
+ if(isset($html->arr['extend_address']))
+ {
+ $html->unit('extend_address', 1);
+ $html->set('extend_address', $html->arr['extend_address']);
+ }else
+ $html->unit('extend_address');
- $html->set('id', $sid);
- $html->set('time', sys::date('min', $server['time']));
- $html->set('date', $server['time'] > $start_point ? 'Сервер продлен до: '.date('d.m.Y', $server['time']) : 'Текущая дата: '.date('d.m.Y', $start_point));
- $html->set('options', 'Выберете период продления '.$options);
- $html->set('slots', $server['slots']);
- $html->set('info', $server['fps'].' FPS');
- $html->set('tarif', $tarif['name']);
- $html->set('sum', $sum);
- $html->set('cur', $cfg['currency']);
+ $html->set('id', $sid);
+ $html->set('time', sys::date('min', $server['time']));
+ $html->set('date', $server['time'] > $start_point ? 'Сервер продлен до: '.date('d.m.Y', $server['time']) : 'Текущая дата: '.date('d.m.Y', $start_point));
+ $html->set('options', 'Выберете период продления '.$options);
+ $html->set('slots', $server['slots']);
+ $html->set('info', $server['fps'].' FPS');
+ $html->set('tarif', $tarif['name']);
+ $html->set('sum', $sum);
+ $html->set('cur', $cfg['currency']);
- $html->pack('main');
+ $html->pack('main');
- return NULL;
- }
+ return NULL;
+ }
public static function plan($server, $tarif_name, $sid)
{
- global $cfg, $sql, $html;
+ global $cfg, $sql, $html;
- $sql->query('SELECT `fps`, `price` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
+ $sql->query('SELECT `fps`, `price` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
- if(!$sql->num())
- return NULL;
+ if(!$sql->num())
+ return NULL;
- $tarif = $sql->get();
+ $tarif = $sql->get();
- $options = 'Выберете тарифный план ';
+ $options = 'Выберете тарифный план ';
- $aPrice = explode(':', $tarif['price']);
- $aFps = explode(':', $tarif['fps']);
+ $aPrice = explode(':', $tarif['price']);
+ $aFps = explode(':', $tarif['fps']);
- // Если есть выбор
- if(count($aFps) > 1)
- {
- // Удалить при наличии fps сервера из выбора
- if(in_array($server['fps'], $aFps))
- unset($aFps[array_search($server['fps'], $aFps)]);
+ // Если есть выбор
+ if(count($aFps) > 1)
+ {
+ // Удалить при наличии fps сервера из выбора
+ if(in_array($server['fps'], $aFps))
+ unset($aFps[array_search($server['fps'], $aFps)]);
- foreach($aFps as $index => $fps)
- $options .= ''
- .$fps.' FPS '
- .'('.$aPrice[$index].' '.$cfg['currency'].'/слот | '
- .($aPrice[$index]*$server['slots']).' '.$cfg['currency'].'/месяц)'
- .' ';
- }else
- return NULL;
+ foreach($aFps as $index => $fps)
+ $options .= ''
+ .$fps.' FPS '
+ .'('.$aPrice[$index].' '.$cfg['currency'].'/слот | '
+ .($aPrice[$index]*$server['slots']).' '.$cfg['currency'].'/месяц)'
+ .' ';
+ }else
+ return NULL;
- $html->get('plan', 'sections/servers/games/tarif');
+ $html->get('plan', 'sections/servers/games/tarif');
- $html->set('id', $sid);
- $html->set('options', $options);
- $html->set('info', $server['fps'].' FPS');
- $html->set('tarif', $tarif_name);
+ $html->set('id', $sid);
+ $html->set('options', $options);
+ $html->set('info', $server['fps'].' FPS');
+ $html->set('tarif', $tarif_name);
- $html->pack('main');
+ $html->pack('main');
- return NULL;
- }
+ return NULL;
+ }
- public static function unit($server, $unit_name, $tarif_name, $sid)
+ public static function unit($server, $unit_name, $tarif_name, $sid)
{
- global $cfg, $sql, $html;
+ global $cfg, $sql, $html;
- if(!$cfg['change_unit'][$server['game']])
- return NULL;
+ if(!$cfg['change_unit'][$server['game']])
+ return NULL;
- $tarifs = $sql->query('SELECT `unit`, `fps` FROM `tarifs` WHERE `game`="'.$server['game'].'" AND `name`="'.$tarif_name.'" AND `id`!="'.$server['tarif'].'" AND `show`="1" ORDER BY `unit`');
- if(!$sql->num($tarifs))
- return NULL;
+ $tarifs = $sql->query('SELECT `unit`, `fps` FROM `tarifs` WHERE `game`="'.$server['game'].'" AND `name`="'.$tarif_name.'" AND `id`!="'.$server['tarif'].'" AND `show`="1" ORDER BY `unit`');
+ if(!$sql->num($tarifs))
+ return NULL;
- $units = 0;
+ $units = 0;
- $options = 'Выберете новую локацию ';
+ $options = 'Выберете новую локацию ';
- while($tarif = $sql->get($tarifs))
- {
- if(!in_array($server['fps'], explode(':', $tarif['fps'])))
- continue;
+ while($tarif = $sql->get($tarifs))
+ {
+ if(!in_array($server['fps'], explode(':', $tarif['fps'])))
+ continue;
- $sql->query('SELECT `id`, `name` FROM `units` WHERE `id`="'.$tarif['unit'].'" AND `show`="1" LIMIT 1');
- if(!$sql->num())
- continue;
+ $sql->query('SELECT `id`, `name` FROM `units` WHERE `id`="'.$tarif['unit'].'" AND `show`="1" LIMIT 1');
+ if(!$sql->num())
+ continue;
- $unit = $sql->get();
+ $unit = $sql->get();
- $options .= ''.$unit['name'].' ';
+ $options .= ''.$unit['name'].' ';
- $units+=1;
- }
+ $units+=1;
+ }
- if(!$units)
- return NULL;
+ if(!$units)
+ return NULL;
- $html->get('unit', 'sections/servers/games/tarif');
+ $html->get('unit', 'sections/servers/games/tarif');
- $html->set('id', $sid);
- $html->set('options', $options);
- $html->set('slots', $server['slots']);
- $html->set('info', $server['fps'].' FPS');
- $html->set('unit', $unit_name);
- $html->set('tarif', $tarif_name);
+ $html->set('id', $sid);
+ $html->set('options', $options);
+ $html->set('slots', $server['slots']);
+ $html->set('info', $server['fps'].' FPS');
+ $html->set('unit', $unit_name);
+ $html->set('tarif', $tarif_name);
- $html->pack('main');
+ $html->pack('main');
- return NULL;
- }
+ return NULL;
+ }
- public static function unit_new($tarif, $unit, $server, $mcache)
- {
- global $ssh, $sql, $user, $start_point;
+ public static function unit_new($tarif, $unit, $server, $mcache)
+ {
+ global $ssh, $sql, $user, $start_point;
- // Проверка ssh соединения с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- sys::outjs(array('e' => sys::text('error', 'ssh')));
+ // Проверка ssh соединения с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ sys::outjs(array('e' => sys::text('error', 'ssh')));
- // Директория сборки
- $path = $tarif['path'].$tarif['pack'];
+ // Директория сборки
+ $path = $tarif['path'].$tarif['pack'];
- // Директория игрового сервера
- $install = $tarif['install'].$server['uid'];
+ // Директория игрового сервера
+ $install = $tarif['install'].$server['uid'];
- // Пользователь сервера
- $uS = 'server'.$server['uid'];
+ // Пользователь сервера
+ $uS = 'server'.$server['uid'];
- $ssh->set('mkdir '.$install.';' // Создание директории
- .'useradd -d '.$install.' -g servers -u '.$server['uid'].' '.$uS.';' // Создание пользователя сервера на локации
- .'chown '.$uS.':1000 '.$install.';' // Изменение владельца и группы директории
- .'cd '.$install.' && sudo -u '.$uS.' screen -dmS i_'.$server['uid'].' cp -r '.$path.'/. .'); // Копирование файлов сборки для сервера
+ $ssh->set('mkdir '.$install.';' // Создание директории
+ .'useradd -d '.$install.' -g servers -u '.$server['uid'].' '.$uS.';' // Создание пользователя сервера на локации
+ .'chown '.$uS.':1000 '.$install.';' // Изменение владельца и группы директории
+ .'cd '.$install.' && sudo -u '.$uS.' screen -dmS i_'.$server['uid'].' cp -r '.$path.'/. .'); // Копирование файлов сборки для сервера
- $address = explode(':', $server['address']);
+ $address = explode(':', $server['address']);
- $fix_one = $tarif['core_fix'] ? 1 : 0;
+ $fix_one = $tarif['core_fix'] ? 1 : 0;
- // Обновление данных нового сервера
- $sql->query('UPDATE `servers` set
- `unit`="'.$tarif['unit'].'",
- `tarif`="'.$tarif['id'].'",
- `address`="'.$server['address'].'",
- `port`="'.$address[1].'",
- `status`="install",
- `name`="'.$tarif['hostname'].'",
- `pack`="'.$tarif['pack'].'",
- `map_start`="'.$tarif['map'].'",
- `vac`="1",
- `hdd`="'.$tarif['hdd'].'",
- `time`="'.$tarif['time'].'",
- `autostop`="'.$tarif['autostop'].'",
- `core_fix`="'.$tarif['core_fix'].'",
- `core_fix_one`="'.$fix_one.'",
- `reinstall`="'.$start_point.'" WHERE `id`="'.$server['id'].'" LIMIT 1');
+ // Обновление данных нового сервера
+ $sql->query('UPDATE `servers` set
+ `unit`="'.$tarif['unit'].'",
+ `tarif`="'.$tarif['id'].'",
+ `address`="'.$server['address'].'",
+ `port`="'.$address[1].'",
+ `status`="install",
+ `name`="'.$tarif['hostname'].'",
+ `pack`="'.$tarif['pack'].'",
+ `map_start`="'.$tarif['map'].'",
+ `vac`="1",
+ `hdd`="'.$tarif['hdd'].'",
+ `time`="'.$tarif['time'].'",
+ `autostop`="'.$tarif['autostop'].'",
+ `core_fix`="'.$tarif['core_fix'].'",
+ `core_fix_one`="'.$fix_one.'",
+ `reinstall`="'.$start_point.'" WHERE `id`="'.$server['id'].'" LIMIT 1');
- // Запись установленных плагинов
- if($tarif['plugins'])
- {
- // Массив идентификаторов плагинов
- $aPlugins = sys::b64js($tarif['plugins_install']);
+ // Запись установленных плагинов
+ if($tarif['plugins'])
+ {
+ // Массив идентификаторов плагинов
+ $aPlugins = sys::b64js($tarif['plugins_install']);
- if(isset($aPlugins[$tarif['pack']]))
- {
- $plugins = explode(',', $aPlugins[$tarif['pack']]);
+ if(isset($aPlugins[$tarif['pack']]))
+ {
+ $plugins = explode(',', $aPlugins[$tarif['pack']]);
- foreach($plugins as $plugin)
- if($plugin)
- $sql->query('INSERT INTO `plugins_install` set `server`="'.$server['id'].'", `plugin`="'.$plugin.'", `time`="'.$start_point.'"');
- }
- }
+ foreach($plugins as $plugin)
+ if($plugin)
+ $sql->query('INSERT INTO `plugins_install` set `server`="'.$server['id'].'", `plugin`="'.$plugin.'", `time`="'.$start_point.'"');
+ }
+ }
- return NULL;
- }
+ return NULL;
+ }
}
?>
\ No newline at end of file
diff --git a/system/library/games/csgo/action.php b/system/library/games/csgo/action.php
index ab3c467..c3d83d2 100644
--- a/system/library/games/csgo/action.php
+++ b/system/library/games/csgo/action.php
@@ -1,302 +1,302 @@
query('SELECT `uid`, `unit`, `tarif`, `game`, `address`, `slots_start`, `name`, `tickrate`, `map_start`, `vac`, `time_start`, `core_fix`, `pingboost` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `uid`, `unit`, `tarif`, `game`, `address`, `slots_start`, `name`, `tickrate`, `map_start`, `vac`, `time_start`, `core_fix`, `pingboost` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
+ $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
$tarif = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return array('e' => sys::text('error', 'ssh'));
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return array('e' => sys::text('error', 'ssh'));
- list($ip, $port) = explode(':', $server['address']);
+ list($ip, $port) = explode(':', $server['address']);
- // Убить процессы
- $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
- .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
+ // Убить процессы
+ $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
+ .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
- $taskset = '';
+ $taskset = '';
- // Если включена система автораспределения и не установлен фиксированный поток
- if($cfg['cpu_route'] AND !$server['core_fix'])
- {
- $proc_stat = array();
+ // Если включена система автораспределения и не установлен фиксированный поток
+ if($cfg['cpu_route'] AND !$server['core_fix'])
+ {
+ $proc_stat = array();
- $proc_stat[0] = $ssh->get('cat /proc/stat');
- }
+ $proc_stat[0] = $ssh->get('cat /proc/stat');
+ }
- // Проверка наличия стартовой карты
- $ssh->set('cd '.$tarif['install'].$server['uid'].'/csgo/maps/ && du -ah | grep -e "\.bsp$" | awk \'{print $2}\'');
+ // Проверка наличия стартовой карты
+ $ssh->set('cd '.$tarif['install'].$server['uid'].'/csgo/maps/ && du -ah | grep -e "\.bsp$" | awk \'{print $2}\'');
- include_once(LIB.'games/games.php');
+ include_once(LIB.'games/games.php');
- if(games::map($server['map_start'], $ssh->get()))
- return array('e' => sys::updtext(sys::text('servers', 'nomap'), array('map' => $server['map_start'].'.bsp')));
+ if(games::map($server['map_start'], $ssh->get()))
+ return array('e' => sys::updtext(sys::text('servers', 'nomap'), array('map' => $server['map_start'].'.bsp')));
- // Если система автораспределения продолжить парсинг загрузки процессора
- if(isset($proc_stat))
- {
- $proc_stat[1] = $ssh->get('cat /proc/stat');
+ // Если система автораспределения продолжить парсинг загрузки процессора
+ if(isset($proc_stat))
+ {
+ $proc_stat[1] = $ssh->get('cat /proc/stat');
- // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
- $core = sys::cpu_idle($proc_stat, $server['unit'], false); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
+ // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
+ $core = sys::cpu_idle($proc_stat, $server['unit'], false); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
- if(!is_numeric($core))
- return array('e' => sys::text('error', 'cpu'));
+ if(!is_numeric($core))
+ return array('e' => sys::text('error', 'cpu'));
- $taskset = 'taskset -c '.$core;
- }
+ $taskset = 'taskset -c '.$core;
+ }
- if($server['core_fix'])
- {
- $core = $server['core_fix']-1;
- $taskset = 'taskset -c '.$core;
- }
+ if($server['core_fix'])
+ {
+ $core = $server['core_fix']-1;
+ $taskset = 'taskset -c '.$core;
+ }
- // Античит VAC
- $vac = $server['vac'] == 0 ? '-insecure' : '-secure';
+ // Античит VAC
+ $vac = $server['vac'] == 0 ? '-insecure' : '-secure';
- // Боты
- $bots = $cfg['bots'][$server['game']] ? '' : '-nobots';
+ // Боты
+ $bots = $cfg['bots'][$server['game']] ? '' : '-nobots';
- // TV
- $tv = $server['tv'] ? '+tv_enable 1 +tv_maxclients 30 +tv_port '.($port+10000) : '-nohltv';
+ // TV
+ $tv = $server['tv'] ? '+tv_enable 1 +tv_maxclients 30 +tv_port '.($port+10000) : '-nohltv';
- $check = explode('/', $server['map_start']);
+ $check = explode('/', $server['map_start']);
- // Стартовая карта
- $map = $check[0] == 'workshop' ? '+workshop_start_map '.$check[1] : '+map \''.$server['map_start'].'\'';
+ // Стартовая карта
+ $map = $check[0] == 'workshop' ? '+workshop_start_map '.$check[1] : '+map \''.$server['map_start'].'\'';
- // Игровой режим
- $mods = array(
- 1 => '+game_type 0 +game_mode 0',
- 2 => '+game_type 0 +game_mode 1',
- 3 => '+game_type 1 +game_mode 0',
- 4 => '+game_type 1 +game_mode 1',
- 5 => '+game_type 1 +game_mode 2'
- );
+ // Игровой режим
+ $mods = array(
+ 1 => '+game_type 0 +game_mode 0',
+ 2 => '+game_type 0 +game_mode 1',
+ 3 => '+game_type 1 +game_mode 0',
+ 4 => '+game_type 1 +game_mode 1',
+ 5 => '+game_type 1 +game_mode 2'
+ );
- $mod = !$server['pingboost'] ? $mods[2] : $mods[$server['pingboost']];
+ $mod = !$server['pingboost'] ? $mods[2] : $mods[$server['pingboost']];
- // Параметры запуска
- $bash = './srcds_run -debug -game csgo -norestart -condebug console.log -usercon -tickrate '.$server['tickrate'].' '.$mod.' +servercfgfile server.cfg '.$map.' -maxplayers_override '.$server['slots_start'].' +ip '.$ip.' +net_public_adr '.$ip.' +port '.$port.' -sv_lan 0 '.$vac.' '.$bots.' '.$tv;
+ // Параметры запуска
+ $bash = './srcds_run -debug -game csgo -norestart -condebug console.log -usercon -tickrate '.$server['tickrate'].' '.$mod.' +servercfgfile server.cfg '.$map.' -maxplayers_override '.$server['slots_start'].' +ip '.$ip.' +net_public_adr '.$ip.' +port '.$port.' -sv_lan 0 '.$vac.' '.$bots.' '.$tv;
- // Временный файл
- $temp = sys::temp($bash);
+ // Временный файл
+ $temp = sys::temp($bash);
- // Обновление файла start.sh
- $ssh->setfile($temp, $tarif['install'].$server['uid'].'/start.sh', 0500);
+ // Обновление файла start.sh
+ $ssh->setfile($temp, $tarif['install'].$server['uid'].'/start.sh', 0500);
- // Строка запуска
- $ssh->set('cd '.$tarif['install'].$server['uid'].';' // переход в директорию игрового сервера
- .'rm *.pid;' // Удаление *.pid файлов
- .'sudo -u server'.$server['uid'].' mkdir -p csgo/oldstart;' // Создание папки логов
- .'cat csgo/console.log >> csgo/oldstart/'.date('d.m.Y_H:i:s', $server['time_start']).'.log; rm csgo/console.log; rm csgo/oldstart/01.01.1970_03:00:00.log;' // Перемещение лога предыдущего запуска
- .'chown server'.$server['uid'].':1000 start.sh;' // Обновление владельца файла start.sh
- .'sudo -u server'.$server['uid'].' screen -dmS s_'.$server['uid'].' '.$taskset.' sh -c "./start.sh"'); // Запуск игровго сервера
+ // Строка запуска
+ $ssh->set('cd '.$tarif['install'].$server['uid'].';' // переход в директорию игрового сервера
+ .'rm *.pid;' // Удаление *.pid файлов
+ .'sudo -u server'.$server['uid'].' mkdir -p csgo/oldstart;' // Создание папки логов
+ .'cat csgo/console.log >> csgo/oldstart/'.date('d.m.Y_H:i:s', $server['time_start']).'.log; rm csgo/console.log; rm csgo/oldstart/01.01.1970_03:00:00.log;' // Перемещение лога предыдущего запуска
+ .'chown server'.$server['uid'].':1000 start.sh;' // Обновление владельца файла start.sh
+ .'sudo -u server'.$server['uid'].' screen -dmS s_'.$server['uid'].' '.$taskset.' sh -c "./start.sh"'); // Запуск игровго сервера
- $core = !isset($core) ? 0 : $core+1;
+ $core = !isset($core) ? 0 : $core+1;
- // Обновление информации в базе
- $sql->query('UPDATE `servers` set `status`="'.$type.'", `online`="0", `players`="", `core_use`="'.$core.'", `time_start`="'.$start_point.'", `stop`="1" WHERE `id`="'.$id.'" LIMIT 1');
+ // Обновление информации в базе
+ $sql->query('UPDATE `servers` set `status`="'.$type.'", `online`="0", `players`="", `core_use`="'.$core.'", `time_start`="'.$start_point.'", `stop`="1" WHERE `id`="'.$id.'" LIMIT 1');
- unlink($temp);
+ unlink($temp);
- // Сброс кеша
- actions::clmcache($id);
+ // Сброс кеша
+ actions::clmcache($id);
- sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0, 'players' => ''));
- sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0));
+ sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0, 'players' => ''));
+ sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0));
- return array('s' => 'ok');
- }
+ return array('s' => 'ok');
+ }
public static function change($id, $map = false)
{
- global $cfg, $sql, $html, $user, $mcache;
+ global $cfg, $sql, $html, $user, $mcache;
- // Если в кеше есть карты
- if($mcache->get('server_maps_change_'.$id) != '' AND !$map)
- return array('maps' => $mcache->get('server_maps_change_'.$id));
+ // Если в кеше есть карты
+ if($mcache->get('server_maps_change_'.$id) != '' AND !$map)
+ return array('maps' => $mcache->get('server_maps_change_'.$id));
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- include(LIB.'games/games.php');
+ include(LIB.'games/games.php');
- $sql->query('SELECT `uid`, `unit`, `game`, `tarif`, `online`, `players`, `name` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `uid`, `unit`, `game`, `tarif`, `online`, `players`, `name` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
$unit = $sql->get();
- $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
+ $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
$tarif = $sql->get();
- // Проверка ssh соедниения пу с локацией
+ // Проверка ssh соедниения пу с локацией
if(!$ssh->auth($unit['passwd'], $unit['address']))
return array('e' => sys::text('error', 'ssh'));
- // Массив карт игрового сервера (папка "maps")
- $aMaps = explode("\n", $ssh->get('cd '.$tarif['install'].$server['uid'].'/csgo/maps/ && du -ah | grep -e "\.bsp$" | awk \'{print $2}\''));
+ // Массив карт игрового сервера (папка "maps")
+ $aMaps = explode("\n", $ssh->get('cd '.$tarif['install'].$server['uid'].'/csgo/maps/ && du -ah | grep -e "\.bsp$" | awk \'{print $2}\''));
- // Удаление пустого элемента
- unset($aMaps[count($aMaps)-1]);
+ // Удаление пустого элемента
+ unset($aMaps[count($aMaps)-1]);
- // Удаление ".bsp"
- $aMaps = str_ireplace(array('./', '.bsp'), '', $aMaps);
+ // Удаление ".bsp"
+ $aMaps = str_ireplace(array('./', '.bsp'), '', $aMaps);
- // Если выбрана карта
- if($map)
- {
- $map = str_replace('|', '/', $map);
+ // Если выбрана карта
+ if($map)
+ {
+ $map = str_replace('|', '/', $map);
- // Проверка наличия выбранной карты
- if(games::map($map, $aMaps))
- return array('e' => sys::updtext(sys::text('servers', 'change'), array('map' => $map.'.bsp')));
+ // Проверка наличия выбранной карты
+ if(games::map($map, $aMaps))
+ return array('e' => sys::updtext(sys::text('servers', 'change'), array('map' => $map.'.bsp')));
- // Отправка команды changelevel
- $ssh->set('sudo -u server'.$server['uid'].' screen -p 0 -S s_'.$server['uid'].' -X eval '."'stuff \"changelevel ".sys::cmd($map)."\"\015'");
+ // Отправка команды changelevel
+ $ssh->set('sudo -u server'.$server['uid'].' screen -p 0 -S s_'.$server['uid'].' -X eval '."'stuff \"changelevel ".sys::cmd($map)."\"\015'");
- // Обновление информации в базе
- $sql->query('UPDATE `servers` set `status`="change" WHERE `id`="'.$id.'" LIMIT 1');
+ // Обновление информации в базе
+ $sql->query('UPDATE `servers` set `status`="change" WHERE `id`="'.$id.'" LIMIT 1');
- // Сброс кеша
- actions::clmcache($id);
+ // Сброс кеша
+ actions::clmcache($id);
- sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'change', 'online' => $server['online'], 'players' => base64_decode($server['players'])));
- sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'change', 'online' => $server['online']));
+ sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'change', 'online' => $server['online'], 'players' => base64_decode($server['players'])));
+ sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'change', 'online' => $server['online']));
- return array('s' => 'ok');
- }
+ return array('s' => 'ok');
+ }
- // Сортировка списка карт
- sort($aMaps);
- reset($aMaps);
+ // Сортировка списка карт
+ sort($aMaps);
+ reset($aMaps);
- // Генерация списка карт для выбора
- foreach($aMaps as $map)
- {
- $aName = explode('/', $map);
- $name = end($aName);
+ // Генерация списка карт для выбора
+ foreach($aMaps as $map)
+ {
+ $aName = explode('/', $map);
+ $name = end($aName);
- $html->get('change_list', 'sections/servers/csgo');
+ $html->get('change_list', 'sections/servers/csgo');
- $html->set('img', file_exists(DIR.'/maps/'.$server['game'].'/'.$name.'.jpg') ? $cfg['http'].'maps/'.$server['game'].'/'.$name.'.jpg' : $cfg['http'].'template/images/status/none.jpg');
- $html->set('map', str_replace('/', '|', $map));
- $html->set('name', $name);
- $html->set('id', $id);
+ $html->set('img', file_exists(DIR.'/maps/'.$server['game'].'/'.$name.'.jpg') ? $cfg['http'].'maps/'.$server['game'].'/'.$name.'.jpg' : $cfg['http'].'template/images/status/none.jpg');
+ $html->set('map', str_replace('/', '|', $map));
+ $html->set('name', $name);
+ $html->set('id', $id);
- if(count($aName) > 1)
- $html->unit('workshop', true);
- else
- $html->unit('workshop');
+ if(count($aName) > 1)
+ $html->unit('workshop', true);
+ else
+ $html->unit('workshop');
- $html->pack('maps');
- }
+ $html->pack('maps');
+ }
- // Запись карт в кеш
- $mcache->set('server_maps_change_'.$id, $html->arr['maps'], false, 60);
+ // Запись карт в кеш
+ $mcache->set('server_maps_change_'.$id, $html->arr['maps'], false, 60);
- return array('maps' => $html->arr['maps']);
- }
+ return array('maps' => $html->arr['maps']);
+ }
public static function update($id)
{
- global $cfg, $sql, $user, $start_point;
+ global $cfg, $sql, $user, $start_point;
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- $sql->query('SELECT `uid`, `unit`, `tarif`, `game`, `name`, `ftp`, `update`, `core_fix` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `uid`, `unit`, `tarif`, `game`, `name`, `ftp`, `update`, `core_fix` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- // Проверка времени обновления
- $update = $server['update']+$cfg['update'][$server['game']]*60;
+ // Проверка времени обновления
+ $update = $server['update']+$cfg['update'][$server['game']]*60;
- if($update > $start_point AND $user['group'] != 'admin')
- return array('e' => sys::updtext(sys::text('servers', 'update'), array('time' => sys::date('max', $update))));
+ if($update > $start_point AND $user['group'] != 'admin')
+ return array('e' => sys::updtext(sys::text('servers', 'update'), array('time' => sys::date('max', $update))));
- $sql->query('SELECT `address`, `passwd`, `sql_login`, `sql_passwd`, `sql_port`, `sql_ftp` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $sql->query('SELECT `address`, `passwd`, `sql_login`, `sql_passwd`, `sql_port`, `sql_ftp` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
$unit = $sql->get();
- $sql->query('SELECT `install`, `plugins_install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
+ $sql->query('SELECT `install`, `plugins_install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
$tarif = $sql->get();
- // Проверка ssh соедниения пу с локацией
+ // Проверка ssh соедниения пу с локацией
if(!$ssh->auth($unit['passwd'], $unit['address']))
return array('e' => sys::text('error', 'ssh'));
- $taskset = '';
+ $taskset = '';
- // Если включена система автораспределения и не установлен фиксированный поток
- if($cfg['cpu_route'] AND !$server['core_fix'])
- {
- $proc_stat = array();
+ // Если включена система автораспределения и не установлен фиксированный поток
+ if($cfg['cpu_route'] AND !$server['core_fix'])
+ {
+ $proc_stat = array();
- $proc_stat[0] = $ssh->get('cat /proc/stat');
- }
+ $proc_stat[0] = $ssh->get('cat /proc/stat');
+ }
- // Директория игрового сервера
- $install = $tarif['install'].$server['uid'];
+ // Директория игрового сервера
+ $install = $tarif['install'].$server['uid'];
- // Если система автораспределения продолжить парсинг загрузки процессора
- if(isset($proc_stat))
- {
- $proc_stat[1] = $ssh->get('cat /proc/stat');
+ // Если система автораспределения продолжить парсинг загрузки процессора
+ if(isset($proc_stat))
+ {
+ $proc_stat[1] = $ssh->get('cat /proc/stat');
- // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
- $core = sys::cpu_idle($proc_stat, $server['unit'], false); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
+ // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
+ $core = sys::cpu_idle($proc_stat, $server['unit'], false); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
- if(!is_numeric($core))
- return array('e' => 'Не удается выполнить операцию, нет свободного потока.');
+ if(!is_numeric($core))
+ return array('e' => 'Не удается выполнить операцию, нет свободного потока.');
- $taskset = 'taskset -c '.$core;
- }
+ $taskset = 'taskset -c '.$core;
+ }
- if($server['core_fix'])
- {
- $core = $server['core_fix']-1;
- $taskset = 'taskset -c '.$core;
- }
+ if($server['core_fix'])
+ {
+ $core = $server['core_fix']-1;
+ $taskset = 'taskset -c '.$core;
+ }
- $ssh->set('cd '.$cfg['steamcmd'].' && '.$taskset.' screen -dmS u_'.$server['uid'].' sh -c "'
- .'./steamcmd.sh +login anonymous +force_install_dir "'.$install.'" +app_update 740 +quit;'
- .'cd '.$install.';'
- .'chown -R server'.$server['uid'].':servers .;'
- .'find . -type d -exec chmod 700 {} \;;'
- .'find . -type f -exec chmod 600 {} \;;'
- .'chmod 500 '.params::$aFileGame[$server['game']].'"');
+ $ssh->set('cd '.$cfg['steamcmd'].' && '.$taskset.' screen -dmS u_'.$server['uid'].' sh -c "'
+ .'./steamcmd.sh +login anonymous +force_install_dir "'.$install.'" +app_update 740 +quit;'
+ .'cd '.$install.';'
+ .'chown -R server'.$server['uid'].':servers .;'
+ .'find . -type d -exec chmod 700 {} \;;'
+ .'find . -type f -exec chmod 600 {} \;;'
+ .'chmod 500 '.params::$aFileGame[$server['game']].'"');
- $core = !isset($core) ? 0 : $core+1;
+ $core = !isset($core) ? 0 : $core+1;
- // Обновление информации в базе
- $sql->query('UPDATE `servers` set `status`="update", `update`="'.$start_point.'", `core_use`="'.$core.'" WHERE `id`="'.$id.'" LIMIT 1');
+ // Обновление информации в базе
+ $sql->query('UPDATE `servers` set `status`="update", `update`="'.$start_point.'", `core_use`="'.$core.'" WHERE `id`="'.$id.'" LIMIT 1');
- // Логирование
- $sql->query('INSERT INTO `logs_sys` set `user`="'.$user['id'].'", `server`="'.$id.'", `text`="'.sys::text('syslogs', 'update').'", `time`="'.$start_point.'"');
+ // Логирование
+ $sql->query('INSERT INTO `logs_sys` set `user`="'.$user['id'].'", `server`="'.$id.'", `text`="'.sys::text('syslogs', 'update').'", `time`="'.$start_point.'"');
- // Сброс кеша
- actions::clmcache($id);
+ // Сброс кеша
+ actions::clmcache($id);
- sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'update', 'online' => 0, 'players' => ''));
- sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'update', 'online' => 0));
+ sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'update', 'online' => 0, 'players' => ''));
+ sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'update', 'online' => 0));
- return array('s' => 'ok');
- }
+ return array('s' => 'ok');
+ }
}
?>
\ No newline at end of file
diff --git a/system/library/games/csgo/rcon.php b/system/library/games/csgo/rcon.php
index 74182de..f40eb6f 100644
--- a/system/library/games/csgo/rcon.php
+++ b/system/library/games/csgo/rcon.php
@@ -1,112 +1,112 @@
Connect($ip, $port, 3, SourceQuery::SOURCE);
+ $sq->Connect($ip, $port, 3, SourceQuery::SOURCE);
- $sq->SetRconPassword(rcon::rcon_passwd($server));
+ $sq->SetRconPassword(rcon::rcon_passwd($server));
- $out = $sq->Rcon($cmd);
+ $out = $sq->Rcon($cmd);
- $sq->Disconnect();
+ $sq->Disconnect();
- return $out;
- }
+ return $out;
+ }
- public static function players($data)
- {
- $aPlayers = array();
- $n = 1;
+ public static function players($data)
+ {
+ $aPlayers = array();
+ $n = 1;
- $lines = explode("\n", $data);
+ $lines = explode("\n", $data);
- foreach($lines as $line)
- {
- if(strpos($line, '#') === FALSE)
- continue;
+ foreach($lines as $line)
+ {
+ if(strpos($line, '#') === FALSE)
+ continue;
- $start = strpos($line, '"')+1;
- $end = strrpos($line, '"');
+ $start = strpos($line, '"')+1;
+ $end = strrpos($line, '"');
- $userid = sys::int(substr($line, 0, $start));
+ $userid = sys::int(substr($line, 0, $start));
- $name = htmlspecialchars(substr($line, $start, $end-$start));
+ $name = htmlspecialchars(substr($line, $start, $end-$start));
- $line = trim(substr($line, $end + 1));
+ $line = trim(substr($line, $end + 1));
- $aData = array_values(array_diff(explode(' ', $line), array('', ' ')));
+ $aData = array_values(array_diff(explode(' ', $line), array('', ' ')));
- $steamid = trim($aData[0]);
- $ip = trim(sys::first(explode(':', $aData[5])));
+ $steamid = trim($aData[0]);
+ $ip = trim(sys::first(explode(':', $aData[5])));
- if((sys::valid($steamid, 'steamid') AND sys::valid($steamid, 'steamid3')) || sys::valid($ip, 'ip'))
- continue;
+ if((sys::valid($steamid, 'steamid') AND sys::valid($steamid, 'steamid3')) || sys::valid($ip, 'ip'))
+ continue;
- $aPlayers[$n]['userid'] = $userid;
- $aPlayers[$n]['name'] = $name;
- $aPlayers[$n]['steamid'] = $steamid;
- $aPlayers[$n]['time'] = trim($aData[1]);
- $aPlayers[$n]['ping'] = trim($aData[2]);
- $aPlayers[$n]['ip'] = $ip;
+ $aPlayers[$n]['userid'] = $userid;
+ $aPlayers[$n]['name'] = $name;
+ $aPlayers[$n]['steamid'] = $steamid;
+ $aPlayers[$n]['time'] = trim($aData[1]);
+ $aPlayers[$n]['ping'] = trim($aData[2]);
+ $aPlayers[$n]['ip'] = $ip;
- $whois = rcon::country($ip);
+ $whois = rcon::country($ip);
- $aPlayers[$n]['ico'] = $whois['ico'];
- $aPlayers[$n]['country'] = $whois['name'];
+ $aPlayers[$n]['ico'] = $whois['ico'];
+ $aPlayers[$n]['country'] = $whois['name'];
- $n+=1;
- }
+ $n+=1;
+ }
- return $aPlayers;
- }
+ return $aPlayers;
+ }
- public static function rcon_passwd($server)
- {
- global $cfg, $sql, $user;
+ public static function rcon_passwd($server)
+ {
+ global $cfg, $sql, $user;
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
$unit = $sql->get();
- if(!$ssh->auth($unit['passwd'], $unit['address']))
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
sys::outjs(array('e' => sys::text('error', 'ssh')));
- $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
- $tarif = $sql->get();
+ $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
+ $tarif = $sql->get();
- $ssh->set('cat '.$tarif['install'].'/'.$server['uid'].'/csgo/cfg/server.cfg | grep rcon_password');
- $get = explode(' ', str_replace('"', '', trim($ssh->get())));
- $rcon = trim(end($get));
+ $ssh->set('cat '.$tarif['install'].'/'.$server['uid'].'/csgo/cfg/server.cfg | grep rcon_password');
+ $get = explode(' ', str_replace('"', '', trim($ssh->get())));
+ $rcon = trim(end($get));
- if(!isset($rcon{0}))
- sys::outjs(array('r' => 'Необходимо установить rcon пароль (rcon_password).', 'url' => $cfg['http'].'servers/id/'.$server['id'].'/section/settings/subsection/server'), $nmch);
+ if(!isset($rcon{0}))
+ sys::outjs(array('r' => 'Необходимо установить rcon пароль (rcon_password).', 'url' => $cfg['http'].'servers/id/'.$server['id'].'/section/settings/subsection/server'), $nmch);
- return $rcon;
- }
+ return $rcon;
+ }
- public static function country($ip)
- {
- global $SxGeo;
+ public static function country($ip)
+ {
+ global $SxGeo;
- $cData = $SxGeo->getCityFull($ip);
- $ico = sys::country($cData['country']['iso']);
+ $cData = $SxGeo->getCityFull($ip);
+ $ico = sys::country($cData['country']['iso']);
- return array('ico' => $ico, 'name' => empty($cData['country']['name_ru']) ? 'Не определена' : $cData['country']['name_ru']);
- }
- }
+ return array('ico' => $ico, 'name' => empty($cData['country']['name_ru']) ? 'Не определена' : $cData['country']['name_ru']);
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/games/csgo/scan.php b/system/library/games/csgo/scan.php
index 5e498aa..f19df98 100644
--- a/system/library/games/csgo/scan.php
+++ b/system/library/games/csgo/scan.php
@@ -1,142 +1,142 @@
get($nmch)))
- return $mcache->get($nmch);
+ if(is_array($mcache->get($nmch)))
+ return $mcache->get($nmch);
- $out = array();
+ $out = array();
- $info = scan::info($sq, $id);
+ $info = scan::info($sq, $id);
- $sql->query('SELECT `game`, `name`, `map`, `online`, `players`, `status`, `time`, `overdue` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `game`, `name`, `map`, `online`, `players`, `status`, `time`, `overdue` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- $out['time'] = 'Арендован до: '.date('d.m.Y - H:i', $server['time']);
+ $out['time'] = 'Арендован до: '.date('d.m.Y - H:i', $server['time']);
- if($server['status'] == 'overdue')
- $out['time_end'] = 'Удаление через: '.sys::date('min', $server['overdue']+$cfg['server_delete']*86400);
- else
- $out['time_end'] = 'Осталось: '.sys::date('min', $server['time']);
+ if($server['status'] == 'overdue')
+ $out['time_end'] = 'Удаление через: '.sys::date('min', $server['overdue']+$cfg['server_delete']*86400);
+ else
+ $out['time_end'] = 'Осталось: '.sys::date('min', $server['time']);
- if(!$info['status'])
- {
- $out['name'] = $server['name'];
- $out['status'] = sys::status($server['status'], $server['game'], $server['map']);
- $out['online'] = $server['online'];
- $out['image'] = ' ';
- $out['buttons'] = sys::buttons($id, $server['status']);
+ if(!$info['status'])
+ {
+ $out['name'] = $server['name'];
+ $out['status'] = sys::status($server['status'], $server['game'], $server['map']);
+ $out['online'] = $server['online'];
+ $out['image'] = ' ';
+ $out['buttons'] = sys::buttons($id, $server['status']);
- if($players_get)
- $out['players'] = base64_decode($server['players']);
+ if($players_get)
+ $out['players'] = base64_decode($server['players']);
- $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
+ $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
- return $out;
- }
+ return $out;
+ }
- if($players_get)
- $players = scan::info($sq, $id, true);
+ if($players_get)
+ $players = scan::info($sq, $id, true);
- $out['name'] = htmlspecialchars($info['name']);
- $out['status'] = sys::status('working', $server['game'], $info['map']);
- $out['online'] = $info['online'];
- $out['image'] = ' ';
- $out['buttons'] = sys::buttons($id, 'working');
- $out['players'] = '';
+ $out['name'] = htmlspecialchars($info['name']);
+ $out['status'] = sys::status('working', $server['game'], $info['map']);
+ $out['online'] = $info['online'];
+ $out['image'] = ' ';
+ $out['buttons'] = sys::buttons($id, 'working');
+ $out['players'] = '';
- if($players_get)
- {
- foreach($players as $index => $player)
- {
- $html->get($server['game'], 'sections/servers/players');
+ if($players_get)
+ {
+ foreach($players as $index => $player)
+ {
+ $html->get($server['game'], 'sections/servers/players');
- $html->set('i', $player['i']);
- $html->set('name', $player['name']);
- $html->set('score', $player['score']);
- $html->set('time', $player['time']);
+ $html->set('i', $player['i']);
+ $html->set('name', $player['name']);
+ $html->set('score', $player['score']);
+ $html->set('time', $player['time']);
- $html->pack('list');
- }
+ $html->pack('list');
+ }
- $out['players'] = isset($html->arr['list']) ? $html->arr['list'] : '';
- }
+ $out['players'] = isset($html->arr['list']) ? $html->arr['list'] : '';
+ }
- $sql->query('UPDATE `servers` set '
- .'`name`="'.$out['name'].'", '
- .'`online`="'.$out['online'].'", '
- .'`map`="'.$info['map'].'", '
- .'`status`="working" WHERE `id`="'.$id.'" LIMIT 1');
+ $sql->query('UPDATE `servers` set '
+ .'`name`="'.$out['name'].'", '
+ .'`online`="'.$out['online'].'", '
+ .'`map`="'.$info['map'].'", '
+ .'`status`="working" WHERE `id`="'.$id.'" LIMIT 1');
- if($players_get)
- $sql->query('UPDATE `servers` set `players`="'.base64_encode($out['players']).'" WHERE `id`="'.$id.'" LIMIT 1');
+ if($players_get)
+ $sql->query('UPDATE `servers` set `players`="'.base64_encode($out['players']).'" WHERE `id`="'.$id.'" LIMIT 1');
- $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
+ $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
- return $out;
- }
+ return $out;
+ }
- public static function info($sq, $id, $pl = false)
- {
- global $sql;
+ public static function info($sq, $id, $pl = false)
+ {
+ global $sql;
- $sql->query('SELECT `address` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `address` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- list($ip, $port) = explode(':', $server['address']);
+ list($ip, $port) = explode(':', $server['address']);
- $sq->Connect($ip, $port, 1, SourceQuery::SOURCE);
+ $sq->Connect($ip, $port, 1, SourceQuery::SOURCE);
- if($pl)
- {
- $players = $sq->GetPlayers();
+ if($pl)
+ {
+ $players = $sq->GetPlayers();
- $i = 1;
- $data = array();
+ $i = 1;
+ $data = array();
- foreach($players as $n => $player)
- {
- $data[$i]['i'] = $i;
- $data[$i]['name'] = $player['Name'] == '' ? 'Подключается' : $player['Name'];
- $data[$i]['score'] = $player['Frags'];
- $data[$i]['time'] = $player['TimeF'];
+ foreach($players as $n => $player)
+ {
+ $data[$i]['i'] = $i;
+ $data[$i]['name'] = $player['Name'] == '' ? 'Подключается' : $player['Name'];
+ $data[$i]['score'] = $player['Frags'];
+ $data[$i]['time'] = $player['TimeF'];
- $i+=1;
- }
+ $i+=1;
+ }
- return $data;
- }
+ return $data;
+ }
- $data = $sq->GetInfo();
+ $data = $sq->GetInfo();
- $map = explode('/', $data['Map']);
+ $map = explode('/', $data['Map']);
- $server['name'] = $data['HostName'];
- $server['map'] = end($map);
- $server['online'] = $data['Players'];
- $server['status'] = strlen($server['map']) > 3 ? true : false;
+ $server['name'] = $data['HostName'];
+ $server['map'] = end($map);
+ $server['online'] = $data['Players'];
+ $server['status'] = strlen($server['map']) > 3 ? true : false;
- return $server;
- }
- }
+ return $server;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/games/csgo/service.php b/system/library/games/csgo/service.php
index 6f3729c..0657d50 100644
--- a/system/library/games/csgo/service.php
+++ b/system/library/games/csgo/service.php
@@ -1,369 +1,369 @@
query('SELECT `address`, `test` FROM `units` WHERE `id`="'.$aData['unit'].'" AND `csgo`="1" AND `show`="1" LIMIT 1');
- if(!$sql->num())
- sys::outjs(array('e' => 'Локация не найдена.'));
+ // Проверка локации
+ $sql->query('SELECT `address`, `test` FROM `units` WHERE `id`="'.$aData['unit'].'" AND `csgo`="1" AND `show`="1" LIMIT 1');
+ if(!$sql->num())
+ sys::outjs(array('e' => 'Локация не найдена.'));
- $unit = $sql->get();
+ $unit = $sql->get();
- // Проверка тарифа
- $sql->query('SELECT `id` FROM `tarifs` WHERE `id`="'.$aData['tarif'].'" AND `unit`="'.$aData['unit'].'" AND `show`="1" LIMIT 1');
- if(!$sql->num())
- sys::outjs(array('e' => 'Тариф не найден.'));
+ // Проверка тарифа
+ $sql->query('SELECT `id` FROM `tarifs` WHERE `id`="'.$aData['tarif'].'" AND `unit`="'.$aData['unit'].'" AND `show`="1" LIMIT 1');
+ if(!$sql->num())
+ sys::outjs(array('e' => 'Тариф не найден.'));
- $sql->query('SELECT '
- .'`slots_min`,'
- .'`slots_max`,'
- .'`port_min`,'
- .'`port_max`,'
- .'`hostname`,'
- .'`packs`,'
- .'`tickrate`,'
- .'`time`,'
- .'`test`,'
- .'`tests`,'
- .'`discount`,'
- .'`map`,'
- .'`ftp`,'
- .'`plugins`,'
- .'`console`,'
- .'`stats`,'
- .'`copy`,'
- .'`web`,'
- .'`plugins_install`,'
- .'`hdd`,'
- .'`autostop`,'
- .'`core_fix`,'
- .'`ip`,'
- .'`price`'
- .' FROM `tarifs` WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
+ $sql->query('SELECT '
+ .'`slots_min`,'
+ .'`slots_max`,'
+ .'`port_min`,'
+ .'`port_max`,'
+ .'`hostname`,'
+ .'`packs`,'
+ .'`tickrate`,'
+ .'`time`,'
+ .'`test`,'
+ .'`tests`,'
+ .'`discount`,'
+ .'`map`,'
+ .'`ftp`,'
+ .'`plugins`,'
+ .'`console`,'
+ .'`stats`,'
+ .'`copy`,'
+ .'`web`,'
+ .'`plugins_install`,'
+ .'`hdd`,'
+ .'`autostop`,'
+ .'`core_fix`,'
+ .'`ip`,'
+ .'`price`'
+ .' FROM `tarifs` WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
- $tarif = $sql->get();
+ $tarif = $sql->get();
- // Проверка сборки
- if(!array_key_exists($aData['pack'], sys::b64djs($tarif['packs'], true)))
- sys::outjs(array('e' => 'Сборка не найдена.'));
+ // Проверка сборки
+ if(!array_key_exists($aData['pack'], sys::b64djs($tarif['packs'], true)))
+ sys::outjs(array('e' => 'Сборка не найдена.'));
- // Проверка TickRate
- if(!in_array($aData['tickrate'], explode(':', $tarif['tickrate'])))
- sys::outjs(array('e' => 'Переданные данные tickrate неверны.'));
+ // Проверка TickRate
+ if(!in_array($aData['tickrate'], explode(':', $tarif['tickrate'])))
+ sys::outjs(array('e' => 'Переданные данные tickrate неверны.'));
- $test = 0;
+ $test = 0;
- // Проверка периода на тест
- if($aData['test'])
- {
- if(!$tarif['test'] || !$unit['test'])
- sys::outjs(array('e' => 'Тестовый период недоступен.'));
+ // Проверка периода на тест
+ if($aData['test'])
+ {
+ if(!$tarif['test'] || !$unit['test'])
+ sys::outjs(array('e' => 'Тестовый период недоступен.'));
- // Проверка на повторный запрос
- $sql->query('SELECT `id`, `game` FROM `tests` WHERE `user`="'.$user['id'].'" LIMIT 1');
- if($sql->num())
- {
- $test_info = $sql->get();
+ // Проверка на повторный запрос
+ $sql->query('SELECT `id`, `game` FROM `tests` WHERE `user`="'.$user['id'].'" LIMIT 1');
+ if($sql->num())
+ {
+ $test_info = $sql->get();
- if(!$cfg['tests']['game'] || $test_info['game'] == 'csgo')
- sys::outjs(array('e' => 'Тестовый период предоставляется один раз.'));
+ if(!$cfg['tests']['game'] || $test_info['game'] == 'csgo')
+ sys::outjs(array('e' => 'Тестовый период предоставляется один раз.'));
- $sql->query('SELECT `id` FROM `servers` WHERE `user`="'.$user['id'].'" AND `test`="1" LIMIT 1');
- if($sql->num() AND !$cfg['tests']['sametime'])
- sys::outjs(array('e' => 'Чтобы получить тестовый период другой игры, дождитесь окончания текущего.'));
- }
+ $sql->query('SELECT `id` FROM `servers` WHERE `user`="'.$user['id'].'" AND `test`="1" LIMIT 1');
+ if($sql->num() AND !$cfg['tests']['sametime'])
+ sys::outjs(array('e' => 'Чтобы получить тестовый период другой игры, дождитесь окончания текущего.'));
+ }
- // Проверка наличия мест на локации
- $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `test`="1" AND `time`>"'.$start_point.'" LIMIT '.$unit['test']);
- if($sql->num() == $unit['test'])
- sys::outjs(array('e' => 'Свободного места для тестового периода нет.'));
+ // Проверка наличия мест на локации
+ $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `test`="1" AND `time`>"'.$start_point.'" LIMIT '.$unit['test']);
+ if($sql->num() == $unit['test'])
+ sys::outjs(array('e' => 'Свободного места для тестового периода нет.'));
- // Проверка наличия мест для выбранного тарифа
- $sql->query('SELECT `id` FROM `servers` WHERE `tarif`="'.$aData['tarif'].'" AND `test`="1" AND `time`>"'.$start_point.'" LIMIT '.$tarif['tests']);
- if($sql->num() == $tarif['tests'])
- sys::outjs(array('e' => 'Свободного места для тестового периода выбранного тарифа нет.'));
+ // Проверка наличия мест для выбранного тарифа
+ $sql->query('SELECT `id` FROM `servers` WHERE `tarif`="'.$aData['tarif'].'" AND `test`="1" AND `time`>"'.$start_point.'" LIMIT '.$tarif['tests']);
+ if($sql->num() == $tarif['tests'])
+ sys::outjs(array('e' => 'Свободного места для тестового периода выбранного тарифа нет.'));
- $test = 1;
- }else
- // Проверка периода
- if(!$cfg['settlement_period'] AND !in_array($aData['time'], explode(':', $tarif['time'])))
- sys::outjs(array('e' => 'Переданные данные периода неверны.'));
+ $test = 1;
+ }else
+ // Проверка периода
+ if(!$cfg['settlement_period'] AND !in_array($aData['time'], explode(':', $tarif['time'])))
+ sys::outjs(array('e' => 'Переданные данные периода неверны.'));
- // Проверка слот
- if($aData['slots'] < $tarif['slots_min'] || $aData['slots'] > $tarif['slots_max'])
- sys::outjs(array('e' => 'Переданные данные слот неверны.'));
+ // Проверка слот
+ if($aData['slots'] < $tarif['slots_min'] || $aData['slots'] > $tarif['slots_max'])
+ sys::outjs(array('e' => 'Переданные данные слот неверны.'));
- // Определение цены
- $aPrice = explode(':', $tarif['price']);
- $price = $aPrice[array_search($aData['tickrate'], explode(':', $tarif['tickrate']))];
+ // Определение цены
+ $aPrice = explode(':', $tarif['price']);
+ $price = $aPrice[array_search($aData['tickrate'], explode(':', $tarif['tickrate']))];
- // Определение суммы
- if($cfg['settlement_period'])
- {
- // Цена аренды за расчетный период
- $sum = games::define_sum($tarif['discount'], $price, $aData['slots'], $start_point);
+ // Определение суммы
+ if($cfg['settlement_period'])
+ {
+ // Цена аренды за расчетный период
+ $sum = games::define_sum($tarif['discount'], $price, $aData['slots'], $start_point);
- $aData['time'] = games::define_period('buy', params::$aDayMonth);
- }else
- $sum = games::define_sum($tarif['discount'], $price, $aData['slots'], $aData['time']);
+ $aData['time'] = games::define_period('buy', params::$aDayMonth);
+ }else
+ $sum = games::define_sum($tarif['discount'], $price, $aData['slots'], $aData['time']);
- // Проверка промо-кода
- $promo = games::define_promo(
- $aData['promo'],
- array(
- 'tarif' => $aData['tarif'],
- 'tickrate' => $aData['tickrate'],
- 'slots' => $aData['slots'],
- 'time' => $aData['time'],
- 'user' => $user['id']
- ),
- $tarif['discount'],
- $sum
- );
+ // Проверка промо-кода
+ $promo = games::define_promo(
+ $aData['promo'],
+ array(
+ 'tarif' => $aData['tarif'],
+ 'tickrate' => $aData['tickrate'],
+ 'slots' => $aData['slots'],
+ 'time' => $aData['time'],
+ 'user' => $user['id']
+ ),
+ $tarif['discount'],
+ $sum
+ );
- $days = $aData['time']; // Кол-во дней аренды
+ $days = $aData['time']; // Кол-во дней аренды
- // Использование промо-кода
- if(is_array($promo))
- {
- if(array_key_exists('sum', $promo))
- $sum = $promo['sum'];
- else
- $days += $promo['days']; // Кол-во дней аренды с учетом подарочных (промо-код)
- }
+ // Использование промо-кода
+ if(is_array($promo))
+ {
+ if(array_key_exists('sum', $promo))
+ $sum = $promo['sum'];
+ else
+ $days += $promo['days']; // Кол-во дней аренды с учетом подарочных (промо-код)
+ }
- // Проверка баланса
- if($user['balance'] < $sum)
- sys::outjs(array('e' => 'У вас не хватает '.(round($sum-$user['balance'], 2)).' '.$cfg['currency']));
+ // Проверка баланса
+ if($user['balance'] < $sum)
+ sys::outjs(array('e' => 'У вас не хватает '.(round($sum-$user['balance'], 2)).' '.$cfg['currency']));
- // Выделенный адрес игрового сервера
- if(!empty($tarif['ip']))
- {
- $aIp = explode(':', $tarif['ip']);
+ // Выделенный адрес игрового сервера
+ if(!empty($tarif['ip']))
+ {
+ $aIp = explode(':', $tarif['ip']);
- $ip = false;
- $port = params::$aDefPort['csgo'];
+ $ip = false;
+ $port = params::$aDefPort['csgo'];
- // Проверка наличия свободного адреса
- foreach($aIp as $adr)
- {
- $adr = trim($adr);
+ // Проверка наличия свободного адреса
+ foreach($aIp as $adr)
+ {
+ $adr = trim($adr);
- $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `address` LIKE "'.$adr.':%" LIMIT 1');
- if(!$sql->num())
- {
- $ip = $adr;
+ $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `address` LIKE "'.$adr.':%" LIMIT 1');
+ if(!$sql->num())
+ {
+ $ip = $adr;
- break;
- }
- }
- }else{
- $ip = sys::first(explode(':', $unit['address']));
- $port = false;
+ break;
+ }
+ }
+ }else{
+ $ip = sys::first(explode(':', $unit['address']));
+ $port = false;
- // Проверка наличия свободного порта
- for($tarif['port_min']; $tarif['port_min'] <= $tarif['port_max']; $tarif['port_min']+=1)
- {
- $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND (`address`="'.$ip.':'.$tarif['port_min'].'" OR `port`="'.$tarif['port_min'].'") LIMIT 1');
- if(!$sql->num())
- {
- $port = $tarif['port_min'];
+ // Проверка наличия свободного порта
+ for($tarif['port_min']; $tarif['port_min'] <= $tarif['port_max']; $tarif['port_min']+=1)
+ {
+ $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND (`address`="'.$ip.':'.$tarif['port_min'].'" OR `port`="'.$tarif['port_min'].'") LIMIT 1');
+ if(!$sql->num())
+ {
+ $port = $tarif['port_min'];
- break;
- }
- }
- }
+ break;
+ }
+ }
+ }
- if(!$ip || !$port)
- {
- $sql->query('UPDATE `tarifs` set `show`="0" WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
+ if(!$ip || !$port)
+ {
+ $sql->query('UPDATE `tarifs` set `show`="0" WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
- sys::outjs(array('e' => 'К сожалению нет доступных мест, обратитесь в тех.поддержку.'));
- }
+ sys::outjs(array('e' => 'К сожалению нет доступных мест, обратитесь в тех.поддержку.'));
+ }
- if($test)
- $aData['time'] = games::time($start_point, $tarif['test']);
- else
- $aData['time'] = games::time($start_point, $days);
+ if($test)
+ $aData['time'] = games::time($start_point, $tarif['test']);
+ else
+ $aData['time'] = games::time($start_point, $days);
- $fix_one = 0;
- $core = 0;
+ $fix_one = 0;
+ $core = 0;
- if($tarif['core_fix'] != '')
- {
- $aCore = explode(',', $tarif['core_fix']);
+ if($tarif['core_fix'] != '')
+ {
+ $aCore = explode(',', $tarif['core_fix']);
- foreach($aCore as $cpu)
- {
- $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `tarif`="'.$aData['tarif'].'" AND `core_fix`="'.$cpu.'" AND `core_fix_one`="1" LIMIT 1');
+ foreach($aCore as $cpu)
+ {
+ $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `tarif`="'.$aData['tarif'].'" AND `core_fix`="'.$cpu.'" AND `core_fix_one`="1" LIMIT 1');
- if($sql->num())
- continue;
+ if($sql->num())
+ continue;
- $fix_one = 1;
- $core = $cpu;
+ $fix_one = 1;
+ $core = $cpu;
- break;
- }
+ break;
+ }
- if(!$core)
- {
- $sql->query('UPDATE `tarifs` set `show`="0" WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
+ if(!$core)
+ {
+ $sql->query('UPDATE `tarifs` set `show`="0" WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
- sys::outjs(array('e' => 'К сожалению нет доступных мест, обратитесь в тех.поддержку.'));
- }
- }
+ sys::outjs(array('e' => 'К сожалению нет доступных мест, обратитесь в тех.поддержку.'));
+ }
+ }
- $ram = $tarif['param_fix'] ? $aData['ram'] : $cfg['ram']['csgo']*$aSDATA['slots'];
+ $ram = $tarif['param_fix'] ? $aData['ram'] : $cfg['ram']['csgo']*$aSDATA['slots'];
- // Массив данных
- $aSDATA = array(
- 'unit' => $aData['unit'], // идентификатор локации
- 'tarif' => $aData['tarif'], // идентификатор тарифа
- 'ram' => $ram, // значение ram
- 'param_fix' => $tarif['param_fix'], // фиксированные параметры
- 'tickrate' => $aData['tickrate'], // значение tickrate
- 'pack' => $aData['pack'], // Выбранная сборка для установки
- 'time' => $aData['time'], // Время аренды
- 'days' => $days, // Число дней
- 'sum' => $sum, // Сумма списания
- 'test' => $test, // тестовый период
- 'address' => $ip.':'.$port, // адрес игрового сервера
- 'port' => $port, // порт игрового сервера
- 'slots' => $aData['slots'], // Кол-во слот
- 'map' => $tarif['map'], // Фиксированное значение слот
- 'autostop' => $tarif['autostop'], // Выключение при 0 онлайне
- 'ftp' => $tarif['ftp'], // Использование ftp
- 'plugins' => $tarif['plugins'], // Использование плагинов
- 'console' => $tarif['console'], // Использование консоли
- 'stats' => $tarif['stats'], // Использование графиков (ведение статистики)
- 'copy' => $tarif['copy'], // Использование резервных копий
- 'web' => $tarif['web'], // Использование доп услуг
- 'plugins_install' => $tarif['plugins_install'], // Список установленных плагинов
- 'hdd' => $tarif['hdd'], // Дисковое пространство
- 'core_fix' => $core, // Выделенный поток
- 'core_fix_one' => $fix_one, // Выделенный поток
- 'promo' => $promo // Использование промо-кода
- );
+ // Массив данных
+ $aSDATA = array(
+ 'unit' => $aData['unit'], // идентификатор локации
+ 'tarif' => $aData['tarif'], // идентификатор тарифа
+ 'ram' => $ram, // значение ram
+ 'param_fix' => $tarif['param_fix'], // фиксированные параметры
+ 'tickrate' => $aData['tickrate'], // значение tickrate
+ 'pack' => $aData['pack'], // Выбранная сборка для установки
+ 'time' => $aData['time'], // Время аренды
+ 'days' => $days, // Число дней
+ 'sum' => $sum, // Сумма списания
+ 'test' => $test, // тестовый период
+ 'address' => $ip.':'.$port, // адрес игрового сервера
+ 'port' => $port, // порт игрового сервера
+ 'slots' => $aData['slots'], // Кол-во слот
+ 'map' => $tarif['map'], // Фиксированное значение слот
+ 'autostop' => $tarif['autostop'], // Выключение при 0 онлайне
+ 'ftp' => $tarif['ftp'], // Использование ftp
+ 'plugins' => $tarif['plugins'], // Использование плагинов
+ 'console' => $tarif['console'], // Использование консоли
+ 'stats' => $tarif['stats'], // Использование графиков (ведение статистики)
+ 'copy' => $tarif['copy'], // Использование резервных копий
+ 'web' => $tarif['web'], // Использование доп услуг
+ 'plugins_install' => $tarif['plugins_install'], // Список установленных плагинов
+ 'hdd' => $tarif['hdd'], // Дисковое пространство
+ 'core_fix' => $core, // Выделенный поток
+ 'core_fix_one' => $fix_one, // Выделенный поток
+ 'promo' => $promo // Использование промо-кода
+ );
- return $aSDATA;
- }
+ return $aSDATA;
+ }
- public static function install($aSDATA = array())
- {
- global $cfg, $sql, $user, $start_point;
+ public static function install($aSDATA = array())
+ {
+ global $cfg, $sql, $user, $start_point;
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- // Массив данных локации (адрес,пароль)
- $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$aSDATA['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ // Массив данных локации (адрес,пароль)
+ $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$aSDATA['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- // Проверка ssh соединения с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- sys::outjs(array('e' => sys::text('error', 'ssh')));
+ // Проверка ssh соединения с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ sys::outjs(array('e' => sys::text('error', 'ssh')));
- // Массив данных тарифа (путь сборки,путь установки)
- $sql->query('SELECT `path`, `install`, `hostname` FROM `tarifs` WHERE `id`="'.$aSDATA['tarif'].'" LIMIT 1');
- $tarif = $sql->get();
+ // Массив данных тарифа (путь сборки,путь установки)
+ $sql->query('SELECT `path`, `install`, `hostname` FROM `tarifs` WHERE `id`="'.$aSDATA['tarif'].'" LIMIT 1');
+ $tarif = $sql->get();
- // Получение идентификаторов игрового сервера
- $sql->query('INSERT INTO `servers` set uid="1"');
- $id = $sql->id();
- $uid = $id+1000;
+ // Получение идентификаторов игрового сервера
+ $sql->query('INSERT INTO `servers` set uid="1"');
+ $id = $sql->id();
+ $uid = $id+1000;
- // Директория сборки
- $path = $tarif['path'].$aSDATA['pack'];
+ // Директория сборки
+ $path = $tarif['path'].$aSDATA['pack'];
- // Директория игрового сервера
- $install = $tarif['install'].$uid;
+ // Директория игрового сервера
+ $install = $tarif['install'].$uid;
- $ssh->set('mkdir '.$install.';' // Создание директории
- .'useradd -s /bin/false -d '.$install.' -g servers -u '.$uid.' server'.$uid.';' // Создание пользователя сервера на локации
- .'chown server'.$uid.':1000 '.$install.';' // Изменение владельца и группы директории
- .'cd '.$install.' && sudo -u server'.$uid.' screen -dmS i_'.$uid.' sh -c "cp -r '.$path.'/. .;' // Копирование файлов сборки для сервера
- .'find . -type d -exec chmod 700 {} \;;'
- .'find . -type f -exec chmod 600 {} \;;'
- .'chmod 500 '.params::$aFileGame['csgo'].'"');
+ $ssh->set('mkdir '.$install.';' // Создание директории
+ .'useradd -s /bin/false -d '.$install.' -g servers -u '.$uid.' server'.$uid.';' // Создание пользователя сервера на локации
+ .'chown server'.$uid.':1000 '.$install.';' // Изменение владельца и группы директории
+ .'cd '.$install.' && sudo -u server'.$uid.' screen -dmS i_'.$uid.' sh -c "cp -r '.$path.'/. .;' // Копирование файлов сборки для сервера
+ .'find . -type d -exec chmod 700 {} \;;'
+ .'find . -type f -exec chmod 600 {} \;;'
+ .'chmod 500 '.params::$aFileGame['csgo'].'"');
- // Запись данных нового сервера
- $sql->query('UPDATE `servers` set
- `uid`="'.$uid.'",
- `unit`="'.$aSDATA['unit'].'",
- `tarif`="'.$aSDATA['tarif'].'",
- `user`="'.$user['id'].'",
- `address`="'.$aSDATA['address'].'",
- `port`="'.$aSDATA['port'].'",
- `game`="csgo",
- `slots`="'.$aSDATA['slots'].'",
- `slots_start`="'.$aSDATA['slots'].'",
- `status`="install",
- `name`="'.$tarif['hostname'].'",
- `pack`="'.$aSDATA['pack'].'",
- `plugins_use`="'.$aSDATA['plugins'].'",
- `ftp_use`="'.$aSDATA['ftp'].'",
- `console_use`="'.$aSDATA['console'].'",
- `stats_use`="'.$aSDATA['stats'].'",
- `copy_use`="'.$aSDATA['copy'].'",
- `web_use`="'.$aSDATA['web'].'",
- `tickrate`="'.$aSDATA['tickrate'].'",
- `map_start`="'.$aSDATA['map'].'",
- `vac`="1",
- `hdd`="'.$aSDATA['hdd'].'",
- `time`="'.$aSDATA['time'].'",
- `date`="'.$start_point.'",
- `test`="'.$aSDATA['test'].'",
- `ram`="'.$aSDATA['ram'].'",
- `core_fix`="'.$aSDATA['core_fix'].'",
- `core_fix_one`="'.$aSDATA['core_fix_one'].'",
- `autostop`="'.$aSDATA['autostop'].'" WHERE `id`="'.$id.'" LIMIT 1');
+ // Запись данных нового сервера
+ $sql->query('UPDATE `servers` set
+ `uid`="'.$uid.'",
+ `unit`="'.$aSDATA['unit'].'",
+ `tarif`="'.$aSDATA['tarif'].'",
+ `user`="'.$user['id'].'",
+ `address`="'.$aSDATA['address'].'",
+ `port`="'.$aSDATA['port'].'",
+ `game`="csgo",
+ `slots`="'.$aSDATA['slots'].'",
+ `slots_start`="'.$aSDATA['slots'].'",
+ `status`="install",
+ `name`="'.$tarif['hostname'].'",
+ `pack`="'.$aSDATA['pack'].'",
+ `plugins_use`="'.$aSDATA['plugins'].'",
+ `ftp_use`="'.$aSDATA['ftp'].'",
+ `console_use`="'.$aSDATA['console'].'",
+ `stats_use`="'.$aSDATA['stats'].'",
+ `copy_use`="'.$aSDATA['copy'].'",
+ `web_use`="'.$aSDATA['web'].'",
+ `tickrate`="'.$aSDATA['tickrate'].'",
+ `map_start`="'.$aSDATA['map'].'",
+ `vac`="1",
+ `hdd`="'.$aSDATA['hdd'].'",
+ `time`="'.$aSDATA['time'].'",
+ `date`="'.$start_point.'",
+ `test`="'.$aSDATA['test'].'",
+ `ram`="'.$aSDATA['ram'].'",
+ `core_fix`="'.$aSDATA['core_fix'].'",
+ `core_fix_one`="'.$aSDATA['core_fix_one'].'",
+ `autostop`="'.$aSDATA['autostop'].'" WHERE `id`="'.$id.'" LIMIT 1');
- // Запись установленных плагинов
- if($aSDATA['plugins'])
- {
- // Массив идентификаторов плагинов
- $aPlugins = sys::b64djs($aSDATA['plugins_install']);
+ // Запись установленных плагинов
+ if($aSDATA['plugins'])
+ {
+ // Массив идентификаторов плагинов
+ $aPlugins = sys::b64djs($aSDATA['plugins_install']);
- if(isset($aPlugins[$aSDATA['pack']]))
- {
- $plugins = explode(',', $aPlugins[$aSDATA['pack']]);
+ if(isset($aPlugins[$aSDATA['pack']]))
+ {
+ $plugins = explode(',', $aPlugins[$aSDATA['pack']]);
- foreach($plugins as $plugin)
- if($plugin)
- $sql->query('INSERT INTO `plugins_install` set `server`="'.$id.'", `plugin`="'.$plugin.'", `time`="'.$start_point.'"');
- }
- }
+ foreach($plugins as $plugin)
+ if($plugin)
+ $sql->query('INSERT INTO `plugins_install` set `server`="'.$id.'", `plugin`="'.$plugin.'", `time`="'.$start_point.'"');
+ }
+ }
- // Списание средств с баланса пользователя
- $sql->query('UPDATE `users` set `balance`="'.($user['balance']-$aSDATA['sum']).'" WHERE `id`="'.$user['id'].'" LIMIT 1');
+ // Списание средств с баланса пользователя
+ $sql->query('UPDATE `users` set `balance`="'.($user['balance']-$aSDATA['sum']).'" WHERE `id`="'.$user['id'].'" LIMIT 1');
- // Запись получения тестового периода
- if($aSDATA['test'])
- {
- $sql->query('INSERT INTO `tests` set `server`="'.$id.'", `unit`="'.$aSDATA['unit'].'", `game`="csgo", `user`="'.$user['id'].'", `time`="'.$start_point.'"');
- $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server_test'), array('id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="0"');
- }else{
- // Реф. система
- games::part($user['id'], $aSDATA['sum']);
+ // Запись получения тестового периода
+ if($aSDATA['test'])
+ {
+ $sql->query('INSERT INTO `tests` set `server`="'.$id.'", `unit`="'.$aSDATA['unit'].'", `game`="csgo", `user`="'.$user['id'].'", `time`="'.$start_point.'"');
+ $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server_test'), array('id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="0"');
+ }else{
+ // Реф. система
+ games::part($user['id'], $aSDATA['sum']);
- // Запись логов
- if(!is_array($aSDATA['promo']))
- $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server'), array('days' => games::parse_day($aSDATA['days'], true), 'money' => $aSDATA['sum'], 'id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="'.$aSDATA['sum'].'"');
- else{
- $sql->query('UPDATE `servers` set `benefit`="'.$aSDATA['time'].'" WHERE `id`="'.$id.'" LIMIT 1');
- $sql->query('INSERT INTO `promo_use` set `promo`="'.$aSDATA['promo']['id'].'", `user`="'.$user['id'].'", `time`="'.$start_point.'"');
- $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server_promo'), array('days' => games::parse_day($aSDATA['days'], true), 'money' => $aSDATA['sum'], 'promo' => $aSDATA['promo']['cod'], 'id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="'.$aSDATA['sum'].'"');
- }
- }
+ // Запись логов
+ if(!is_array($aSDATA['promo']))
+ $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server'), array('days' => games::parse_day($aSDATA['days'], true), 'money' => $aSDATA['sum'], 'id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="'.$aSDATA['sum'].'"');
+ else{
+ $sql->query('UPDATE `servers` set `benefit`="'.$aSDATA['time'].'" WHERE `id`="'.$id.'" LIMIT 1');
+ $sql->query('INSERT INTO `promo_use` set `promo`="'.$aSDATA['promo']['id'].'", `user`="'.$user['id'].'", `time`="'.$start_point.'"');
+ $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server_promo'), array('days' => games::parse_day($aSDATA['days'], true), 'money' => $aSDATA['sum'], 'promo' => $aSDATA['promo']['cod'], 'id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="'.$aSDATA['sum'].'"');
+ }
+ }
- return $id;
- }
+ return $id;
+ }
}
?>
\ No newline at end of file
diff --git a/system/library/games/csgo/tarif.php b/system/library/games/csgo/tarif.php
index 0aba2f5..5dffa48 100644
--- a/system/library/games/csgo/tarif.php
+++ b/system/library/games/csgo/tarif.php
@@ -1,225 +1,225 @@
get('extend', 'sections/servers/games/tarif');
+ $html->get('extend', 'sections/servers/games/tarif');
- if(isset($html->arr['extend_address']))
- {
- $html->unit('extend_address', 1);
- $html->set('extend_address', $html->arr['extend_address']);
- }else
- $html->unit('extend_address');
+ if(isset($html->arr['extend_address']))
+ {
+ $html->unit('extend_address', 1);
+ $html->set('extend_address', $html->arr['extend_address']);
+ }else
+ $html->unit('extend_address');
- $html->set('id', $sid);
- $html->set('time', sys::date('min', $server['time']));
- $html->set('options', 'Выберете период продления '.$options);
- $html->set('slots', $server['slots']);
- $html->set('info', $server['tickrate'].' TickRate');
- $html->set('tarif', $tarif_name);
- $html->set('cur', $cfg['currency']);
+ $html->set('id', $sid);
+ $html->set('time', sys::date('min', $server['time']));
+ $html->set('options', 'Выберете период продления '.$options);
+ $html->set('slots', $server['slots']);
+ $html->set('info', $server['tickrate'].' TickRate');
+ $html->set('tarif', $tarif_name);
+ $html->set('cur', $cfg['currency']);
- $html->pack('main');
+ $html->pack('main');
- return NULL;
- }
+ return NULL;
+ }
public static function extend_sp($server, $tarif, $sid)
{
- global $cfg, $sql, $html, $start_point;
+ global $cfg, $sql, $html, $start_point;
- tarifs::extend_address($server['game'], $sid);
+ tarifs::extend_address($server['game'], $sid);
- $aPrice = explode(':', $tarif['price']);
- $aTICK = explode(':', $tarif['tickrate']);
+ $aPrice = explode(':', $tarif['price']);
+ $aTICK = explode(':', $tarif['tickrate']);
- $sum = $tarif['slots'] ? $aPrice[array_search($server['tickrate'], $aTICK)] : $aPrice[array_search($server['tickrate'], $aTICK)]*$server['slots'];
+ $sum = $tarif['slots'] ? $aPrice[array_search($server['tickrate'], $aTICK)] : $aPrice[array_search($server['tickrate'], $aTICK)]*$server['slots'];
- $html->get('extend_sp', 'sections/servers/games/tarif');
+ $html->get('extend_sp', 'sections/servers/games/tarif');
- if(isset($html->arr['extend_address']))
- {
- $html->unit('extend_address', 1);
- $html->set('extend_address', $html->arr['extend_address']);
- }else
- $html->unit('extend_address');
+ if(isset($html->arr['extend_address']))
+ {
+ $html->unit('extend_address', 1);
+ $html->set('extend_address', $html->arr['extend_address']);
+ }else
+ $html->unit('extend_address');
- $html->set('id', $sid);
- $html->set('time', sys::date('min', $server['time']));
- $html->set('date', $server['time'] > $start_point ? 'Сервер продлен до: '.date('d.m.Y', $server['time']) : 'Текущая дата: '.date('d.m.Y', $start_point));
- $html->set('options', 'Выберете период продления '.$options);
- $html->set('slots', $server['slots']);
- $html->set('info', $server['tickrate'].' TickRate');
- $html->set('tarif', $tarif['name']);
- $html->set('sum', $sum);
- $html->set('cur', $cfg['currency']);
+ $html->set('id', $sid);
+ $html->set('time', sys::date('min', $server['time']));
+ $html->set('date', $server['time'] > $start_point ? 'Сервер продлен до: '.date('d.m.Y', $server['time']) : 'Текущая дата: '.date('d.m.Y', $start_point));
+ $html->set('options', 'Выберете период продления '.$options);
+ $html->set('slots', $server['slots']);
+ $html->set('info', $server['tickrate'].' TickRate');
+ $html->set('tarif', $tarif['name']);
+ $html->set('sum', $sum);
+ $html->set('cur', $cfg['currency']);
- $html->pack('main');
+ $html->pack('main');
- return NULL;
- }
+ return NULL;
+ }
public static function plan($server, $tarif_name, $sid)
{
- global $cfg, $sql, $html;
+ global $cfg, $sql, $html;
- $sql->query('SELECT `tickrate`, `price` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
+ $sql->query('SELECT `tickrate`, `price` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
- if(!$sql->num())
- return NULL;
+ if(!$sql->num())
+ return NULL;
- $tarif = $sql->get();
+ $tarif = $sql->get();
- $options = 'Выберете тарифный план ';
+ $options = 'Выберете тарифный план ';
- $aPrice = explode(':', $tarif['price']);
- $aTick = explode(':', $tarif['tickrate']);
+ $aPrice = explode(':', $tarif['price']);
+ $aTick = explode(':', $tarif['tickrate']);
- // Если есть выбор
- if(count($aTick) > 1)
- {
- // Удалить при наличии tickrate сервера из выбора
- if(in_array($server['tickrate'], $aTick))
- unset($aTick[array_search($server['tickrate'], $aTick)]);
+ // Если есть выбор
+ if(count($aTick) > 1)
+ {
+ // Удалить при наличии tickrate сервера из выбора
+ if(in_array($server['tickrate'], $aTick))
+ unset($aTick[array_search($server['tickrate'], $aTick)]);
- foreach($aTick as $index => $tickrate)
- $options .= ''
- .$tickrate.' TickRate '
- .'('.$aPrice[$index].' '.$cfg['currency'].'/слот | '
- .($aPrice[$index]*$server['slots']).' '.$cfg['currency'].'/месяц)'
- .' ';
- }else
- return NULL;
+ foreach($aTick as $index => $tickrate)
+ $options .= ''
+ .$tickrate.' TickRate '
+ .'('.$aPrice[$index].' '.$cfg['currency'].'/слот | '
+ .($aPrice[$index]*$server['slots']).' '.$cfg['currency'].'/месяц)'
+ .' ';
+ }else
+ return NULL;
- $html->get('plan', 'sections/servers/games/tarif');
+ $html->get('plan', 'sections/servers/games/tarif');
- $html->set('id', $sid);
- $html->set('options', $options);
- $html->set('info', $server['tickrate'].' TickRate');
- $html->set('tarif', $tarif_name);
+ $html->set('id', $sid);
+ $html->set('options', $options);
+ $html->set('info', $server['tickrate'].' TickRate');
+ $html->set('tarif', $tarif_name);
- $html->pack('main');
+ $html->pack('main');
- return NULL;
- }
+ return NULL;
+ }
- public static function unit($server, $unit_name, $tarif_name, $sid)
+ public static function unit($server, $unit_name, $tarif_name, $sid)
{
- global $cfg, $sql, $html;
+ global $cfg, $sql, $html;
- if(!$cfg['change_unit'][$server['game']])
- return NULL;
+ if(!$cfg['change_unit'][$server['game']])
+ return NULL;
- $tarifs = $sql->query('SELECT `unit`, `tickrate` FROM `tarifs` WHERE `game`="'.$server['game'].'" AND `name`="'.$tarif_name.'" AND `id`!="'.$server['tarif'].'" AND `show`="1" ORDER BY `unit`');
- if(!$sql->num($tarifs))
- return NULL;
+ $tarifs = $sql->query('SELECT `unit`, `tickrate` FROM `tarifs` WHERE `game`="'.$server['game'].'" AND `name`="'.$tarif_name.'" AND `id`!="'.$server['tarif'].'" AND `show`="1" ORDER BY `unit`');
+ if(!$sql->num($tarifs))
+ return NULL;
- $units = 0;
+ $units = 0;
- $options = 'Выберете новую локацию ';
+ $options = 'Выберете новую локацию ';
- while($tarif = $sql->get($tarifs))
- {
- if(!in_array($server['tickrate'], explode(':', $tarif['tickrate'])))
- continue;
+ while($tarif = $sql->get($tarifs))
+ {
+ if(!in_array($server['tickrate'], explode(':', $tarif['tickrate'])))
+ continue;
- $sql->query('SELECT `id`, `name` FROM `units` WHERE `id`="'.$tarif['unit'].'" AND `show`="1" LIMIT 1');
- if(!$sql->num())
- continue;
+ $sql->query('SELECT `id`, `name` FROM `units` WHERE `id`="'.$tarif['unit'].'" AND `show`="1" LIMIT 1');
+ if(!$sql->num())
+ continue;
- $unit = $sql->get();
+ $unit = $sql->get();
- $options .= ''.$unit['name'].' ';
+ $options .= ''.$unit['name'].' ';
- $units+=1;
- }
+ $units+=1;
+ }
- if(!$units)
- return NULL;
+ if(!$units)
+ return NULL;
- $html->get('unit', 'sections/servers/games/tarif');
+ $html->get('unit', 'sections/servers/games/tarif');
- $html->set('id', $sid);
- $html->set('options', $options);
- $html->set('slots', $server['slots']);
- $html->set('info', $server['tickrate'].' TickRate');
- $html->set('unit', $unit_name);
- $html->set('tarif', $tarif_name);
+ $html->set('id', $sid);
+ $html->set('options', $options);
+ $html->set('slots', $server['slots']);
+ $html->set('info', $server['tickrate'].' TickRate');
+ $html->set('unit', $unit_name);
+ $html->set('tarif', $tarif_name);
- $html->pack('main');
+ $html->pack('main');
- return NULL;
- }
+ return NULL;
+ }
- public static function unit_new($tarif, $unit, $server, $mcache)
- {
- global $ssh, $sql, $user, $start_point;
+ public static function unit_new($tarif, $unit, $server, $mcache)
+ {
+ global $ssh, $sql, $user, $start_point;
- // Проверка ssh соединения с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- sys::outjs(array('e' => sys::text('error', 'ssh')));
+ // Проверка ssh соединения с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ sys::outjs(array('e' => sys::text('error', 'ssh')));
- // Директория сборки
- $path = $tarif['path'].$tarif['pack'];
+ // Директория сборки
+ $path = $tarif['path'].$tarif['pack'];
- // Директория игрового сервера
- $install = $tarif['install'].$server['uid'];
+ // Директория игрового сервера
+ $install = $tarif['install'].$server['uid'];
- // Пользователь сервера
- $uS = 'server'.$server['uid'];
+ // Пользователь сервера
+ $uS = 'server'.$server['uid'];
- $ssh->set('mkdir '.$install.';' // Создание директории
- .'useradd -d '.$install.' -g servers -u '.$server['uid'].' '.$uS.';' // Создание пользователя сервера на локации
- .'chown '.$uS.':1000 '.$install.';' // Изменение владельца и группы директории
- .'cd '.$install.' && sudo -u '.$uS.' screen -dmS i_'.$server['uid'].' cp -r '.$path.'/. .'); // Копирование файлов сборки для сервера
+ $ssh->set('mkdir '.$install.';' // Создание директории
+ .'useradd -d '.$install.' -g servers -u '.$server['uid'].' '.$uS.';' // Создание пользователя сервера на локации
+ .'chown '.$uS.':1000 '.$install.';' // Изменение владельца и группы директории
+ .'cd '.$install.' && sudo -u '.$uS.' screen -dmS i_'.$server['uid'].' cp -r '.$path.'/. .'); // Копирование файлов сборки для сервера
- $address = explode(':', $server['address']);
+ $address = explode(':', $server['address']);
- $fix_one = $tarif['core_fix'] ? 1 : 0;
+ $fix_one = $tarif['core_fix'] ? 1 : 0;
- // Обновление данных нового сервера
- $sql->query('UPDATE `servers` set
- `unit`="'.$tarif['unit'].'",
- `tarif`="'.$tarif['id'].'",
- `address`="'.$server['address'].'",
- `port`="'.$address[1].'",
- `status`="install",
- `name`="'.$tarif['hostname'].'",
- `pack`="'.$tarif['pack'].'",
- `map_start`="'.$tarif['map'].'",
- `vac`="1",
- `hdd`="'.$tarif['hdd'].'",
- `time`="'.$tarif['time'].'",
- `autostop`="'.$tarif['autostop'].'",
- `core_fix`="'.$tarif['core_fix'].'",
- `core_fix_one`="'.$fix_one.'",
- `reinstall`="'.$start_point.'" WHERE `id`="'.$server['id'].'" LIMIT 1');
+ // Обновление данных нового сервера
+ $sql->query('UPDATE `servers` set
+ `unit`="'.$tarif['unit'].'",
+ `tarif`="'.$tarif['id'].'",
+ `address`="'.$server['address'].'",
+ `port`="'.$address[1].'",
+ `status`="install",
+ `name`="'.$tarif['hostname'].'",
+ `pack`="'.$tarif['pack'].'",
+ `map_start`="'.$tarif['map'].'",
+ `vac`="1",
+ `hdd`="'.$tarif['hdd'].'",
+ `time`="'.$tarif['time'].'",
+ `autostop`="'.$tarif['autostop'].'",
+ `core_fix`="'.$tarif['core_fix'].'",
+ `core_fix_one`="'.$fix_one.'",
+ `reinstall`="'.$start_point.'" WHERE `id`="'.$server['id'].'" LIMIT 1');
- // Запись установленных плагинов
- if($tarif['plugins'])
- {
- // Массив идентификаторов плагинов
- $aPlugins = sys::b64js($tarif['plugins_install']);
+ // Запись установленных плагинов
+ if($tarif['plugins'])
+ {
+ // Массив идентификаторов плагинов
+ $aPlugins = sys::b64js($tarif['plugins_install']);
- if(isset($aPlugins[$tarif['pack']]))
- {
- $plugins = explode(',', $aPlugins[$tarif['pack']]);
+ if(isset($aPlugins[$tarif['pack']]))
+ {
+ $plugins = explode(',', $aPlugins[$tarif['pack']]);
- foreach($plugins as $plugin)
- if($plugin)
- $sql->query('INSERT INTO `plugins_install` set `server`="'.$server['id'].'", `plugin`="'.$plugin.'", `time`="'.$start_point.'"');
- }
- }
+ foreach($plugins as $plugin)
+ if($plugin)
+ $sql->query('INSERT INTO `plugins_install` set `server`="'.$server['id'].'", `plugin`="'.$plugin.'", `time`="'.$start_point.'"');
+ }
+ }
- return NULL;
- }
+ return NULL;
+ }
}
?>
\ No newline at end of file
diff --git a/system/library/games/css/action.php b/system/library/games/css/action.php
index 334800b..f01075f 100644
--- a/system/library/games/css/action.php
+++ b/system/library/games/css/action.php
@@ -1,189 +1,189 @@
query('SELECT `uid`, `unit`, `tarif`, `game`, `address`, `slots_start`, `name`, `tickrate`, `map_start`, `vac`, `time_start`, `core_fix` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `uid`, `unit`, `tarif`, `game`, `address`, `slots_start`, `name`, `tickrate`, `map_start`, `vac`, `time_start`, `core_fix` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
+ $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
$tarif = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
-
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return array('e' => sys::text('error', 'ssh'));
-
- list($ip, $port) = explode(':', $server['address']);
-
- // Убить процессы
- $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
- .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
-
- $taskset = '';
-
- // Если включена система автораспределения и не установлен фиксированный поток
- if($cfg['cpu_route'] AND !$server['core_fix'])
- {
- $proc_stat = array();
-
- $proc_stat[0] = $ssh->get('cat /proc/stat');
- }
-
- // Проверка наличия стартовой карты
- $ssh->set('cd '.$tarif['install'].$server['uid'].'/cstrike/maps/ && ls | grep .bsp | grep -v .bsp.');
-
- if($server['map_start'] != '' AND !in_array($server['map_start'], str_replace('.bsp', '', explode("\n", $ssh->get()))))
- return array('e' => sys::updtext(sys::text('servers', 'nomap'), array('map' => $server['map_start'].'.bsp')));
-
- // Если система автораспределения продолжить парсинг загрузки процессора
- if(isset($proc_stat))
- {
- $proc_stat[1] = $ssh->get('cat /proc/stat');
-
- // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
- $core = sys::cpu_idle($proc_stat, $server['unit'], false); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
-
- if(!is_numeric($core))
- return array('e' => sys::text('error', 'cpu'));
-
- $taskset = 'taskset -c '.$core;
- }
-
- if($server['core_fix'])
- {
- $core = $server['core_fix']-1;
- $taskset = 'taskset -c '.$core;
- }
-
- // Античит VAC
- $vac = $server['vac'] == 0 ? '-insecure' : '-secure';
-
- // Боты
- $bots = $cfg['bots'][$server['game']] ? '' : '-nobots';
-
- // TV
- $tv = $server['tv'] ? '+tv_enable 1 +tv_maxclients 30 +tv_port '.($port+10000) : '-nohltv';
-
- // Параметры запуска
- $bash = './srcds_run -debug -game cstrike -norestart -condebug console.log -tickrate '.$server['tickrate'].' +servercfgfile server.cfg +map \''.$server['map_start'].'\' +maxplayers '.$server['slots_start'].' +ip '.$ip.' +port '.$port.' -sv_lan 0 '.$vac.' '.$bots.' '.$tv;
-
- // Временный файл
- $temp = sys::temp($bash);
-
- // Обновление файла start.sh
- $ssh->setfile($temp, $tarif['install'].$server['uid'].'/start.sh', 0500);
-
- // Строка запуска
- $ssh->set('cd '.$tarif['install'].$server['uid'].';' // переход в директорию игрового сервера
- .'rm *.pid;' // Удаление *.pid файлов
- .'sudo -u server'.$server['uid'].' mkdir -p cstrike/oldstart;' // Создание папки логов
- .'cat cstrike/console.log >> cstrike/oldstart/'.date('d.m.Y_H:i:s', $server['time_start']).'.log; rm cstrike/console.log; rm cstrike/oldstart/01.01.1970_03:00:00.log;' // Перемещение лога предыдущего запуска
- .'chown server'.$server['uid'].':1000 start.sh;' // Обновление владельца файла start.sh
- .'sudo -u server'.$server['uid'].' screen -dmS s_'.$server['uid'].' '.$taskset.' sh -c "./start.sh"'); // Запуск игровго сервера
-
- $core = !isset($core) ? 0 : $core+1;
-
- // Обновление информации в базе
- $sql->query('UPDATE `servers` set `status`="'.$type.'", `online`="0", `players`="", `core_use`="'.$core.'", `time_start`="'.$start_point.'", `stop`="1" WHERE `id`="'.$id.'" LIMIT 1');
-
- unlink($temp);
-
- // Сброс кеша
- actions::clmcache($id);
-
- sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0, 'players' => ''));
- sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0));
-
- return array('s' => 'ok');
- }
-
- public static function update($id)
- {
- global $cfg, $sql, $user, $start_point;
-
- include(LIB.'ssh.php');
-
- $sql->query('SELECT `uid`, `unit`, `tarif`, `game`, `name`, `ftp`, `update`, `core_fix` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
-
- // Проверка времени обновления
- $update = $server['update']+$cfg['update'][$server['game']]*60;
-
- if($update > $start_point AND $user['group'] != 'admin')
- return array('e' => sys::updtext(sys::text('servers', 'update'), array('time' => sys::date('max', $update))));
-
- $sql->query('SELECT `address`, `passwd`, `sql_login`, `sql_passwd`, `sql_port`, `sql_ftp` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
$unit = $sql->get();
- $sql->query('SELECT `install`, `plugins_install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
- $tarif = $sql->get();
-
- // Проверка ssh соедниения пу с локацией
+ // Проверка ssh соедниения пу с локацией
if(!$ssh->auth($unit['passwd'], $unit['address']))
return array('e' => sys::text('error', 'ssh'));
- $taskset = '';
+ list($ip, $port) = explode(':', $server['address']);
- // Если включена система автораспределения и не установлен фиксированный поток
- if($cfg['cpu_route'] AND !$server['core_fix'])
- {
- $proc_stat = array();
+ // Убить процессы
+ $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
+ .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
- $proc_stat[0] = $ssh->get('cat /proc/stat');
- }
+ $taskset = '';
- // Директория игрового сервера
- $install = $tarif['install'].$server['uid'];
+ // Если включена система автораспределения и не установлен фиксированный поток
+ if($cfg['cpu_route'] AND !$server['core_fix'])
+ {
+ $proc_stat = array();
- // Если система автораспределения продолжить парсинг загрузки процессора
- if(isset($proc_stat))
- {
- $proc_stat[1] = $ssh->get('cat /proc/stat');
+ $proc_stat[0] = $ssh->get('cat /proc/stat');
+ }
- // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
- $core = sys::cpu_idle($proc_stat, $server['unit'], false); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
+ // Проверка наличия стартовой карты
+ $ssh->set('cd '.$tarif['install'].$server['uid'].'/cstrike/maps/ && ls | grep .bsp | grep -v .bsp.');
- if(!is_numeric($core))
- return array('e' => 'Не удается выполнить операцию, нет свободного потока.');
+ if($server['map_start'] != '' AND !in_array($server['map_start'], str_replace('.bsp', '', explode("\n", $ssh->get()))))
+ return array('e' => sys::updtext(sys::text('servers', 'nomap'), array('map' => $server['map_start'].'.bsp')));
- $taskset = 'taskset -c '.$core;
- }
+ // Если система автораспределения продолжить парсинг загрузки процессора
+ if(isset($proc_stat))
+ {
+ $proc_stat[1] = $ssh->get('cat /proc/stat');
- if($server['core_fix'])
- {
- $core = $server['core_fix']-1;
- $taskset = 'taskset -c '.$core;
- }
+ // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
+ $core = sys::cpu_idle($proc_stat, $server['unit'], false); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
- $ssh->set('cd '.$cfg['steamcmd'].' && sudo -u server'.$server['uid'].' '.$taskset.' sh -c "screen -dmS u_'.$server['uid'].' ./steamcmd.sh +login anonymous +force_install_dir "'.$install.'" +app_update 232330 +quit"');
+ if(!is_numeric($core))
+ return array('e' => sys::text('error', 'cpu'));
- $core = !isset($core) ? 0 : $core+1;
+ $taskset = 'taskset -c '.$core;
+ }
- // Обновление информации в базе
- $sql->query('UPDATE `servers` set `status`="update", `update`="'.$start_point.'", `core_use`="'.$core.'" WHERE `id`="'.$id.'" LIMIT 1');
+ if($server['core_fix'])
+ {
+ $core = $server['core_fix']-1;
+ $taskset = 'taskset -c '.$core;
+ }
- // Логирование
- $sql->query('INSERT INTO `logs_sys` set `user`="'.$user['id'].'", `server`="'.$id.'", `text`="'.sys::text('syslogs', 'update').'", `time`="'.$start_point.'"');
+ // Античит VAC
+ $vac = $server['vac'] == 0 ? '-insecure' : '-secure';
- // Сброс кеша
- actions::clmcache($id);
+ // Боты
+ $bots = $cfg['bots'][$server['game']] ? '' : '-nobots';
- sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'update', 'online' => 0, 'players' => ''));
- sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'update', 'online' => 0));
+ // TV
+ $tv = $server['tv'] ? '+tv_enable 1 +tv_maxclients 30 +tv_port '.($port+10000) : '-nohltv';
- return array('s' => 'ok');
- }
+ // Параметры запуска
+ $bash = './srcds_run -debug -game cstrike -norestart -condebug console.log -tickrate '.$server['tickrate'].' +servercfgfile server.cfg +map \''.$server['map_start'].'\' +maxplayers '.$server['slots_start'].' +ip '.$ip.' +port '.$port.' -sv_lan 0 '.$vac.' '.$bots.' '.$tv;
+
+ // Временный файл
+ $temp = sys::temp($bash);
+
+ // Обновление файла start.sh
+ $ssh->setfile($temp, $tarif['install'].$server['uid'].'/start.sh', 0500);
+
+ // Строка запуска
+ $ssh->set('cd '.$tarif['install'].$server['uid'].';' // переход в директорию игрового сервера
+ .'rm *.pid;' // Удаление *.pid файлов
+ .'sudo -u server'.$server['uid'].' mkdir -p cstrike/oldstart;' // Создание папки логов
+ .'cat cstrike/console.log >> cstrike/oldstart/'.date('d.m.Y_H:i:s', $server['time_start']).'.log; rm cstrike/console.log; rm cstrike/oldstart/01.01.1970_03:00:00.log;' // Перемещение лога предыдущего запуска
+ .'chown server'.$server['uid'].':1000 start.sh;' // Обновление владельца файла start.sh
+ .'sudo -u server'.$server['uid'].' screen -dmS s_'.$server['uid'].' '.$taskset.' sh -c "./start.sh"'); // Запуск игровго сервера
+
+ $core = !isset($core) ? 0 : $core+1;
+
+ // Обновление информации в базе
+ $sql->query('UPDATE `servers` set `status`="'.$type.'", `online`="0", `players`="", `core_use`="'.$core.'", `time_start`="'.$start_point.'", `stop`="1" WHERE `id`="'.$id.'" LIMIT 1');
+
+ unlink($temp);
+
+ // Сброс кеша
+ actions::clmcache($id);
+
+ sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0, 'players' => ''));
+ sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0));
+
+ return array('s' => 'ok');
+ }
+
+ public static function update($id)
+ {
+ global $cfg, $sql, $user, $start_point;
+
+ include(LIB.'ssh.php');
+
+ $sql->query('SELECT `uid`, `unit`, `tarif`, `game`, `name`, `ftp`, `update`, `core_fix` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
+
+ // Проверка времени обновления
+ $update = $server['update']+$cfg['update'][$server['game']]*60;
+
+ if($update > $start_point AND $user['group'] != 'admin')
+ return array('e' => sys::updtext(sys::text('servers', 'update'), array('time' => sys::date('max', $update))));
+
+ $sql->query('SELECT `address`, `passwd`, `sql_login`, `sql_passwd`, `sql_port`, `sql_ftp` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
+
+ $sql->query('SELECT `install`, `plugins_install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
+ $tarif = $sql->get();
+
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return array('e' => sys::text('error', 'ssh'));
+
+ $taskset = '';
+
+ // Если включена система автораспределения и не установлен фиксированный поток
+ if($cfg['cpu_route'] AND !$server['core_fix'])
+ {
+ $proc_stat = array();
+
+ $proc_stat[0] = $ssh->get('cat /proc/stat');
+ }
+
+ // Директория игрового сервера
+ $install = $tarif['install'].$server['uid'];
+
+ // Если система автораспределения продолжить парсинг загрузки процессора
+ if(isset($proc_stat))
+ {
+ $proc_stat[1] = $ssh->get('cat /proc/stat');
+
+ // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
+ $core = sys::cpu_idle($proc_stat, $server['unit'], false); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
+
+ if(!is_numeric($core))
+ return array('e' => 'Не удается выполнить операцию, нет свободного потока.');
+
+ $taskset = 'taskset -c '.$core;
+ }
+
+ if($server['core_fix'])
+ {
+ $core = $server['core_fix']-1;
+ $taskset = 'taskset -c '.$core;
+ }
+
+ $ssh->set('cd '.$cfg['steamcmd'].' && sudo -u server'.$server['uid'].' '.$taskset.' sh -c "screen -dmS u_'.$server['uid'].' ./steamcmd.sh +login anonymous +force_install_dir "'.$install.'" +app_update 232330 +quit"');
+
+ $core = !isset($core) ? 0 : $core+1;
+
+ // Обновление информации в базе
+ $sql->query('UPDATE `servers` set `status`="update", `update`="'.$start_point.'", `core_use`="'.$core.'" WHERE `id`="'.$id.'" LIMIT 1');
+
+ // Логирование
+ $sql->query('INSERT INTO `logs_sys` set `user`="'.$user['id'].'", `server`="'.$id.'", `text`="'.sys::text('syslogs', 'update').'", `time`="'.$start_point.'"');
+
+ // Сброс кеша
+ actions::clmcache($id);
+
+ sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'update', 'online' => 0, 'players' => ''));
+ sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'update', 'online' => 0));
+
+ return array('s' => 'ok');
+ }
}
?>
\ No newline at end of file
diff --git a/system/library/games/css/rcon.php b/system/library/games/css/rcon.php
index 6a97e06..9896e8a 100644
--- a/system/library/games/css/rcon.php
+++ b/system/library/games/css/rcon.php
@@ -1,112 +1,112 @@
Connect($ip, $port, 3, SourceQuery::SOURCE);
+ $sq->Connect($ip, $port, 3, SourceQuery::SOURCE);
- $sq->SetRconPassword(rcon::rcon_passwd($server));
+ $sq->SetRconPassword(rcon::rcon_passwd($server));
- $out = $sq->Rcon($cmd);
+ $out = $sq->Rcon($cmd);
- $sq->Disconnect();
+ $sq->Disconnect();
- return $out;
- }
+ return $out;
+ }
- public static function players($data)
- {
- $aPlayers = array();
- $n = 1;
+ public static function players($data)
+ {
+ $aPlayers = array();
+ $n = 1;
- $lines = explode("\n", $data);
+ $lines = explode("\n", $data);
- foreach($lines as $line)
- {
- if(strpos($line, '#') === FALSE)
- continue;
+ foreach($lines as $line)
+ {
+ if(strpos($line, '#') === FALSE)
+ continue;
- $start = strpos($line, '"')+1;
- $end = strrpos($line, '"');
+ $start = strpos($line, '"')+1;
+ $end = strrpos($line, '"');
- $userid = sys::int(substr($line, 0, $start));
+ $userid = sys::int(substr($line, 0, $start));
- $name = htmlspecialchars(substr($line, $start, $end-$start));
+ $name = htmlspecialchars(substr($line, $start, $end-$start));
- $line = trim(substr($line, $end + 1));
+ $line = trim(substr($line, $end + 1));
- $aData = array_values(array_diff(explode(' ', $line), array('', ' ')));
+ $aData = array_values(array_diff(explode(' ', $line), array('', ' ')));
- $steamid = trim($aData[0]);
- $ip = trim(sys::first(explode(':', $aData[5])));
+ $steamid = trim($aData[0]);
+ $ip = trim(sys::first(explode(':', $aData[5])));
- if((sys::valid($steamid, 'steamid') AND sys::valid($steamid, 'steamid3')) || sys::valid($ip, 'ip'))
- continue;
+ if((sys::valid($steamid, 'steamid') AND sys::valid($steamid, 'steamid3')) || sys::valid($ip, 'ip'))
+ continue;
- $aPlayers[$n]['userid'] = $userid;
- $aPlayers[$n]['name'] = $name;
- $aPlayers[$n]['steamid'] = $steamid;
- $aPlayers[$n]['time'] = trim($aData[1]);
- $aPlayers[$n]['ping'] = trim($aData[2]);
- $aPlayers[$n]['ip'] = $ip;
+ $aPlayers[$n]['userid'] = $userid;
+ $aPlayers[$n]['name'] = $name;
+ $aPlayers[$n]['steamid'] = $steamid;
+ $aPlayers[$n]['time'] = trim($aData[1]);
+ $aPlayers[$n]['ping'] = trim($aData[2]);
+ $aPlayers[$n]['ip'] = $ip;
- $whois = rcon::country($ip);
+ $whois = rcon::country($ip);
- $aPlayers[$n]['ico'] = $whois['ico'];
- $aPlayers[$n]['country'] = $whois['name'];
+ $aPlayers[$n]['ico'] = $whois['ico'];
+ $aPlayers[$n]['country'] = $whois['name'];
- $n+=1;
- }
+ $n+=1;
+ }
- return $aPlayers;
- }
+ return $aPlayers;
+ }
- public static function rcon_passwd($server)
- {
- global $cfg, $sql, $user;
+ public static function rcon_passwd($server)
+ {
+ global $cfg, $sql, $user;
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
$unit = $sql->get();
- if(!$ssh->auth($unit['passwd'], $unit['address']))
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
sys::outjs(array('e' => sys::text('error', 'ssh')));
- $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
- $tarif = $sql->get();
+ $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
+ $tarif = $sql->get();
- $ssh->set('cat '.$tarif['install'].'/'.$server['uid'].'/cstrike/cfg/server.cfg | grep rcon_password');
- $get = explode(' ', str_replace('"', '', trim($ssh->get())));
- $rcon = trim(end($get));
+ $ssh->set('cat '.$tarif['install'].'/'.$server['uid'].'/cstrike/cfg/server.cfg | grep rcon_password');
+ $get = explode(' ', str_replace('"', '', trim($ssh->get())));
+ $rcon = trim(end($get));
- if(!isset($rcon{0}))
- sys::outjs(array('r' => 'Необходимо установить rcon пароль (rcon_password).', 'url' => $cfg['http'].'servers/id/'.$server['id'].'/section/settings/subsection/server'), $nmch);
+ if(!isset($rcon{0}))
+ sys::outjs(array('r' => 'Необходимо установить rcon пароль (rcon_password).', 'url' => $cfg['http'].'servers/id/'.$server['id'].'/section/settings/subsection/server'), $nmch);
- return $rcon;
- }
+ return $rcon;
+ }
- public static function country($ip)
- {
- global $SxGeo;
+ public static function country($ip)
+ {
+ global $SxGeo;
- $cData = $SxGeo->getCityFull($ip);
- $ico = sys::country($cData['country']['iso']);
+ $cData = $SxGeo->getCityFull($ip);
+ $ico = sys::country($cData['country']['iso']);
- return array('ico' => $ico, 'name' => empty($cData['country']['name_ru']) ? 'Не определена' : $cData['country']['name_ru']);
- }
- }
+ return array('ico' => $ico, 'name' => empty($cData['country']['name_ru']) ? 'Не определена' : $cData['country']['name_ru']);
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/games/css/scan.php b/system/library/games/css/scan.php
index ca76ba3..aeb3bdd 100644
--- a/system/library/games/css/scan.php
+++ b/system/library/games/css/scan.php
@@ -1,140 +1,140 @@
get($nmch)))
- return $mcache->get($nmch);
+ if(is_array($mcache->get($nmch)))
+ return $mcache->get($nmch);
- $out = array();
+ $out = array();
- $info = scan::info($sq, $id);
+ $info = scan::info($sq, $id);
- $sql->query('SELECT `game`, `name`, `map`, `online`, `players`, `status`, `time`, `overdue` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `game`, `name`, `map`, `online`, `players`, `status`, `time`, `overdue` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- $out['time'] = 'Арендован до: '.date('d.m.Y - H:i', $server['time']);
+ $out['time'] = 'Арендован до: '.date('d.m.Y - H:i', $server['time']);
- if($server['status'] == 'overdue')
- $out['time_end'] = 'Удаление через: '.sys::date('min', $server['overdue']+$cfg['server_delete']*86400);
- else
- $out['time_end'] = 'Осталось: '.sys::date('min', $server['time']);
+ if($server['status'] == 'overdue')
+ $out['time_end'] = 'Удаление через: '.sys::date('min', $server['overdue']+$cfg['server_delete']*86400);
+ else
+ $out['time_end'] = 'Осталось: '.sys::date('min', $server['time']);
- if(!$info['status'])
- {
- $out['name'] = $server['name'];
- $out['status'] = sys::status($server['status'], $server['game'], $server['map']);
- $out['online'] = $server['online'];
- $out['image'] = ' ';
- $out['buttons'] = sys::buttons($id, $server['status']);
+ if(!$info['status'])
+ {
+ $out['name'] = $server['name'];
+ $out['status'] = sys::status($server['status'], $server['game'], $server['map']);
+ $out['online'] = $server['online'];
+ $out['image'] = ' ';
+ $out['buttons'] = sys::buttons($id, $server['status']);
- if($players_get)
- $out['players'] = base64_decode($server['players']);
+ if($players_get)
+ $out['players'] = base64_decode($server['players']);
- $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
+ $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
- return $out;
- }
+ return $out;
+ }
- if($players_get)
- $players = scan::info($sq, $id, true);
+ if($players_get)
+ $players = scan::info($sq, $id, true);
- $out['name'] = htmlspecialchars($info['name']);
- $out['status'] = sys::status('working', $server['game'], $info['map']);
- $out['online'] = $info['online'];
- $out['image'] = ' ';
- $out['buttons'] = sys::buttons($id, 'working');
- $out['players'] = '';
+ $out['name'] = htmlspecialchars($info['name']);
+ $out['status'] = sys::status('working', $server['game'], $info['map']);
+ $out['online'] = $info['online'];
+ $out['image'] = ' ';
+ $out['buttons'] = sys::buttons($id, 'working');
+ $out['players'] = '';
- if($players_get)
- {
- foreach($players as $index => $player)
- {
- $html->get($server['game'], 'sections/servers/players');
+ if($players_get)
+ {
+ foreach($players as $index => $player)
+ {
+ $html->get($server['game'], 'sections/servers/players');
- $html->set('i', $player['i']);
- $html->set('name', $player['name']);
- $html->set('score', $player['score']);
- $html->set('time', $player['time']);
+ $html->set('i', $player['i']);
+ $html->set('name', $player['name']);
+ $html->set('score', $player['score']);
+ $html->set('time', $player['time']);
- $html->pack('list');
- }
+ $html->pack('list');
+ }
- $out['players'] = isset($html->arr['list']) ? $html->arr['list'] : '';
- }
+ $out['players'] = isset($html->arr['list']) ? $html->arr['list'] : '';
+ }
- $sql->query('UPDATE `servers` set '
- .'`name`="'.$out['name'].'", '
- .'`online`="'.$out['online'].'", '
- .'`map`="'.$info['map'].'", '
- .'`status`="working" WHERE `id`="'.$id.'" LIMIT 1');
+ $sql->query('UPDATE `servers` set '
+ .'`name`="'.$out['name'].'", '
+ .'`online`="'.$out['online'].'", '
+ .'`map`="'.$info['map'].'", '
+ .'`status`="working" WHERE `id`="'.$id.'" LIMIT 1');
- if($players_get)
- $sql->query('UPDATE `servers` set `players`="'.base64_encode($out['players']).'" WHERE `id`="'.$id.'" LIMIT 1');
+ if($players_get)
+ $sql->query('UPDATE `servers` set `players`="'.base64_encode($out['players']).'" WHERE `id`="'.$id.'" LIMIT 1');
- $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
+ $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
- return $out;
- }
+ return $out;
+ }
- public static function info($sq, $id, $pl = false)
- {
- global $sql;
+ public static function info($sq, $id, $pl = false)
+ {
+ global $sql;
- $sql->query('SELECT `address` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `address` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- list($ip, $port) = explode(':', $server['address']);
+ list($ip, $port) = explode(':', $server['address']);
- $sq->Connect($ip, $port, 1, SourceQuery::SOURCE);
+ $sq->Connect($ip, $port, 1, SourceQuery::SOURCE);
- if($pl)
- {
- $players = $sq->GetPlayers();
+ if($pl)
+ {
+ $players = $sq->GetPlayers();
- $i = 1;
- $data = array();
+ $i = 1;
+ $data = array();
- foreach($players as $n => $player)
- {
- $data[$i]['i'] = $i;
- $data[$i]['name'] = $player['Name'] == '' ? 'Подключается' : $player['Name'];
- $data[$i]['score'] = $player['Frags'];
- $data[$i]['time'] = $player['TimeF'];
+ foreach($players as $n => $player)
+ {
+ $data[$i]['i'] = $i;
+ $data[$i]['name'] = $player['Name'] == '' ? 'Подключается' : $player['Name'];
+ $data[$i]['score'] = $player['Frags'];
+ $data[$i]['time'] = $player['TimeF'];
- $i+=1;
- }
+ $i+=1;
+ }
- return $data;
- }
+ return $data;
+ }
- $data = $sq->GetInfo();
+ $data = $sq->GetInfo();
- $server['name'] = $data['HostName'];
- $server['map'] = $data['Map'];
- $server['online'] = $data['Players'];
- $server['status'] = strlen($server['map']) > 3 ? true : false;
+ $server['name'] = $data['HostName'];
+ $server['map'] = $data['Map'];
+ $server['online'] = $data['Players'];
+ $server['status'] = strlen($server['map']) > 3 ? true : false;
- return $server;
- }
- }
+ return $server;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/games/css/service.php b/system/library/games/css/service.php
index efc9a89..d541dad 100644
--- a/system/library/games/css/service.php
+++ b/system/library/games/css/service.php
@@ -1,369 +1,369 @@
query('SELECT `address`, `test` FROM `units` WHERE `id`="'.$aData['unit'].'" AND `css`="1" AND `show`="1" LIMIT 1');
- if(!$sql->num())
- sys::outjs(array('e' => 'Локация не найдена.'));
+ // Проверка локации
+ $sql->query('SELECT `address`, `test` FROM `units` WHERE `id`="'.$aData['unit'].'" AND `css`="1" AND `show`="1" LIMIT 1');
+ if(!$sql->num())
+ sys::outjs(array('e' => 'Локация не найдена.'));
- $unit = $sql->get();
+ $unit = $sql->get();
- // Проверка тарифа
- $sql->query('SELECT `id` FROM `tarifs` WHERE `id`="'.$aData['tarif'].'" AND `unit`="'.$aData['unit'].'" AND `show`="1" LIMIT 1');
- if(!$sql->num())
- sys::outjs(array('e' => 'Тариф не найден.'));
+ // Проверка тарифа
+ $sql->query('SELECT `id` FROM `tarifs` WHERE `id`="'.$aData['tarif'].'" AND `unit`="'.$aData['unit'].'" AND `show`="1" LIMIT 1');
+ if(!$sql->num())
+ sys::outjs(array('e' => 'Тариф не найден.'));
- $sql->query('SELECT '
- .'`slots_min`,'
- .'`slots_max`,'
- .'`port_min`,'
- .'`port_max`,'
- .'`hostname`,'
- .'`packs`,'
- .'`tickrate`,'
- .'`time`,'
- .'`test`,'
- .'`tests`,'
- .'`discount`,'
- .'`map`,'
- .'`ftp`,'
- .'`plugins`,'
- .'`console`,'
- .'`stats`,'
- .'`copy`,'
- .'`web`,'
- .'`plugins_install`,'
- .'`hdd`,'
- .'`autostop`,'
- .'`core_fix`,'
- .'`ip`,'
- .'`price`'
- .' FROM `tarifs` WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
+ $sql->query('SELECT '
+ .'`slots_min`,'
+ .'`slots_max`,'
+ .'`port_min`,'
+ .'`port_max`,'
+ .'`hostname`,'
+ .'`packs`,'
+ .'`tickrate`,'
+ .'`time`,'
+ .'`test`,'
+ .'`tests`,'
+ .'`discount`,'
+ .'`map`,'
+ .'`ftp`,'
+ .'`plugins`,'
+ .'`console`,'
+ .'`stats`,'
+ .'`copy`,'
+ .'`web`,'
+ .'`plugins_install`,'
+ .'`hdd`,'
+ .'`autostop`,'
+ .'`core_fix`,'
+ .'`ip`,'
+ .'`price`'
+ .' FROM `tarifs` WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
- $tarif = $sql->get();
+ $tarif = $sql->get();
- // Проверка сборки
- if(!array_key_exists($aData['pack'], sys::b64djs($tarif['packs'], true)))
- sys::outjs(array('e' => 'Сборка не найдена.'));
+ // Проверка сборки
+ if(!array_key_exists($aData['pack'], sys::b64djs($tarif['packs'], true)))
+ sys::outjs(array('e' => 'Сборка не найдена.'));
- // Проверка TickRate
- if(!in_array($aData['tickrate'], explode(':', $tarif['tickrate'])))
- sys::outjs(array('e' => 'Переданные данные tickrate неверны.'));
+ // Проверка TickRate
+ if(!in_array($aData['tickrate'], explode(':', $tarif['tickrate'])))
+ sys::outjs(array('e' => 'Переданные данные tickrate неверны.'));
- $test = 0;
+ $test = 0;
- // Проверка периода на тест
- if($aData['test'])
- {
- if(!$tarif['test'] || !$unit['test'])
- sys::outjs(array('e' => 'Тестовый период недоступен.'));
+ // Проверка периода на тест
+ if($aData['test'])
+ {
+ if(!$tarif['test'] || !$unit['test'])
+ sys::outjs(array('e' => 'Тестовый период недоступен.'));
- // Проверка на повторный запрос
- $sql->query('SELECT `id`, `game` FROM `tests` WHERE `user`="'.$user['id'].'" LIMIT 1');
- if($sql->num())
- {
- $test_info = $sql->get();
+ // Проверка на повторный запрос
+ $sql->query('SELECT `id`, `game` FROM `tests` WHERE `user`="'.$user['id'].'" LIMIT 1');
+ if($sql->num())
+ {
+ $test_info = $sql->get();
- if(!$cfg['tests']['game'] || $test_info['game'] == 'css')
- sys::outjs(array('e' => 'Тестовый период предоставляется один раз.'));
+ if(!$cfg['tests']['game'] || $test_info['game'] == 'css')
+ sys::outjs(array('e' => 'Тестовый период предоставляется один раз.'));
- $sql->query('SELECT `id` FROM `servers` WHERE `user`="'.$user['id'].'" AND `test`="1" LIMIT 1');
- if($sql->num() AND !$cfg['tests']['sametime'])
- sys::outjs(array('e' => 'Чтобы получить тестовый период другой игры, дождитесь окончания текущего.'));
- }
+ $sql->query('SELECT `id` FROM `servers` WHERE `user`="'.$user['id'].'" AND `test`="1" LIMIT 1');
+ if($sql->num() AND !$cfg['tests']['sametime'])
+ sys::outjs(array('e' => 'Чтобы получить тестовый период другой игры, дождитесь окончания текущего.'));
+ }
- // Проверка наличия мест на локации
- $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `test`="1" AND `time`>"'.$start_point.'" LIMIT '.$unit['test']);
- if($sql->num() == $unit['test'])
- sys::outjs(array('e' => 'Свободного места для тестового периода нет.'));
+ // Проверка наличия мест на локации
+ $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `test`="1" AND `time`>"'.$start_point.'" LIMIT '.$unit['test']);
+ if($sql->num() == $unit['test'])
+ sys::outjs(array('e' => 'Свободного места для тестового периода нет.'));
- // Проверка наличия мест для выбранного тарифа
- $sql->query('SELECT `id` FROM `servers` WHERE `tarif`="'.$aData['tarif'].'" AND `test`="1" AND `time`>"'.$start_point.'" LIMIT '.$tarif['tests']);
- if($sql->num() == $tarif['tests'])
- sys::outjs(array('e' => 'Свободного места для тестового периода выбранного тарифа нет.'));
+ // Проверка наличия мест для выбранного тарифа
+ $sql->query('SELECT `id` FROM `servers` WHERE `tarif`="'.$aData['tarif'].'" AND `test`="1" AND `time`>"'.$start_point.'" LIMIT '.$tarif['tests']);
+ if($sql->num() == $tarif['tests'])
+ sys::outjs(array('e' => 'Свободного места для тестового периода выбранного тарифа нет.'));
- $test = 1;
- }else
- // Проверка периода
- if(!$cfg['settlement_period'] AND !in_array($aData['time'], explode(':', $tarif['time'])))
- sys::outjs(array('e' => 'Переданные данные периода неверны.'));
+ $test = 1;
+ }else
+ // Проверка периода
+ if(!$cfg['settlement_period'] AND !in_array($aData['time'], explode(':', $tarif['time'])))
+ sys::outjs(array('e' => 'Переданные данные периода неверны.'));
- // Проверка слот
- if($aData['slots'] < $tarif['slots_min'] || $aData['slots'] > $tarif['slots_max'])
- sys::outjs(array('e' => 'Переданные данные слот неверны.'));
+ // Проверка слот
+ if($aData['slots'] < $tarif['slots_min'] || $aData['slots'] > $tarif['slots_max'])
+ sys::outjs(array('e' => 'Переданные данные слот неверны.'));
- // Определение цены
- $aPrice = explode(':', $tarif['price']);
- $price = $aPrice[array_search($aData['tickrate'], explode(':', $tarif['tickrate']))];
+ // Определение цены
+ $aPrice = explode(':', $tarif['price']);
+ $price = $aPrice[array_search($aData['tickrate'], explode(':', $tarif['tickrate']))];
- // Определение суммы
- if($cfg['settlement_period'])
- {
- // Цена аренды за расчетный период
- $sum = games::define_sum($tarif['discount'], $price, $aData['slots'], $start_point);
+ // Определение суммы
+ if($cfg['settlement_period'])
+ {
+ // Цена аренды за расчетный период
+ $sum = games::define_sum($tarif['discount'], $price, $aData['slots'], $start_point);
- $aData['time'] = games::define_period('buy', params::$aDayMonth);
- }else
- $sum = games::define_sum($tarif['discount'], $price, $aData['slots'], $aData['time']);
+ $aData['time'] = games::define_period('buy', params::$aDayMonth);
+ }else
+ $sum = games::define_sum($tarif['discount'], $price, $aData['slots'], $aData['time']);
- // Проверка промо-кода
- $promo = games::define_promo(
- $aData['promo'],
- array(
- 'tarif' => $aData['tarif'],
- 'tickrate' => $aData['tickrate'],
- 'slots' => $aData['slots'],
- 'time' => $aData['time'],
- 'user' => $user['id']
- ),
- $tarif['discount'],
- $sum
- );
+ // Проверка промо-кода
+ $promo = games::define_promo(
+ $aData['promo'],
+ array(
+ 'tarif' => $aData['tarif'],
+ 'tickrate' => $aData['tickrate'],
+ 'slots' => $aData['slots'],
+ 'time' => $aData['time'],
+ 'user' => $user['id']
+ ),
+ $tarif['discount'],
+ $sum
+ );
- $days = $aData['time']; // Кол-во дней аренды
+ $days = $aData['time']; // Кол-во дней аренды
- // Использование промо-кода
- if(is_array($promo))
- {
- if(array_key_exists('sum', $promo))
- $sum = $promo['sum'];
- else
- $days += $promo['days']; // Кол-во дней аренды с учетом подарочных (промо-код)
- }
+ // Использование промо-кода
+ if(is_array($promo))
+ {
+ if(array_key_exists('sum', $promo))
+ $sum = $promo['sum'];
+ else
+ $days += $promo['days']; // Кол-во дней аренды с учетом подарочных (промо-код)
+ }
- // Проверка баланса
- if($user['balance'] < $sum)
- sys::outjs(array('e' => 'У вас не хватает '.(round($sum-$user['balance'], 2)).' '.$cfg['currency']));
+ // Проверка баланса
+ if($user['balance'] < $sum)
+ sys::outjs(array('e' => 'У вас не хватает '.(round($sum-$user['balance'], 2)).' '.$cfg['currency']));
- // Выделенный адрес игрового сервера
- if(!empty($tarif['ip']))
- {
- $aIp = explode(':', $tarif['ip']);
+ // Выделенный адрес игрового сервера
+ if(!empty($tarif['ip']))
+ {
+ $aIp = explode(':', $tarif['ip']);
- $ip = false;
- $port = params::$aDefPort['css'];
+ $ip = false;
+ $port = params::$aDefPort['css'];
- // Проверка наличия свободного адреса
- foreach($aIp as $adr)
- {
- $adr = trim($adr);
+ // Проверка наличия свободного адреса
+ foreach($aIp as $adr)
+ {
+ $adr = trim($adr);
- $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `address` LIKE "'.$adr.':%" LIMIT 1');
- if(!$sql->num())
- {
- $ip = $adr;
+ $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `address` LIKE "'.$adr.':%" LIMIT 1');
+ if(!$sql->num())
+ {
+ $ip = $adr;
- break;
- }
- }
- }else{
- $ip = sys::first(explode(':', $unit['address']));
- $port = false;
+ break;
+ }
+ }
+ }else{
+ $ip = sys::first(explode(':', $unit['address']));
+ $port = false;
- // Проверка наличия свободного порта
- for($tarif['port_min']; $tarif['port_min'] <= $tarif['port_max']; $tarif['port_min']+=1)
- {
- $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND (`address`="'.$ip.':'.$tarif['port_min'].'" OR `port`="'.$tarif['port_min'].'") LIMIT 1');
- if(!$sql->num())
- {
- $port = $tarif['port_min'];
+ // Проверка наличия свободного порта
+ for($tarif['port_min']; $tarif['port_min'] <= $tarif['port_max']; $tarif['port_min']+=1)
+ {
+ $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND (`address`="'.$ip.':'.$tarif['port_min'].'" OR `port`="'.$tarif['port_min'].'") LIMIT 1');
+ if(!$sql->num())
+ {
+ $port = $tarif['port_min'];
- break;
- }
- }
- }
+ break;
+ }
+ }
+ }
- if(!$ip || !$port)
- {
- $sql->query('UPDATE `tarifs` set `show`="0" WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
+ if(!$ip || !$port)
+ {
+ $sql->query('UPDATE `tarifs` set `show`="0" WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
- sys::outjs(array('e' => 'К сожалению нет доступных мест, обратитесь в тех.поддержку.'));
- }
+ sys::outjs(array('e' => 'К сожалению нет доступных мест, обратитесь в тех.поддержку.'));
+ }
- if($test)
- $aData['time'] = games::time($start_point, $tarif['test']);
- else
- $aData['time'] = games::time($start_point, $days);
+ if($test)
+ $aData['time'] = games::time($start_point, $tarif['test']);
+ else
+ $aData['time'] = games::time($start_point, $days);
- $fix_one = 0;
- $core = 0;
+ $fix_one = 0;
+ $core = 0;
- if($tarif['core_fix'] != '')
- {
- $aCore = explode(',', $tarif['core_fix']);
+ if($tarif['core_fix'] != '')
+ {
+ $aCore = explode(',', $tarif['core_fix']);
- foreach($aCore as $cpu)
- {
- $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `tarif`="'.$aData['tarif'].'" AND `core_fix`="'.$cpu.'" AND `core_fix_one`="1" LIMIT 1');
+ foreach($aCore as $cpu)
+ {
+ $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `tarif`="'.$aData['tarif'].'" AND `core_fix`="'.$cpu.'" AND `core_fix_one`="1" LIMIT 1');
- if($sql->num())
- continue;
+ if($sql->num())
+ continue;
- $fix_one = 1;
- $core = $cpu;
+ $fix_one = 1;
+ $core = $cpu;
- break;
- }
+ break;
+ }
- if(!$core)
- {
- $sql->query('UPDATE `tarifs` set `show`="0" WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
+ if(!$core)
+ {
+ $sql->query('UPDATE `tarifs` set `show`="0" WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
- sys::outjs(array('e' => 'К сожалению нет доступных мест, обратитесь в тех.поддержку.'));
- }
- }
+ sys::outjs(array('e' => 'К сожалению нет доступных мест, обратитесь в тех.поддержку.'));
+ }
+ }
- $ram = $tarif['param_fix'] ? $aData['ram'] : $cfg['ram']['css']*$aSDATA['slots'];
+ $ram = $tarif['param_fix'] ? $aData['ram'] : $cfg['ram']['css']*$aSDATA['slots'];
- // Массив данных
- $aSDATA = array(
- 'unit' => $aData['unit'], // идентификатор локации
- 'tarif' => $aData['tarif'], // идентификатор тарифа
- 'ram' => $ram, // значение ram
- 'param_fix' => $tarif['param_fix'], // фиксированные параметры
- 'tickrate' => $aData['tickrate'], // значение tickrate
- 'pack' => $aData['pack'], // Выбранная сборка для установки
- 'time' => $aData['time'], // Время аренды
- 'days' => $days, // Число дней
- 'sum' => $sum, // Сумма списания
- 'test' => $test, // тестовый период
- 'address' => $ip.':'.$port, // адрес игрового сервера
- 'port' => $port, // порт игрового сервера
- 'slots' => $aData['slots'], // Кол-во слот
- 'map' => $tarif['map'], // Фиксированное значение слот
- 'autostop' => $tarif['autostop'], // Выключение при 0 онлайне
- 'ftp' => $tarif['ftp'], // Использование ftp
- 'plugins' => $tarif['plugins'], // Использование плагинов
- 'console' => $tarif['console'], // Использование консоли
- 'stats' => $tarif['stats'], // Использование графиков (ведение статистики)
- 'copy' => $tarif['copy'], // Использование резервных копий
- 'web' => $tarif['web'], // Использование доп услуг
- 'plugins_install' => $tarif['plugins_install'], // Список установленных плагинов
- 'hdd' => $tarif['hdd'], // Дисковое пространство
- 'core_fix' => $core, // Выделенный поток
- 'core_fix_one' => $fix_one, // Выделенный поток
- 'promo' => $promo // Использование промо-кода
- );
+ // Массив данных
+ $aSDATA = array(
+ 'unit' => $aData['unit'], // идентификатор локации
+ 'tarif' => $aData['tarif'], // идентификатор тарифа
+ 'ram' => $ram, // значение ram
+ 'param_fix' => $tarif['param_fix'], // фиксированные параметры
+ 'tickrate' => $aData['tickrate'], // значение tickrate
+ 'pack' => $aData['pack'], // Выбранная сборка для установки
+ 'time' => $aData['time'], // Время аренды
+ 'days' => $days, // Число дней
+ 'sum' => $sum, // Сумма списания
+ 'test' => $test, // тестовый период
+ 'address' => $ip.':'.$port, // адрес игрового сервера
+ 'port' => $port, // порт игрового сервера
+ 'slots' => $aData['slots'], // Кол-во слот
+ 'map' => $tarif['map'], // Фиксированное значение слот
+ 'autostop' => $tarif['autostop'], // Выключение при 0 онлайне
+ 'ftp' => $tarif['ftp'], // Использование ftp
+ 'plugins' => $tarif['plugins'], // Использование плагинов
+ 'console' => $tarif['console'], // Использование консоли
+ 'stats' => $tarif['stats'], // Использование графиков (ведение статистики)
+ 'copy' => $tarif['copy'], // Использование резервных копий
+ 'web' => $tarif['web'], // Использование доп услуг
+ 'plugins_install' => $tarif['plugins_install'], // Список установленных плагинов
+ 'hdd' => $tarif['hdd'], // Дисковое пространство
+ 'core_fix' => $core, // Выделенный поток
+ 'core_fix_one' => $fix_one, // Выделенный поток
+ 'promo' => $promo // Использование промо-кода
+ );
- return $aSDATA;
- }
+ return $aSDATA;
+ }
- public static function install($aSDATA = array())
- {
- global $cfg, $sql, $user, $start_point;
+ public static function install($aSDATA = array())
+ {
+ global $cfg, $sql, $user, $start_point;
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- // Массив данных локации (адрес,пароль)
- $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$aSDATA['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ // Массив данных локации (адрес,пароль)
+ $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$aSDATA['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- // Проверка ssh соединения с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- sys::outjs(array('e' => sys::text('error', 'ssh')));
+ // Проверка ssh соединения с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ sys::outjs(array('e' => sys::text('error', 'ssh')));
- // Массив данных тарифа (путь сборки,путь установки)
- $sql->query('SELECT `path`, `install`, `hostname` FROM `tarifs` WHERE `id`="'.$aSDATA['tarif'].'" LIMIT 1');
- $tarif = $sql->get();
+ // Массив данных тарифа (путь сборки,путь установки)
+ $sql->query('SELECT `path`, `install`, `hostname` FROM `tarifs` WHERE `id`="'.$aSDATA['tarif'].'" LIMIT 1');
+ $tarif = $sql->get();
- // Получение идентификаторов игрового сервера
- $sql->query('INSERT INTO `servers` set uid="1"');
- $id = $sql->id();
- $uid = $id+1000;
+ // Получение идентификаторов игрового сервера
+ $sql->query('INSERT INTO `servers` set uid="1"');
+ $id = $sql->id();
+ $uid = $id+1000;
- // Директория сборки
- $path = $tarif['path'].$aSDATA['pack'];
+ // Директория сборки
+ $path = $tarif['path'].$aSDATA['pack'];
- // Директория игрового сервера
- $install = $tarif['install'].$uid;
+ // Директория игрового сервера
+ $install = $tarif['install'].$uid;
- $ssh->set('mkdir '.$install.';' // Создание директории
- .'useradd -s /bin/false -d '.$install.' -g servers -u '.$uid.' server'.$uid.';' // Создание пользователя сервера на локации
- .'chown server'.$uid.':1000 '.$install.';' // Изменение владельца и группы директории
- .'cd '.$install.' && sudo -u server'.$uid.' screen -dmS i_'.$uid.' sh -c "cp -r '.$path.'/. .;' // Копирование файлов сборки для сервера
- .'find . -type d -exec chmod 700 {} \;;'
- .'find . -type f -exec chmod 600 {} \;;'
- .'chmod 500 '.params::$aFileGame['css'].'"');
+ $ssh->set('mkdir '.$install.';' // Создание директории
+ .'useradd -s /bin/false -d '.$install.' -g servers -u '.$uid.' server'.$uid.';' // Создание пользователя сервера на локации
+ .'chown server'.$uid.':1000 '.$install.';' // Изменение владельца и группы директории
+ .'cd '.$install.' && sudo -u server'.$uid.' screen -dmS i_'.$uid.' sh -c "cp -r '.$path.'/. .;' // Копирование файлов сборки для сервера
+ .'find . -type d -exec chmod 700 {} \;;'
+ .'find . -type f -exec chmod 600 {} \;;'
+ .'chmod 500 '.params::$aFileGame['css'].'"');
- // Запись данных нового сервера
- $sql->query('UPDATE `servers` set
- `uid`="'.$uid.'",
- `unit`="'.$aSDATA['unit'].'",
- `tarif`="'.$aSDATA['tarif'].'",
- `user`="'.$user['id'].'",
- `address`="'.$aSDATA['address'].'",
- `port`="'.$aSDATA['port'].'",
- `game`="css",
- `slots`="'.$aSDATA['slots'].'",
- `slots_start`="'.$aSDATA['slots'].'",
- `status`="install",
- `name`="'.$tarif['hostname'].'",
- `pack`="'.$aSDATA['pack'].'",
- `plugins_use`="'.$aSDATA['plugins'].'",
- `ftp_use`="'.$aSDATA['ftp'].'",
- `console_use`="'.$aSDATA['console'].'",
- `stats_use`="'.$aSDATA['stats'].'",
- `copy_use`="'.$aSDATA['copy'].'",
- `web_use`="'.$aSDATA['web'].'",
- `tickrate`="'.$aSDATA['tickrate'].'",
- `map_start`="'.$aSDATA['map'].'",
- `vac`="1",
- `hdd`="'.$aSDATA['hdd'].'",
- `time`="'.$aSDATA['time'].'",
- `date`="'.$start_point.'",
- `test`="'.$aSDATA['test'].'",
- `ram`="'.$aSDATA['ram'].'",
- `core_fix`="'.$aSDATA['core_fix'].'",
- `core_fix_one`="'.$aSDATA['core_fix_one'].'",
- `autostop`="'.$aSDATA['autostop'].'" WHERE `id`="'.$id.'" LIMIT 1');
+ // Запись данных нового сервера
+ $sql->query('UPDATE `servers` set
+ `uid`="'.$uid.'",
+ `unit`="'.$aSDATA['unit'].'",
+ `tarif`="'.$aSDATA['tarif'].'",
+ `user`="'.$user['id'].'",
+ `address`="'.$aSDATA['address'].'",
+ `port`="'.$aSDATA['port'].'",
+ `game`="css",
+ `slots`="'.$aSDATA['slots'].'",
+ `slots_start`="'.$aSDATA['slots'].'",
+ `status`="install",
+ `name`="'.$tarif['hostname'].'",
+ `pack`="'.$aSDATA['pack'].'",
+ `plugins_use`="'.$aSDATA['plugins'].'",
+ `ftp_use`="'.$aSDATA['ftp'].'",
+ `console_use`="'.$aSDATA['console'].'",
+ `stats_use`="'.$aSDATA['stats'].'",
+ `copy_use`="'.$aSDATA['copy'].'",
+ `web_use`="'.$aSDATA['web'].'",
+ `tickrate`="'.$aSDATA['tickrate'].'",
+ `map_start`="'.$aSDATA['map'].'",
+ `vac`="1",
+ `hdd`="'.$aSDATA['hdd'].'",
+ `time`="'.$aSDATA['time'].'",
+ `date`="'.$start_point.'",
+ `test`="'.$aSDATA['test'].'",
+ `ram`="'.$aSDATA['ram'].'",
+ `core_fix`="'.$aSDATA['core_fix'].'",
+ `core_fix_one`="'.$aSDATA['core_fix_one'].'",
+ `autostop`="'.$aSDATA['autostop'].'" WHERE `id`="'.$id.'" LIMIT 1');
- // Запись установленных плагинов
- if($aSDATA['plugins'])
- {
- // Массив идентификаторов плагинов
- $aPlugins = sys::b64djs($aSDATA['plugins_install']);
+ // Запись установленных плагинов
+ if($aSDATA['plugins'])
+ {
+ // Массив идентификаторов плагинов
+ $aPlugins = sys::b64djs($aSDATA['plugins_install']);
- if(isset($aPlugins[$aSDATA['pack']]))
- {
- $plugins = explode(',', $aPlugins[$aSDATA['pack']]);
+ if(isset($aPlugins[$aSDATA['pack']]))
+ {
+ $plugins = explode(',', $aPlugins[$aSDATA['pack']]);
- foreach($plugins as $plugin)
- if($plugin)
- $sql->query('INSERT INTO `plugins_install` set `server`="'.$id.'", `plugin`="'.$plugin.'", `time`="'.$start_point.'"');
- }
- }
+ foreach($plugins as $plugin)
+ if($plugin)
+ $sql->query('INSERT INTO `plugins_install` set `server`="'.$id.'", `plugin`="'.$plugin.'", `time`="'.$start_point.'"');
+ }
+ }
- // Списание средств с баланса пользователя
- $sql->query('UPDATE `users` set `balance`="'.($user['balance']-$aSDATA['sum']).'" WHERE `id`="'.$user['id'].'" LIMIT 1');
+ // Списание средств с баланса пользователя
+ $sql->query('UPDATE `users` set `balance`="'.($user['balance']-$aSDATA['sum']).'" WHERE `id`="'.$user['id'].'" LIMIT 1');
- // Запись получения тестового периода
- if($aSDATA['test'])
- {
- $sql->query('INSERT INTO `tests` set `server`="'.$id.'", `unit`="'.$aSDATA['unit'].'", `game`="css", `user`="'.$user['id'].'", `time`="'.$start_point.'"');
- $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server_test'), array('id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="0"');
- }else{
- // Реф. система
- games::part($user['id'], $aSDATA['sum']);
+ // Запись получения тестового периода
+ if($aSDATA['test'])
+ {
+ $sql->query('INSERT INTO `tests` set `server`="'.$id.'", `unit`="'.$aSDATA['unit'].'", `game`="css", `user`="'.$user['id'].'", `time`="'.$start_point.'"');
+ $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server_test'), array('id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="0"');
+ }else{
+ // Реф. система
+ games::part($user['id'], $aSDATA['sum']);
- // Запись логов
- if(!is_array($aSDATA['promo']))
- $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server'), array('days' => games::parse_day($aSDATA['days'], true), 'money' => $aSDATA['sum'], 'id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="'.$aSDATA['sum'].'"');
- else{
- $sql->query('UPDATE `servers` set `benefit`="'.$aSDATA['time'].'" WHERE `id`="'.$id.'" LIMIT 1');
- $sql->query('INSERT INTO `promo_use` set `promo`="'.$aSDATA['promo']['id'].'", `user`="'.$user['id'].'", `time`="'.$start_point.'"');
- $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server_promo'), array('days' => games::parse_day($aSDATA['days'], true), 'money' => $aSDATA['sum'], 'promo' => $aSDATA['promo']['cod'], 'id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="'.$aSDATA['sum'].'"');
- }
- }
+ // Запись логов
+ if(!is_array($aSDATA['promo']))
+ $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server'), array('days' => games::parse_day($aSDATA['days'], true), 'money' => $aSDATA['sum'], 'id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="'.$aSDATA['sum'].'"');
+ else{
+ $sql->query('UPDATE `servers` set `benefit`="'.$aSDATA['time'].'" WHERE `id`="'.$id.'" LIMIT 1');
+ $sql->query('INSERT INTO `promo_use` set `promo`="'.$aSDATA['promo']['id'].'", `user`="'.$user['id'].'", `time`="'.$start_point.'"');
+ $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server_promo'), array('days' => games::parse_day($aSDATA['days'], true), 'money' => $aSDATA['sum'], 'promo' => $aSDATA['promo']['cod'], 'id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="'.$aSDATA['sum'].'"');
+ }
+ }
- return $id;
- }
+ return $id;
+ }
}
?>
\ No newline at end of file
diff --git a/system/library/games/css/tarif.php b/system/library/games/css/tarif.php
index 0aba2f5..5dffa48 100644
--- a/system/library/games/css/tarif.php
+++ b/system/library/games/css/tarif.php
@@ -1,225 +1,225 @@
get('extend', 'sections/servers/games/tarif');
+ $html->get('extend', 'sections/servers/games/tarif');
- if(isset($html->arr['extend_address']))
- {
- $html->unit('extend_address', 1);
- $html->set('extend_address', $html->arr['extend_address']);
- }else
- $html->unit('extend_address');
+ if(isset($html->arr['extend_address']))
+ {
+ $html->unit('extend_address', 1);
+ $html->set('extend_address', $html->arr['extend_address']);
+ }else
+ $html->unit('extend_address');
- $html->set('id', $sid);
- $html->set('time', sys::date('min', $server['time']));
- $html->set('options', 'Выберете период продления '.$options);
- $html->set('slots', $server['slots']);
- $html->set('info', $server['tickrate'].' TickRate');
- $html->set('tarif', $tarif_name);
- $html->set('cur', $cfg['currency']);
+ $html->set('id', $sid);
+ $html->set('time', sys::date('min', $server['time']));
+ $html->set('options', 'Выберете период продления '.$options);
+ $html->set('slots', $server['slots']);
+ $html->set('info', $server['tickrate'].' TickRate');
+ $html->set('tarif', $tarif_name);
+ $html->set('cur', $cfg['currency']);
- $html->pack('main');
+ $html->pack('main');
- return NULL;
- }
+ return NULL;
+ }
public static function extend_sp($server, $tarif, $sid)
{
- global $cfg, $sql, $html, $start_point;
+ global $cfg, $sql, $html, $start_point;
- tarifs::extend_address($server['game'], $sid);
+ tarifs::extend_address($server['game'], $sid);
- $aPrice = explode(':', $tarif['price']);
- $aTICK = explode(':', $tarif['tickrate']);
+ $aPrice = explode(':', $tarif['price']);
+ $aTICK = explode(':', $tarif['tickrate']);
- $sum = $tarif['slots'] ? $aPrice[array_search($server['tickrate'], $aTICK)] : $aPrice[array_search($server['tickrate'], $aTICK)]*$server['slots'];
+ $sum = $tarif['slots'] ? $aPrice[array_search($server['tickrate'], $aTICK)] : $aPrice[array_search($server['tickrate'], $aTICK)]*$server['slots'];
- $html->get('extend_sp', 'sections/servers/games/tarif');
+ $html->get('extend_sp', 'sections/servers/games/tarif');
- if(isset($html->arr['extend_address']))
- {
- $html->unit('extend_address', 1);
- $html->set('extend_address', $html->arr['extend_address']);
- }else
- $html->unit('extend_address');
+ if(isset($html->arr['extend_address']))
+ {
+ $html->unit('extend_address', 1);
+ $html->set('extend_address', $html->arr['extend_address']);
+ }else
+ $html->unit('extend_address');
- $html->set('id', $sid);
- $html->set('time', sys::date('min', $server['time']));
- $html->set('date', $server['time'] > $start_point ? 'Сервер продлен до: '.date('d.m.Y', $server['time']) : 'Текущая дата: '.date('d.m.Y', $start_point));
- $html->set('options', 'Выберете период продления '.$options);
- $html->set('slots', $server['slots']);
- $html->set('info', $server['tickrate'].' TickRate');
- $html->set('tarif', $tarif['name']);
- $html->set('sum', $sum);
- $html->set('cur', $cfg['currency']);
+ $html->set('id', $sid);
+ $html->set('time', sys::date('min', $server['time']));
+ $html->set('date', $server['time'] > $start_point ? 'Сервер продлен до: '.date('d.m.Y', $server['time']) : 'Текущая дата: '.date('d.m.Y', $start_point));
+ $html->set('options', 'Выберете период продления '.$options);
+ $html->set('slots', $server['slots']);
+ $html->set('info', $server['tickrate'].' TickRate');
+ $html->set('tarif', $tarif['name']);
+ $html->set('sum', $sum);
+ $html->set('cur', $cfg['currency']);
- $html->pack('main');
+ $html->pack('main');
- return NULL;
- }
+ return NULL;
+ }
public static function plan($server, $tarif_name, $sid)
{
- global $cfg, $sql, $html;
+ global $cfg, $sql, $html;
- $sql->query('SELECT `tickrate`, `price` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
+ $sql->query('SELECT `tickrate`, `price` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
- if(!$sql->num())
- return NULL;
+ if(!$sql->num())
+ return NULL;
- $tarif = $sql->get();
+ $tarif = $sql->get();
- $options = 'Выберете тарифный план ';
+ $options = 'Выберете тарифный план ';
- $aPrice = explode(':', $tarif['price']);
- $aTick = explode(':', $tarif['tickrate']);
+ $aPrice = explode(':', $tarif['price']);
+ $aTick = explode(':', $tarif['tickrate']);
- // Если есть выбор
- if(count($aTick) > 1)
- {
- // Удалить при наличии tickrate сервера из выбора
- if(in_array($server['tickrate'], $aTick))
- unset($aTick[array_search($server['tickrate'], $aTick)]);
+ // Если есть выбор
+ if(count($aTick) > 1)
+ {
+ // Удалить при наличии tickrate сервера из выбора
+ if(in_array($server['tickrate'], $aTick))
+ unset($aTick[array_search($server['tickrate'], $aTick)]);
- foreach($aTick as $index => $tickrate)
- $options .= ''
- .$tickrate.' TickRate '
- .'('.$aPrice[$index].' '.$cfg['currency'].'/слот | '
- .($aPrice[$index]*$server['slots']).' '.$cfg['currency'].'/месяц)'
- .' ';
- }else
- return NULL;
+ foreach($aTick as $index => $tickrate)
+ $options .= ''
+ .$tickrate.' TickRate '
+ .'('.$aPrice[$index].' '.$cfg['currency'].'/слот | '
+ .($aPrice[$index]*$server['slots']).' '.$cfg['currency'].'/месяц)'
+ .' ';
+ }else
+ return NULL;
- $html->get('plan', 'sections/servers/games/tarif');
+ $html->get('plan', 'sections/servers/games/tarif');
- $html->set('id', $sid);
- $html->set('options', $options);
- $html->set('info', $server['tickrate'].' TickRate');
- $html->set('tarif', $tarif_name);
+ $html->set('id', $sid);
+ $html->set('options', $options);
+ $html->set('info', $server['tickrate'].' TickRate');
+ $html->set('tarif', $tarif_name);
- $html->pack('main');
+ $html->pack('main');
- return NULL;
- }
+ return NULL;
+ }
- public static function unit($server, $unit_name, $tarif_name, $sid)
+ public static function unit($server, $unit_name, $tarif_name, $sid)
{
- global $cfg, $sql, $html;
+ global $cfg, $sql, $html;
- if(!$cfg['change_unit'][$server['game']])
- return NULL;
+ if(!$cfg['change_unit'][$server['game']])
+ return NULL;
- $tarifs = $sql->query('SELECT `unit`, `tickrate` FROM `tarifs` WHERE `game`="'.$server['game'].'" AND `name`="'.$tarif_name.'" AND `id`!="'.$server['tarif'].'" AND `show`="1" ORDER BY `unit`');
- if(!$sql->num($tarifs))
- return NULL;
+ $tarifs = $sql->query('SELECT `unit`, `tickrate` FROM `tarifs` WHERE `game`="'.$server['game'].'" AND `name`="'.$tarif_name.'" AND `id`!="'.$server['tarif'].'" AND `show`="1" ORDER BY `unit`');
+ if(!$sql->num($tarifs))
+ return NULL;
- $units = 0;
+ $units = 0;
- $options = 'Выберете новую локацию ';
+ $options = 'Выберете новую локацию ';
- while($tarif = $sql->get($tarifs))
- {
- if(!in_array($server['tickrate'], explode(':', $tarif['tickrate'])))
- continue;
+ while($tarif = $sql->get($tarifs))
+ {
+ if(!in_array($server['tickrate'], explode(':', $tarif['tickrate'])))
+ continue;
- $sql->query('SELECT `id`, `name` FROM `units` WHERE `id`="'.$tarif['unit'].'" AND `show`="1" LIMIT 1');
- if(!$sql->num())
- continue;
+ $sql->query('SELECT `id`, `name` FROM `units` WHERE `id`="'.$tarif['unit'].'" AND `show`="1" LIMIT 1');
+ if(!$sql->num())
+ continue;
- $unit = $sql->get();
+ $unit = $sql->get();
- $options .= ''.$unit['name'].' ';
+ $options .= ''.$unit['name'].' ';
- $units+=1;
- }
+ $units+=1;
+ }
- if(!$units)
- return NULL;
+ if(!$units)
+ return NULL;
- $html->get('unit', 'sections/servers/games/tarif');
+ $html->get('unit', 'sections/servers/games/tarif');
- $html->set('id', $sid);
- $html->set('options', $options);
- $html->set('slots', $server['slots']);
- $html->set('info', $server['tickrate'].' TickRate');
- $html->set('unit', $unit_name);
- $html->set('tarif', $tarif_name);
+ $html->set('id', $sid);
+ $html->set('options', $options);
+ $html->set('slots', $server['slots']);
+ $html->set('info', $server['tickrate'].' TickRate');
+ $html->set('unit', $unit_name);
+ $html->set('tarif', $tarif_name);
- $html->pack('main');
+ $html->pack('main');
- return NULL;
- }
+ return NULL;
+ }
- public static function unit_new($tarif, $unit, $server, $mcache)
- {
- global $ssh, $sql, $user, $start_point;
+ public static function unit_new($tarif, $unit, $server, $mcache)
+ {
+ global $ssh, $sql, $user, $start_point;
- // Проверка ssh соединения с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- sys::outjs(array('e' => sys::text('error', 'ssh')));
+ // Проверка ssh соединения с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ sys::outjs(array('e' => sys::text('error', 'ssh')));
- // Директория сборки
- $path = $tarif['path'].$tarif['pack'];
+ // Директория сборки
+ $path = $tarif['path'].$tarif['pack'];
- // Директория игрового сервера
- $install = $tarif['install'].$server['uid'];
+ // Директория игрового сервера
+ $install = $tarif['install'].$server['uid'];
- // Пользователь сервера
- $uS = 'server'.$server['uid'];
+ // Пользователь сервера
+ $uS = 'server'.$server['uid'];
- $ssh->set('mkdir '.$install.';' // Создание директории
- .'useradd -d '.$install.' -g servers -u '.$server['uid'].' '.$uS.';' // Создание пользователя сервера на локации
- .'chown '.$uS.':1000 '.$install.';' // Изменение владельца и группы директории
- .'cd '.$install.' && sudo -u '.$uS.' screen -dmS i_'.$server['uid'].' cp -r '.$path.'/. .'); // Копирование файлов сборки для сервера
+ $ssh->set('mkdir '.$install.';' // Создание директории
+ .'useradd -d '.$install.' -g servers -u '.$server['uid'].' '.$uS.';' // Создание пользователя сервера на локации
+ .'chown '.$uS.':1000 '.$install.';' // Изменение владельца и группы директории
+ .'cd '.$install.' && sudo -u '.$uS.' screen -dmS i_'.$server['uid'].' cp -r '.$path.'/. .'); // Копирование файлов сборки для сервера
- $address = explode(':', $server['address']);
+ $address = explode(':', $server['address']);
- $fix_one = $tarif['core_fix'] ? 1 : 0;
+ $fix_one = $tarif['core_fix'] ? 1 : 0;
- // Обновление данных нового сервера
- $sql->query('UPDATE `servers` set
- `unit`="'.$tarif['unit'].'",
- `tarif`="'.$tarif['id'].'",
- `address`="'.$server['address'].'",
- `port`="'.$address[1].'",
- `status`="install",
- `name`="'.$tarif['hostname'].'",
- `pack`="'.$tarif['pack'].'",
- `map_start`="'.$tarif['map'].'",
- `vac`="1",
- `hdd`="'.$tarif['hdd'].'",
- `time`="'.$tarif['time'].'",
- `autostop`="'.$tarif['autostop'].'",
- `core_fix`="'.$tarif['core_fix'].'",
- `core_fix_one`="'.$fix_one.'",
- `reinstall`="'.$start_point.'" WHERE `id`="'.$server['id'].'" LIMIT 1');
+ // Обновление данных нового сервера
+ $sql->query('UPDATE `servers` set
+ `unit`="'.$tarif['unit'].'",
+ `tarif`="'.$tarif['id'].'",
+ `address`="'.$server['address'].'",
+ `port`="'.$address[1].'",
+ `status`="install",
+ `name`="'.$tarif['hostname'].'",
+ `pack`="'.$tarif['pack'].'",
+ `map_start`="'.$tarif['map'].'",
+ `vac`="1",
+ `hdd`="'.$tarif['hdd'].'",
+ `time`="'.$tarif['time'].'",
+ `autostop`="'.$tarif['autostop'].'",
+ `core_fix`="'.$tarif['core_fix'].'",
+ `core_fix_one`="'.$fix_one.'",
+ `reinstall`="'.$start_point.'" WHERE `id`="'.$server['id'].'" LIMIT 1');
- // Запись установленных плагинов
- if($tarif['plugins'])
- {
- // Массив идентификаторов плагинов
- $aPlugins = sys::b64js($tarif['plugins_install']);
+ // Запись установленных плагинов
+ if($tarif['plugins'])
+ {
+ // Массив идентификаторов плагинов
+ $aPlugins = sys::b64js($tarif['plugins_install']);
- if(isset($aPlugins[$tarif['pack']]))
- {
- $plugins = explode(',', $aPlugins[$tarif['pack']]);
+ if(isset($aPlugins[$tarif['pack']]))
+ {
+ $plugins = explode(',', $aPlugins[$tarif['pack']]);
- foreach($plugins as $plugin)
- if($plugin)
- $sql->query('INSERT INTO `plugins_install` set `server`="'.$server['id'].'", `plugin`="'.$plugin.'", `time`="'.$start_point.'"');
- }
- }
+ foreach($plugins as $plugin)
+ if($plugin)
+ $sql->query('INSERT INTO `plugins_install` set `server`="'.$server['id'].'", `plugin`="'.$plugin.'", `time`="'.$start_point.'"');
+ }
+ }
- return NULL;
- }
+ return NULL;
+ }
}
?>
\ No newline at end of file
diff --git a/system/library/games/cssold/action.php b/system/library/games/cssold/action.php
index 3786d72..a3072ff 100644
--- a/system/library/games/cssold/action.php
+++ b/system/library/games/cssold/action.php
@@ -1,116 +1,116 @@
query('SELECT `uid`, `unit`, `tarif`, `game`, `address`, `slots_start`, `name`, `tickrate`, `fps`, `map_start`, `vac`, `time_start`, `core_fix` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `uid`, `unit`, `tarif`, `game`, `address`, `slots_start`, `name`, `tickrate`, `fps`, `map_start`, `vac`, `time_start`, `core_fix` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
- $tarif = $sql->get();
+ $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
+ $tarif = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return array('e' => sys::text('error', 'ssh'));
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return array('e' => sys::text('error', 'ssh'));
- list($ip, $port) = explode(':', $server['address']);
+ list($ip, $port) = explode(':', $server['address']);
- // Убить процессы
- $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
- .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
+ // Убить процессы
+ $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
+ .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
- $taskset = '';
+ $taskset = '';
- // Если включена система автораспределения и не установлен фиксированный поток
- if($cfg['cpu_route'] AND !$server['core_fix'])
- {
- $proc_stat = array();
+ // Если включена система автораспределения и не установлен фиксированный поток
+ if($cfg['cpu_route'] AND !$server['core_fix'])
+ {
+ $proc_stat = array();
- $proc_stat[0] = $ssh->get('cat /proc/stat');
- }
+ $proc_stat[0] = $ssh->get('cat /proc/stat');
+ }
- // Проверка наличия стартовой карты
- $ssh->set('cd '.$tarif['install'].$server['uid'].'/cstrike/maps/ && ls | grep .bsp | grep -v .bsp.');
+ // Проверка наличия стартовой карты
+ $ssh->set('cd '.$tarif['install'].$server['uid'].'/cstrike/maps/ && ls | grep .bsp | grep -v .bsp.');
- if($server['map_start'] != '' AND !in_array($server['map_start'], str_replace('.bsp', '', explode("\n", $ssh->get()))))
- return array('e' => sys::updtext(sys::text('servers', 'nomap'), array('map' => $server['map_start'].'.bsp')));
+ if($server['map_start'] != '' AND !in_array($server['map_start'], str_replace('.bsp', '', explode("\n", $ssh->get()))))
+ return array('e' => sys::updtext(sys::text('servers', 'nomap'), array('map' => $server['map_start'].'.bsp')));
- // Если система автораспределения продолжить парсинг загрузки процессора
- if(isset($proc_stat))
- {
- $proc_stat[1] = $ssh->get('cat /proc/stat');
+ // Если система автораспределения продолжить парсинг загрузки процессора
+ if(isset($proc_stat))
+ {
+ $proc_stat[1] = $ssh->get('cat /proc/stat');
- // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
- $core = sys::cpu_idle($proc_stat, $server['unit'], false); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
+ // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
+ $core = sys::cpu_idle($proc_stat, $server['unit'], false); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
- if(!is_numeric($core))
- return array('e' => sys::text('error', 'cpu'));
+ if(!is_numeric($core))
+ return array('e' => sys::text('error', 'cpu'));
- $taskset = 'taskset -c '.$core;
- }
+ $taskset = 'taskset -c '.$core;
+ }
- if($server['core_fix'])
- {
- $core = $server['core_fix']-1;
- $taskset = 'taskset -c '.$core;
- }
+ if($server['core_fix'])
+ {
+ $core = $server['core_fix']-1;
+ $taskset = 'taskset -c '.$core;
+ }
- // Античит VAC
- $vac = $server['vac'] == 0 ? '-insecure' : '-secure';
+ // Античит VAC
+ $vac = $server['vac'] == 0 ? '-insecure' : '-secure';
- // Боты
- $bots = $cfg['bots'][$server['game']] ? '' : '-nobots';
+ // Боты
+ $bots = $cfg['bots'][$server['game']] ? '' : '-nobots';
- // TV
- $tv = $server['tv'] ? '+tv_enable 1 +tv_maxclients 30 +tv_port '.($port+10000) : '-nohltv';
+ // TV
+ $tv = $server['tv'] ? '+tv_enable 1 +tv_maxclients 30 +tv_port '.($port+10000) : '-nohltv';
- // FPS
- $fps = $server['fps']+$cfg['fpsplus'];
+ // FPS
+ $fps = $server['fps']+$cfg['fpsplus'];
- // Параметры запуска
- $bash = './srcds_run -debug -game cstrike -norestart -condebug console.log -tickrate '.$server['tickrate'].' +fps_egp '.$fps.' +servercfgfile server.cfg +map \''.$server['map_start'].'\' +maxplayers '.$server['slots_start'].' +ip '.$ip.' +port '.$port.' +sv_lan 0 -nomaster -localcser '.$vac.' '.$bots.' '.$tv;
+ // Параметры запуска
+ $bash = './srcds_run -debug -game cstrike -norestart -condebug console.log -tickrate '.$server['tickrate'].' +fps_egp '.$fps.' +servercfgfile server.cfg +map \''.$server['map_start'].'\' +maxplayers '.$server['slots_start'].' +ip '.$ip.' +port '.$port.' +sv_lan 0 -nomaster -localcser '.$vac.' '.$bots.' '.$tv;
- // Временный файл
- $temp = sys::temp($bash);
+ // Временный файл
+ $temp = sys::temp($bash);
- // Обновление файла start.sh
- $ssh->setfile($temp, $tarif['install'].$server['uid'].'/start.sh', 0500);
+ // Обновление файла start.sh
+ $ssh->setfile($temp, $tarif['install'].$server['uid'].'/start.sh', 0500);
- // Строка запуска
- $ssh->set('cd '.$tarif['install'].$server['uid'].';' // переход в директорию игрового сервера
- .'rm *.pid;' // Удаление *.pid файлов
- .'mv console.log oldstart.log;' // Перемещение лога предыдущего запуска в файл oldstart.log
- .'sudo -u server'.$server['uid'].' mkdir -p cstrike/oldstart;' // Создание папки логов
- .'cat cstrike/console.log >> cstrike/oldstart/'.date('d.m.Y_H:i:s', $server['time_start']).'.log; rm cstrike/console.log; rm cstrike/oldstart/01.01.1970_03:00:00.log;' // Перемещение лога предыдущего запуска
- .'chown server'.$server['uid'].':1000 start.sh;' // Обновление владельца файла start.sh
- .'sudo -u server'.$server['uid'].' screen -dmS s_'.$server['uid'].' '.$taskset.' sh -c "./start.sh"'); // Запуск игровго сервера
+ // Строка запуска
+ $ssh->set('cd '.$tarif['install'].$server['uid'].';' // переход в директорию игрового сервера
+ .'rm *.pid;' // Удаление *.pid файлов
+ .'mv console.log oldstart.log;' // Перемещение лога предыдущего запуска в файл oldstart.log
+ .'sudo -u server'.$server['uid'].' mkdir -p cstrike/oldstart;' // Создание папки логов
+ .'cat cstrike/console.log >> cstrike/oldstart/'.date('d.m.Y_H:i:s', $server['time_start']).'.log; rm cstrike/console.log; rm cstrike/oldstart/01.01.1970_03:00:00.log;' // Перемещение лога предыдущего запуска
+ .'chown server'.$server['uid'].':1000 start.sh;' // Обновление владельца файла start.sh
+ .'sudo -u server'.$server['uid'].' screen -dmS s_'.$server['uid'].' '.$taskset.' sh -c "./start.sh"'); // Запуск игровго сервера
- $core = !isset($core) ? 0 : $core+1;
+ $core = !isset($core) ? 0 : $core+1;
- // Обновление информации в базе
- $sql->query('UPDATE `servers` set `status`="'.$type.'", `online`="0", `players`="", `core_use`="'.$core.'", `time_start`="'.$start_point.'", `stop`="1" WHERE `id`="'.$id.'" LIMIT 1');
+ // Обновление информации в базе
+ $sql->query('UPDATE `servers` set `status`="'.$type.'", `online`="0", `players`="", `core_use`="'.$core.'", `time_start`="'.$start_point.'", `stop`="1" WHERE `id`="'.$id.'" LIMIT 1');
- unlink($temp);
+ unlink($temp);
- // Сброс кеша
- actions::clmcache($id);
+ // Сброс кеша
+ actions::clmcache($id);
- sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0, 'players' => ''));
- sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0));
+ sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0, 'players' => ''));
+ sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0));
- return array('s' => 'ok');
- }
- }
+ return array('s' => 'ok');
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/games/cssold/rcon.php b/system/library/games/cssold/rcon.php
index 40627de..8d9d451 100644
--- a/system/library/games/cssold/rcon.php
+++ b/system/library/games/cssold/rcon.php
@@ -1,112 +1,112 @@
Connect($ip, $port, 3, SourceQuery::SOURCE);
+ $sq->Connect($ip, $port, 3, SourceQuery::SOURCE);
- $sq->SetRconPassword(rcon::rcon_passwd($server));
+ $sq->SetRconPassword(rcon::rcon_passwd($server));
- $out = $sq->Rcon($cmd);
+ $out = $sq->Rcon($cmd);
- $sq->Disconnect();
+ $sq->Disconnect();
- return $out;
- }
+ return $out;
+ }
- public static function players($data)
- {
- $aPlayers = array();
- $n = 1;
+ public static function players($data)
+ {
+ $aPlayers = array();
+ $n = 1;
- $lines = explode("\n", $data);
+ $lines = explode("\n", $data);
- foreach($lines as $line)
- {
- if(strpos($line, '#') === FALSE)
- continue;
+ foreach($lines as $line)
+ {
+ if(strpos($line, '#') === FALSE)
+ continue;
- $start = strpos($line, '"')+1;
- $end = strrpos($line, '"');
+ $start = strpos($line, '"')+1;
+ $end = strrpos($line, '"');
- $userid = sys::int(substr($line, 0, $start));
+ $userid = sys::int(substr($line, 0, $start));
- $name = htmlspecialchars(substr($line, $start, $end-$start));
+ $name = htmlspecialchars(substr($line, $start, $end-$start));
- $line = trim(substr($line, $end + 1));
+ $line = trim(substr($line, $end + 1));
- $aData = array_values(array_diff(explode(' ', $line), array('', ' ')));
+ $aData = array_values(array_diff(explode(' ', $line), array('', ' ')));
- $steamid = trim($aData[0]);
- $ip = trim(sys::first(explode(':', $aData[5])));
+ $steamid = trim($aData[0]);
+ $ip = trim(sys::first(explode(':', $aData[5])));
- if(sys::valid($steamid, 'steamid') || sys::valid($ip, 'ip'))
- continue;
+ if(sys::valid($steamid, 'steamid') || sys::valid($ip, 'ip'))
+ continue;
- $aPlayers[$n]['userid'] = $userid;
- $aPlayers[$n]['name'] = $name;
- $aPlayers[$n]['steamid'] = $steamid;
- $aPlayers[$n]['time'] = trim($aData[1]);
- $aPlayers[$n]['ping'] = trim($aData[2]);
- $aPlayers[$n]['ip'] = $ip;
+ $aPlayers[$n]['userid'] = $userid;
+ $aPlayers[$n]['name'] = $name;
+ $aPlayers[$n]['steamid'] = $steamid;
+ $aPlayers[$n]['time'] = trim($aData[1]);
+ $aPlayers[$n]['ping'] = trim($aData[2]);
+ $aPlayers[$n]['ip'] = $ip;
- $whois = rcon::country($ip);
+ $whois = rcon::country($ip);
- $aPlayers[$n]['ico'] = $whois['ico'];
- $aPlayers[$n]['country'] = $whois['name'];
+ $aPlayers[$n]['ico'] = $whois['ico'];
+ $aPlayers[$n]['country'] = $whois['name'];
- $n+=1;
- }
+ $n+=1;
+ }
- return $aPlayers;
- }
+ return $aPlayers;
+ }
- public static function rcon_passwd($server)
- {
- global $cfg, $sql, $user;
+ public static function rcon_passwd($server)
+ {
+ global $cfg, $sql, $user;
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
$unit = $sql->get();
- if(!$ssh->auth($unit['passwd'], $unit['address']))
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
sys::outjs(array('e' => sys::text('error', 'ssh')));
- $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
- $tarif = $sql->get();
+ $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
+ $tarif = $sql->get();
- $ssh->set('cat '.$tarif['install'].'/'.$server['uid'].'/cstrike/cfg/server.cfg | grep rcon_password');
- $get = explode(' ', str_replace('"', '', trim($ssh->get())));
- $rcon = trim(end($get));
+ $ssh->set('cat '.$tarif['install'].'/'.$server['uid'].'/cstrike/cfg/server.cfg | grep rcon_password');
+ $get = explode(' ', str_replace('"', '', trim($ssh->get())));
+ $rcon = trim(end($get));
- if(!isset($rcon{0}))
- sys::outjs(array('r' => 'Необходимо установить rcon пароль (rcon_password).', 'url' => $cfg['http'].'servers/id/'.$server['id'].'/section/settings/subsection/server'), $nmch);
+ if(!isset($rcon{0}))
+ sys::outjs(array('r' => 'Необходимо установить rcon пароль (rcon_password).', 'url' => $cfg['http'].'servers/id/'.$server['id'].'/section/settings/subsection/server'), $nmch);
- return $rcon;
- }
+ return $rcon;
+ }
- public static function country($ip)
- {
- global $SxGeo;
+ public static function country($ip)
+ {
+ global $SxGeo;
- $cData = $SxGeo->getCityFull($ip);
- $ico = sys::country($cData['country']['iso']);
+ $cData = $SxGeo->getCityFull($ip);
+ $ico = sys::country($cData['country']['iso']);
- return array('ico' => $ico, 'name' => empty($cData['country']['name_ru']) ? 'Не определена' : $cData['country']['name_ru']);
- }
- }
+ return array('ico' => $ico, 'name' => empty($cData['country']['name_ru']) ? 'Не определена' : $cData['country']['name_ru']);
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/games/cssold/scan.php b/system/library/games/cssold/scan.php
index ca76ba3..aeb3bdd 100644
--- a/system/library/games/cssold/scan.php
+++ b/system/library/games/cssold/scan.php
@@ -1,140 +1,140 @@
get($nmch)))
- return $mcache->get($nmch);
+ if(is_array($mcache->get($nmch)))
+ return $mcache->get($nmch);
- $out = array();
+ $out = array();
- $info = scan::info($sq, $id);
+ $info = scan::info($sq, $id);
- $sql->query('SELECT `game`, `name`, `map`, `online`, `players`, `status`, `time`, `overdue` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `game`, `name`, `map`, `online`, `players`, `status`, `time`, `overdue` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- $out['time'] = 'Арендован до: '.date('d.m.Y - H:i', $server['time']);
+ $out['time'] = 'Арендован до: '.date('d.m.Y - H:i', $server['time']);
- if($server['status'] == 'overdue')
- $out['time_end'] = 'Удаление через: '.sys::date('min', $server['overdue']+$cfg['server_delete']*86400);
- else
- $out['time_end'] = 'Осталось: '.sys::date('min', $server['time']);
+ if($server['status'] == 'overdue')
+ $out['time_end'] = 'Удаление через: '.sys::date('min', $server['overdue']+$cfg['server_delete']*86400);
+ else
+ $out['time_end'] = 'Осталось: '.sys::date('min', $server['time']);
- if(!$info['status'])
- {
- $out['name'] = $server['name'];
- $out['status'] = sys::status($server['status'], $server['game'], $server['map']);
- $out['online'] = $server['online'];
- $out['image'] = ' ';
- $out['buttons'] = sys::buttons($id, $server['status']);
+ if(!$info['status'])
+ {
+ $out['name'] = $server['name'];
+ $out['status'] = sys::status($server['status'], $server['game'], $server['map']);
+ $out['online'] = $server['online'];
+ $out['image'] = ' ';
+ $out['buttons'] = sys::buttons($id, $server['status']);
- if($players_get)
- $out['players'] = base64_decode($server['players']);
+ if($players_get)
+ $out['players'] = base64_decode($server['players']);
- $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
+ $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
- return $out;
- }
+ return $out;
+ }
- if($players_get)
- $players = scan::info($sq, $id, true);
+ if($players_get)
+ $players = scan::info($sq, $id, true);
- $out['name'] = htmlspecialchars($info['name']);
- $out['status'] = sys::status('working', $server['game'], $info['map']);
- $out['online'] = $info['online'];
- $out['image'] = ' ';
- $out['buttons'] = sys::buttons($id, 'working');
- $out['players'] = '';
+ $out['name'] = htmlspecialchars($info['name']);
+ $out['status'] = sys::status('working', $server['game'], $info['map']);
+ $out['online'] = $info['online'];
+ $out['image'] = ' ';
+ $out['buttons'] = sys::buttons($id, 'working');
+ $out['players'] = '';
- if($players_get)
- {
- foreach($players as $index => $player)
- {
- $html->get($server['game'], 'sections/servers/players');
+ if($players_get)
+ {
+ foreach($players as $index => $player)
+ {
+ $html->get($server['game'], 'sections/servers/players');
- $html->set('i', $player['i']);
- $html->set('name', $player['name']);
- $html->set('score', $player['score']);
- $html->set('time', $player['time']);
+ $html->set('i', $player['i']);
+ $html->set('name', $player['name']);
+ $html->set('score', $player['score']);
+ $html->set('time', $player['time']);
- $html->pack('list');
- }
+ $html->pack('list');
+ }
- $out['players'] = isset($html->arr['list']) ? $html->arr['list'] : '';
- }
+ $out['players'] = isset($html->arr['list']) ? $html->arr['list'] : '';
+ }
- $sql->query('UPDATE `servers` set '
- .'`name`="'.$out['name'].'", '
- .'`online`="'.$out['online'].'", '
- .'`map`="'.$info['map'].'", '
- .'`status`="working" WHERE `id`="'.$id.'" LIMIT 1');
+ $sql->query('UPDATE `servers` set '
+ .'`name`="'.$out['name'].'", '
+ .'`online`="'.$out['online'].'", '
+ .'`map`="'.$info['map'].'", '
+ .'`status`="working" WHERE `id`="'.$id.'" LIMIT 1');
- if($players_get)
- $sql->query('UPDATE `servers` set `players`="'.base64_encode($out['players']).'" WHERE `id`="'.$id.'" LIMIT 1');
+ if($players_get)
+ $sql->query('UPDATE `servers` set `players`="'.base64_encode($out['players']).'" WHERE `id`="'.$id.'" LIMIT 1');
- $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
+ $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
- return $out;
- }
+ return $out;
+ }
- public static function info($sq, $id, $pl = false)
- {
- global $sql;
+ public static function info($sq, $id, $pl = false)
+ {
+ global $sql;
- $sql->query('SELECT `address` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `address` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- list($ip, $port) = explode(':', $server['address']);
+ list($ip, $port) = explode(':', $server['address']);
- $sq->Connect($ip, $port, 1, SourceQuery::SOURCE);
+ $sq->Connect($ip, $port, 1, SourceQuery::SOURCE);
- if($pl)
- {
- $players = $sq->GetPlayers();
+ if($pl)
+ {
+ $players = $sq->GetPlayers();
- $i = 1;
- $data = array();
+ $i = 1;
+ $data = array();
- foreach($players as $n => $player)
- {
- $data[$i]['i'] = $i;
- $data[$i]['name'] = $player['Name'] == '' ? 'Подключается' : $player['Name'];
- $data[$i]['score'] = $player['Frags'];
- $data[$i]['time'] = $player['TimeF'];
+ foreach($players as $n => $player)
+ {
+ $data[$i]['i'] = $i;
+ $data[$i]['name'] = $player['Name'] == '' ? 'Подключается' : $player['Name'];
+ $data[$i]['score'] = $player['Frags'];
+ $data[$i]['time'] = $player['TimeF'];
- $i+=1;
- }
+ $i+=1;
+ }
- return $data;
- }
+ return $data;
+ }
- $data = $sq->GetInfo();
+ $data = $sq->GetInfo();
- $server['name'] = $data['HostName'];
- $server['map'] = $data['Map'];
- $server['online'] = $data['Players'];
- $server['status'] = strlen($server['map']) > 3 ? true : false;
+ $server['name'] = $data['HostName'];
+ $server['map'] = $data['Map'];
+ $server['online'] = $data['Players'];
+ $server['status'] = strlen($server['map']) > 3 ? true : false;
- return $server;
- }
- }
+ return $server;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/games/cssold/service.php b/system/library/games/cssold/service.php
index 80cab04..1afeb43 100644
--- a/system/library/games/cssold/service.php
+++ b/system/library/games/cssold/service.php
@@ -1,378 +1,378 @@
query('SELECT `address`, `test` FROM `units` WHERE `id`="'.$aData['unit'].'" AND `cssold`="1" AND `show`="1" LIMIT 1');
- if(!$sql->num())
- sys::outjs(array('e' => 'Локация не найдена.'));
+ // Проверка локации
+ $sql->query('SELECT `address`, `test` FROM `units` WHERE `id`="'.$aData['unit'].'" AND `cssold`="1" AND `show`="1" LIMIT 1');
+ if(!$sql->num())
+ sys::outjs(array('e' => 'Локация не найдена.'));
- $unit = $sql->get();
+ $unit = $sql->get();
- // Проверка тарифа
- $sql->query('SELECT `id` FROM `tarifs` WHERE `id`="'.$aData['tarif'].'" AND `unit`="'.$aData['unit'].'" AND `show`="1" LIMIT 1');
- if(!$sql->num())
- sys::outjs(array('e' => 'Тариф не найден.'));
+ // Проверка тарифа
+ $sql->query('SELECT `id` FROM `tarifs` WHERE `id`="'.$aData['tarif'].'" AND `unit`="'.$aData['unit'].'" AND `show`="1" LIMIT 1');
+ if(!$sql->num())
+ sys::outjs(array('e' => 'Тариф не найден.'));
- $sql->query('SELECT '
- .'`slots_min`,'
- .'`slots_max`,'
- .'`port_min`,'
- .'`port_max`,'
- .'`hostname`,'
- .'`packs`,'
- .'`fps`,'
- .'`tickrate`,'
- .'`time`,'
- .'`test`,'
- .'`tests`,'
- .'`discount`,'
- .'`map`,'
- .'`ftp`,'
- .'`plugins`,'
- .'`console`,'
- .'`stats`,'
- .'`copy`,'
- .'`web`,'
- .'`plugins_install`,'
- .'`hdd`,'
- .'`autostop`,'
- .'`core_fix`,'
- .'`ip`,'
- .'`price`'
- .' FROM `tarifs` WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
+ $sql->query('SELECT '
+ .'`slots_min`,'
+ .'`slots_max`,'
+ .'`port_min`,'
+ .'`port_max`,'
+ .'`hostname`,'
+ .'`packs`,'
+ .'`fps`,'
+ .'`tickrate`,'
+ .'`time`,'
+ .'`test`,'
+ .'`tests`,'
+ .'`discount`,'
+ .'`map`,'
+ .'`ftp`,'
+ .'`plugins`,'
+ .'`console`,'
+ .'`stats`,'
+ .'`copy`,'
+ .'`web`,'
+ .'`plugins_install`,'
+ .'`hdd`,'
+ .'`autostop`,'
+ .'`core_fix`,'
+ .'`ip`,'
+ .'`price`'
+ .' FROM `tarifs` WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
- $tarif = $sql->get();
+ $tarif = $sql->get();
- // Проверка сборки
- if(!array_key_exists($aData['pack'], sys::b64djs($tarif['packs'], true)))
- sys::outjs(array('e' => 'Сборка не найдена.'));
+ // Проверка сборки
+ if(!array_key_exists($aData['pack'], sys::b64djs($tarif['packs'], true)))
+ sys::outjs(array('e' => 'Сборка не найдена.'));
- // Проверка FPS
- if(!in_array($aData['fps'], explode(':', $tarif['fps'])))
- sys::outjs(array('e' => 'Переданные данные fps неверны.'));
+ // Проверка FPS
+ if(!in_array($aData['fps'], explode(':', $tarif['fps'])))
+ sys::outjs(array('e' => 'Переданные данные fps неверны.'));
- // Проверка TickRate
- if(!in_array($aData['tickrate'], explode(':', $tarif['tickrate'])))
- sys::outjs(array('e' => 'Переданные данные tickrate неверны.'));
+ // Проверка TickRate
+ if(!in_array($aData['tickrate'], explode(':', $tarif['tickrate'])))
+ sys::outjs(array('e' => 'Переданные данные tickrate неверны.'));
- $test = 0;
+ $test = 0;
- // Проверка периода на тест
- if($aData['test'])
- {
- if(!$tarif['test'] || !$unit['test'])
- sys::outjs(array('e' => 'Тестовый период недоступен.'));
+ // Проверка периода на тест
+ if($aData['test'])
+ {
+ if(!$tarif['test'] || !$unit['test'])
+ sys::outjs(array('e' => 'Тестовый период недоступен.'));
- // Проверка на повторный запрос
- $sql->query('SELECT `id`, `game` FROM `tests` WHERE `user`="'.$user['id'].'" LIMIT 1');
- if($sql->num())
- {
- $test_info = $sql->get();
+ // Проверка на повторный запрос
+ $sql->query('SELECT `id`, `game` FROM `tests` WHERE `user`="'.$user['id'].'" LIMIT 1');
+ if($sql->num())
+ {
+ $test_info = $sql->get();
- if(!$cfg['tests']['game'] || $test_info['game'] == 'cssold')
- sys::outjs(array('e' => 'Тестовый период предоставляется один раз.'));
+ if(!$cfg['tests']['game'] || $test_info['game'] == 'cssold')
+ sys::outjs(array('e' => 'Тестовый период предоставляется один раз.'));
- $sql->query('SELECT `id` FROM `servers` WHERE `user`="'.$user['id'].'" AND `test`="1" LIMIT 1');
- if($sql->num() AND !$cfg['tests']['sametime'])
- sys::outjs(array('e' => 'Чтобы получить тестовый период другой игры, дождитесь окончания текущего.'));
- }
+ $sql->query('SELECT `id` FROM `servers` WHERE `user`="'.$user['id'].'" AND `test`="1" LIMIT 1');
+ if($sql->num() AND !$cfg['tests']['sametime'])
+ sys::outjs(array('e' => 'Чтобы получить тестовый период другой игры, дождитесь окончания текущего.'));
+ }
- // Проверка наличия мест на локации
- $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `test`="1" AND `time`>"'.$start_point.'" LIMIT '.$unit['test']);
- if($sql->num() == $unit['test'])
- sys::outjs(array('e' => 'Свободного места для тестового периода нет.'));
+ // Проверка наличия мест на локации
+ $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `test`="1" AND `time`>"'.$start_point.'" LIMIT '.$unit['test']);
+ if($sql->num() == $unit['test'])
+ sys::outjs(array('e' => 'Свободного места для тестового периода нет.'));
- // Проверка наличия мест для выбранного тарифа
- $sql->query('SELECT `id` FROM `servers` WHERE `tarif`="'.$aData['tarif'].'" AND `test`="1" AND `time`>"'.$start_point.'" LIMIT '.$tarif['tests']);
- if($sql->num() == $tarif['tests'])
- sys::outjs(array('e' => 'Свободного места для тестового периода выбранного тарифа нет.'));
+ // Проверка наличия мест для выбранного тарифа
+ $sql->query('SELECT `id` FROM `servers` WHERE `tarif`="'.$aData['tarif'].'" AND `test`="1" AND `time`>"'.$start_point.'" LIMIT '.$tarif['tests']);
+ if($sql->num() == $tarif['tests'])
+ sys::outjs(array('e' => 'Свободного места для тестового периода выбранного тарифа нет.'));
- $test = 1;
- }else
- // Проверка периода
- if(!$cfg['settlement_period'] AND !in_array($aData['time'], explode(':', $tarif['time'])))
- sys::outjs(array('e' => 'Переданные данные периода неверны.'));
+ $test = 1;
+ }else
+ // Проверка периода
+ if(!$cfg['settlement_period'] AND !in_array($aData['time'], explode(':', $tarif['time'])))
+ sys::outjs(array('e' => 'Переданные данные периода неверны.'));
- // Проверка слот
- if($aData['slots'] < $tarif['slots_min'] || $aData['slots'] > $tarif['slots_max'])
- sys::outjs(array('e' => 'Переданные данные слот неверны.'));
+ // Проверка слот
+ if($aData['slots'] < $tarif['slots_min'] || $aData['slots'] > $tarif['slots_max'])
+ sys::outjs(array('e' => 'Переданные данные слот неверны.'));
- $aPrice = sys::b64djs($tarif['price'], true);
+ $aPrice = sys::b64djs($tarif['price'], true);
- // Определение цены
- $price = $aPrice[$aData['tickrate'].'_'.$aData['fps']];
+ // Определение цены
+ $price = $aPrice[$aData['tickrate'].'_'.$aData['fps']];
- // Определение суммы
- if($cfg['settlement_period'])
- {
- // Цена аренды за расчетный период
- $sum = games::define_sum($tarif['discount'], $price, $aData['slots'], $start_point);
+ // Определение суммы
+ if($cfg['settlement_period'])
+ {
+ // Цена аренды за расчетный период
+ $sum = games::define_sum($tarif['discount'], $price, $aData['slots'], $start_point);
- $aData['time'] = games::define_period('buy', params::$aDayMonth);
- }else
- $sum = games::define_sum($tarif['discount'], $price, $aData['slots'], $aData['time']);
+ $aData['time'] = games::define_period('buy', params::$aDayMonth);
+ }else
+ $sum = games::define_sum($tarif['discount'], $price, $aData['slots'], $aData['time']);
- // Проверка промо-кода
- $promo = games::define_promo(
- $aData['promo'],
- array(
- 'tarif' => $aData['tarif'],
- 'tickrate' => $aData['tickrate'],
- 'fps' => $aData['fps'],
- 'slots' => $aData['slots'],
- 'time' => $aData['time'],
- 'user' => $user['id']
- ),
- $tarif['discount'],
- $sum
- );
+ // Проверка промо-кода
+ $promo = games::define_promo(
+ $aData['promo'],
+ array(
+ 'tarif' => $aData['tarif'],
+ 'tickrate' => $aData['tickrate'],
+ 'fps' => $aData['fps'],
+ 'slots' => $aData['slots'],
+ 'time' => $aData['time'],
+ 'user' => $user['id']
+ ),
+ $tarif['discount'],
+ $sum
+ );
- $days = $aData['time']; // Кол-во дней аренды
+ $days = $aData['time']; // Кол-во дней аренды
- // Использование промо-кода
- if(is_array($promo))
- {
- if(array_key_exists('sum', $promo))
- $sum = $promo['sum'];
- else
- $days += $promo['days']; // Кол-во дней аренды с учетом подарочных (промо-код)
- }
+ // Использование промо-кода
+ if(is_array($promo))
+ {
+ if(array_key_exists('sum', $promo))
+ $sum = $promo['sum'];
+ else
+ $days += $promo['days']; // Кол-во дней аренды с учетом подарочных (промо-код)
+ }
- // Проверка баланса
- if($user['balance'] < $sum)
- sys::outjs(array('e' => 'У вас не хватает '.(round($sum-$user['balance'], 2)).' '.$cfg['currency']));
+ // Проверка баланса
+ if($user['balance'] < $sum)
+ sys::outjs(array('e' => 'У вас не хватает '.(round($sum-$user['balance'], 2)).' '.$cfg['currency']));
- // Выделенный адрес игрового сервера
- if(!empty($tarif['ip']))
- {
- $aIp = explode(':', $tarif['ip']);
+ // Выделенный адрес игрового сервера
+ if(!empty($tarif['ip']))
+ {
+ $aIp = explode(':', $tarif['ip']);
- $ip = false;
- $port = params::$aDefPort['cssold'];
+ $ip = false;
+ $port = params::$aDefPort['cssold'];
- // Проверка наличия свободного адреса
- foreach($aIp as $adr)
- {
- $adr = trim($adr);
+ // Проверка наличия свободного адреса
+ foreach($aIp as $adr)
+ {
+ $adr = trim($adr);
- $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `address` LIKE "'.$adr.':%" LIMIT 1');
- if(!$sql->num())
- {
- $ip = $adr;
+ $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `address` LIKE "'.$adr.':%" LIMIT 1');
+ if(!$sql->num())
+ {
+ $ip = $adr;
- break;
- }
- }
- }else{
- $ip = sys::first(explode(':', $unit['address']));
- $port = false;
+ break;
+ }
+ }
+ }else{
+ $ip = sys::first(explode(':', $unit['address']));
+ $port = false;
- // Проверка наличия свободного порта
- for($tarif['port_min']; $tarif['port_min'] <= $tarif['port_max']; $tarif['port_min']+=1)
- {
- $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND (`address`="'.$ip.':'.$tarif['port_min'].'" OR `port`="'.$tarif['port_min'].'") LIMIT 1');
- if(!$sql->num())
- {
- $port = $tarif['port_min'];
+ // Проверка наличия свободного порта
+ for($tarif['port_min']; $tarif['port_min'] <= $tarif['port_max']; $tarif['port_min']+=1)
+ {
+ $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND (`address`="'.$ip.':'.$tarif['port_min'].'" OR `port`="'.$tarif['port_min'].'") LIMIT 1');
+ if(!$sql->num())
+ {
+ $port = $tarif['port_min'];
- break;
- }
- }
- }
+ break;
+ }
+ }
+ }
- if(!$ip || !$port)
- {
- $sql->query('UPDATE `tarifs` set `show`="0" WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
+ if(!$ip || !$port)
+ {
+ $sql->query('UPDATE `tarifs` set `show`="0" WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
- sys::outjs(array('e' => 'К сожалению нет доступных мест, обратитесь в тех.поддержку.'));
- }
+ sys::outjs(array('e' => 'К сожалению нет доступных мест, обратитесь в тех.поддержку.'));
+ }
- if($test)
- $aData['time'] = games::time($start_point, $tarif['test']);
- else
- $aData['time'] = games::time($start_point, $days);
+ if($test)
+ $aData['time'] = games::time($start_point, $tarif['test']);
+ else
+ $aData['time'] = games::time($start_point, $days);
- $fix_one = 0;
- $core = 0;
+ $fix_one = 0;
+ $core = 0;
- if($tarif['core_fix'] != '')
- {
- $aCore = explode(',', $tarif['core_fix']);
+ if($tarif['core_fix'] != '')
+ {
+ $aCore = explode(',', $tarif['core_fix']);
- foreach($aCore as $cpu)
- {
- $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `tarif`="'.$aData['tarif'].'" AND `core_fix`="'.$cpu.'" AND `core_fix_one`="1" LIMIT 1');
+ foreach($aCore as $cpu)
+ {
+ $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `tarif`="'.$aData['tarif'].'" AND `core_fix`="'.$cpu.'" AND `core_fix_one`="1" LIMIT 1');
- if($sql->num())
- continue;
+ if($sql->num())
+ continue;
- $fix_one = 1;
- $core = $cpu;
+ $fix_one = 1;
+ $core = $cpu;
- break;
- }
+ break;
+ }
- if(!$core)
- {
- $sql->query('UPDATE `tarifs` set `show`="0" WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
+ if(!$core)
+ {
+ $sql->query('UPDATE `tarifs` set `show`="0" WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
- sys::outjs(array('e' => 'К сожалению нет доступных мест, обратитесь в тех.поддержку.'));
- }
- }
+ sys::outjs(array('e' => 'К сожалению нет доступных мест, обратитесь в тех.поддержку.'));
+ }
+ }
- $ram = $tarif['param_fix'] ? $aData['ram'] : $cfg['ram']['cssold']*$aSDATA['slots'];
+ $ram = $tarif['param_fix'] ? $aData['ram'] : $cfg['ram']['cssold']*$aSDATA['slots'];
- // Массив данных
- $aSDATA = array(
- 'unit' => $aData['unit'], // идентификатор локации
- 'tarif' => $aData['tarif'], // идентификатор тарифа
- 'ram' => $ram, // значение ram
- 'param_fix' => $tarif['param_fix'], // фиксированные параметры
- 'tickrate' => $aData['tickrate'], // значение tickrate
- 'fps' => $aData['fps'], // значение fps
- 'pack' => $aData['pack'], // Выбранная сборка для установки
- 'time' => $aData['time'], // Время аренды
- 'days' => $days, // Число дней
- 'sum' => $sum, // Сумма списания
- 'test' => $test, // тестовый период
- 'address' => $ip.':'.$port, // адрес игрового сервера
- 'port' => $port, // порт игрового сервера
- 'slots' => $aData['slots'], // Кол-во слот
- 'map' => $tarif['map'], // Фиксированное значение слот
- 'autostop' => $tarif['autostop'], // Выключение при 0 онлайне
- 'ftp' => $tarif['ftp'], // Использование ftp
- 'plugins' => $tarif['plugins'], // Использование плагинов
- 'console' => $tarif['console'], // Использование консоли
- 'stats' => $tarif['stats'], // Использование графиков (ведение статистики)
- 'copy' => $tarif['copy'], // Использование резервных копий
- 'web' => $tarif['web'], // Использование доп услуг
- 'plugins_install' => $tarif['plugins_install'], // Список установленных плагинов
- 'hdd' => $tarif['hdd'], // Дисковое пространство
- 'core_fix' => $core, // Выделенный поток
- 'core_fix_one' => $fix_one, // Выделенный поток
- 'promo' => $promo // Использование промо-кода
- );
+ // Массив данных
+ $aSDATA = array(
+ 'unit' => $aData['unit'], // идентификатор локации
+ 'tarif' => $aData['tarif'], // идентификатор тарифа
+ 'ram' => $ram, // значение ram
+ 'param_fix' => $tarif['param_fix'], // фиксированные параметры
+ 'tickrate' => $aData['tickrate'], // значение tickrate
+ 'fps' => $aData['fps'], // значение fps
+ 'pack' => $aData['pack'], // Выбранная сборка для установки
+ 'time' => $aData['time'], // Время аренды
+ 'days' => $days, // Число дней
+ 'sum' => $sum, // Сумма списания
+ 'test' => $test, // тестовый период
+ 'address' => $ip.':'.$port, // адрес игрового сервера
+ 'port' => $port, // порт игрового сервера
+ 'slots' => $aData['slots'], // Кол-во слот
+ 'map' => $tarif['map'], // Фиксированное значение слот
+ 'autostop' => $tarif['autostop'], // Выключение при 0 онлайне
+ 'ftp' => $tarif['ftp'], // Использование ftp
+ 'plugins' => $tarif['plugins'], // Использование плагинов
+ 'console' => $tarif['console'], // Использование консоли
+ 'stats' => $tarif['stats'], // Использование графиков (ведение статистики)
+ 'copy' => $tarif['copy'], // Использование резервных копий
+ 'web' => $tarif['web'], // Использование доп услуг
+ 'plugins_install' => $tarif['plugins_install'], // Список установленных плагинов
+ 'hdd' => $tarif['hdd'], // Дисковое пространство
+ 'core_fix' => $core, // Выделенный поток
+ 'core_fix_one' => $fix_one, // Выделенный поток
+ 'promo' => $promo // Использование промо-кода
+ );
- return $aSDATA;
- }
+ return $aSDATA;
+ }
- public static function install($aSDATA = array())
- {
- global $cfg, $sql, $user, $start_point;
+ public static function install($aSDATA = array())
+ {
+ global $cfg, $sql, $user, $start_point;
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- // Массив данных локации (адрес,пароль)
- $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$aSDATA['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ // Массив данных локации (адрес,пароль)
+ $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$aSDATA['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- // Проверка ssh соединения с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- sys::outjs(array('e' => sys::text('error', 'ssh')));
+ // Проверка ssh соединения с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ sys::outjs(array('e' => sys::text('error', 'ssh')));
- // Массив данных тарифа (путь сборки,путь установки)
- $sql->query('SELECT `path`, `install`, `hostname` FROM `tarifs` WHERE `id`="'.$aSDATA['tarif'].'" LIMIT 1');
- $tarif = $sql->get();
+ // Массив данных тарифа (путь сборки,путь установки)
+ $sql->query('SELECT `path`, `install`, `hostname` FROM `tarifs` WHERE `id`="'.$aSDATA['tarif'].'" LIMIT 1');
+ $tarif = $sql->get();
- // Получение идентификаторов игрового сервера
- $sql->query('INSERT INTO `servers` set uid="1"');
- $id = $sql->id();
- $uid = $id+1000;
+ // Получение идентификаторов игрового сервера
+ $sql->query('INSERT INTO `servers` set uid="1"');
+ $id = $sql->id();
+ $uid = $id+1000;
- // Директория сборки
- $path = $tarif['path'].$aSDATA['pack'];
+ // Директория сборки
+ $path = $tarif['path'].$aSDATA['pack'];
- // Директория игрового сервера
- $install = $tarif['install'].$uid;
+ // Директория игрового сервера
+ $install = $tarif['install'].$uid;
- $ssh->set('mkdir '.$install.';' // Создание директории
- .'useradd -s /bin/false -d '.$install.' -g servers -u '.$uid.' server'.$uid.';' // Создание пользователя сервера на локации
- .'chown server'.$uid.':1000 '.$install.';' // Изменение владельца и группы директории
- .'cd '.$install.' && sudo -u server'.$uid.' screen -dmS i_'.$uid.' sh -c "cp -r '.$path.'/. .;' // Копирование файлов сборки для сервера
- .'find . -type d -exec chmod 700 {} \;;'
- .'find . -type f -exec chmod 600 {} \;;'
- .'chmod 500 '.params::$aFileGame['cssold'].'"');
+ $ssh->set('mkdir '.$install.';' // Создание директории
+ .'useradd -s /bin/false -d '.$install.' -g servers -u '.$uid.' server'.$uid.';' // Создание пользователя сервера на локации
+ .'chown server'.$uid.':1000 '.$install.';' // Изменение владельца и группы директории
+ .'cd '.$install.' && sudo -u server'.$uid.' screen -dmS i_'.$uid.' sh -c "cp -r '.$path.'/. .;' // Копирование файлов сборки для сервера
+ .'find . -type d -exec chmod 700 {} \;;'
+ .'find . -type f -exec chmod 600 {} \;;'
+ .'chmod 500 '.params::$aFileGame['cssold'].'"');
- // Запись данных нового сервера
- $sql->query('UPDATE `servers` set
- `uid`="'.$uid.'",
- `unit`="'.$aSDATA['unit'].'",
- `tarif`="'.$aSDATA['tarif'].'",
- `user`="'.$user['id'].'",
- `address`="'.$aSDATA['address'].'",
- `port`="'.$aSDATA['port'].'",
- `game`="cssold",
- `slots`="'.$aSDATA['slots'].'",
- `slots_start`="'.$aSDATA['slots'].'",
- `status`="install",
- `name`="'.$tarif['hostname'].'",
- `pack`="'.$aSDATA['pack'].'",
- `plugins_use`="'.$aSDATA['plugins'].'",
- `ftp_use`="'.$aSDATA['ftp'].'",
- `console_use`="'.$aSDATA['console'].'",
- `stats_use`="'.$aSDATA['stats'].'",
- `copy_use`="'.$aSDATA['copy'].'",
- `web_use`="'.$aSDATA['web'].'",
- `tickrate`="'.$aSDATA['tickrate'].'",
- `fps`="'.$aSDATA['fps'].'",
- `map_start`="'.$aSDATA['map'].'",
- `vac`="1",
- `hdd`="'.$aSDATA['hdd'].'",
- `time`="'.$aSDATA['time'].'",
- `date`="'.$start_point.'",
- `test`="'.$aSDATA['test'].'",
- `ram`="'.$aSDATA['ram'].'",
- `core_fix`="'.$aSDATA['core_fix'].'",
- `core_fix_one`="'.$aSDATA['core_fix_one'].'",
- `autostop`="'.$aSDATA['autostop'].'" WHERE `id`="'.$id.'" LIMIT 1');
+ // Запись данных нового сервера
+ $sql->query('UPDATE `servers` set
+ `uid`="'.$uid.'",
+ `unit`="'.$aSDATA['unit'].'",
+ `tarif`="'.$aSDATA['tarif'].'",
+ `user`="'.$user['id'].'",
+ `address`="'.$aSDATA['address'].'",
+ `port`="'.$aSDATA['port'].'",
+ `game`="cssold",
+ `slots`="'.$aSDATA['slots'].'",
+ `slots_start`="'.$aSDATA['slots'].'",
+ `status`="install",
+ `name`="'.$tarif['hostname'].'",
+ `pack`="'.$aSDATA['pack'].'",
+ `plugins_use`="'.$aSDATA['plugins'].'",
+ `ftp_use`="'.$aSDATA['ftp'].'",
+ `console_use`="'.$aSDATA['console'].'",
+ `stats_use`="'.$aSDATA['stats'].'",
+ `copy_use`="'.$aSDATA['copy'].'",
+ `web_use`="'.$aSDATA['web'].'",
+ `tickrate`="'.$aSDATA['tickrate'].'",
+ `fps`="'.$aSDATA['fps'].'",
+ `map_start`="'.$aSDATA['map'].'",
+ `vac`="1",
+ `hdd`="'.$aSDATA['hdd'].'",
+ `time`="'.$aSDATA['time'].'",
+ `date`="'.$start_point.'",
+ `test`="'.$aSDATA['test'].'",
+ `ram`="'.$aSDATA['ram'].'",
+ `core_fix`="'.$aSDATA['core_fix'].'",
+ `core_fix_one`="'.$aSDATA['core_fix_one'].'",
+ `autostop`="'.$aSDATA['autostop'].'" WHERE `id`="'.$id.'" LIMIT 1');
- // Запись установленных плагинов
- if($aSDATA['plugins'])
- {
- // Массив идентификаторов плагинов
- $aPlugins = sys::b64djs($aSDATA['plugins_install']);
+ // Запись установленных плагинов
+ if($aSDATA['plugins'])
+ {
+ // Массив идентификаторов плагинов
+ $aPlugins = sys::b64djs($aSDATA['plugins_install']);
- if(isset($aPlugins[$aSDATA['pack']]))
- {
- $plugins = explode(',', $aPlugins[$aSDATA['pack']]);
+ if(isset($aPlugins[$aSDATA['pack']]))
+ {
+ $plugins = explode(',', $aPlugins[$aSDATA['pack']]);
- foreach($plugins as $plugin)
- if($plugin)
- $sql->query('INSERT INTO `plugins_install` set `server`="'.$id.'", `plugin`="'.$plugin.'", `time`="'.$start_point.'"');
- }
- }
+ foreach($plugins as $plugin)
+ if($plugin)
+ $sql->query('INSERT INTO `plugins_install` set `server`="'.$id.'", `plugin`="'.$plugin.'", `time`="'.$start_point.'"');
+ }
+ }
- // Списание средств с баланса пользователя
- $sql->query('UPDATE `users` set `balance`="'.($user['balance']-$aSDATA['sum']).'" WHERE `id`="'.$user['id'].'" LIMIT 1');
+ // Списание средств с баланса пользователя
+ $sql->query('UPDATE `users` set `balance`="'.($user['balance']-$aSDATA['sum']).'" WHERE `id`="'.$user['id'].'" LIMIT 1');
- // Запись получения тестового периода
- if($aSDATA['test'])
- {
- $sql->query('INSERT INTO `tests` set `server`="'.$id.'", `unit`="'.$aSDATA['unit'].'", `game`="cssold", `user`="'.$user['id'].'", `time`="'.$start_point.'"');
- $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server_test'), array('id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="0"');
- }else{
- // Реф. система
- games::part($user['id'], $aSDATA['sum']);
+ // Запись получения тестового периода
+ if($aSDATA['test'])
+ {
+ $sql->query('INSERT INTO `tests` set `server`="'.$id.'", `unit`="'.$aSDATA['unit'].'", `game`="cssold", `user`="'.$user['id'].'", `time`="'.$start_point.'"');
+ $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server_test'), array('id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="0"');
+ }else{
+ // Реф. система
+ games::part($user['id'], $aSDATA['sum']);
- // Запись логов
- if(!is_array($aSDATA['promo']))
- $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server'), array('days' => games::parse_day($aSDATA['days'], true), 'money' => $aSDATA['sum'], 'id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="'.$aSDATA['sum'].'"');
- else{
- $sql->query('UPDATE `servers` set `benefit`="'.$aSDATA['time'].'" WHERE `id`="'.$id.'" LIMIT 1');
- $sql->query('INSERT INTO `promo_use` set `promo`="'.$aSDATA['promo']['id'].'", `user`="'.$user['id'].'", `time`="'.$start_point.'"');
- $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server_promo'), array('days' => games::parse_day($aSDATA['days'], true), 'money' => $aSDATA['sum'], 'promo' => $aSDATA['promo']['cod'], 'id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="'.$aSDATA['sum'].'"');
- }
- }
+ // Запись логов
+ if(!is_array($aSDATA['promo']))
+ $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server'), array('days' => games::parse_day($aSDATA['days'], true), 'money' => $aSDATA['sum'], 'id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="'.$aSDATA['sum'].'"');
+ else{
+ $sql->query('UPDATE `servers` set `benefit`="'.$aSDATA['time'].'" WHERE `id`="'.$id.'" LIMIT 1');
+ $sql->query('INSERT INTO `promo_use` set `promo`="'.$aSDATA['promo']['id'].'", `user`="'.$user['id'].'", `time`="'.$start_point.'"');
+ $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server_promo'), array('days' => games::parse_day($aSDATA['days'], true), 'money' => $aSDATA['sum'], 'promo' => $aSDATA['promo']['cod'], 'id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="'.$aSDATA['sum'].'"');
+ }
+ }
- return $id;
- }
+ return $id;
+ }
}
?>
\ No newline at end of file
diff --git a/system/library/games/cssold/tarif.php b/system/library/games/cssold/tarif.php
index c98df60..5c575f1 100644
--- a/system/library/games/cssold/tarif.php
+++ b/system/library/games/cssold/tarif.php
@@ -1,244 +1,244 @@
get('extend', 'sections/servers/games/tarif');
+ $html->get('extend', 'sections/servers/games/tarif');
- if(isset($html->arr['extend_address']))
- {
- $html->unit('extend_address', 1);
- $html->set('extend_address', $html->arr['extend_address']);
- }else
- $html->unit('extend_address');
+ if(isset($html->arr['extend_address']))
+ {
+ $html->unit('extend_address', 1);
+ $html->set('extend_address', $html->arr['extend_address']);
+ }else
+ $html->unit('extend_address');
- $html->set('id', $sid);
- $html->set('time', sys::date('min', $server['time']));
- $html->set('options', 'Выберете период продления '.$options);
- $html->set('slots', $server['slots']);
- $html->set('info', $server['tickrate'].' TickRate / '.$server['fps'].' FPS');
- $html->set('tarif', $tarif_name);
- $html->set('cur', $cfg['currency']);
+ $html->set('id', $sid);
+ $html->set('time', sys::date('min', $server['time']));
+ $html->set('options', 'Выберете период продления '.$options);
+ $html->set('slots', $server['slots']);
+ $html->set('info', $server['tickrate'].' TickRate / '.$server['fps'].' FPS');
+ $html->set('tarif', $tarif_name);
+ $html->set('cur', $cfg['currency']);
- $html->pack('main');
+ $html->pack('main');
- return NULL;
- }
+ return NULL;
+ }
public static function extend_sp($server, $tarif, $sid)
{
- global $cfg, $sql, $html, $start_point;
+ global $cfg, $sql, $html, $start_point;
- tarifs::extend_address($server['game'], $sid);
+ tarifs::extend_address($server['game'], $sid);
- $aPrice = sys::b64djs($tarif['price']);
+ $aPrice = sys::b64djs($tarif['price']);
- $sum = $tarif['slots'] ? $aPrice[$server['tickrate'].'_'.$server['fps']] : $aPrice[$server['tickrate'].'_'.$server['fps']]*$server['slots'];
+ $sum = $tarif['slots'] ? $aPrice[$server['tickrate'].'_'.$server['fps']] : $aPrice[$server['tickrate'].'_'.$server['fps']]*$server['slots'];
- $html->get('extend_sp', 'sections/servers/games/tarif');
+ $html->get('extend_sp', 'sections/servers/games/tarif');
- if(isset($html->arr['extend_address']))
- {
- $html->unit('extend_address', 1);
- $html->set('extend_address', $html->arr['extend_address']);
- }else
- $html->unit('extend_address');
+ if(isset($html->arr['extend_address']))
+ {
+ $html->unit('extend_address', 1);
+ $html->set('extend_address', $html->arr['extend_address']);
+ }else
+ $html->unit('extend_address');
- $html->set('id', $sid);
- $html->set('time', sys::date('min', $server['time']));
- $html->set('date', $server['time'] > $start_point ? 'Сервер продлен до: '.date('d.m.Y', $server['time']) : 'Текущая дата: '.date('d.m.Y', $start_point));
- $html->set('options', 'Выберете период продления '.$options);
- $html->set('slots', $server['slots']);
- $html->set('info', $server['tickrate'].' TickRate / '.$server['fps'].' FPS');
- $html->set('tarif', $tarif['name']);
- $html->set('sum', $sum);
- $html->set('cur', $cfg['currency']);
+ $html->set('id', $sid);
+ $html->set('time', sys::date('min', $server['time']));
+ $html->set('date', $server['time'] > $start_point ? 'Сервер продлен до: '.date('d.m.Y', $server['time']) : 'Текущая дата: '.date('d.m.Y', $start_point));
+ $html->set('options', 'Выберете период продления '.$options);
+ $html->set('slots', $server['slots']);
+ $html->set('info', $server['tickrate'].' TickRate / '.$server['fps'].' FPS');
+ $html->set('tarif', $tarif['name']);
+ $html->set('sum', $sum);
+ $html->set('cur', $cfg['currency']);
- $html->pack('main');
+ $html->pack('main');
- return NULL;
- }
+ return NULL;
+ }
public static function plan($server, $tarif_name, $sid)
{
- global $cfg, $sql, $html;
+ global $cfg, $sql, $html;
- $sql->query('SELECT `fps`, `tickrate`, `price` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
+ $sql->query('SELECT `fps`, `tickrate`, `price` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
- if(!$sql->num())
- return NULL;
+ if(!$sql->num())
+ return NULL;
- $tarif = $sql->get();
+ $tarif = $sql->get();
- $options = '';
+ $options = '';
- $aPrice = sys::b64djs($tarif['price']);
+ $aPrice = sys::b64djs($tarif['price']);
- unset($aPrice[$server['tickrate'].'_'.$server['fps']]);
+ unset($aPrice[$server['tickrate'].'_'.$server['fps']]);
- foreach($aPrice as $param => $price)
- {
- list($tickrate, $fps) = explode('_', $param);
+ foreach($aPrice as $param => $price)
+ {
+ list($tickrate, $fps) = explode('_', $param);
- $options .= ''
- .$tickrate.' TickRate / '
- .$fps.' FPS '
- .'('.$price.' '.$cfg['currency'].'/слот | '
- .($price*$server['slots']).' '.$cfg['currency'].'/месяц)'
- .' ';
- }
+ $options .= ''
+ .$tickrate.' TickRate / '
+ .$fps.' FPS '
+ .'('.$price.' '.$cfg['currency'].'/слот | '
+ .($price*$server['slots']).' '.$cfg['currency'].'/месяц)'
+ .' ';
+ }
- if($options == '')
- return NULL;
+ if($options == '')
+ return NULL;
- $html->get('plan', 'sections/servers/games/tarif');
+ $html->get('plan', 'sections/servers/games/tarif');
- $html->set('id', $sid);
- $html->set('options', 'Выберете тарифный план '.$options);
- $html->set('info', $server['tickrate'].' TickRate / '.$server['fps'].' FPS');
- $html->set('tarif', $tarif_name);
+ $html->set('id', $sid);
+ $html->set('options', 'Выберете тарифный план '.$options);
+ $html->set('info', $server['tickrate'].' TickRate / '.$server['fps'].' FPS');
+ $html->set('tarif', $tarif_name);
- $html->pack('main');
+ $html->pack('main');
- return NULL;
- }
+ return NULL;
+ }
- public static function unit($server, $unit_name, $tarif_name, $sid)
+ public static function unit($server, $unit_name, $tarif_name, $sid)
{
- global $cfg, $sql, $html;
+ global $cfg, $sql, $html;
- if(!$cfg['change_unit'][$server['game']])
- return NULL;
+ if(!$cfg['change_unit'][$server['game']])
+ return NULL;
- $tarifs = $sql->query('SELECT `unit`, `fps`, `tickrate`, `price` FROM `tarifs` WHERE `game`="'.$server['game'].'" AND `name`="'.$tarif_name.'" AND `id`!="'.$server['tarif'].'" AND `show`="1" ORDER BY `unit`');
- if(!$sql->num($tarifs))
- return NULL;
+ $tarifs = $sql->query('SELECT `unit`, `fps`, `tickrate`, `price` FROM `tarifs` WHERE `game`="'.$server['game'].'" AND `name`="'.$tarif_name.'" AND `id`!="'.$server['tarif'].'" AND `show`="1" ORDER BY `unit`');
+ if(!$sql->num($tarifs))
+ return NULL;
- $units = 0;
+ $units = 0;
- $options = 'Выберете новую локацию ';
+ $options = 'Выберете новую локацию ';
- while($tarif = $sql->get($tarifs))
- {
- if(!array_key_exists($server['tickrate'].'_'.$server['fps'], sys::b64djs($tarif['price'])))
- continue;
+ while($tarif = $sql->get($tarifs))
+ {
+ if(!array_key_exists($server['tickrate'].'_'.$server['fps'], sys::b64djs($tarif['price'])))
+ continue;
- $sql->query('SELECT `id`, `name` FROM `units` WHERE `id`="'.$tarif['unit'].'" AND `show`="1" LIMIT 1');
- if(!$sql->num())
- continue;
+ $sql->query('SELECT `id`, `name` FROM `units` WHERE `id`="'.$tarif['unit'].'" AND `show`="1" LIMIT 1');
+ if(!$sql->num())
+ continue;
- $unit = $sql->get();
+ $unit = $sql->get();
- $options .= ''.$unit['name'].' ';
+ $options .= ''.$unit['name'].' ';
- $units+=1;
- }
+ $units+=1;
+ }
- if(!$units)
- return NULL;
+ if(!$units)
+ return NULL;
- $html->get('unit', 'sections/servers/games/tarif');
+ $html->get('unit', 'sections/servers/games/tarif');
- $html->set('id', $sid);
- $html->set('options', $options);
- $html->set('slots', $server['slots']);
- $html->set('info', $server['tickrate'].' TickRate / '.$server['fps'].' FPS');
- $html->set('unit', $unit_name);
- $html->set('tarif', $tarif_name);
+ $html->set('id', $sid);
+ $html->set('options', $options);
+ $html->set('slots', $server['slots']);
+ $html->set('info', $server['tickrate'].' TickRate / '.$server['fps'].' FPS');
+ $html->set('unit', $unit_name);
+ $html->set('tarif', $tarif_name);
- $html->pack('main');
+ $html->pack('main');
- return NULL;
- }
+ return NULL;
+ }
- public static function unit_new($tarif, $unit, $server, $mcache)
- {
- global $ssh, $sql, $user, $start_point;
+ public static function unit_new($tarif, $unit, $server, $mcache)
+ {
+ global $ssh, $sql, $user, $start_point;
- // Проверка ssh соединения с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- sys::outjs(array('e' => sys::text('error', 'ssh')));
+ // Проверка ssh соединения с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ sys::outjs(array('e' => sys::text('error', 'ssh')));
- // Директория сборки
- $path = $tarif['path'].$tarif['pack'];
+ // Директория сборки
+ $path = $tarif['path'].$tarif['pack'];
- // Директория игрового сервера
- $install = $tarif['install'].$server['uid'];
+ // Директория игрового сервера
+ $install = $tarif['install'].$server['uid'];
- // Пользователь сервера
- $uS = 'server'.$server['uid'];
+ // Пользователь сервера
+ $uS = 'server'.$server['uid'];
- $ssh->set('mkdir '.$install.';' // Создание директории
- .'useradd -d '.$install.' -g servers -u '.$server['uid'].' '.$uS.';' // Создание пользователя сервера на локации
- .'chown '.$uS.':1000 '.$install.';' // Изменение владельца и группы директории
- .'cd '.$install.' && sudo -u '.$uS.' screen -dmS i_'.$server['uid'].' cp -r '.$path.'/. .'); // Копирование файлов сборки для сервера
+ $ssh->set('mkdir '.$install.';' // Создание директории
+ .'useradd -d '.$install.' -g servers -u '.$server['uid'].' '.$uS.';' // Создание пользователя сервера на локации
+ .'chown '.$uS.':1000 '.$install.';' // Изменение владельца и группы директории
+ .'cd '.$install.' && sudo -u '.$uS.' screen -dmS i_'.$server['uid'].' cp -r '.$path.'/. .'); // Копирование файлов сборки для сервера
- $address = explode(':', $server['address']);
+ $address = explode(':', $server['address']);
- $fix_one = $tarif['core_fix'] ? 1 : 0;
+ $fix_one = $tarif['core_fix'] ? 1 : 0;
- // Обновление данных нового сервера
- $sql->query('UPDATE `servers` set
- `unit`="'.$tarif['unit'].'",
- `tarif`="'.$tarif['id'].'",
- `address`="'.$server['address'].'",
- `port`="'.$address[1].'",
- `status`="install",
- `name`="'.$tarif['hostname'].'",
- `pack`="'.$tarif['pack'].'",
- `map_start`="'.$tarif['map'].'",
- `vac`="1",
- `hdd`="'.$tarif['hdd'].'",
- `time`="'.$tarif['time'].'",
- `autostop`="'.$tarif['autostop'].'",
- `core_fix`="'.$tarif['core_fix'].'",
- `core_fix_one`="'.$fix_one.'",
- `reinstall`="'.$start_point.'" WHERE `id`="'.$server['id'].'" LIMIT 1');
+ // Обновление данных нового сервера
+ $sql->query('UPDATE `servers` set
+ `unit`="'.$tarif['unit'].'",
+ `tarif`="'.$tarif['id'].'",
+ `address`="'.$server['address'].'",
+ `port`="'.$address[1].'",
+ `status`="install",
+ `name`="'.$tarif['hostname'].'",
+ `pack`="'.$tarif['pack'].'",
+ `map_start`="'.$tarif['map'].'",
+ `vac`="1",
+ `hdd`="'.$tarif['hdd'].'",
+ `time`="'.$tarif['time'].'",
+ `autostop`="'.$tarif['autostop'].'",
+ `core_fix`="'.$tarif['core_fix'].'",
+ `core_fix_one`="'.$fix_one.'",
+ `reinstall`="'.$start_point.'" WHERE `id`="'.$server['id'].'" LIMIT 1');
- // Запись установленных плагинов
- if($tarif['plugins'])
- {
- // Массив идентификаторов плагинов
- $aPlugins = sys::b64js($tarif['plugins_install']);
+ // Запись установленных плагинов
+ if($tarif['plugins'])
+ {
+ // Массив идентификаторов плагинов
+ $aPlugins = sys::b64js($tarif['plugins_install']);
- if(isset($aPlugins[$tarif['pack']]))
- {
- $plugins = explode(',', $aPlugins[$tarif['pack']]);
+ if(isset($aPlugins[$tarif['pack']]))
+ {
+ $plugins = explode(',', $aPlugins[$tarif['pack']]);
- foreach($plugins as $plugin)
- if($plugin)
- $sql->query('INSERT INTO `plugins_install` set `server`="'.$server['id'].'", `plugin`="'.$plugin.'", `time`="'.$start_point.'"');
- }
- }
+ foreach($plugins as $plugin)
+ if($plugin)
+ $sql->query('INSERT INTO `plugins_install` set `server`="'.$server['id'].'", `plugin`="'.$plugin.'", `time`="'.$start_point.'"');
+ }
+ }
- return NULL;
- }
+ return NULL;
+ }
- public static function price($plan)
- {
- $aPrice = array_values(sys::b64djs($plan));
+ public static function price($plan)
+ {
+ $aPrice = array_values(sys::b64djs($plan));
- $check = $aPrice[0];
+ $check = $aPrice[0];
- unset($aPrice[0]);
+ unset($aPrice[0]);
- if(!count($aPrice))
- return false;
+ if(!count($aPrice))
+ return false;
- foreach($aPrice as $price)
- {
- if($check != $price)
- return true;
- }
+ foreach($aPrice as $price)
+ {
+ if($check != $price)
+ return true;
+ }
- return false;
- }
+ return false;
+ }
}
?>
\ No newline at end of file
diff --git a/system/library/games/games.php b/system/library/games/games.php
index aa7bbc3..a105683 100644
--- a/system/library/games/games.php
+++ b/system/library/games/games.php
@@ -1,810 +1,810 @@
'устанавливается',
- 'reinstall' => 'переустанавливается',
- 'update' => 'обновляется',
- 'recovery' => 'восстанавливается',
- 'overdue' => 'не оплачен',
- 'blocked' => 'заблокирован'
- );
-
- $msg = sys::updtext(sys::text('servers', 'determine'), array('status' => $aText[$status]));
-
- if($go)
- sys::out($msg);
-
- $html->get('informer');
-
- $html->set('[class]', 'info_red');
- $html->set('[text]', $msg);
-
- $html->pack($tpl);
-
- return false;
- }
-
- public static function crontab_week($week)
- {
- $aWeek = array();
- $aWeek[1] = isset($week['\'1\'']) ? 'Пн., ' : '';
- $aWeek[2] = isset($week['\'2\'']) ? 'Вт., ' : '';
- $aWeek[3] = isset($week['\'3\'']) ? 'Ср., ' : '';
- $aWeek[4] = isset($week['\'4\'']) ? 'Чт., ' : '';
- $aWeek[5] = isset($week['\'5\'']) ? 'Пт., ' : '';
- $aWeek[6] = isset($week['\'6\'']) ? 'Сб., ' : '';
- $aWeek[7] = isset($week['\'7\'']) ? 'Вс., ' : '';
-
- $days = '';
-
- foreach($aWeek as $index => $val)
- {
- if($val == '')
- continue;
-
- $days .= $val;
- }
-
- $days = substr($days, 0, -2);
-
- if($days == '')
- $days = 'Пн., Вт., Ср., Чт., Пт., Сб., Вс.';
-
- return $days;
- }
-
- public static function crontab_time($allhour, $hour, $minute)
- {
- if($allhour)
- return 'Каждый час';
-
- $aHour = array(
- '00', '01', '02',
- '03', '04', '05',
- '06', '07', '08',
- '09', '10', '11',
- '12', '13', '14',
- '15', '16', '17',
- '18', '19', '20',
- '21', '22', '23'
- );
-
- $aMinute = array(
- '00', '05', '10',
- '15', '20', '25',
- '30', '35', '40',
- '45', '50', '55'
- );
-
- if(!in_array($hour, $aHour))
- $hour = '00';
-
- if(!in_array($minute, $aMinute))
- $minute = '00';
+ return $cfg['url'].'template/images/country/none.png';
+ }
+
+ public static function determine($status, $go = false, $tpl = 'content')
+ {
+ global $html, $text;
+
+ if(!in_array($status, array('install', 'reinstall', 'update', 'recovery', 'overdue', 'blocked')))
+ return true;
+
+ $aText = array(
+ 'install' => 'устанавливается',
+ 'reinstall' => 'переустанавливается',
+ 'update' => 'обновляется',
+ 'recovery' => 'восстанавливается',
+ 'overdue' => 'не оплачен',
+ 'blocked' => 'заблокирован'
+ );
+
+ $msg = sys::updtext(sys::text('servers', 'determine'), array('status' => $aText[$status]));
+
+ if($go)
+ sys::out($msg);
+
+ $html->get('informer');
+
+ $html->set('[class]', 'info_red');
+ $html->set('[text]', $msg);
+
+ $html->pack($tpl);
+
+ return false;
+ }
+
+ public static function crontab_week($week)
+ {
+ $aWeek = array();
+ $aWeek[1] = isset($week['\'1\'']) ? 'Пн., ' : '';
+ $aWeek[2] = isset($week['\'2\'']) ? 'Вт., ' : '';
+ $aWeek[3] = isset($week['\'3\'']) ? 'Ср., ' : '';
+ $aWeek[4] = isset($week['\'4\'']) ? 'Чт., ' : '';
+ $aWeek[5] = isset($week['\'5\'']) ? 'Пт., ' : '';
+ $aWeek[6] = isset($week['\'6\'']) ? 'Сб., ' : '';
+ $aWeek[7] = isset($week['\'7\'']) ? 'Вс., ' : '';
+
+ $days = '';
+
+ foreach($aWeek as $index => $val)
+ {
+ if($val == '')
+ continue;
+
+ $days .= $val;
+ }
+
+ $days = substr($days, 0, -2);
+
+ if($days == '')
+ $days = 'Пн., Вт., Ср., Чт., Пт., Сб., Вс.';
+
+ return $days;
+ }
+
+ public static function crontab_time($allhour, $hour, $minute)
+ {
+ if($allhour)
+ return 'Каждый час';
+
+ $aHour = array(
+ '00', '01', '02',
+ '03', '04', '05',
+ '06', '07', '08',
+ '09', '10', '11',
+ '12', '13', '14',
+ '15', '16', '17',
+ '18', '19', '20',
+ '21', '22', '23'
+ );
+
+ $aMinute = array(
+ '00', '05', '10',
+ '15', '20', '25',
+ '30', '35', '40',
+ '45', '50', '55'
+ );
+
+ if(!in_array($hour, $aHour))
+ $hour = '00';
+
+ if(!in_array($minute, $aMinute))
+ $minute = '00';
- return $hour.':'.$minute;
- }
-
- public static function crontab($id, $cid, $data = array())
- {
- global $cfg;
-
- if($data['allhour'])
- $time = '0 * * * ';
- else{
- $hour = array(
- '00', '01', '02',
- '03', '04', '05',
- '06', '07', '08',
- '09', '10', '11',
- '12', '13', '14',
- '15', '16', '17',
- '18', '19', '20',
- '21', '22', '23'
- );
-
- $minute = array(
- '00', '05', '10',
- '15', '20', '25',
- '30', '35', '40',
- '45', '50', '55'
- );
+ return $hour.':'.$minute;
+ }
+
+ public static function crontab($id, $cid, $data = array())
+ {
+ global $cfg;
+
+ if($data['allhour'])
+ $time = '0 * * * ';
+ else{
+ $hour = array(
+ '00', '01', '02',
+ '03', '04', '05',
+ '06', '07', '08',
+ '09', '10', '11',
+ '12', '13', '14',
+ '15', '16', '17',
+ '18', '19', '20',
+ '21', '22', '23'
+ );
+
+ $minute = array(
+ '00', '05', '10',
+ '15', '20', '25',
+ '30', '35', '40',
+ '45', '50', '55'
+ );
- if(!in_array($data['hour'], $hour))
- $data['hour'] = '00';
+ if(!in_array($data['hour'], $hour))
+ $data['hour'] = '00';
- if(!in_array($data['minute'], $minute))
- $data['minute'] = '00';
-
- $time = $data['minute'].' '.$data['hour'].' * * ';
- }
-
- $week = array();
- $week[1] = isset($data['week']['\'1\'']) ? 1 : 0;
- $week[2] = isset($data['week']['\'2\'']) ? 2 : 0;
- $week[3] = isset($data['week']['\'3\'']) ? 3 : 0;
- $week[4] = isset($data['week']['\'4\'']) ? 4 : 0;
- $week[5] = isset($data['week']['\'5\'']) ? 5 : 0;
- $week[6] = isset($data['week']['\'6\'']) ? 6 : 0;
- $week[7] = isset($data['week']['\'7\'']) ? 7 : 0;
-
- $check = 0;
+ if(!in_array($data['minute'], $minute))
+ $data['minute'] = '00';
+
+ $time = $data['minute'].' '.$data['hour'].' * * ';
+ }
+
+ $week = array();
+ $week[1] = isset($data['week']['\'1\'']) ? 1 : 0;
+ $week[2] = isset($data['week']['\'2\'']) ? 2 : 0;
+ $week[3] = isset($data['week']['\'3\'']) ? 3 : 0;
+ $week[4] = isset($data['week']['\'4\'']) ? 4 : 0;
+ $week[5] = isset($data['week']['\'5\'']) ? 5 : 0;
+ $week[6] = isset($data['week']['\'6\'']) ? 6 : 0;
+ $week[7] = isset($data['week']['\'7\'']) ? 7 : 0;
+
+ $check = 0;
- foreach($week as $index => $val)
- $check+= $val;
+ foreach($week as $index => $val)
+ $check+= $val;
- if($check == 28 || !$check)
- $week = '*';
- else{
- $weeks = $week[1].','.$week[2].','.$week[3].','.$week[4].','.$week[5].','.$week[6].','.$week[7];
- $weeks = str_replace(array(',0', '0'), '', $weeks);
- $week = $weeks[0] == ',' ? substr($weeks, 1) : $weeks;
- }
+ if($check == 28 || !$check)
+ $week = '*';
+ else{
+ $weeks = $week[1].','.$week[2].','.$week[3].','.$week[4].','.$week[5].','.$week[6].','.$week[7];
+ $weeks = str_replace(array(',0', '0'), '', $weeks);
+ $week = $weeks[0] == ',' ? substr($weeks, 1) : $weeks;
+ }
- $cron_task = $time.$week.' screen -dmS s'.$id.' bash -c \'cd /var/enginegp && php cron.php '.$cfg['cron_key'].' server_cron '.$id.' '.$cid.'\'';
-
- return $cron_task;
- }
-
- public static function parse_tarif($aTarif = array(), $aUnit = array())
- {
- global $cfg, $mcache;
-
- $nmch = 'parse_tarif_'.$aTarif['id'];
-
- $cache = $mcache->get($nmch);
-
- if(is_array($cache))
- return $cache;
-
- if(isset($aTarif['fps']))
- $aFPS = explode(':', $aTarif['fps']);
-
- if(isset($aTarif['tickrate']))
- $aTICKRATE = explode(':', $aTarif['tickrate']);
-
- if(isset($aTarif['ram']))
- $aRAM = explode(':', $aTarif['ram']);
-
- $fps = '';
-
- if(isset($aFPS))
- foreach($aFPS as $value)
- $fps .= ''.$value.' FPS ';
-
- $tickrate = '';
+ $cron_task = $time.$week.' screen -dmS s'.$id.' bash -c \'cd /var/enginegp && php cron.php '.$cfg['cron_key'].' server_cron '.$id.' '.$cid.'\'';
+
+ return $cron_task;
+ }
+
+ public static function parse_tarif($aTarif = array(), $aUnit = array())
+ {
+ global $cfg, $mcache;
+
+ $nmch = 'parse_tarif_'.$aTarif['id'];
+
+ $cache = $mcache->get($nmch);
+
+ if(is_array($cache))
+ return $cache;
+
+ if(isset($aTarif['fps']))
+ $aFPS = explode(':', $aTarif['fps']);
+
+ if(isset($aTarif['tickrate']))
+ $aTICKRATE = explode(':', $aTarif['tickrate']);
+
+ if(isset($aTarif['ram']))
+ $aRAM = explode(':', $aTarif['ram']);
+
+ $fps = '';
+
+ if(isset($aFPS))
+ foreach($aFPS as $value)
+ $fps .= ''.$value.' FPS ';
+
+ $tickrate = '';
- if(isset($aTICKRATE))
- foreach($aTICKRATE as $value)
- $tickrate .= ''.$value.' TickRate ';
+ if(isset($aTICKRATE))
+ foreach($aTICKRATE as $value)
+ $tickrate .= ''.$value.' TickRate ';
- $ram = '';
-
- if(isset($aRAM))
- {
- if($aTarif['param_fix'])
- foreach($aRAM as $value)
- $ram .= ''.$value.' Ram ';
- else
- foreach($aRAM as $value)
- $ram .= ''.$value.' Ram/Слот ';
- }
-
- $packs = '';
- $aPack = sys::b64djs($aTarif['packs'], true);
+ $ram = '';
+
+ if(isset($aRAM))
+ {
+ if($aTarif['param_fix'])
+ foreach($aRAM as $value)
+ $ram .= ''.$value.' Ram ';
+ else
+ foreach($aRAM as $value)
+ $ram .= ''.$value.' Ram/Слот ';
+ }
+
+ $packs = '';
+ $aPack = sys::b64djs($aTarif['packs'], true);
- if(is_array($aPack))
- foreach($aPack as $index => $name)
- $packs .= ''.$name.' ';
+ if(is_array($aPack))
+ foreach($aPack as $index => $name)
+ $packs .= ''.$name.' ';
- $slots = '';
+ $slots = '';
- for($i = $aTarif['slots_min']; $i <= $aTarif['slots_max']; $i+=1)
- $slots .= ''.$i.' шт. ';
+ for($i = $aTarif['slots_min']; $i <= $aTarif['slots_max']; $i+=1)
+ $slots .= ''.$i.' шт. ';
- $aTime = explode(':', $aTarif['time']);
+ $aTime = explode(':', $aTarif['time']);
- $time = games::parse_time($aTime, $aTarif['discount'], $aTarif['id']);
+ $time = games::parse_time($aTime, $aTarif['discount'], $aTarif['id']);
- if($aTarif['test'] AND $aUnit['test'])
- $time .= 'Тестовый период '.games::parse_day($aTarif['test']).' ';
+ if($aTarif['test'] AND $aUnit['test'])
+ $time .= 'Тестовый период '.games::parse_day($aTarif['test']).' ';
- $data = array(
- 'packs' => $packs,
- 'slots' => $slots,
- 'time' => $time,
- 'fps' => $fps,
- 'tickrate' => $tickrate,
- 'ram' => $ram
- );
+ $data = array(
+ 'packs' => $packs,
+ 'slots' => $slots,
+ 'time' => $time,
+ 'fps' => $fps,
+ 'tickrate' => $tickrate,
+ 'ram' => $ram
+ );
- $mcache->set($nmch, $data, false, 60);
-
- return $data;
- }
+ $mcache->set($nmch, $data, false, 60);
+
+ return $data;
+ }
- public static function parse_time($aTime, $discount, $tarif, $type = 'buy')
- {
- global $cfg;
+ public static function parse_time($aTime, $discount, $tarif, $type = 'buy')
+ {
+ global $cfg;
- $time = '';
+ $time = '';
- $arr = isset(params::$disconunt['service'][$tarif]) ? $tarif : 'time';
+ $arr = isset(params::$disconunt['service'][$tarif]) ? $tarif : 'time';
- foreach($aTime as $value)
- {
- if(array_key_exists($value, params::$disconunt['service'][$arr][$type]) AND $discount)
- {
- $data = explode(':', params::$disconunt['service'][$arr][$type][$value]);
+ foreach($aTime as $value)
+ {
+ if(array_key_exists($value, params::$disconunt['service'][$arr][$type]) AND $discount)
+ {
+ $data = explode(':', params::$disconunt['service'][$arr][$type][$value]);
- // Если наценка
- if($data[0] == '+')
- {
- // Если значение в процентах
- if(substr($data[1], -1) == '%')
- $time .= ''.games::parse_day($value).' (Наценка '.$data[1].') ';
- else
- $time .= ''.games::parse_day($value).' (Наценка '.sys::int($data[1]).' '.$cfg['currency'].') ';
- }else{
- // Если значение в процентах
- if(substr($data[1], -1) == '%')
- $time .= ''.games::parse_day($value).' (Скидка '.$data[1].') ';
- else
- $time .= ''.games::parse_day($value).' (Скидка '.sys::int($data[1]).' '.$cfg['currency'].') ';
- }
- }else
- $time .= ''.games::parse_day($value).' ';
- }
+ // Если наценка
+ if($data[0] == '+')
+ {
+ // Если значение в процентах
+ if(substr($data[1], -1) == '%')
+ $time .= ''.games::parse_day($value).' (Наценка '.$data[1].') ';
+ else
+ $time .= ''.games::parse_day($value).' (Наценка '.sys::int($data[1]).' '.$cfg['currency'].') ';
+ }else{
+ // Если значение в процентах
+ if(substr($data[1], -1) == '%')
+ $time .= ''.games::parse_day($value).' (Скидка '.$data[1].') ';
+ else
+ $time .= ''.games::parse_day($value).' (Скидка '.sys::int($data[1]).' '.$cfg['currency'].') ';
+ }
+ }else
+ $time .= ''.games::parse_day($value).' ';
+ }
- return $time;
- }
+ return $time;
+ }
- public static function define_period($type, $aD_M, $time = 0)
- {
- global $start_point;
+ public static function define_period($type, $aD_M, $time = 0)
+ {
+ global $start_point;
- if($time < $start_point)
- $time = $start_point;
+ if($time < $start_point)
+ $time = $start_point;
- $day = $type == 'extend' ? date('d', $time) : date('d', $start_point);
- $month = $type == 'extend' ? date('n', $time) : date('n', $start_point);
-
- $period = $aD_M[$month]-$day;
+ $day = $type == 'extend' ? date('d', $time) : date('d', $start_point);
+ $month = $type == 'extend' ? date('n', $time) : date('n', $start_point);
+
+ $period = $aD_M[$month]-$day;
- if($day > 15)
- $period += $month != 12 ? $aD_M[$month+1] : $aD_M[1];
-
- return $period+1;
- }
-
- public static function define_sum($discount, $price, $slots, $time, $type = 'buy')
- {
- global $sql, $user, $cfg, $start_point;
-
- if($cfg['settlement_period'])
- {
- if($time < $start_point)
- $time = $start_point;
-
- $day = $type == 'extend' ? date('d', $time) : date('d', $start_point);
- $month = $type == 'extend' ? date('n', $time) : date('n', $start_point);
+ if($day > 15)
+ $period += $month != 12 ? $aD_M[$month+1] : $aD_M[1];
+
+ return $period+1;
+ }
+
+ public static function define_sum($discount, $price, $slots, $time, $type = 'buy')
+ {
+ global $sql, $user, $cfg, $start_point;
+
+ if($cfg['settlement_period'])
+ {
+ if($time < $start_point)
+ $time = $start_point;
+
+ $day = $type == 'extend' ? date('d', $time) : date('d', $start_point);
+ $month = $type == 'extend' ? date('n', $time) : date('n', $start_point);
- $period = params::$aDayMonth[$month]+1-$day;
-
- $new_month_sum = 0;
-
- if($day > 15)
- $new_month_sum = ceil($price*$slots);
-
- $sum = params::$aDayMonth[$month] == $period ? $price*$slots : floor($price*$slots/30*$period)+$new_month_sum;
- }else{
- $sum = floor($price*$slots/30*$time);
-
- if(array_key_exists($time, params::$disconunt['service']['time'][$type]) AND $discount)
- {
- $data = explode(':', params::$disconunt['service']['time'][$type][$time]);
-
- // Если наценка
- if($data[0] == '+')
- {
- // Если значение в процентах
- if(substr($data[1], -1) == '%')
- $sum = ceil($sum+$sum/100*intval($data[1]));
- else
- $sum = $sum+intval($data[1]);
- }else{
- // Если значение в процентах
- if(substr($data[1], -1) == '%')
- $sum = ceil($sum-$sum/100*intval($data[1]));
- else
- $sum = $sum-intval($data[1]);
- }
- }
- }
-
- $sel = $type == 'buy' ? 'rental' : 'extend';
-
- $sql->query('SELECT `'.$sel.'` FROM `users` WHERE `id`="'.$user['id'].'" LIMIT 1');
- $user = array_merge($user, $sql->get());
-
- $sum = strpos($user[$sel], '%') ? $sum-$sum/100*$user[$sel] : $sum-$user[$sel];
-
- if($sum < 0)
- sys::outjs(array('e' => 'Ошибка: сумма за услугу неверна'));
-
- return $sum;
- }
-
- public static function define_promo($cod, $data, $discount, $sum, $type = 'buy')
- {
- global $cfg, $sql, $go, $start_point;
-
- // Проверка формата кода
- if(sys::valid($cod, 'promo'))
- {
- if(!$go)
- sys::outjs(array('e' => 'Промо-код имеет неверный формат.'));
-
- return NULL;
- }
-
- $sql->query('SELECT `id`, `value`, `discount`, `data`, `hits`, `use`, `extend`, `user`, `server` FROM `promo` WHERE `cod`="'.$cod.'" AND `tarif`="'.$data['tarif'].'" AND `time`>"'.$start_point.'" LIMIT 1');
-
- // Проверка наличия промо-кода
- if(!$sql->num())
- {
- if(!$go)
- sys::outjs(array('e' => 'Промо-код не найден.'));
-
- return NULL;
- }
-
- $promo = $sql->get();
-
- // Проверка типа при аренде
- if($type == 'buy' AND $promo['extend'])
- {
- if(!$go)
- sys::outjs(array('e' => 'Промо-код для продления игрового сервера.'));
-
- return NULL;
- }
-
- // Проверка типа при продлении
- if($type != 'buy' AND !$promo['extend'])
- {
- if(!$go)
- sys::outjs(array('e' => 'Промо-код для аренды нового игрового сервера.'));
-
- return NULL;
- }
-
- // Проверка доступности на пользователя
- if($promo['user'] AND $data['user'] != $promo['user'])
- {
- if(!$go)
- sys::outjs(array('e' => 'Промо-код не найден.'));
-
- return NULL;
- }
-
- // Проверка доступности на сервер
- if($promo['server'] AND $data['server'] != $promo['server'])
- {
- if(!$go)
- sys::outjs(array('e' => 'Промо-код не найден.'));
-
- return NULL;
- }
-
- $use = $promo['use'] < 1 ? '1' : $promo['use'];
-
- // Проверка доступности
- $sql->query('SELECT `id` FROM `promo_use` WHERE `promo`="'.$promo['id'].'" LIMIT '.$use);
- if($sql->num() >= $promo['use'])
- {
- if(!$go)
- sys::outjs(array('e' => 'Промо-код использован максимальное количество раз.'));
-
- return NULL;
- }
-
- // Данные для сравнения
- $data_promo = sys::b64djs($promo['data'], true);
-
- $check = 0;
-
- // Проверка периода
- if(in_array($data['time'], explode(':', $data_promo['time'])))
- $check = 1;
-
- // Проверка значения FPS
- if((isset($data['fps']) AND isset($data_promo['fps'])) AND in_array($data['fps'], explode(':', $data_promo['fps'])))
- $check+= 1;
-
- // Проверка значения TICKRATE
- if((isset($data['tickrate']) AND isset($data_promo['tickrate'])) AND in_array($data['tickrate'], explode(':', $data_promo['tickrate'])))
- $check+= 1;
-
- // Проверка значения RAM
- if((isset($data['ram']) AND isset($data_promo['ram'])) AND in_array($data['ram'], explode(':', $data_promo['ram'])))
- $check+= 1;
-
- // Проверка кол-ва слот
- if(isset($data_promo['slots']))
- {
- // Если совпало по перечислению слот (через число:число:число ...)
- if(in_array($data['slots'], explode(':', $data_promo['slots'])))
- $check+= 1;
- else{
- // Если указан диапозон слот
- $aSl = explode('-', $data_promo['slots']);
- if(count($aSl) == 2 AND ($data['slots'] >= $aSl[0] AND $data['slots'] <= $aSl[1]))
- $check+= 1;
- }
- }
-
- // Проверка совпадений
- if($check < $promo['hits'])
- {
- if(!$go)
- sys::outjs(array('e' => 'Условия для данного промо-кода не выполнены.'));
-
- return NULL;
- }
-
- // Если скидка
- if($promo['discount'])
- {
- // Если не суммировать скидки
- if(!$cfg['promo_discount'])
- {
- if(array_key_exists($data['time'], params::$disconunt['service']['time'][$type]) AND $discount)
- {
- $data = explode(':', params::$disconunt['service']['time'][$type][$data['time']]);
-
- // Если скидка
- if($data[0] == '-')
- {
- // Если значение в процентах
- if(substr($data[1], -1) == '%')
- $sum = ceil($sum+$sum/100*intval($data[1]));
- else
- $sum = $sum+intval($data[1]);
- }
- }
- }
+ $period = params::$aDayMonth[$month]+1-$day;
+
+ $new_month_sum = 0;
+
+ if($day > 15)
+ $new_month_sum = ceil($price*$slots);
+
+ $sum = params::$aDayMonth[$month] == $period ? $price*$slots : floor($price*$slots/30*$period)+$new_month_sum;
+ }else{
+ $sum = floor($price*$slots/30*$time);
+
+ if(array_key_exists($time, params::$disconunt['service']['time'][$type]) AND $discount)
+ {
+ $data = explode(':', params::$disconunt['service']['time'][$type][$time]);
+
+ // Если наценка
+ if($data[0] == '+')
+ {
+ // Если значение в процентах
+ if(substr($data[1], -1) == '%')
+ $sum = ceil($sum+$sum/100*intval($data[1]));
+ else
+ $sum = $sum+intval($data[1]);
+ }else{
+ // Если значение в процентах
+ if(substr($data[1], -1) == '%')
+ $sum = ceil($sum-$sum/100*intval($data[1]));
+ else
+ $sum = $sum-intval($data[1]);
+ }
+ }
+ }
+
+ $sel = $type == 'buy' ? 'rental' : 'extend';
+
+ $sql->query('SELECT `'.$sel.'` FROM `users` WHERE `id`="'.$user['id'].'" LIMIT 1');
+ $user = array_merge($user, $sql->get());
+
+ $sum = strpos($user[$sel], '%') ? $sum-$sum/100*$user[$sel] : $sum-$user[$sel];
+
+ if($sum < 0)
+ sys::outjs(array('e' => 'Ошибка: сумма за услугу неверна'));
+
+ return $sum;
+ }
+
+ public static function define_promo($cod, $data, $discount, $sum, $type = 'buy')
+ {
+ global $cfg, $sql, $go, $start_point;
+
+ // Проверка формата кода
+ if(sys::valid($cod, 'promo'))
+ {
+ if(!$go)
+ sys::outjs(array('e' => 'Промо-код имеет неверный формат.'));
+
+ return NULL;
+ }
+
+ $sql->query('SELECT `id`, `value`, `discount`, `data`, `hits`, `use`, `extend`, `user`, `server` FROM `promo` WHERE `cod`="'.$cod.'" AND `tarif`="'.$data['tarif'].'" AND `time`>"'.$start_point.'" LIMIT 1');
+
+ // Проверка наличия промо-кода
+ if(!$sql->num())
+ {
+ if(!$go)
+ sys::outjs(array('e' => 'Промо-код не найден.'));
+
+ return NULL;
+ }
+
+ $promo = $sql->get();
+
+ // Проверка типа при аренде
+ if($type == 'buy' AND $promo['extend'])
+ {
+ if(!$go)
+ sys::outjs(array('e' => 'Промо-код для продления игрового сервера.'));
+
+ return NULL;
+ }
+
+ // Проверка типа при продлении
+ if($type != 'buy' AND !$promo['extend'])
+ {
+ if(!$go)
+ sys::outjs(array('e' => 'Промо-код для аренды нового игрового сервера.'));
+
+ return NULL;
+ }
+
+ // Проверка доступности на пользователя
+ if($promo['user'] AND $data['user'] != $promo['user'])
+ {
+ if(!$go)
+ sys::outjs(array('e' => 'Промо-код не найден.'));
+
+ return NULL;
+ }
+
+ // Проверка доступности на сервер
+ if($promo['server'] AND $data['server'] != $promo['server'])
+ {
+ if(!$go)
+ sys::outjs(array('e' => 'Промо-код не найден.'));
+
+ return NULL;
+ }
+
+ $use = $promo['use'] < 1 ? '1' : $promo['use'];
+
+ // Проверка доступности
+ $sql->query('SELECT `id` FROM `promo_use` WHERE `promo`="'.$promo['id'].'" LIMIT '.$use);
+ if($sql->num() >= $promo['use'])
+ {
+ if(!$go)
+ sys::outjs(array('e' => 'Промо-код использован максимальное количество раз.'));
+
+ return NULL;
+ }
+
+ // Данные для сравнения
+ $data_promo = sys::b64djs($promo['data'], true);
+
+ $check = 0;
+
+ // Проверка периода
+ if(in_array($data['time'], explode(':', $data_promo['time'])))
+ $check = 1;
+
+ // Проверка значения FPS
+ if((isset($data['fps']) AND isset($data_promo['fps'])) AND in_array($data['fps'], explode(':', $data_promo['fps'])))
+ $check+= 1;
+
+ // Проверка значения TICKRATE
+ if((isset($data['tickrate']) AND isset($data_promo['tickrate'])) AND in_array($data['tickrate'], explode(':', $data_promo['tickrate'])))
+ $check+= 1;
+
+ // Проверка значения RAM
+ if((isset($data['ram']) AND isset($data_promo['ram'])) AND in_array($data['ram'], explode(':', $data_promo['ram'])))
+ $check+= 1;
+
+ // Проверка кол-ва слот
+ if(isset($data_promo['slots']))
+ {
+ // Если совпало по перечислению слот (через число:число:число ...)
+ if(in_array($data['slots'], explode(':', $data_promo['slots'])))
+ $check+= 1;
+ else{
+ // Если указан диапозон слот
+ $aSl = explode('-', $data_promo['slots']);
+ if(count($aSl) == 2 AND ($data['slots'] >= $aSl[0] AND $data['slots'] <= $aSl[1]))
+ $check+= 1;
+ }
+ }
+
+ // Проверка совпадений
+ if($check < $promo['hits'])
+ {
+ if(!$go)
+ sys::outjs(array('e' => 'Условия для данного промо-кода не выполнены.'));
+
+ return NULL;
+ }
+
+ // Если скидка
+ if($promo['discount'])
+ {
+ // Если не суммировать скидки
+ if(!$cfg['promo_discount'])
+ {
+ if(array_key_exists($data['time'], params::$disconunt['service']['time'][$type]) AND $discount)
+ {
+ $data = explode(':', params::$disconunt['service']['time'][$type][$data['time']]);
+
+ // Если скидка
+ if($data[0] == '-')
+ {
+ // Если значение в процентах
+ if(substr($data[1], -1) == '%')
+ $sum = ceil($sum+$sum/100*intval($data[1]));
+ else
+ $sum = $sum+intval($data[1]);
+ }
+ }
+ }
- // Пересчет суммы
- if(substr($promo['value'], -1) == '%')
- $sum = $sum-ceil($sum/100*intval($promo['value']));
- else
- $sum = $sum-intval($promo['value']);
+ // Пересчет суммы
+ if(substr($promo['value'], -1) == '%')
+ $sum = $sum-ceil($sum/100*intval($promo['value']));
+ else
+ $sum = $sum-intval($promo['value']);
- if(!$go)
- sys::outjs(array('sum' => $sum, 'discount' => 1, 'cur' => $cfg['currency']));
+ if(!$go)
+ sys::outjs(array('sum' => $sum, 'discount' => 1, 'cur' => $cfg['currency']));
- return array('id' => $promo['id'], 'cod' => $cod, 'sum' => $sum);
+ return array('id' => $promo['id'], 'cod' => $cod, 'sum' => $sum);
- }
+ }
- // Подарочные дни
- $days = intval($promo['value']);
+ // Подарочные дни
+ $days = intval($promo['value']);
- if(!$go)
- sys::outjs(array('days' => games::parse_day($days)));
+ if(!$go)
+ sys::outjs(array('days' => games::parse_day($days)));
- return array('id' => $promo['id'], 'cod' => $cod, 'days' => $days);
- }
+ return array('id' => $promo['id'], 'cod' => $cod, 'days' => $days);
+ }
- public static function info_tarif($game, $tarif, $param)
- {
- if($game == 'cs')
- return $tarif.' / '.$param['fps'].' FPS';
+ public static function info_tarif($game, $tarif, $param)
+ {
+ if($game == 'cs')
+ return $tarif.' / '.$param['fps'].' FPS';
- if($game == 'mc')
- return $tarif.' / '.$param['ram'].' RAM';
+ if($game == 'mc')
+ return $tarif.' / '.$param['ram'].' RAM';
- if($game == 'cssold')
- return $tarif.' / '.$param['fps'].' FPS / '.$param['tickrate'].' TickRate';
+ if($game == 'cssold')
+ return $tarif.' / '.$param['fps'].' FPS / '.$param['tickrate'].' TickRate';
- if(in_array($game, array('css', 'csgo')))
- return $tarif.' / '.$param['tickrate'].' TickRate';
+ if(in_array($game, array('css', 'csgo')))
+ return $tarif.' / '.$param['tickrate'].' TickRate';
- return $tarif;
- }
+ return $tarif;
+ }
- public static function maplist($id, $unit, $folder, $map, $go, $mcache = '', $ctrl = false)
- {
- global $user, $sql;
+ public static function maplist($id, $unit, $folder, $map, $go, $mcache = '', $ctrl = false)
+ {
+ global $user, $sql;
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- {
- if($go)
- sys::outjs(array('e' => sys::text('error', 'ssh')), $mcache);
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ {
+ if($go)
+ sys::outjs(array('e' => sys::text('error', 'ssh')), $mcache);
- sys::outjs(array('maps', 'unknown '));
- }
+ sys::outjs(array('maps', 'unknown '));
+ }
- // Генерация списка карт
- $aMaps = array_diff(explode("\n", $ssh->get('cd '.$folder.' && du -ah | grep -e "\.bsp$" | awk \'{print $2}\'')), array(''));
+ // Генерация списка карт
+ $aMaps = array_diff(explode("\n", $ssh->get('cd '.$folder.' && du -ah | grep -e "\.bsp$" | awk \'{print $2}\'')), array(''));
- // Удаление ".bsp"
- $aMaps = str_ireplace(array('./', '.bsp'), '', $aMaps);
+ // Удаление ".bsp"
+ $aMaps = str_ireplace(array('./', '.bsp'), '', $aMaps);
- if($go)
- {
- $map = str_replace('|', '/', urldecode($map));
+ if($go)
+ {
+ $map = str_replace('|', '/', urldecode($map));
- $sqlq = $ctrl ? 'control_' : '';
+ $sqlq = $ctrl ? 'control_' : '';
- // Проверка наличия выбранной карты
- if(in_array($map, $aMaps))
- $sql->query('UPDATE `'.$sqlq.'servers` set `map_start`="'.$map.'" WHERE `id`="'.$id.'" LIMIT 1');
+ // Проверка наличия выбранной карты
+ if(in_array($map, $aMaps))
+ $sql->query('UPDATE `'.$sqlq.'servers` set `map_start`="'.$map.'" WHERE `id`="'.$id.'" LIMIT 1');
- sys::outjs(array('s' => 'ok'), $mcache);
- }
+ sys::outjs(array('s' => 'ok'), $mcache);
+ }
- sort($aMaps);
- reset($aMaps);
+ sort($aMaps);
+ reset($aMaps);
- $ismap = in_array($map, $aMaps);
- $maps = $ismap ? ''.$map.' ' : 'Указанная ранее карта "'.$map.'" не найдена ';
+ $ismap = in_array($map, $aMaps);
+ $maps = $ismap ? ''.$map.' ' : 'Указанная ранее карта "'.$map.'" не найдена ';
- // Удаление стартовой карты
- if($ismap)
- unset($aMaps[array_search($map, $aMaps)]);
+ // Удаление стартовой карты
+ if($ismap)
+ unset($aMaps[array_search($map, $aMaps)]);
- foreach($aMaps as $map)
- $maps .= ''.$map.' ';
+ foreach($aMaps as $map)
+ $maps .= ''.$map.' ';
- sys::outjs(array('maps' => $maps));
- }
+ sys::outjs(array('maps' => $maps));
+ }
- public static function owners($aRights)
- {
- if(array_search(0, $aRights))
- return 'Есть ограничения в доступе.';
+ public static function owners($aRights)
+ {
+ if(array_search(0, $aRights))
+ return 'Есть ограничения в доступе.';
- return 'Выданы все права.';
- }
+ return 'Выданы все права.';
+ }
- public static function part($uid, $money)
- {
- global $cfg, $sql, $start_point;
+ public static function part($uid, $money)
+ {
+ global $cfg, $sql, $start_point;
- if($cfg['part'])
- return NULL;
+ if($cfg['part'])
+ return NULL;
- $sql->query('SELECT `part` FROM `users` WHERE `id`="'.$uid.'" LIMIT 1');
- $user = $sql->get();
+ $sql->query('SELECT `part` FROM `users` WHERE `id`="'.$uid.'" LIMIT 1');
+ $user = $sql->get();
- if(!$user['part'])
- return NULL;
+ if(!$user['part'])
+ return NULL;
- $sql->query('SELECT `balance`, `part_money` FROM `users` WHERE `id`="'.$user['part'].'" LIMIT 1');
- if(!$sql->num())
- return NULL;
+ $sql->query('SELECT `balance`, `part_money` FROM `users` WHERE `id`="'.$user['part'].'" LIMIT 1');
+ if(!$sql->num())
+ return NULL;
- $user = array_merge($user, $sql->get());
+ $user = array_merge($user, $sql->get());
- $sum = round($money/100*$cfg['part_proc'], 2);
+ $sum = round($money/100*$cfg['part_proc'], 2);
- if($cfg['part_money'])
- $sql->query('UPDATE `users` set `part_money`="'.($user['part_money']+$sum).'" WHERE `id`="'.$user['part'].'" LIMIT 1');
- else
- $sql->query('UPDATE `users` set `balance`="'.($user['balance']+$sum).'" WHERE `id`="'.$user['part'].'" LIMIT 1');
+ if($cfg['part_money'])
+ $sql->query('UPDATE `users` set `part_money`="'.($user['part_money']+$sum).'" WHERE `id`="'.$user['part'].'" LIMIT 1');
+ else
+ $sql->query('UPDATE `users` set `balance`="'.($user['balance']+$sum).'" WHERE `id`="'.$user['part'].'" LIMIT 1');
- $sql->query('INSERT INTO `logs` set `user`="'.$user['part'].'", `text`="'.sys::updtext(sys::text('logs', 'part'),
- array('part' => $uid, 'money' => $sum)).'", `date`="'.$start_point.'", `type`="part", `money`="'.$sum.'"');
+ $sql->query('INSERT INTO `logs` set `user`="'.$user['part'].'", `text`="'.sys::updtext(sys::text('logs', 'part'),
+ array('part' => $uid, 'money' => $sum)).'", `date`="'.$start_point.'", `type`="part", `money`="'.$sum.'"');
- return NULL;
- }
+ return NULL;
+ }
- public static function map($map, $aMaps)
- {
- if(!is_array($aMaps))
- $aMaps = explode("\n", str_ireplace(array('./', '.bsp'), '', $aMaps));
+ public static function map($map, $aMaps)
+ {
+ if(!is_array($aMaps))
+ $aMaps = explode("\n", str_ireplace(array('./', '.bsp'), '', $aMaps));
- if(in_array($map, $aMaps))
- return false;
+ if(in_array($map, $aMaps))
+ return false;
- return true;
- }
+ return true;
+ }
- public static function mapsql($arr = array())
- {
- $sql = 'AND (';
+ public static function mapsql($arr = array())
+ {
+ $sql = 'AND (';
- foreach($arr as $map)
- $sql .= ' `name` REGEXP FROM_BASE64(\''.base64_encode('^'.$map.'\_').'\') OR';
+ foreach($arr as $map)
+ $sql .= ' `name` REGEXP FROM_BASE64(\''.base64_encode('^'.$map.'\_').'\') OR';
- return $sql == 'AND (' ? '' : substr($sql, 0, -3).')';
- }
+ return $sql == 'AND (' ? '' : substr($sql, 0, -3).')';
+ }
- public static function iptables_whois($mcache)
- {
- $address = isset($_POST['address']) ? trim($_POST['address']) : sys::outjs(array('info' => 'Не удалось получить информацию.'), $mcache);
+ public static function iptables_whois($mcache)
+ {
+ $address = isset($_POST['address']) ? trim($_POST['address']) : sys::outjs(array('info' => 'Не удалось получить информацию.'), $mcache);
- if(sys::valid($address, 'ip'))
- sys::outjs(array('e' => sys::text('servers', 'firewall')), $mcache);
+ if(sys::valid($address, 'ip'))
+ sys::outjs(array('e' => sys::text('servers', 'firewall')), $mcache);
- include(LIB.'geo.php');
+ include(LIB.'geo.php');
- $SxGeo = new SxGeo(DATA.'SxGeoCity.dat');
+ $SxGeo = new SxGeo(DATA.'SxGeoCity.dat');
- $data = $SxGeo->getCityFull($address);
+ $data = $SxGeo->getCityFull($address);
- $info = 'Информация об IP адресе:';
+ $info = 'Информация об IP адресе:';
- if($data['country']['name_ru'] != '')
- {
- $info .= 'Страна: '.$data['country']['name_ru'];
+ if($data['country']['name_ru'] != '')
+ {
+ $info .= '
Страна: '.$data['country']['name_ru'];
- if($data['city']['name_ru'] != '')
- $info .= '
Город: '.$data['city']['name_ru'];
+ if($data['city']['name_ru'] != '')
+ $info .= '
Город: '.$data['city']['name_ru'];
- $info .= '
Подсеть: '.sys::whois($address);
+ $info .= '
Подсеть: '.sys::whois($address);
- }else
- $info = 'Не удалось получить информацию.';
+ }else
+ $info = 'Не удалось получить информацию.';
- sys::outjs(array('info' => $info), $mcache);
- }
+ sys::outjs(array('info' => $info), $mcache);
+ }
- public static function iptables($id, $action, $source, $dest, $unit, $snw = false, $ssh = false)
- {
- global $cfg, $sql, $start_point;
+ public static function iptables($id, $action, $source, $dest, $unit, $snw = false, $ssh = false)
+ {
+ global $cfg, $sql, $start_point;
- if(!$ssh)
- {
- $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$unit.'" LIMIT 1');
- $unit = $sql->get();
+ if(!$ssh)
+ {
+ $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$unit.'" LIMIT 1');
+ $unit = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return array('e' => sys::text('all', 'ssh'));
- }
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return array('e' => sys::text('all', 'ssh'));
+ }
- switch($action)
- {
- case 'block':
- if(sys::valid($source, 'ip'))
- return array('e' => sys::text('servers', 'firewall'));
+ switch($action)
+ {
+ case 'block':
+ if(sys::valid($source, 'ip'))
+ return array('e' => sys::text('servers', 'firewall'));
- // Если подсеть
- if($snw)
- {
- $source = sys::whois($source);
+ // Если подсеть
+ if($snw)
+ {
+ $source = sys::whois($source);
- if($source == 'не определена')
- return array('e' => 'Не удалось определить подсеть для указанного адреса.');
- }
+ if($source == 'не определена')
+ return array('e' => 'Не удалось определить подсеть для указанного адреса.');
+ }
- $sql->query('SELECT `id` FROM `firewall` WHERE `sip`="'.$source.'" AND `server`="'.$id.'" LIMIT 1');
+ $sql->query('SELECT `id` FROM `firewall` WHERE `sip`="'.$source.'" AND `server`="'.$id.'" LIMIT 1');
- // Если такое правило уже добавлено или указан адрес сайта (ПУ)
- if($sql->num() || ($source == $cfg['ip'] || $source == $cfg['subnet']))
- return array('s' => 'ok');
+ // Если такое правило уже добавлено или указан адрес сайта (ПУ)
+ if($sql->num() || ($source == $cfg['ip'] || $source == $cfg['subnet']))
+ return array('s' => 'ok');
- $sql->query('INSERT INTO `firewall` set `sip`="'.$source.'", `dest`="'.$dest[0].':'.$dest[1].'", `server`="'.$id.'", `time`="'.$start_point.'"');
+ $sql->query('INSERT INTO `firewall` set `sip`="'.$source.'", `dest`="'.$dest[0].':'.$dest[1].'", `server`="'.$id.'", `time`="'.$start_point.'"');
- $line = $sql->id();
+ $line = $sql->id();
- $rule = 'iptables -I INPUT -s '.$source.' -p udp -d '.$dest[0].' --dport '.$dest[1].' -j DROP;';
+ $rule = 'iptables -I INPUT -s '.$source.' -p udp -d '.$dest[0].' --dport '.$dest[1].' -j DROP;';
- $ssh->set($rule.' echo -e "#'.$line.';\n'.$rule.'" >> /root/'.$cfg['iptables']);
+ $ssh->set($rule.' echo -e "#'.$line.';\n'.$rule.'" >> /root/'.$cfg['iptables']);
- return array('s' => 'ok');
+ return array('s' => 'ok');
- case 'unblock':
- if(!is_numeric($source) AND sys::valid($source, 'ip'))
- return array('e' => sys::text('servers', 'firewall'));
+ case 'unblock':
+ if(!is_numeric($source) AND sys::valid($source, 'ip'))
+ return array('e' => sys::text('servers', 'firewall'));
- if(is_numeric($source))
- {
- $sql->query('SELECT `id`, `sip` FROM `firewall` WHERE `id`="'.$source.'" AND `server`="'.$id.'" LIMIT 1');
+ if(is_numeric($source))
+ {
+ $sql->query('SELECT `id`, `sip` FROM `firewall` WHERE `id`="'.$source.'" AND `server`="'.$id.'" LIMIT 1');
- // Если такое правило отсутствует
- if(!$sql->num())
- return array('s' => 'ok');
- }else{
- $sql->query('SELECT `id`, `sip` FROM `firewall` WHERE `sip`="'.$source.'" AND `server`="'.$id.'" LIMIT 1');
+ // Если такое правило отсутствует
+ if(!$sql->num())
+ return array('s' => 'ok');
+ }else{
+ $sql->query('SELECT `id`, `sip` FROM `firewall` WHERE `sip`="'.$source.'" AND `server`="'.$id.'" LIMIT 1');
- // Если одиночный адрес не найден, проверить на блокировку подсети
- if(!$sql->num())
- {
- $source = sys::whois($source);
+ // Если одиночный адрес не найден, проверить на блокировку подсети
+ if(!$sql->num())
+ {
+ $source = sys::whois($source);
- $sql->query('SELECT `id` FROM `firewall` WHERE `sip`="'.$source.'" AND `server`="'.$id.'" LIMIT 1');
+ $sql->query('SELECT `id` FROM `firewall` WHERE `sip`="'.$source.'" AND `server`="'.$id.'" LIMIT 1');
- if($sql->num())
- {
- $firewall = $sql->get();
+ if($sql->num())
+ {
+ $firewall = $sql->get();
- return array('i' => 'Указанный адрес входит в заблокированную подсеть, разблокировать подсеть?', 'id' => $firewall['id']);
- }
+ return array('i' => 'Указанный адрес входит в заблокированную подсеть, разблокировать подсеть?', 'id' => $firewall['id']);
+ }
- return array('s' => 'ok');
- }
- }
+ return array('s' => 'ok');
+ }
+ }
- $firewall = $sql->get();
+ $firewall = $sql->get();
- $ssh->set('iptables -D INPUT -s '.$firewall['sip'].' -p udp -d '.$dest[0].' --dport '.$dest[1].' -j DROP;'
- .'sed "`nl '.$cfg['iptables'].' | grep \"#'.$firewall['id'].'\" | awk \'{print $1","$1+1}\'`d" '.$cfg['iptables'].' > '.$cfg['iptables'].'_temp; cat '.$cfg['iptables'].'_temp > '.$cfg['iptables'].'; rm '.$cfg['iptables'].'_temp');
+ $ssh->set('iptables -D INPUT -s '.$firewall['sip'].' -p udp -d '.$dest[0].' --dport '.$dest[1].' -j DROP;'
+ .'sed "`nl '.$cfg['iptables'].' | grep \"#'.$firewall['id'].'\" | awk \'{print $1","$1+1}\'`d" '.$cfg['iptables'].' > '.$cfg['iptables'].'_temp; cat '.$cfg['iptables'].'_temp > '.$cfg['iptables'].'; rm '.$cfg['iptables'].'_temp');
- $sql->query('DELETE FROM `firewall` WHERE `id`="'.$firewall['id'].'" LIMIT 1');
+ $sql->query('DELETE FROM `firewall` WHERE `id`="'.$firewall['id'].'" LIMIT 1');
- return array('s' => 'ok');
+ return array('s' => 'ok');
- case 'remove':
- $sql->query('SELECT `id`, `sip`, `dest` FROM `firewall` WHERE `server`="'.$id.'"');
+ case 'remove':
+ $sql->query('SELECT `id`, `sip`, `dest` FROM `firewall` WHERE `server`="'.$id.'"');
- $aRule = array();
+ $aRule = array();
- while($firewall = $sql->get())
- {
- list($ip, $port) = explode(':', $firewall['dest']);
+ while($firewall = $sql->get())
+ {
+ list($ip, $port) = explode(':', $firewall['dest']);
- $aRule[$firewall['id']] = 'iptables -D INPUT -s '.$firewall['sip'].' -p udp -d '.$ip.' --dport '.$port.' -j DROP;';
- }
+ $aRule[$firewall['id']] = 'iptables -D INPUT -s '.$firewall['sip'].' -p udp -d '.$ip.' --dport '.$port.' -j DROP;';
+ }
- $nRule = count($aRule);
+ $nRule = count($aRule);
- if(!$nRule)
- return NULL;
+ if(!$nRule)
+ return NULL;
- $cmd = '';
+ $cmd = '';
- foreach($aRule as $line => $rule)
- $cmd .= $rule.'sed "`nl '.$cfg['iptables'].' | grep "#'.$line.'" | awk \'{print $1","$1+1}\'`d" '.$cfg['iptables'].' > '.$cfg['iptables'].'_temp; cat '.$cfg['iptables'].'_temp > '.$cfg['iptables'].'; rm '.$cfg['iptables'].'_temp';
+ foreach($aRule as $line => $rule)
+ $cmd .= $rule.'sed "`nl '.$cfg['iptables'].' | grep "#'.$line.'" | awk \'{print $1","$1+1}\'`d" '.$cfg['iptables'].' > '.$cfg['iptables'].'_temp; cat '.$cfg['iptables'].'_temp > '.$cfg['iptables'].'; rm '.$cfg['iptables'].'_temp';
- $ssh->set($cmd);
+ $ssh->set($cmd);
- $sql->query('DELETE FROM `firewall` WHERE `server`="'.$id.'" LIMIT '.$nRule);
+ $sql->query('DELETE FROM `firewall` WHERE `server`="'.$id.'" LIMIT '.$nRule);
- return array('s' => 'ok');
- }
- }
- }
+ return array('s' => 'ok');
+ }
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/games/graph.php b/system/library/games/graph.php
index 493141a..f76e70e 100644
--- a/system/library/games/graph.php
+++ b/system/library/games/graph.php
@@ -1,404 +1,404 @@
addPoints($aOnline, 'ONLINE');
-
- // CPU
- $MyData->addPoints($aCPU, 'CPU');
-
- // RAM
- $MyData->addPoints($aRAM, 'RAM');
-
- // HDD
- $MyData->addPoints($aHDD, 'HDD');
-
- // Время
- $MyData->addPoints($aData['time'], 'TIME');
-
- $MyData->setSerieOnAxis('CPU', 1);
- $MyData->setSerieOnAxis('RAM', 1);
- $MyData->setSerieOnAxis('HDD', 1);
- $MyData->setAxisPosition(1, AXIS_POSITION_RIGHT);
-
- $MyData->setAxisName(0, 'Онлайн');
- $MyData->setAxisName(1, 'Нагрузка %');
-
- $MyData->setAbscissa('TIME');
-
- // Сечение линии
- $MyData->setSerieTicks('ONLINE', 4);
-
- // Цвет линий
- $MyData->setPalette('ONLINE', array('R' => 68, 'G' => 148, 'B' => 224));
- $MyData->setPalette('CPU', array('R' => 216, 'G' => 65, 'B' => 65));
- $MyData->setPalette('RAM', array('R' => 26, 'G' => 150, 'B' => 38));
- $MyData->setPalette('HDD', array('R' => 205, 'G' => 196, 'B' => 37));
-
- $myPicture = new pImage(896, 220, $MyData);
-
- $myPicture->drawFilledRectangle(0, 0, 896, 220, array('R' => 255, 'G' => 255, 'B' => 255));
-
- $myPicture->drawRectangle(0, 0, 895, 219, array('R' => 221, 'G' => 221, 'B' => 221));
-
- $myPicture->setFontProperties(array('R' => 25, 'G' => 25, 'B' => 25, 'FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8));
- $myPicture->setGraphArea(40, 20, 616, 190);
- $myPicture->drawFilledRectangle(40, 20, 616, 190, array('R' => 240, 'G' => 242, 'B' => 242, 'Alpha' => 100));
- $myPicture->drawScale(array('XMargin' => 5, 'YMargin' => 5, 'GridR' => 76, 'GridG' => 109, 'GridB' => 120, 'LabelSkip' => 0, 'DrawSubTicks' => TRUE, 'Mode' => SCALE_MODE_MANUAL, 'Factors' => array(0 => array($slots), 1 => array(25, 50, 75, 100)), 'ManualScale' => array(0 => array('Min' => 0, 'Max' => $slots), 1 => array('Min' => 0, 'Max' => 100))));
-
- $myPicture->drawText(676, 34, 'Средний онлайн: '.graph::average($aOnline), array('R' => 25, 'G' => 25, 'B' => 25, 'FontName' => LIB.'games/graph/fonts/arianamu.ttf', 'FontSize' => 10, 'Align' => TEXT_ALIGN_BOTTOMLEFT));
- $myPicture->drawText(676, 54, 'Средняя нагрузка (CPU): '.graph::average($aCPU).'%', array('R' => 25, 'G' => 25, 'B' => 25, 'FontName' => LIB.'games/graph/fonts/arianamu.ttf', 'FontSize' => 10, 'Align' => TEXT_ALIGN_BOTTOMLEFT));
- $myPicture->drawText(676, 74, 'Средняя нагрузка (RAM): '.graph::average($aRAM).'%', array('R' => 25, 'G' => 25, 'B' => 25, 'FontName' => LIB.'games/graph/fonts/arianamu.ttf', 'FontSize' => 10, 'Align' => TEXT_ALIGN_BOTTOMLEFT));
- $myPicture->drawText(676, 94, 'Средняя нагрузка (HDD): '.graph::average($aHDD).'%', array('R' => 25, 'G' => 25, 'B' => 25, 'FontName' => LIB.'games/graph/fonts/arianamu.ttf', 'FontSize' => 10, 'Align' => TEXT_ALIGN_BOTTOMLEFT));
-
- $myPicture->drawText(676, 129, 'Максимальный онлайн: '.max($aOnline), array('R' => 25, 'G' => 25, 'B' => 25, 'FontName' => LIB.'games/graph/fonts/arianamu.ttf', 'FontSize' => 10, 'Align' => TEXT_ALIGN_BOTTOMLEFT));
- $myPicture->drawText(676, 153, 'Максимальная нагрузка (CPU): '.max($aCPU).'%', array('R' => 25, 'G' => 25, 'B' => 25, 'FontName' => LIB.'games/graph/fonts/arianamu.ttf', 'FontSize' => 10, 'Align' => TEXT_ALIGN_BOTTOMLEFT));
- $myPicture->drawText(676, 173, 'Максимальная нагрузка (RAM): '.max($aRAM).'%', array('R' => 25, 'G' => 25, 'B' => 25, 'FontName' => LIB.'games/graph/fonts/arianamu.ttf', 'FontSize' => 10, 'Align' => TEXT_ALIGN_BOTTOMLEFT));
- $myPicture->drawText(676, 193, 'Максимальная нагрузка (HDD): '.max($aHDD).'%', array('R' => 25, 'G' => 25, 'B' => 25, 'FontName' => LIB.'games/graph/fonts/arianamu.ttf', 'FontSize' => 10, 'Align' => TEXT_ALIGN_BOTTOMLEFT));
-
- $myPicture->setFontProperties(array('FontName'=> LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 7));
- $myPicture->drawSplineChart();
- $myPicture->setShadow(FALSE);
-
- $myPicture->drawLegend(466, 10, array('Style' => LEGEND_NOBORDER, 'Mode' => LEGEND_HORIZONTAL));
-
- $myPicture->render(TEMP.(md5($key.'full_'.$time)).'.png');
-
- unset($MyData, $myPicture);
-
- return NULL;
- }
-
- public static function first($server, $aPoints, $aStyle, $style, $key)
+ public static function full($server, $slots, $key, $time)
{
- global $cfg, $aGname;
+ // Массивы данных
+ $aData = graph::graph_data($time, $server, $slots);
- $MyData = new pData();
+ $aOnline = $aData['online'];
- // Значения
- $MyData->addPoints($aPoints, 'ONLINE');
+ $aCPU = $aData['cpu'];
+ $aRAM = $aData['ram'];
+ $aHDD = $aData['hdd'];
- $MyData->addPoints(array(VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID), 'NONE');
- $MyData->setAbscissa('NONE');
+ $MyData = new pData();
- // Цвет линии
- $MyData->setPalette('ONLINE', $aStyle[$style]['line']);
+ // Онлайн
+ $MyData->addPoints($aOnline, 'ONLINE');
- // Размер баннера
- $myPicture = new pImage(160, 248, $MyData);
+ // CPU
+ $MyData->addPoints($aCPU, 'CPU');
- // Цвет фона
- $myPicture->drawFilledRectangle(0, 0, 160, 248, $aStyle[$style]['fon']);
+ // RAM
+ $MyData->addPoints($aRAM, 'RAM');
- // Обводка
- $myPicture->drawRectangle(0, 0, 159, 247, $aStyle[$style]['border']);
+ // HDD
+ $MyData->addPoints($aHDD, 'HDD');
- // Шрифт текста
- $myPicture->setFontProperties(array_merge($aStyle[$style]['color'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 5)));
+ // Время
+ $MyData->addPoints($aData['time'], 'TIME');
- // Размер графика
- $myPicture->setGraphArea(35, 160, 150, 210);
+ $MyData->setSerieOnAxis('CPU', 1);
+ $MyData->setSerieOnAxis('RAM', 1);
+ $MyData->setSerieOnAxis('HDD', 1);
+ $MyData->setAxisPosition(1, AXIS_POSITION_RIGHT);
- // Цвет фона графика
- $myPicture->drawFilledRectangle(35, 160, 150, 210, $aStyle[$style]['graph']);
+ $MyData->setAxisName(0, 'Онлайн');
+ $MyData->setAxisName(1, 'Нагрузка %');
- // График
- $myPicture->drawScale(array('XMargin' => 5, 'YMargin' => 5, 'CycleBackground' => TRUE, 'LabelSkip' => 0, 'DrawSubTicks' => TRUE, 'Mode' => SCALE_MODE_MANUAL, 'Factors' => array(0 => array($server['slots_start'])), 'ManualScale' => array(0 => array('Min' => 0, 'Max' => $server['slots_start']))));
+ $MyData->setAbscissa('TIME');
- // Название игрового сервера
- $myPicture->drawFilledRectangle(0, 0, 18, 248, $aStyle[$style]['leftbox']);
- $myPicture->drawText(14, 245, $server['name'], array_merge($aStyle[$style]['boxcolor'], array('Angle' => 90, 'FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 10)));
- $myPicture->drawFilledRectangle(0, 0, 18, 5, $aStyle[$style]['leftbox']);
+ // Сечение линии
+ $MyData->setSerieTicks('ONLINE', 4);
- // Адрес игрового сервера
- $myPicture->drawFilledRectangle(25, 5, 153, 18, $aStyle[$style]['box']);
- $myPicture->drawText(28, 17, 'Адрес сервера', array_merge($aStyle[$style]['boxcolor'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
- $myPicture->drawText(26, 30, $server['address'], array_merge($aStyle[$style]['color'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
+ // Цвет линий
+ $MyData->setPalette('ONLINE', array('R' => 68, 'G' => 148, 'B' => 224));
+ $MyData->setPalette('CPU', array('R' => 216, 'G' => 65, 'B' => 65));
+ $MyData->setPalette('RAM', array('R' => 26, 'G' => 150, 'B' => 38));
+ $MyData->setPalette('HDD', array('R' => 205, 'G' => 196, 'B' => 37));
- // Статус игрового сервера
- $myPicture->drawFilledRectangle(25, 35, 153, 48, $aStyle[$style]['box']);
- $myPicture->drawText(28, 47, 'Состояние сервера', array_merge($aStyle[$style]['boxcolor'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
- $myPicture->drawText(26, 62, graph::status($server['status'], $server['map']), array_merge($aStyle[$style]['color'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
+ $myPicture = new pImage(896, 220, $MyData);
- // Игроки на игровом сервере
- $myPicture->drawFilledRectangle(25, 65, 153, 78, $aStyle[$style]['box']);
- $myPicture->drawText(28, 77, 'Игроки на сервере', array_merge($aStyle[$style]['boxcolor'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
- $myPicture->drawText(26, 92, $server['online'].' / '.$server['slots_start'], array_merge($aStyle[$style]['color'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
+ $myPicture->drawFilledRectangle(0, 0, 896, 220, array('R' => 255, 'G' => 255, 'B' => 255));
- // Полоска загрузки
- $myPicture->drawProgress(83, 82, ceil($server['slots_start']/100*$server['online']), array_merge($aStyle[$style]['progress'], array('Width' => 70, 'Height' => 8)));
+ $myPicture->drawRectangle(0, 0, 895, 219, array('R' => 221, 'G' => 221, 'B' => 221));
- // Тип игрового сервера
- $myPicture->drawFilledRectangle(25, 95, 153, 108, $aStyle[$style]['box']);
- $myPicture->drawText(28, 107, 'Тип сервера', array_merge($aStyle[$style]['boxcolor'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
- $myPicture->drawText(26, 122, $aGname[$server['game']], array_merge($aStyle[$style]['color'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
+ $myPicture->setFontProperties(array('R' => 25, 'G' => 25, 'B' => 25, 'FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8));
+ $myPicture->setGraphArea(40, 20, 616, 190);
+ $myPicture->drawFilledRectangle(40, 20, 616, 190, array('R' => 240, 'G' => 242, 'B' => 242, 'Alpha' => 100));
+ $myPicture->drawScale(array('XMargin' => 5, 'YMargin' => 5, 'GridR' => 76, 'GridG' => 109, 'GridB' => 120, 'LabelSkip' => 0, 'DrawSubTicks' => TRUE, 'Mode' => SCALE_MODE_MANUAL, 'Factors' => array(0 => array($slots), 1 => array(25, 50, 75, 100)), 'ManualScale' => array(0 => array('Min' => 0, 'Max' => $slots), 1 => array('Min' => 0, 'Max' => 100))));
- // Хостинг игровых серверов
- $myPicture->drawText(89, 230, $cfg['graph'], array_merge($aStyle[$style]['color'], array('FontSize' => 10, 'Align' => TEXT_ALIGN_BOTTOMMIDDLE)));
- $myPicture->drawText(89, 245, 'Хостинг игровых серверов', array_merge($aStyle[$style]['color'], array('FontSize' => 8, 'Align' => TEXT_ALIGN_BOTTOMMIDDLE)));
+ $myPicture->drawText(676, 34, 'Средний онлайн: '.graph::average($aOnline), array('R' => 25, 'G' => 25, 'B' => 25, 'FontName' => LIB.'games/graph/fonts/arianamu.ttf', 'FontSize' => 10, 'Align' => TEXT_ALIGN_BOTTOMLEFT));
+ $myPicture->drawText(676, 54, 'Средняя нагрузка (CPU): '.graph::average($aCPU).'%', array('R' => 25, 'G' => 25, 'B' => 25, 'FontName' => LIB.'games/graph/fonts/arianamu.ttf', 'FontSize' => 10, 'Align' => TEXT_ALIGN_BOTTOMLEFT));
+ $myPicture->drawText(676, 74, 'Средняя нагрузка (RAM): '.graph::average($aRAM).'%', array('R' => 25, 'G' => 25, 'B' => 25, 'FontName' => LIB.'games/graph/fonts/arianamu.ttf', 'FontSize' => 10, 'Align' => TEXT_ALIGN_BOTTOMLEFT));
+ $myPicture->drawText(676, 94, 'Средняя нагрузка (HDD): '.graph::average($aHDD).'%', array('R' => 25, 'G' => 25, 'B' => 25, 'FontName' => LIB.'games/graph/fonts/arianamu.ttf', 'FontSize' => 10, 'Align' => TEXT_ALIGN_BOTTOMLEFT));
- $myPicture->drawSplineChart();
+ $myPicture->drawText(676, 129, 'Максимальный онлайн: '.max($aOnline), array('R' => 25, 'G' => 25, 'B' => 25, 'FontName' => LIB.'games/graph/fonts/arianamu.ttf', 'FontSize' => 10, 'Align' => TEXT_ALIGN_BOTTOMLEFT));
+ $myPicture->drawText(676, 153, 'Максимальная нагрузка (CPU): '.max($aCPU).'%', array('R' => 25, 'G' => 25, 'B' => 25, 'FontName' => LIB.'games/graph/fonts/arianamu.ttf', 'FontSize' => 10, 'Align' => TEXT_ALIGN_BOTTOMLEFT));
+ $myPicture->drawText(676, 173, 'Максимальная нагрузка (RAM): '.max($aRAM).'%', array('R' => 25, 'G' => 25, 'B' => 25, 'FontName' => LIB.'games/graph/fonts/arianamu.ttf', 'FontSize' => 10, 'Align' => TEXT_ALIGN_BOTTOMLEFT));
+ $myPicture->drawText(676, 193, 'Максимальная нагрузка (HDD): '.max($aHDD).'%', array('R' => 25, 'G' => 25, 'B' => 25, 'FontName' => LIB.'games/graph/fonts/arianamu.ttf', 'FontSize' => 10, 'Align' => TEXT_ALIGN_BOTTOMLEFT));
- $myPicture->render(TEMP.(md5($key.$style.'first')).'.png');
+ $myPicture->setFontProperties(array('FontName'=> LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 7));
+ $myPicture->drawSplineChart();
+ $myPicture->setShadow(FALSE);
- unset($MyData, $myPicture);
+ $myPicture->drawLegend(466, 10, array('Style' => LEGEND_NOBORDER, 'Mode' => LEGEND_HORIZONTAL));
- return NULL;
+ $myPicture->render(TEMP.(md5($key.'full_'.$time)).'.png');
+
+ unset($MyData, $myPicture);
+
+ return NULL;
}
- public static function second($server, $aPoints, $aStyle, $style, $key)
- {
- global $cfg, $aGname;
+ public static function first($server, $aPoints, $aStyle, $style, $key)
+ {
+ global $cfg, $aGname;
- $MyData = new pData();
+ $MyData = new pData();
- // Значения
- $MyData->addPoints($aPoints, 'ONLINE');
+ // Значения
+ $MyData->addPoints($aPoints, 'ONLINE');
- $MyData->addPoints(array(VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID), 'NONE');
- $MyData->setAbscissa('NONE');
+ $MyData->addPoints(array(VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID), 'NONE');
+ $MyData->setAbscissa('NONE');
- // Цвет линии
- $MyData->setPalette('ONLINE', $aStyle[$style]['line']);
+ // Цвет линии
+ $MyData->setPalette('ONLINE', $aStyle[$style]['line']);
- // Размер баннера
- $myPicture = new pImage(560, 95, $MyData);
+ // Размер баннера
+ $myPicture = new pImage(160, 248, $MyData);
- // Цвет фона
- $myPicture->drawFilledRectangle(0, 0, 560, 95, $aStyle[$style]['fon']);
+ // Цвет фона
+ $myPicture->drawFilledRectangle(0, 0, 160, 248, $aStyle[$style]['fon']);
- // Название игрового сервера
- $myPicture->drawFilledRectangle(5, 5, 410, 18, $aStyle[$style]['box']);
- $myPicture->drawText(8, 17, 'Название сервера', array_merge($aStyle[$style]['boxcolor'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
- $myPicture->drawText(6, 31, $server['name'], array_merge($aStyle[$style]['color'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
+ // Обводка
+ $myPicture->drawRectangle(0, 0, 159, 247, $aStyle[$style]['border']);
- // Костыль для "обрезания" названия сервера
- $myPicture->drawFilledRectangle(405, 19, 560, 35, $aStyle[$style]['fon']);
+ // Шрифт текста
+ $myPicture->setFontProperties(array_merge($aStyle[$style]['color'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 5)));
- // Обводка
- $myPicture->drawRectangle(0, 0, 559, 94, $aStyle[$style]['border']);
+ // Размер графика
+ $myPicture->setGraphArea(35, 160, 150, 210);
- // Шрифт текста
- $myPicture->setFontProperties(array_merge($aStyle[$style]['color'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 5)));
+ // Цвет фона графика
+ $myPicture->drawFilledRectangle(35, 160, 150, 210, $aStyle[$style]['graph']);
- // Размер графика
- $myPicture->setGraphArea(430, 5, 554, 60);
+ // График
+ $myPicture->drawScale(array('XMargin' => 5, 'YMargin' => 5, 'CycleBackground' => TRUE, 'LabelSkip' => 0, 'DrawSubTicks' => TRUE, 'Mode' => SCALE_MODE_MANUAL, 'Factors' => array(0 => array($server['slots_start'])), 'ManualScale' => array(0 => array('Min' => 0, 'Max' => $server['slots_start']))));
- // Цвет фона графика
- $myPicture->drawFilledRectangle(430, 5, 554, 60, $aStyle[$style]['graph']);
+ // Название игрового сервера
+ $myPicture->drawFilledRectangle(0, 0, 18, 248, $aStyle[$style]['leftbox']);
+ $myPicture->drawText(14, 245, $server['name'], array_merge($aStyle[$style]['boxcolor'], array('Angle' => 90, 'FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 10)));
+ $myPicture->drawFilledRectangle(0, 0, 18, 5, $aStyle[$style]['leftbox']);
- // График
- $myPicture->drawScale(array('XMargin' => 5, 'YMargin' => 5, 'CycleBackground' => TRUE, 'LabelSkip' => 0, 'DrawSubTicks' => TRUE, 'Mode' => SCALE_MODE_MANUAL, 'Factors' => array(0 => array($server['slots_start'])), 'ManualScale' => array(0 => array('Min' => 0, 'Max' => $server['slots_start']))));
+ // Адрес игрового сервера
+ $myPicture->drawFilledRectangle(25, 5, 153, 18, $aStyle[$style]['box']);
+ $myPicture->drawText(28, 17, 'Адрес сервера', array_merge($aStyle[$style]['boxcolor'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
+ $myPicture->drawText(26, 30, $server['address'], array_merge($aStyle[$style]['color'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
- // Адрес игрового сервера
- $myPicture->drawFilledRectangle(5, 36, 210, 49, $aStyle[$style]['box']);
- $myPicture->drawText(8, 48, 'Адрес сервера', array_merge($aStyle[$style]['boxcolor'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
- $myPicture->drawText(6, 62, $server['address'], array_merge($aStyle[$style]['color'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
+ // Статус игрового сервера
+ $myPicture->drawFilledRectangle(25, 35, 153, 48, $aStyle[$style]['box']);
+ $myPicture->drawText(28, 47, 'Состояние сервера', array_merge($aStyle[$style]['boxcolor'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
+ $myPicture->drawText(26, 62, graph::status($server['status'], $server['map']), array_merge($aStyle[$style]['color'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
- // Статус игрового сервера
- $myPicture->drawFilledRectangle(215, 36, 410, 49, $aStyle[$style]['box']);
- $myPicture->drawText(218, 48, 'Состояние сервера', array_merge($aStyle[$style]['boxcolor'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
- $myPicture->drawText(216, 62, graph::status($server['status'], $server['map']), array_merge($aStyle[$style]['color'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
+ // Игроки на игровом сервере
+ $myPicture->drawFilledRectangle(25, 65, 153, 78, $aStyle[$style]['box']);
+ $myPicture->drawText(28, 77, 'Игроки на сервере', array_merge($aStyle[$style]['boxcolor'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
+ $myPicture->drawText(26, 92, $server['online'].' / '.$server['slots_start'], array_merge($aStyle[$style]['color'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
- // Игроки на игровом сервере
- $myPicture->drawFilledRectangle(5, 67, 210, 80, $aStyle[$style]['box']);
- $myPicture->drawText(8, 79, 'Игроки на сервере', array_merge($aStyle[$style]['boxcolor'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
- $myPicture->drawText(6, 93, $server['online'].' / '.$server['slots_start'], array_merge($aStyle[$style]['color'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
+ // Полоска загрузки
+ $myPicture->drawProgress(83, 82, ceil($server['slots_start']/100*$server['online']), array_merge($aStyle[$style]['progress'], array('Width' => 70, 'Height' => 8)));
- // Полоска загрузки
- $myPicture->drawProgress(90, 83, ceil($server['slots_start']/100*$server['online']), array_merge($aStyle[$style]['progress'], array('Width' => 120, 'Height' => 8)));
+ // Тип игрового сервера
+ $myPicture->drawFilledRectangle(25, 95, 153, 108, $aStyle[$style]['box']);
+ $myPicture->drawText(28, 107, 'Тип сервера', array_merge($aStyle[$style]['boxcolor'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
+ $myPicture->drawText(26, 122, $aGname[$server['game']], array_merge($aStyle[$style]['color'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
- // Тип игрового сервера
- $myPicture->drawFilledRectangle(215, 67, 410, 80, $aStyle[$style]['box']);
- $myPicture->drawText(218, 79, 'Тип сервера', array_merge($aStyle[$style]['boxcolor'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
- $myPicture->drawText(216, 91, $aGname[$server['game']], array_merge($aStyle[$style]['color'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
+ // Хостинг игровых серверов
+ $myPicture->drawText(89, 230, $cfg['graph'], array_merge($aStyle[$style]['color'], array('FontSize' => 10, 'Align' => TEXT_ALIGN_BOTTOMMIDDLE)));
+ $myPicture->drawText(89, 245, 'Хостинг игровых серверов', array_merge($aStyle[$style]['color'], array('FontSize' => 8, 'Align' => TEXT_ALIGN_BOTTOMMIDDLE)));
- // Хостинг игровых серверов
- $myPicture->drawText(490, 77, $cfg['graph'], array('FontSize' => 10, 'Align' => TEXT_ALIGN_BOTTOMMIDDLE));
- $myPicture->drawText(490, 90, 'Хостинг игровых серверов', array('FontSize' => 8, 'Align' => TEXT_ALIGN_BOTTOMMIDDLE));
+ $myPicture->drawSplineChart();
- $myPicture->drawSplineChart();
+ $myPicture->render(TEMP.(md5($key.$style.'first')).'.png');
- $myPicture->render(TEMP.(md5($key.$style.'second')).'.png');
+ unset($MyData, $myPicture);
- unset($MyData, $myPicture);
+ return NULL;
+ }
- return NULL;
- }
+ public static function second($server, $aPoints, $aStyle, $style, $key)
+ {
+ global $cfg, $aGname;
- public static function online_day($server, $max)
- {
- global $sql, $start_point;
+ $MyData = new pData();
- $time = $start_point-86400;
+ // Значения
+ $MyData->addPoints($aPoints, 'ONLINE');
- $aOnline = array();
+ $MyData->addPoints(array(VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID, VOID), 'NONE');
+ $MyData->setAbscissa('NONE');
- $aSel = array();
+ // Цвет линии
+ $MyData->setPalette('ONLINE', $aStyle[$style]['line']);
- $sql->query('SELECT `online` FROM `graph_hour` WHERE `server`="'.$server.'" AND `time`>"'.$time.'" ORDER BY `id` DESC LIMIT 24');
- while($value = $sql->get())
- $aSel[] = $value['online'];
+ // Размер баннера
+ $myPicture = new pImage(560, 95, $MyData);
- $n = count($aSel);
+ // Цвет фона
+ $myPicture->drawFilledRectangle(0, 0, 560, 95, $aStyle[$style]['fon']);
- $n = $n > 1 ? $n-1 : 0;
+ // Название игрового сервера
+ $myPicture->drawFilledRectangle(5, 5, 410, 18, $aStyle[$style]['box']);
+ $myPicture->drawText(8, 17, 'Название сервера', array_merge($aStyle[$style]['boxcolor'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
+ $myPicture->drawText(6, 31, $server['name'], array_merge($aStyle[$style]['color'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
- if($n)
- {
- for($i = $n; $i >= 0; $i-=1)
- $aOnline[] = $aSel[$i] > $max ? $max : $aSel[$i];
- }
+ // Костыль для "обрезания" названия сервера
+ $myPicture->drawFilledRectangle(405, 19, 560, 35, $aStyle[$style]['fon']);
- $add = count($aOnline);
+ // Обводка
+ $myPicture->drawRectangle(0, 0, 559, 94, $aStyle[$style]['border']);
- if($add < 24)
- {
- for($i = $n; $i <= 23; $i+=1)
- $aOnline[] = 0;
- }
+ // Шрифт текста
+ $myPicture->setFontProperties(array_merge($aStyle[$style]['color'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 5)));
- return $aOnline;
- }
+ // Размер графика
+ $myPicture->setGraphArea(430, 5, 554, 60);
- private static function graph_data($period, $server, $max)
- {
- global $sql, $start_point;
+ // Цвет фона графика
+ $myPicture->drawFilledRectangle(430, 5, 554, 60, $aStyle[$style]['graph']);
- $aData = array(
- 'limit' => array(
- 'day' => 24,
- 'week' => 7,
- 'month' => 30
- ),
+ // График
+ $myPicture->drawScale(array('XMargin' => 5, 'YMargin' => 5, 'CycleBackground' => TRUE, 'LabelSkip' => 0, 'DrawSubTicks' => TRUE, 'Mode' => SCALE_MODE_MANUAL, 'Factors' => array(0 => array($server['slots_start'])), 'ManualScale' => array(0 => array('Min' => 0, 'Max' => $server['slots_start']))));
- 'for' => array(
- 'day' => 23,
- 'week' => 6,
- 'month' => 29
- ),
+ // Адрес игрового сервера
+ $myPicture->drawFilledRectangle(5, 36, 210, 49, $aStyle[$style]['box']);
+ $myPicture->drawText(8, 48, 'Адрес сервера', array_merge($aStyle[$style]['boxcolor'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
+ $myPicture->drawText(6, 62, $server['address'], array_merge($aStyle[$style]['color'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
- 'from' => array(
- 'day' => 'graph_hour',
- 'week' => 'graph_day',
- 'month' => 'graph_day'
- ),
+ // Статус игрового сервера
+ $myPicture->drawFilledRectangle(215, 36, 410, 49, $aStyle[$style]['box']);
+ $myPicture->drawText(218, 48, 'Состояние сервера', array_merge($aStyle[$style]['boxcolor'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
+ $myPicture->drawText(216, 62, graph::status($server['status'], $server['map']), array_merge($aStyle[$style]['color'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
- 'time' => array(
- 'day' => 86400,
- 'week' => 604800,
- 'month' => 2592000
- )
- );
+ // Игроки на игровом сервере
+ $myPicture->drawFilledRectangle(5, 67, 210, 80, $aStyle[$style]['box']);
+ $myPicture->drawText(8, 79, 'Игроки на сервере', array_merge($aStyle[$style]['boxcolor'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
+ $myPicture->drawText(6, 93, $server['online'].' / '.$server['slots_start'], array_merge($aStyle[$style]['color'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
- $time = $start_point-$aData['time'][$period];
+ // Полоска загрузки
+ $myPicture->drawProgress(90, 83, ceil($server['slots_start']/100*$server['online']), array_merge($aStyle[$style]['progress'], array('Width' => 120, 'Height' => 8)));
- $aOnline = array();
+ // Тип игрового сервера
+ $myPicture->drawFilledRectangle(215, 67, 410, 80, $aStyle[$style]['box']);
+ $myPicture->drawText(218, 79, 'Тип сервера', array_merge($aStyle[$style]['boxcolor'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
+ $myPicture->drawText(216, 91, $aGname[$server['game']], array_merge($aStyle[$style]['color'], array('FontName' => LIB.'games/graph/fonts/tahoma.ttf', 'FontSize' => 8)));
- $aCPU = array();
- $aRAM = array();
- $aHDD = array();
- $aTime = array();
+ // Хостинг игровых серверов
+ $myPicture->drawText(490, 77, $cfg['graph'], array('FontSize' => 10, 'Align' => TEXT_ALIGN_BOTTOMMIDDLE));
+ $myPicture->drawText(490, 90, 'Хостинг игровых серверов', array('FontSize' => 8, 'Align' => TEXT_ALIGN_BOTTOMMIDDLE));
- $aSel = array();
+ $myPicture->drawSplineChart();
- $sql->query('SELECT `online`, `cpu`, `ram`, `hdd`, `time` FROM `'.$aData['from'][$period].'` WHERE `server`="'.$server.'" AND `time`>"'.$time.'" ORDER BY `id` DESC LIMIT '.$aData['limit'][$period]);
- while($value = $sql->get())
- $aSel[] = array('online' => $value['online'], 'cpu' => $value['cpu'], 'ram' => $value['ram'], 'hdd' => $value['hdd'], 'time' => $value['time']);
+ $myPicture->render(TEMP.(md5($key.$style.'second')).'.png');
- $n = count($aSel);
+ unset($MyData, $myPicture);
- $n = $n > 1 ? $n-1 : 0;
+ return NULL;
+ }
- $next = true;
+ public static function online_day($server, $max)
+ {
+ global $sql, $start_point;
- if(isset($aSel[$n]['online']))
- {
- for($i = $n; $i >= 0; $i-=1)
- {
- $aOnline[] = $aSel[$i]['online'] > $max ? $max : $aSel[$i]['online'];
+ $time = $start_point-86400;
- $aCPU[] = $aSel[$i]['cpu'];
- $aRAM[] = $aSel[$i]['ram'];
- $aHDD[] = $aSel[$i]['hdd'];
+ $aOnline = array();
- if($next)
- {
- $aTime[] = VOID;
+ $aSel = array();
- $next = false;
- }else{
- $aTime[] = $period == 'day' ? date('H:i', $aSel[$i]['time']) : date('d.m', $aSel[$i]['time']);
+ $sql->query('SELECT `online` FROM `graph_hour` WHERE `server`="'.$server.'" AND `time`>"'.$time.'" ORDER BY `id` DESC LIMIT 24');
+ while($value = $sql->get())
+ $aSel[] = $value['online'];
- $next = true;
- }
- }
- }
+ $n = count($aSel);
- $add = count($aOnline);
+ $n = $n > 1 ? $n-1 : 0;
- for($i = $add; $i <= $aData['for'][$period]; $i+=1)
- {
- $aOnline[] = 0;
+ if($n)
+ {
+ for($i = $n; $i >= 0; $i-=1)
+ $aOnline[] = $aSel[$i] > $max ? $max : $aSel[$i];
+ }
- $aCPU[] = 0;
- $aRAM[] = 0;
- $aHDD[] = 0;
+ $add = count($aOnline);
- $aTime[] = VOID;
- }
+ if($add < 24)
+ {
+ for($i = $n; $i <= 23; $i+=1)
+ $aOnline[] = 0;
+ }
- return array('online' => $aOnline, 'cpu' => $aCPU, 'ram' => $aRAM, 'hdd' => $aHDD, 'time' => $aTime);
- }
+ return $aOnline;
+ }
- private static function status($status, $map)
- {
- switch($status)
- {
- case 'working':
- return 'Карта: '.$map;
- case 'off':
- return 'Статус: выключен';
- case 'start':
- return 'Статус: запускается';
- case 'restart':
- return 'Статус: перезапускается';
- case 'change':
- return 'Статус: меняется карта';
- case 'install':
- return 'Статус: устанавливается';
- case 'reinstall':
- return 'Статус: переустанавливается';
- case 'update':
- return 'Статус: обновляется';
- case 'recovery':
- return 'Статус: восстанавливается';
- case 'overdue':
- return 'Статус: просрочен';
- case 'blocked':
- return 'Статус: заблокирован';
- }
- }
+ private static function graph_data($period, $server, $max)
+ {
+ global $sql, $start_point;
- private static function average($arr)
- {
- return !count($arr) ? 0 : ceil(array_sum($arr)/count($arr));
- }
- }
+ $aData = array(
+ 'limit' => array(
+ 'day' => 24,
+ 'week' => 7,
+ 'month' => 30
+ ),
+
+ 'for' => array(
+ 'day' => 23,
+ 'week' => 6,
+ 'month' => 29
+ ),
+
+ 'from' => array(
+ 'day' => 'graph_hour',
+ 'week' => 'graph_day',
+ 'month' => 'graph_day'
+ ),
+
+ 'time' => array(
+ 'day' => 86400,
+ 'week' => 604800,
+ 'month' => 2592000
+ )
+ );
+
+ $time = $start_point-$aData['time'][$period];
+
+ $aOnline = array();
+
+ $aCPU = array();
+ $aRAM = array();
+ $aHDD = array();
+ $aTime = array();
+
+ $aSel = array();
+
+ $sql->query('SELECT `online`, `cpu`, `ram`, `hdd`, `time` FROM `'.$aData['from'][$period].'` WHERE `server`="'.$server.'" AND `time`>"'.$time.'" ORDER BY `id` DESC LIMIT '.$aData['limit'][$period]);
+ while($value = $sql->get())
+ $aSel[] = array('online' => $value['online'], 'cpu' => $value['cpu'], 'ram' => $value['ram'], 'hdd' => $value['hdd'], 'time' => $value['time']);
+
+ $n = count($aSel);
+
+ $n = $n > 1 ? $n-1 : 0;
+
+ $next = true;
+
+ if(isset($aSel[$n]['online']))
+ {
+ for($i = $n; $i >= 0; $i-=1)
+ {
+ $aOnline[] = $aSel[$i]['online'] > $max ? $max : $aSel[$i]['online'];
+
+ $aCPU[] = $aSel[$i]['cpu'];
+ $aRAM[] = $aSel[$i]['ram'];
+ $aHDD[] = $aSel[$i]['hdd'];
+
+ if($next)
+ {
+ $aTime[] = VOID;
+
+ $next = false;
+ }else{
+ $aTime[] = $period == 'day' ? date('H:i', $aSel[$i]['time']) : date('d.m', $aSel[$i]['time']);
+
+ $next = true;
+ }
+ }
+ }
+
+ $add = count($aOnline);
+
+ for($i = $add; $i <= $aData['for'][$period]; $i+=1)
+ {
+ $aOnline[] = 0;
+
+ $aCPU[] = 0;
+ $aRAM[] = 0;
+ $aHDD[] = 0;
+
+ $aTime[] = VOID;
+ }
+
+ return array('online' => $aOnline, 'cpu' => $aCPU, 'ram' => $aRAM, 'hdd' => $aHDD, 'time' => $aTime);
+ }
+
+ private static function status($status, $map)
+ {
+ switch($status)
+ {
+ case 'working':
+ return 'Карта: '.$map;
+ case 'off':
+ return 'Статус: выключен';
+ case 'start':
+ return 'Статус: запускается';
+ case 'restart':
+ return 'Статус: перезапускается';
+ case 'change':
+ return 'Статус: меняется карта';
+ case 'install':
+ return 'Статус: устанавливается';
+ case 'reinstall':
+ return 'Статус: переустанавливается';
+ case 'update':
+ return 'Статус: обновляется';
+ case 'recovery':
+ return 'Статус: восстанавливается';
+ case 'overdue':
+ return 'Статус: просрочен';
+ case 'blocked':
+ return 'Статус: заблокирован';
+ }
+ }
+
+ private static function average($arr)
+ {
+ return !count($arr) ? 0 : ceil(array_sum($arr)/count($arr));
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/games/graph/pData.php b/system/library/games/graph/pData.php
index dc79cb9..7c46584 100644
--- a/system/library/games/graph/pData.php
+++ b/system/library/games/graph/pData.php
@@ -1,518 +1,518 @@
array('R'=>188,'G'=>224,'B'=>46,'Alpha'=>100),
- '1'=>array('R'=>224,'G'=>100,'B'=>46,'Alpha'=>100),
- '2'=>array('R'=>224,'G'=>214,'B'=>46,'Alpha'=>100),
- '3'=>array('R'=>46,'G'=>151,'B'=>224,'Alpha'=>100),
- '4'=>array('R'=>176,'G'=>46,'B'=>224,'Alpha'=>100),
- '5'=>array('R'=>224,'G'=>46,'B'=>117,'Alpha'=>100),
- '6'=>array('R'=>92,'G'=>224,'B'=>46,'Alpha'=>100),
- '7'=>array('R'=>224,'G'=>176,'B'=>46,'Alpha'=>100));
-
- function pData()
- {
- $this->Data = '';
- $this->Data['XAxisDisplay'] = AXIS_FORMAT_DEFAULT;
- $this->Data['XAxisFormat'] = NULL;
- $this->Data['XAxisName'] = NULL;
- $this->Data['XAxisUnit'] = NULL;
- $this->Data['Abscissa'] = NULL;
- $this->Data['AbsicssaPosition'] = AXIS_POSITION_BOTTOM;
- $this->Data['Axis'][0]['Display'] = AXIS_FORMAT_DEFAULT;
- $this->Data['Axis'][0]['Position'] = AXIS_POSITION_LEFT;
- $this->Data['Axis'][0]['Identity'] = AXIS_Y;
- }
-
- function addPoints($Values, $SerieName = 'Serie1')
- {
- if(!isset($this->Data['Series'][$SerieName]))
- $this->initialise($SerieName);
-
- if(is_array($Values))
- {
- foreach($Values as $Key => $Value)
- $this->Data['Series'][$SerieName]['Data'][] = $Value;
- }else
- $this->Data['Series'][$SerieName]['Data'][] = $Values;
-
- if($Values != VOID)
- {
- $StrippedData = $this->stripVOID($this->Data['Series'][$SerieName]['Data']);
-
- if(empty($StrippedData))
- {
- $this->Data['Series'][$SerieName]['Max'] = 0;
- $this->Data['Series'][$SerieName]['Min'] =0;
- return(0);
- }
-
- $this->Data['Series'][$SerieName]['Max'] = max($StrippedData);
- $this->Data['Series'][$SerieName]['Min'] = min($StrippedData);
- }
- }
-
- function stripVOID($Values)
- {
- if(!is_array($Values))
- return(array());
-
- $Result = array();
-
- foreach($Values as $Key => $Value)
- {
- if($Value != VOID)
- $Result[] = $Value;
- }
-
- return($Result);
- }
-
- function getSerieCount($Serie)
- {
- if(isset($this->Data['Series'][$Serie]['Data']))
- return(sizeof($this->Data['Series'][$Serie]['Data']));
-
- return(0);
- }
-
- function removeSerie($Series)
- {
- if(!is_array($Series))
- $Series = $this->convertToArray($Series);
-
- foreach($Series as $Key => $Serie)
- {
- if(isset($this->Data['Series'][$Serie]))
- unset($this->Data['Series'][$Serie]);
- }
- }
-
- function getValueAt($Serie,$Index=0)
- {
- if(isset($this->Data['Series'][$Serie]['Data'][$Index]))
- return($this->Data['Series'][$Serie]['Data'][$Index]);
-
- return(NULL);
- }
-
- function getValues($Serie)
- {
- if(isset($this->Data['Series'][$Serie]['Data']))
- return($this->Data['Series'][$Serie]['Data']);
-
- return(NULL);
- }
-
- function reverseSerie($Series)
- {
- if(!is_array($Series))
- $Series = $this->convertToArray($Series);
-
- foreach($Series as $Key => $Serie)
- {
- if(isset($this->Data['Series'][$Serie]['Data']))
- $this->Data['Series'][$Serie]['Data'] = array_reverse($this->Data['Series'][$Serie]['Data']);
- }
- }
-
- function getSum($Serie)
- {
- if(isset($this->Data['Series'][$Serie]))
- return(array_sum($this->Data['Series'][$Serie]['Data']));
-
- return(NULL);
- }
-
- function getMax($Serie)
- {
- if(isset($this->Data['Series'][$Serie]['Max']))
- return($this->Data['Series'][$Serie]['Max']);
-
- return(NULL);
- }
-
- function getMin($Serie)
- {
- if(isset($this->Data['Series'][$Serie]['Min']))
- return($this->Data['Series'][$Serie]['Min']);
-
- return(NULL);
- }
-
- function setSerieShape($Series, $Shape = SERIE_SHAPE_FILLEDCIRCLE)
- {
- if(!is_array($Series))
- $Series = $this->convertToArray($Series);
-
- foreach($Series as $Key => $Serie)
- {
- if(isset($this->Data['Series'][$Serie]))
- $this->Data['Series'][$Serie]['Shape'] = $Shape;
- }
- }
-
- function setSerieDescription($Series, $Description = 'My serie')
- {
- if(!is_array($Series))
- $Series = $this->convertToArray($Series);
-
- foreach($Series as $Key => $Serie)
- {
- if(isset($this->Data['Series'][$Serie]))
- $this->Data['Series'][$Serie]['Description'] = $Description;
- }
- }
-
- function setSerieDrawable($Series, $Drawable = TRUE)
- {
- if(!is_array($Series))
- $Series = $this->convertToArray($Series);
-
- foreach($Series as $Key => $Serie)
- {
- if(isset($this->Data['Series'][$Serie]))
- $this->Data['Series'][$Serie]['isDrawable'] = $Drawable;
- }
- }
-
- function setSeriePicture($Series,$Picture=NULL)
- {
- if(!is_array($Series))
- $Series = $this->convertToArray($Series);
-
- foreach($Series as $Key => $Serie)
- {
- if(isset($this->Data['Series'][$Serie]))
- $this->Data['Series'][$Serie]['Picture'] = $Picture;
- }
- }
-
- function setXAxisName($Name)
- {
- $this->Data['XAxisName'] = $Name;
- }
-
- function setXAxisDisplay($Mode, $Format = NULL)
- {
- $this->Data['XAxisDisplay'] = $Mode;
- $this->Data['XAxisFormat'] = $Format;
- }
-
- function setXAxisUnit($Unit)
- {
- $this->Data['XAxisUnit'] = $Unit;
- }
-
- function setAbscissa($Serie)
- {
- if(isset($this->Data['Series'][$Serie]))
- $this->Data['Abscissa'] = $Serie;
- }
-
- function setAbsicssaPosition($Position = AXIS_POSITION_BOTTOM)
- {
- $this->Data['AbsicssaPosition'] = $Position;
- }
-
- function setAbscissaName($Name)
- {
- $this->Data['AbscissaName'] = $Name;
- }
-
- function setScatterSerie($SerieX, $SerieY, $ID = 0)
- {
- if(isset($this->Data['Series'][$SerieX]) && isset($this->Data['Series'][$SerieY]))
- {
- $this->initScatterSerie($ID);
- $this->Data['ScatterSeries'][$ID]['X'] = $SerieX;
- $this->Data['ScatterSeries'][$ID]['Y'] = $SerieY;
- }
- }
-
- function setScatterSerieShape($ID, $Shape = SERIE_SHAPE_FILLEDCIRCLE)
- {
- if(isset($this->Data['ScatterSeries'][$ID]))
- $this->Data['ScatterSeries'][$ID]['Shape'] = $Shape;
- }
-
- function setScatterSerieDescription($ID, $Description = 'My serie')
- {
- if(isset($this->Data['ScatterSeries'][$ID]))
- $this->Data['ScatterSeries'][$ID]['Description'] = $Description;
- }
-
- function setScatterSeriePicture($ID, $Picture = NULL)
- {
- if(isset($this->Data['ScatterSeries'][$ID]))
- $this->Data['ScatterSeries'][$ID]['Picture'] = $Picture;
- }
-
- function setScatterSerieDrawable($ID, $Drawable = TRUE)
- {
- if(isset($this->Data['ScatterSeries'][$ID]))
- $this->Data['ScatterSeries'][$ID]['isDrawable'] = $Drawable;
- }
-
- function setScatterSerieTicks($ID, $Width = 0)
- {
- if(isset($this->Data['ScatterSeries'][$ID]))
- $this->Data['ScatterSeries'][$ID]['Ticks'] = $Width;
- }
-
- function setScatterSerieWeight($ID, $Weight = 0)
- {
- if(isset($this->Data['ScatterSeries'][$ID]))
- $this->Data['ScatterSeries'][$ID]['Weight'] = $Weight;
- }
-
- function setScatterSerieColor($ID, $Format)
- {
- $R = isset($Format['R']) ? $Format['R'] : 0;
- $G = isset($Format['G']) ? $Format['G'] : 0;
- $B = isset($Format['B']) ? $Format['B'] : 0;
- $Alpha = isset($Format['Alpha']) ? $Format['Alpha'] : 100;
-
- if(isset($this->Data['ScatterSeries'][$ID]))
- {
- $this->Data['ScatterSeries'][$ID]['Color']['R'] = $R;
- $this->Data['ScatterSeries'][$ID]['Color']['G'] = $G;
- $this->Data['ScatterSeries'][$ID]['Color']['B'] = $B;
- $this->Data['ScatterSeries'][$ID]['Color']['Alpha'] = $Alpha;
- }
- }
-
- function limits()
- {
- $GlobalMin = ABSOLUTE_MAX;
- $GlobalMax = ABSOLUTE_MIN;
-
- foreach($this->Data['Series'] as $Key => $Value)
- {
- if($this->Data['Abscissa'] != $Key && $this->Data['Series'][$Key]['isDrawable'] == TRUE)
- {
- if($GlobalMin > $this->Data['Series'][$Key]['Min'])
- $GlobalMin = $this->Data['Series'][$Key]['Min'];
-
- if($GlobalMax < $this->Data['Series'][$Key]['Max'])
- $GlobalMax = $this->Data['Series'][$Key]['Max'];
- }
- }
-
- $this->Data['Min'] = $GlobalMin;
- $this->Data['Max'] = $GlobalMax;
-
- return(array($GlobalMin,$GlobalMax));
- }
-
- function drawAll()
- {
- foreach($this->Data['Series'] as $Key => $Value)
- {
- if($this->Data['Abscissa'] != $Key)
- $this->Data['Series'][$Key]['isDrawable'] = TRUE;
- }
- }
-
- function getSerieAverage($Serie)
- {
- if(isset($this->Data['Series'][$Serie]))
- {
- $SerieData = $this->stripVOID($this->Data['Series'][$Serie]['Data']);
-
- return(array_sum($SerieData)/sizeof($SerieData));
- }
-
- return(NULL);
- }
-
- function getGeometricMean($Serie)
- {
- if(isset($this->Data['Series'][$Serie]))
- {
- $SerieData = $this->stripVOID($this->Data['Series'][$Serie]['Data']);
- $Seriesum = 1;
-
- foreach($SerieData as $Key => $Value)
- $Seriesum = $Seriesum * $Value;
-
- return(pow($Seriesum,1/sizeof($SerieData)));
- }
-
- return(NULL);
- }
-
- function getHarmonicMean($Serie)
- {
- if(isset($this->Data['Series'][$Serie]))
- {
- $SerieData = $this->stripVOID($this->Data['Series'][$Serie]['Data']);
- $Seriesum = 0;
-
- foreach($SerieData as $Key => $Value)
- $Seriesum = $Seriesum + 1/$Value;
-
- return(sizeof($SerieData)/$Seriesum);
- }
-
- return(NULL);
- }
-
- function getStandardDeviation($Serie)
- {
- if(isset($this->Data['Series'][$Serie]))
- {
- $Average = $this->getSerieAverage($Serie);
- $SerieData = $this->stripVOID($this->Data['Series'][$Serie]['Data']);
-
- $DeviationSum = 0;
-
- foreach($SerieData as $Key => $Value)
- $DeviationSum = $DeviationSum + ($Value-$Average)*($Value-$Average);
-
- $Deviation = sqrt($DeviationSum/count($SerieData));
-
- return($Deviation);
- }
-
- return(NULL);
- }
-
- function getCoefficientOfVariation($Serie)
- {
- if(isset($this->Data['Series'][$Serie]))
- {
- $Average = $this->getSerieAverage($Serie);
- $StandardDeviation = $this->getStandardDeviation($Serie);
-
- if($StandardDeviation != 0)
- return($StandardDeviation/$Average);
- }
-
- return(NULL);
- }
-
- function getSerieMedian($Serie)
- {
- if(isset($this->Data['Series'][$Serie]))
- {
- $SerieData = $this->stripVOID($this->Data['Series'][$Serie]['Data']);
-
- sort($SerieData);
-
- $SerieCenter = floor(sizeof($SerieData)/2);
-
- if(isset($SerieData[$SerieCenter]))
- return($SerieData[$SerieCenter]);
- }
-
- return(NULL);
- }
-
- function getSeriePercentile($Serie = 'Serie1', $Percentil = 95)
- {
- if(!isset($this->Data['Series'][$Serie]['Data']))
- return(NULL);
+ if(!DEFINED('EGP'))
+ exit(header('Refresh: 0; URL=http://'.$_SERVER['SERVER_NAME'].'/404'));
+
+ define('AXIS_FORMAT_DEFAULT', 680001);
+ define('AXIS_FORMAT_TIME', 680002);
+ define('AXIS_FORMAT_DATE', 680003);
+ define('AXIS_FORMAT_METRIC', 680004);
+ define('AXIS_FORMAT_CURRENCY', 680005);
+ define('AXIS_FORMAT_TRAFFIC', 680006);
+ define('AXIS_FORMAT_CUSTOM', 680007);
+ define('AXIS_POSITION_LEFT', 681001);
+ define('AXIS_POSITION_RIGHT', 681002);
+ define('AXIS_POSITION_TOP', 681001);
+ define('AXIS_POSITION_BOTTOM', 681002);
+ define('SERIE_SHAPE_FILLEDCIRCLE', 681011);
+ define('SERIE_SHAPE_FILLEDTRIANGLE', 681012);
+ define('SERIE_SHAPE_FILLEDSQUARE', 681013);
+ define('SERIE_SHAPE_FILLEDDIAMOND', 681017);
+ define('SERIE_SHAPE_CIRCLE', 681014);
+ define('SERIE_SHAPE_TRIANGLE', 681015);
+ define('SERIE_SHAPE_SQUARE', 681016);
+ define('SERIE_SHAPE_DIAMOND', 681018);
+ define('AXIS_X', 682001);
+ define('AXIS_Y', 682002);
+ define('ABSOLUTE_MIN', -10000000000000);
+ define('ABSOLUTE_MAX', 10000000000000);
+ define('VOID' , 0.123456789);
+ define('EURO_SYMBOL', utf8_encode('€'));
+
+ class pData
+ {
+ var $Data;
+
+ var $Palette = array('0'=>array('R'=>188,'G'=>224,'B'=>46,'Alpha'=>100),
+ '1'=>array('R'=>224,'G'=>100,'B'=>46,'Alpha'=>100),
+ '2'=>array('R'=>224,'G'=>214,'B'=>46,'Alpha'=>100),
+ '3'=>array('R'=>46,'G'=>151,'B'=>224,'Alpha'=>100),
+ '4'=>array('R'=>176,'G'=>46,'B'=>224,'Alpha'=>100),
+ '5'=>array('R'=>224,'G'=>46,'B'=>117,'Alpha'=>100),
+ '6'=>array('R'=>92,'G'=>224,'B'=>46,'Alpha'=>100),
+ '7'=>array('R'=>224,'G'=>176,'B'=>46,'Alpha'=>100));
+
+ function pData()
+ {
+ $this->Data = '';
+ $this->Data['XAxisDisplay'] = AXIS_FORMAT_DEFAULT;
+ $this->Data['XAxisFormat'] = NULL;
+ $this->Data['XAxisName'] = NULL;
+ $this->Data['XAxisUnit'] = NULL;
+ $this->Data['Abscissa'] = NULL;
+ $this->Data['AbsicssaPosition'] = AXIS_POSITION_BOTTOM;
+ $this->Data['Axis'][0]['Display'] = AXIS_FORMAT_DEFAULT;
+ $this->Data['Axis'][0]['Position'] = AXIS_POSITION_LEFT;
+ $this->Data['Axis'][0]['Identity'] = AXIS_Y;
+ }
+
+ function addPoints($Values, $SerieName = 'Serie1')
+ {
+ if(!isset($this->Data['Series'][$SerieName]))
+ $this->initialise($SerieName);
+
+ if(is_array($Values))
+ {
+ foreach($Values as $Key => $Value)
+ $this->Data['Series'][$SerieName]['Data'][] = $Value;
+ }else
+ $this->Data['Series'][$SerieName]['Data'][] = $Values;
+
+ if($Values != VOID)
+ {
+ $StrippedData = $this->stripVOID($this->Data['Series'][$SerieName]['Data']);
+
+ if(empty($StrippedData))
+ {
+ $this->Data['Series'][$SerieName]['Max'] = 0;
+ $this->Data['Series'][$SerieName]['Min'] =0;
+ return(0);
+ }
+
+ $this->Data['Series'][$SerieName]['Max'] = max($StrippedData);
+ $this->Data['Series'][$SerieName]['Min'] = min($StrippedData);
+ }
+ }
+
+ function stripVOID($Values)
+ {
+ if(!is_array($Values))
+ return(array());
+
+ $Result = array();
+
+ foreach($Values as $Key => $Value)
+ {
+ if($Value != VOID)
+ $Result[] = $Value;
+ }
+
+ return($Result);
+ }
+
+ function getSerieCount($Serie)
+ {
+ if(isset($this->Data['Series'][$Serie]['Data']))
+ return(sizeof($this->Data['Series'][$Serie]['Data']));
+
+ return(0);
+ }
+
+ function removeSerie($Series)
+ {
+ if(!is_array($Series))
+ $Series = $this->convertToArray($Series);
+
+ foreach($Series as $Key => $Serie)
+ {
+ if(isset($this->Data['Series'][$Serie]))
+ unset($this->Data['Series'][$Serie]);
+ }
+ }
+
+ function getValueAt($Serie,$Index=0)
+ {
+ if(isset($this->Data['Series'][$Serie]['Data'][$Index]))
+ return($this->Data['Series'][$Serie]['Data'][$Index]);
+
+ return(NULL);
+ }
+
+ function getValues($Serie)
+ {
+ if(isset($this->Data['Series'][$Serie]['Data']))
+ return($this->Data['Series'][$Serie]['Data']);
+
+ return(NULL);
+ }
+
+ function reverseSerie($Series)
+ {
+ if(!is_array($Series))
+ $Series = $this->convertToArray($Series);
+
+ foreach($Series as $Key => $Serie)
+ {
+ if(isset($this->Data['Series'][$Serie]['Data']))
+ $this->Data['Series'][$Serie]['Data'] = array_reverse($this->Data['Series'][$Serie]['Data']);
+ }
+ }
+
+ function getSum($Serie)
+ {
+ if(isset($this->Data['Series'][$Serie]))
+ return(array_sum($this->Data['Series'][$Serie]['Data']));
+
+ return(NULL);
+ }
+
+ function getMax($Serie)
+ {
+ if(isset($this->Data['Series'][$Serie]['Max']))
+ return($this->Data['Series'][$Serie]['Max']);
+
+ return(NULL);
+ }
+
+ function getMin($Serie)
+ {
+ if(isset($this->Data['Series'][$Serie]['Min']))
+ return($this->Data['Series'][$Serie]['Min']);
+
+ return(NULL);
+ }
+
+ function setSerieShape($Series, $Shape = SERIE_SHAPE_FILLEDCIRCLE)
+ {
+ if(!is_array($Series))
+ $Series = $this->convertToArray($Series);
+
+ foreach($Series as $Key => $Serie)
+ {
+ if(isset($this->Data['Series'][$Serie]))
+ $this->Data['Series'][$Serie]['Shape'] = $Shape;
+ }
+ }
+
+ function setSerieDescription($Series, $Description = 'My serie')
+ {
+ if(!is_array($Series))
+ $Series = $this->convertToArray($Series);
+
+ foreach($Series as $Key => $Serie)
+ {
+ if(isset($this->Data['Series'][$Serie]))
+ $this->Data['Series'][$Serie]['Description'] = $Description;
+ }
+ }
+
+ function setSerieDrawable($Series, $Drawable = TRUE)
+ {
+ if(!is_array($Series))
+ $Series = $this->convertToArray($Series);
+
+ foreach($Series as $Key => $Serie)
+ {
+ if(isset($this->Data['Series'][$Serie]))
+ $this->Data['Series'][$Serie]['isDrawable'] = $Drawable;
+ }
+ }
+
+ function setSeriePicture($Series,$Picture=NULL)
+ {
+ if(!is_array($Series))
+ $Series = $this->convertToArray($Series);
+
+ foreach($Series as $Key => $Serie)
+ {
+ if(isset($this->Data['Series'][$Serie]))
+ $this->Data['Series'][$Serie]['Picture'] = $Picture;
+ }
+ }
+
+ function setXAxisName($Name)
+ {
+ $this->Data['XAxisName'] = $Name;
+ }
+
+ function setXAxisDisplay($Mode, $Format = NULL)
+ {
+ $this->Data['XAxisDisplay'] = $Mode;
+ $this->Data['XAxisFormat'] = $Format;
+ }
+
+ function setXAxisUnit($Unit)
+ {
+ $this->Data['XAxisUnit'] = $Unit;
+ }
+
+ function setAbscissa($Serie)
+ {
+ if(isset($this->Data['Series'][$Serie]))
+ $this->Data['Abscissa'] = $Serie;
+ }
+
+ function setAbsicssaPosition($Position = AXIS_POSITION_BOTTOM)
+ {
+ $this->Data['AbsicssaPosition'] = $Position;
+ }
+
+ function setAbscissaName($Name)
+ {
+ $this->Data['AbscissaName'] = $Name;
+ }
+
+ function setScatterSerie($SerieX, $SerieY, $ID = 0)
+ {
+ if(isset($this->Data['Series'][$SerieX]) && isset($this->Data['Series'][$SerieY]))
+ {
+ $this->initScatterSerie($ID);
+ $this->Data['ScatterSeries'][$ID]['X'] = $SerieX;
+ $this->Data['ScatterSeries'][$ID]['Y'] = $SerieY;
+ }
+ }
+
+ function setScatterSerieShape($ID, $Shape = SERIE_SHAPE_FILLEDCIRCLE)
+ {
+ if(isset($this->Data['ScatterSeries'][$ID]))
+ $this->Data['ScatterSeries'][$ID]['Shape'] = $Shape;
+ }
+
+ function setScatterSerieDescription($ID, $Description = 'My serie')
+ {
+ if(isset($this->Data['ScatterSeries'][$ID]))
+ $this->Data['ScatterSeries'][$ID]['Description'] = $Description;
+ }
+
+ function setScatterSeriePicture($ID, $Picture = NULL)
+ {
+ if(isset($this->Data['ScatterSeries'][$ID]))
+ $this->Data['ScatterSeries'][$ID]['Picture'] = $Picture;
+ }
+
+ function setScatterSerieDrawable($ID, $Drawable = TRUE)
+ {
+ if(isset($this->Data['ScatterSeries'][$ID]))
+ $this->Data['ScatterSeries'][$ID]['isDrawable'] = $Drawable;
+ }
+
+ function setScatterSerieTicks($ID, $Width = 0)
+ {
+ if(isset($this->Data['ScatterSeries'][$ID]))
+ $this->Data['ScatterSeries'][$ID]['Ticks'] = $Width;
+ }
+
+ function setScatterSerieWeight($ID, $Weight = 0)
+ {
+ if(isset($this->Data['ScatterSeries'][$ID]))
+ $this->Data['ScatterSeries'][$ID]['Weight'] = $Weight;
+ }
+
+ function setScatterSerieColor($ID, $Format)
+ {
+ $R = isset($Format['R']) ? $Format['R'] : 0;
+ $G = isset($Format['G']) ? $Format['G'] : 0;
+ $B = isset($Format['B']) ? $Format['B'] : 0;
+ $Alpha = isset($Format['Alpha']) ? $Format['Alpha'] : 100;
+
+ if(isset($this->Data['ScatterSeries'][$ID]))
+ {
+ $this->Data['ScatterSeries'][$ID]['Color']['R'] = $R;
+ $this->Data['ScatterSeries'][$ID]['Color']['G'] = $G;
+ $this->Data['ScatterSeries'][$ID]['Color']['B'] = $B;
+ $this->Data['ScatterSeries'][$ID]['Color']['Alpha'] = $Alpha;
+ }
+ }
+
+ function limits()
+ {
+ $GlobalMin = ABSOLUTE_MAX;
+ $GlobalMax = ABSOLUTE_MIN;
+
+ foreach($this->Data['Series'] as $Key => $Value)
+ {
+ if($this->Data['Abscissa'] != $Key && $this->Data['Series'][$Key]['isDrawable'] == TRUE)
+ {
+ if($GlobalMin > $this->Data['Series'][$Key]['Min'])
+ $GlobalMin = $this->Data['Series'][$Key]['Min'];
+
+ if($GlobalMax < $this->Data['Series'][$Key]['Max'])
+ $GlobalMax = $this->Data['Series'][$Key]['Max'];
+ }
+ }
+
+ $this->Data['Min'] = $GlobalMin;
+ $this->Data['Max'] = $GlobalMax;
+
+ return(array($GlobalMin,$GlobalMax));
+ }
+
+ function drawAll()
+ {
+ foreach($this->Data['Series'] as $Key => $Value)
+ {
+ if($this->Data['Abscissa'] != $Key)
+ $this->Data['Series'][$Key]['isDrawable'] = TRUE;
+ }
+ }
+
+ function getSerieAverage($Serie)
+ {
+ if(isset($this->Data['Series'][$Serie]))
+ {
+ $SerieData = $this->stripVOID($this->Data['Series'][$Serie]['Data']);
+
+ return(array_sum($SerieData)/sizeof($SerieData));
+ }
+
+ return(NULL);
+ }
+
+ function getGeometricMean($Serie)
+ {
+ if(isset($this->Data['Series'][$Serie]))
+ {
+ $SerieData = $this->stripVOID($this->Data['Series'][$Serie]['Data']);
+ $Seriesum = 1;
+
+ foreach($SerieData as $Key => $Value)
+ $Seriesum = $Seriesum * $Value;
+
+ return(pow($Seriesum,1/sizeof($SerieData)));
+ }
+
+ return(NULL);
+ }
+
+ function getHarmonicMean($Serie)
+ {
+ if(isset($this->Data['Series'][$Serie]))
+ {
+ $SerieData = $this->stripVOID($this->Data['Series'][$Serie]['Data']);
+ $Seriesum = 0;
+
+ foreach($SerieData as $Key => $Value)
+ $Seriesum = $Seriesum + 1/$Value;
+
+ return(sizeof($SerieData)/$Seriesum);
+ }
+
+ return(NULL);
+ }
+
+ function getStandardDeviation($Serie)
+ {
+ if(isset($this->Data['Series'][$Serie]))
+ {
+ $Average = $this->getSerieAverage($Serie);
+ $SerieData = $this->stripVOID($this->Data['Series'][$Serie]['Data']);
+
+ $DeviationSum = 0;
+
+ foreach($SerieData as $Key => $Value)
+ $DeviationSum = $DeviationSum + ($Value-$Average)*($Value-$Average);
+
+ $Deviation = sqrt($DeviationSum/count($SerieData));
+
+ return($Deviation);
+ }
+
+ return(NULL);
+ }
+
+ function getCoefficientOfVariation($Serie)
+ {
+ if(isset($this->Data['Series'][$Serie]))
+ {
+ $Average = $this->getSerieAverage($Serie);
+ $StandardDeviation = $this->getStandardDeviation($Serie);
+
+ if($StandardDeviation != 0)
+ return($StandardDeviation/$Average);
+ }
+
+ return(NULL);
+ }
+
+ function getSerieMedian($Serie)
+ {
+ if(isset($this->Data['Series'][$Serie]))
+ {
+ $SerieData = $this->stripVOID($this->Data['Series'][$Serie]['Data']);
+
+ sort($SerieData);
+
+ $SerieCenter = floor(sizeof($SerieData)/2);
+
+ if(isset($SerieData[$SerieCenter]))
+ return($SerieData[$SerieCenter]);
+ }
+
+ return(NULL);
+ }
+
+ function getSeriePercentile($Serie = 'Serie1', $Percentil = 95)
+ {
+ if(!isset($this->Data['Series'][$Serie]['Data']))
+ return(NULL);
- $Values = count($this->Data['Series'][$Serie]['Data'])-1;
+ $Values = count($this->Data['Series'][$Serie]['Data'])-1;
- if($Values < 0)
- $Values = 0;
+ if($Values < 0)
+ $Values = 0;
- $PercentilID = floor(($Values/100)*$Percentil+.5);
- $SortedValues = $this->Data['Series'][$Serie]['Data'];
+ $PercentilID = floor(($Values/100)*$Percentil+.5);
+ $SortedValues = $this->Data['Series'][$Serie]['Data'];
- sort($SortedValues);
+ sort($SortedValues);
- if(is_numeric($SortedValues[$PercentilID]))
- return($SortedValues[$PercentilID]);
-
- return(NULL);
- }
+ if(is_numeric($SortedValues[$PercentilID]))
+ return($SortedValues[$PercentilID]);
+
+ return(NULL);
+ }
- function addRandomValues($SerieName = 'Serie1', $Options = '')
- {
- $Values = isset($Options['Values']) ? $Options['Values'] : 20;
- $Min = isset($Options['Min']) ? $Options['Min'] : 0;
- $Max = isset($Options['Max']) ? $Options['Max'] : 100;
- $withFloat = isset($Options['withFloat']) ? $Options['withFloat'] : FALSE;
+ function addRandomValues($SerieName = 'Serie1', $Options = '')
+ {
+ $Values = isset($Options['Values']) ? $Options['Values'] : 20;
+ $Min = isset($Options['Min']) ? $Options['Min'] : 0;
+ $Max = isset($Options['Max']) ? $Options['Max'] : 100;
+ $withFloat = isset($Options['withFloat']) ? $Options['withFloat'] : FALSE;
- for($i = 0; $i <= $Values; $i+=1)
- {
- if($withFloat)
- $Value = rand($Min*100,$Max*100)/100;
- else
- $Value = rand($Min, $Max);
+ for($i = 0; $i <= $Values; $i+=1)
+ {
+ if($withFloat)
+ $Value = rand($Min*100,$Max*100)/100;
+ else
+ $Value = rand($Min, $Max);
- $this->addPoints($Value,$SerieName);
- }
- }
+ $this->addPoints($Value,$SerieName);
+ }
+ }
- function containsData()
- {
- if(!isset($this->Data['Series']))
- return(FALSE);
+ function containsData()
+ {
+ if(!isset($this->Data['Series']))
+ return(FALSE);
- $Result = FALSE;
+ $Result = FALSE;
- foreach($this->Data['Series'] as $Key => $Value)
- {
- if($this->Data['Abscissa'] != $Key && $this->Data['Series'][$Key]['isDrawable'] == TRUE)
- $Result=TRUE;
- }
+ foreach($this->Data['Series'] as $Key => $Value)
+ {
+ if($this->Data['Abscissa'] != $Key && $this->Data['Series'][$Key]['isDrawable'] == TRUE)
+ $Result=TRUE;
+ }
- return($Result);
- }
+ return($Result);
+ }
- function setAxisDisplay($AxisID, $Mode = AXIS_FORMAT_DEFAULT, $Format = NULL)
- {
- if(isset($this->Data['Axis'][$AxisID]))
- {
- $this->Data['Axis'][$AxisID]['Display'] = $Mode;
+ function setAxisDisplay($AxisID, $Mode = AXIS_FORMAT_DEFAULT, $Format = NULL)
+ {
+ if(isset($this->Data['Axis'][$AxisID]))
+ {
+ $this->Data['Axis'][$AxisID]['Display'] = $Mode;
- if($Format != NULL)
- $this->Data['Axis'][$AxisID]['Format'] = $Format;
- }
- }
-
- function setAxisPosition($AxisID, $Position = AXIS_POSITION_LEFT)
- {
- if(isset($this->Data['Axis'][$AxisID]))
- {
- $this->Data['Axis'][$AxisID]['Position'] = $Position;
- }
- }
+ if($Format != NULL)
+ $this->Data['Axis'][$AxisID]['Format'] = $Format;
+ }
+ }
+
+ function setAxisPosition($AxisID, $Position = AXIS_POSITION_LEFT)
+ {
+ if(isset($this->Data['Axis'][$AxisID]))
+ {
+ $this->Data['Axis'][$AxisID]['Position'] = $Position;
+ }
+ }
/* Associate an unit to an axis */
function setAxisUnit($AxisID,$Unit)
@@ -525,9 +525,9 @@
/* Associate a color to an axis */
function setAxisColor($AxisID,$Format)
{
- $R = isset($Format['R']) ? $Format['R'] : 0;
- $G = isset($Format['G']) ? $Format['G'] : 0;
- $B = isset($Format['B']) ? $Format['B'] : 0;
+ $R = isset($Format['R']) ? $Format['R'] : 0;
+ $G = isset($Format['G']) ? $Format['G'] : 0;
+ $B = isset($Format['B']) ? $Format['B'] : 0;
$Alpha = isset($Format['Alpha']) ? $Format['Alpha'] : 100;
if ( isset($this->Data['Axis'][$AxisID] ) )
@@ -565,14 +565,14 @@
}
}
- /* define if a serie should be draw with ticks */
+ /* define if a serie should be draw with ticks */
function setSerieTicks($Series,$Width=0)
{
if ( !is_array($Series) ) { $Series = $this->convertToArray($Series); }
foreach($Series as $Key => $Serie) { if ( isset($this->Data['Series'][$Serie]) ) { $this->Data['Series'][$Serie]['Ticks'] = $Width; } }
}
- /* define if a serie should be draw with a special weight */
+ /* define if a serie should be draw with a special weight */
function setSerieWeight($Series,$Weight=0)
{
if ( !is_array($Series) ) { $Series = $this->convertToArray($Series); }
@@ -600,9 +600,9 @@
foreach($Series as $Key => $Serie)
{
- $R = isset($Format['R']) ? $Format['R'] : 0;
- $G = isset($Format['G']) ? $Format['G'] : 0;
- $B = isset($Format['B']) ? $Format['B'] : 0;
+ $R = isset($Format['R']) ? $Format['R'] : 0;
+ $G = isset($Format['G']) ? $Format['G'] : 0;
+ $B = isset($Format['B']) ? $Format['B'] : 0;
$Alpha = isset($Format['Alpha']) ? $Format['Alpha'] : 100;
if ( isset($this->Data['Series'][$Serie]) )
@@ -660,11 +660,11 @@
{
if ( isset($this->Data['ScatterSeries'][$ID]) ) { return(0); }
- $this->Data['ScatterSeries'][$ID]['Description'] = 'Scatter '.$ID;
- $this->Data['ScatterSeries'][$ID]['isDrawable'] = TRUE;
- $this->Data['ScatterSeries'][$ID]['Picture'] = NULL;
- $this->Data['ScatterSeries'][$ID]['Ticks'] = 0;
- $this->Data['ScatterSeries'][$ID]['Weight'] = 0;
+ $this->Data['ScatterSeries'][$ID]['Description'] = 'Scatter '.$ID;
+ $this->Data['ScatterSeries'][$ID]['isDrawable'] = TRUE;
+ $this->Data['ScatterSeries'][$ID]['Picture'] = NULL;
+ $this->Data['ScatterSeries'][$ID]['Ticks'] = 0;
+ $this->Data['ScatterSeries'][$ID]['Weight'] = 0;
if ( isset($this->Palette[$ID]) )
$this->Data['ScatterSeries'][$ID]['Color'] = $this->Palette[$ID];
@@ -682,15 +682,15 @@
{
if ( isset($this->Data['Series']) ) { $ID = count($this->Data['Series']); } else { $ID = 0; }
- $this->Data['Series'][$Serie]['Description'] = $Serie;
- $this->Data['Series'][$Serie]['isDrawable'] = TRUE;
- $this->Data['Series'][$Serie]['Picture'] = NULL;
- $this->Data['Series'][$Serie]['Max'] = NULL;
- $this->Data['Series'][$Serie]['Min'] = NULL;
- $this->Data['Series'][$Serie]['Axis'] = 0;
- $this->Data['Series'][$Serie]['Ticks'] = 0;
- $this->Data['Series'][$Serie]['Weight'] = 0;
- $this->Data['Series'][$Serie]['Shape'] = SERIE_SHAPE_FILLEDCIRCLE;
+ $this->Data['Series'][$Serie]['Description'] = $Serie;
+ $this->Data['Series'][$Serie]['isDrawable'] = TRUE;
+ $this->Data['Series'][$Serie]['Picture'] = NULL;
+ $this->Data['Series'][$Serie]['Max'] = NULL;
+ $this->Data['Series'][$Serie]['Min'] = NULL;
+ $this->Data['Series'][$Serie]['Axis'] = 0;
+ $this->Data['Series'][$Serie]['Ticks'] = 0;
+ $this->Data['Series'][$Serie]['Weight'] = 0;
+ $this->Data['Series'][$Serie]['Shape'] = SERIE_SHAPE_FILLEDCIRCLE;
if ( isset($this->Palette[$ID]) )
$this->Data['Series'][$Serie]['Color'] = $this->Palette[$ID];
@@ -762,10 +762,10 @@
/* Load data from a CSV (or similar) data source */
function importFromCSV($FileName,$Options='')
{
- $Delimiter = isset($Options['Delimiter']) ? $Options['Delimiter'] : ',';
- $GotHeader = isset($Options['GotHeader']) ? $Options['GotHeader'] : FALSE;
- $SkipColumns = isset($Options['SkipColumns']) ? $Options['SkipColumns'] : array(-1);
- $DefaultSerieName = isset($Options['DefaultSerieName']) ? $Options['DefaultSerieName'] : 'Serie';
+ $Delimiter = isset($Options['Delimiter']) ? $Options['Delimiter'] : ',';
+ $GotHeader = isset($Options['GotHeader']) ? $Options['GotHeader'] : FALSE;
+ $SkipColumns = isset($Options['SkipColumns']) ? $Options['SkipColumns'] : array(-1);
+ $DefaultSerieName = isset($Options['DefaultSerieName']) ? $Options['DefaultSerieName'] : 'Serie';
$Handle = @fopen($FileName,'r');
if ($Handle)
@@ -799,12 +799,12 @@
/* Create a dataset based on a formula */
function createFunctionSerie($SerieName,$Formula='',$Options='')
{
- $MinX = isset($Options['MinX']) ? $Options['MinX'] : -10;
- $MaxX = isset($Options['MaxX']) ? $Options['MaxX'] : 10;
- $XStep = isset($Options['XStep']) ? $Options['XStep'] : 1;
- $AutoDescription = isset($Options['AutoDescription']) ? $Options['AutoDescription'] : FALSE;
- $RecordAbscissa = isset($Options['RecordAbscissa']) ? $Options['RecordAbscissa'] : FALSE;
- $AbscissaSerie = isset($Options['AbscissaSerie']) ? $Options['AbscissaSerie'] : 'Abscissa';
+ $MinX = isset($Options['MinX']) ? $Options['MinX'] : -10;
+ $MaxX = isset($Options['MaxX']) ? $Options['MaxX'] : 10;
+ $XStep = isset($Options['XStep']) ? $Options['XStep'] : 1;
+ $AutoDescription = isset($Options['AutoDescription']) ? $Options['AutoDescription'] : FALSE;
+ $RecordAbscissa = isset($Options['RecordAbscissa']) ? $Options['RecordAbscissa'] : FALSE;
+ $AbscissaSerie = isset($Options['AbscissaSerie']) ? $Options['AbscissaSerie'] : 'Abscissa';
if ( $Formula == '' ) { return(0); }
@@ -868,8 +868,8 @@
function __toString()
{ return('pData object.'); }
- function left($value,$NbChar) { return substr($value,0,$NbChar); }
- function right($value,$NbChar) { return substr($value,strlen($value)-$NbChar,$NbChar); }
- function mid($value,$Depart,$NbChar) { return substr($value,$Depart-1,$NbChar); }
+ function left($value,$NbChar) { return substr($value,0,$NbChar); }
+ function right($value,$NbChar) { return substr($value,strlen($value)-$NbChar,$NbChar); }
+ function mid($value,$Depart,$NbChar) { return substr($value,$Depart-1,$NbChar); }
}
?>
\ No newline at end of file
diff --git a/system/library/games/graph/pDraw.php b/system/library/games/graph/pDraw.php
index cc49e57..f7a0acb 100644
--- a/system/library/games/graph/pDraw.php
+++ b/system/library/games/graph/pDraw.php
@@ -1,73 +1,73 @@
fixBoxCoordinates($X1,$Y1,$X2,$Y2);
@@ -239,14 +239,14 @@
/* Draw a rectangle with rounded corners */
function drawRoundedFilledRectangle($X1,$Y1,$X2,$Y2,$Radius,$Format="")
{
- $R = isset($Format["R"]) ? $Format["R"] : 0;
- $G = isset($Format["G"]) ? $Format["G"] : 0;
- $B = isset($Format["B"]) ? $Format["B"] : 0;
- $BorderR = isset($Format["BorderR"]) ? $Format["BorderR"] : -1;
- $BorderG = isset($Format["BorderG"]) ? $Format["BorderG"] : -1;
- $BorderB = isset($Format["BorderB"]) ? $Format["BorderB"] : -1;
- $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 100;
- $Surrounding = isset($Format["Surrounding"]) ? $Format["Surrounding"] : NULL;
+ $R = isset($Format["R"]) ? $Format["R"] : 0;
+ $G = isset($Format["G"]) ? $Format["G"] : 0;
+ $B = isset($Format["B"]) ? $Format["B"] : 0;
+ $BorderR = isset($Format["BorderR"]) ? $Format["BorderR"] : -1;
+ $BorderG = isset($Format["BorderG"]) ? $Format["BorderG"] : -1;
+ $BorderB = isset($Format["BorderB"]) ? $Format["BorderB"] : -1;
+ $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 100;
+ $Surrounding = isset($Format["Surrounding"]) ? $Format["Surrounding"] : NULL;
/* Temporary fix for AA issue */
$Y1 = floor($Y1); $Y2 = floor($Y2); $X1 = floor($X1); $X2 = floor($X2);
@@ -324,14 +324,14 @@
/* Draw a rectangle with rounded corners */
function drawRoundedFilledRectangle_deprecated($X1,$Y1,$X2,$Y2,$Radius,$Format="")
{
- $R = isset($Format["R"]) ? $Format["R"] : 0;
- $G = isset($Format["G"]) ? $Format["G"] : 0;
- $B = isset($Format["B"]) ? $Format["B"] : 0;
- $BorderR = isset($Format["BorderR"]) ? $Format["BorderR"] : -1;
- $BorderG = isset($Format["BorderG"]) ? $Format["BorderG"] : -1;
- $BorderB = isset($Format["BorderB"]) ? $Format["BorderB"] : -1;
- $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 100;
- $Surrounding = isset($Format["Surrounding"]) ? $Format["Surrounding"] : NULL;
+ $R = isset($Format["R"]) ? $Format["R"] : 0;
+ $G = isset($Format["G"]) ? $Format["G"] : 0;
+ $B = isset($Format["B"]) ? $Format["B"] : 0;
+ $BorderR = isset($Format["BorderR"]) ? $Format["BorderR"] : -1;
+ $BorderG = isset($Format["BorderG"]) ? $Format["BorderG"] : -1;
+ $BorderB = isset($Format["BorderB"]) ? $Format["BorderB"] : -1;
+ $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 100;
+ $Surrounding = isset($Format["Surrounding"]) ? $Format["Surrounding"] : NULL;
if ( $Surrounding != NULL ) { $BorderR = $R+$Surrounding; $BorderG = $G+$Surrounding; $BorderB = $B+$Surrounding; }
if ( $BorderR == -1 ) { $BorderR = $R; $BorderG = $G; $BorderB = $B; }
@@ -403,12 +403,12 @@
/* Draw a rectangle */
function drawRectangle($X1,$Y1,$X2,$Y2,$Format="")
{
- $R = isset($Format["R"]) ? $Format["R"] : 0;
- $G = isset($Format["G"]) ? $Format["G"] : 0;
- $B = isset($Format["B"]) ? $Format["B"] : 0;
- $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 100;
- $Ticks = isset($Format["Ticks"]) ? $Format["Ticks"] : NULL;
- $NoAngle = isset($Format["NoAngle"]) ? $Format["NoAngle"] : FALSE;
+ $R = isset($Format["R"]) ? $Format["R"] : 0;
+ $G = isset($Format["G"]) ? $Format["G"] : 0;
+ $B = isset($Format["B"]) ? $Format["B"] : 0;
+ $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 100;
+ $Ticks = isset($Format["Ticks"]) ? $Format["Ticks"] : NULL;
+ $NoAngle = isset($Format["NoAngle"]) ? $Format["NoAngle"] : FALSE;
if ($X1 > $X2) { list($X1, $X2) = array($X2, $X1); }
if ($Y1 > $Y2) { list($Y1, $Y2) = array($Y2, $Y1); }
@@ -440,23 +440,23 @@
/* Draw a filled rectangle */
function drawFilledRectangle($X1,$Y1,$X2,$Y2,$Format="")
{
- $R = isset($Format["R"]) ? $Format["R"] : 0;
- $G = isset($Format["G"]) ? $Format["G"] : 0;
- $B = isset($Format["B"]) ? $Format["B"] : 0;
- $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 100;
- $BorderR = isset($Format["BorderR"]) ? $Format["BorderR"] : -1;
- $BorderG = isset($Format["BorderG"]) ? $Format["BorderG"] : -1;
- $BorderB = isset($Format["BorderB"]) ? $Format["BorderB"] : -1;
- $BorderAlpha = isset($Format["BorderAlpha"]) ? $Format["BorderAlpha"] : $Alpha;
- $Surrounding = isset($Format["Surrounding"]) ? $Format["Surrounding"] : NULL;
- $Ticks = isset($Format["Ticks"]) ? $Format["Ticks"] : NULL;
- $NoAngle = isset($Format["NoAngle"]) ? $Format["NoAngle"] : NULL;
- $Dash = isset($Format["Dash"]) ? $Format["Dash"] : FALSE;
- $DashStep = isset($Format["DashStep"]) ? $Format["DashStep"] : 4;
- $DashR = isset($Format["DashR"]) ? $Format["DashR"] : 0;
- $DashG = isset($Format["DashG"]) ? $Format["DashG"] : 0;
- $DashB = isset($Format["DashB"]) ? $Format["DashB"] : 0;
- $NoBorder = isset($Format["NoBorder"]) ? $Format["NoBorder"] : FALSE;
+ $R = isset($Format["R"]) ? $Format["R"] : 0;
+ $G = isset($Format["G"]) ? $Format["G"] : 0;
+ $B = isset($Format["B"]) ? $Format["B"] : 0;
+ $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 100;
+ $BorderR = isset($Format["BorderR"]) ? $Format["BorderR"] : -1;
+ $BorderG = isset($Format["BorderG"]) ? $Format["BorderG"] : -1;
+ $BorderB = isset($Format["BorderB"]) ? $Format["BorderB"] : -1;
+ $BorderAlpha = isset($Format["BorderAlpha"]) ? $Format["BorderAlpha"] : $Alpha;
+ $Surrounding = isset($Format["Surrounding"]) ? $Format["Surrounding"] : NULL;
+ $Ticks = isset($Format["Ticks"]) ? $Format["Ticks"] : NULL;
+ $NoAngle = isset($Format["NoAngle"]) ? $Format["NoAngle"] : NULL;
+ $Dash = isset($Format["Dash"]) ? $Format["Dash"] : FALSE;
+ $DashStep = isset($Format["DashStep"]) ? $Format["DashStep"] : 4;
+ $DashR = isset($Format["DashR"]) ? $Format["DashR"] : 0;
+ $DashG = isset($Format["DashG"]) ? $Format["DashG"] : 0;
+ $DashB = isset($Format["DashB"]) ? $Format["DashB"] : 0;
+ $NoBorder = isset($Format["NoBorder"]) ? $Format["NoBorder"] : FALSE;
if ( $Surrounding != NULL ) { $BorderR = $R+$Surrounding; $BorderG = $G+$Surrounding; $BorderB = $B+$Surrounding; }
@@ -544,16 +544,16 @@
/* Drawn a spline based on the bezier function */
function drawSpline($Coordinates,$Format="")
{
- $R = isset($Format["R"]) ? $Format["R"] : 0;
- $G = isset($Format["G"]) ? $Format["G"] : 0;
- $B = isset($Format["B"]) ? $Format["B"] : 0;
- $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 100;
- $Force = isset($Format["Force"]) ? $Format["Force"] : 30;
- $Forces = isset($Format["Forces"]) ? $Format["Forces"] : NULL;
- $ShowC = isset($Format["ShowControl"]) ? $Format["ShowControl"] : FALSE;
- $Ticks = isset($Format["Ticks"]) ? $Format["Ticks"] : NULL;
- $PathOnly = isset($Format["PathOnly"]) ? $Format["PathOnly"] : FALSE;
- $Weight = isset($Format["Weight"]) ? $Format["Weight"] : NULL;
+ $R = isset($Format["R"]) ? $Format["R"] : 0;
+ $G = isset($Format["G"]) ? $Format["G"] : 0;
+ $B = isset($Format["B"]) ? $Format["B"] : 0;
+ $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 100;
+ $Force = isset($Format["Force"]) ? $Format["Force"] : 30;
+ $Forces = isset($Format["Forces"]) ? $Format["Forces"] : NULL;
+ $ShowC = isset($Format["ShowControl"]) ? $Format["ShowControl"] : FALSE;
+ $Ticks = isset($Format["Ticks"]) ? $Format["Ticks"] : NULL;
+ $PathOnly = isset($Format["PathOnly"]) ? $Format["PathOnly"] : FALSE;
+ $Weight = isset($Format["Weight"]) ? $Format["Weight"] : NULL;
$Cpt = NULL; $Mode = NULL; $Result = "";
for($i=1;$i<=count($Coordinates)-1;$i++)
@@ -603,20 +603,20 @@
/* Draw a bezier curve with two controls points */
function drawBezier($X1,$Y1,$X2,$Y2,$Xv1,$Yv1,$Xv2,$Yv2,$Format="")
{
- $R = isset($Format["R"]) ? $Format["R"] : 0;
- $G = isset($Format["G"]) ? $Format["G"] : 0;
- $B = isset($Format["B"]) ? $Format["B"] : 0;
- $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 100;
- $ShowC = isset($Format["ShowControl"]) ? $Format["ShowControl"] : FALSE;
- $Segments = isset($Format["Segments"]) ? $Format["Segments"] : NULL;
- $Ticks = isset($Format["Ticks"]) ? $Format["Ticks"] : NULL;
+ $R = isset($Format["R"]) ? $Format["R"] : 0;
+ $G = isset($Format["G"]) ? $Format["G"] : 0;
+ $B = isset($Format["B"]) ? $Format["B"] : 0;
+ $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 100;
+ $ShowC = isset($Format["ShowControl"]) ? $Format["ShowControl"] : FALSE;
+ $Segments = isset($Format["Segments"]) ? $Format["Segments"] : NULL;
+ $Ticks = isset($Format["Ticks"]) ? $Format["Ticks"] : NULL;
$NoDraw = isset($Format["NoDraw"]) ? $Format["NoDraw"] : FALSE;
$PathOnly = isset($Format["PathOnly"]) ? $Format["PathOnly"] : FALSE;
$Weight = isset($Format["Weight"]) ? $Format["Weight"] : NULL;
- $DrawArrow = isset($Format["DrawArrow"]) ? $Format["DrawArrow"] : FALSE;
- $ArrowSize = isset($Format["ArrowSize"]) ? $Format["ArrowSize"] : 10;
- $ArrowRatio = isset($Format["ArrowRatio"]) ? $Format["ArrowRatio"] : .5;
- $ArrowTwoHeads = isset($Format["ArrowTwoHeads"]) ? $Format["ArrowTwoHeads"] : FALSE;
+ $DrawArrow = isset($Format["DrawArrow"]) ? $Format["DrawArrow"] : FALSE;
+ $ArrowSize = isset($Format["ArrowSize"]) ? $Format["ArrowSize"] : 10;
+ $ArrowRatio = isset($Format["ArrowRatio"]) ? $Format["ArrowRatio"] : .5;
+ $ArrowTwoHeads = isset($Format["ArrowTwoHeads"]) ? $Format["ArrowTwoHeads"] : FALSE;
if ( $Segments == NULL )
{
@@ -707,15 +707,15 @@
/* Draw a line between two points */
function drawLine($X1,$Y1,$X2,$Y2,$Format="")
{
- $R = isset($Format["R"]) ? $Format["R"] : 0;
- $G = isset($Format["G"]) ? $Format["G"] : 0;
- $B = isset($Format["B"]) ? $Format["B"] : 0;
- $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 100;
- $Ticks = isset($Format["Ticks"]) ? $Format["Ticks"] : NULL;
- $Cpt = isset($Format["Cpt"]) ? $Format["Cpt"] : 1;
- $Mode = isset($Format["Mode"]) ? $Format["Mode"] : 1;
- $Weight = isset($Format["Weight"]) ? $Format["Weight"] : NULL;
- $Threshold = isset($Format["Threshold"]) ? $Format["Threshold"] : NULL;
+ $R = isset($Format["R"]) ? $Format["R"] : 0;
+ $G = isset($Format["G"]) ? $Format["G"] : 0;
+ $B = isset($Format["B"]) ? $Format["B"] : 0;
+ $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 100;
+ $Ticks = isset($Format["Ticks"]) ? $Format["Ticks"] : NULL;
+ $Cpt = isset($Format["Cpt"]) ? $Format["Cpt"] : 1;
+ $Mode = isset($Format["Mode"]) ? $Format["Mode"] : 1;
+ $Weight = isset($Format["Weight"]) ? $Format["Weight"] : NULL;
+ $Threshold = isset($Format["Threshold"]) ? $Format["Threshold"] : NULL;
if ( $this->Antialias == FALSE && $Ticks == NULL )
{
@@ -760,7 +760,7 @@
$Points[] = cos(deg2rad($Angle-90)) * $Weight + $Xa; $Points[] = sin(deg2rad($Angle-90)) * $Weight + $Ya;
$Points[] = cos(deg2rad($Angle+90)) * $Weight + $Xa; $Points[] = sin(deg2rad($Angle+90)) * $Weight + $Ya;
$Points[] = cos(deg2rad($Angle+90)) * $Weight + $Xb; $Points[] = sin(deg2rad($Angle+90)) * $Weight + $Yb;
- $Points[] = cos(deg2rad($Angle-90)) * $Weight + $Xb; $Points[] = sin(deg2rad($Angle-90)) * $Weight + $Yb;
+ $Points[] = cos(deg2rad($Angle-90)) * $Weight + $Xb; $Points[] = sin(deg2rad($Angle-90)) * $Weight + $Yb;
$this->drawPolygon($Points,$PolySettings);
}
@@ -814,14 +814,14 @@
/* Draw a circle */
function drawCircle($Xc,$Yc,$Height,$Width,$Format="")
{
- $R = isset($Format["R"]) ? $Format["R"] : 0;
- $G = isset($Format["G"]) ? $Format["G"] : 0;
- $B = isset($Format["B"]) ? $Format["B"] : 0;
+ $R = isset($Format["R"]) ? $Format["R"] : 0;
+ $G = isset($Format["G"]) ? $Format["G"] : 0;
+ $B = isset($Format["B"]) ? $Format["B"] : 0;
$Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 100;
$Ticks = isset($Format["Ticks"]) ? $Format["Ticks"] : NULL;
- $Height = abs($Height);
- $Width = abs($Width);
+ $Height = abs($Height);
+ $Width = abs($Width);
if ( $Height == 0 ) { $Height = 1; }
if ( $Width == 0 ) { $Width = 1; }
@@ -866,16 +866,16 @@
/* Draw a filled circle */
function drawFilledCircle($X,$Y,$Radius,$Format="")
{
- $R = isset($Format["R"]) ? $Format["R"] : 0;
- $G = isset($Format["G"]) ? $Format["G"] : 0;
- $B = isset($Format["B"]) ? $Format["B"] : 0;
- $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 100;
- $BorderR = isset($Format["BorderR"]) ? $Format["BorderR"] : -1;
- $BorderG = isset($Format["BorderG"]) ? $Format["BorderG"] : -1;
- $BorderB = isset($Format["BorderB"]) ? $Format["BorderB"] : -1;
- $BorderAlpha = isset($Format["BorderAlpha"]) ? $Format["BorderAlpha"] : $Alpha;
- $Ticks = isset($Format["Ticks"]) ? $Format["Ticks"] : NULL;
- $Surrounding = isset($Format["Surrounding"]) ? $Format["Surrounding"] : NULL;
+ $R = isset($Format["R"]) ? $Format["R"] : 0;
+ $G = isset($Format["G"]) ? $Format["G"] : 0;
+ $B = isset($Format["B"]) ? $Format["B"] : 0;
+ $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 100;
+ $BorderR = isset($Format["BorderR"]) ? $Format["BorderR"] : -1;
+ $BorderG = isset($Format["BorderG"]) ? $Format["BorderG"] : -1;
+ $BorderB = isset($Format["BorderB"]) ? $Format["BorderB"] : -1;
+ $BorderAlpha = isset($Format["BorderAlpha"]) ? $Format["BorderAlpha"] : $Alpha;
+ $Ticks = isset($Format["Ticks"]) ? $Format["Ticks"] : NULL;
+ $Surrounding = isset($Format["Surrounding"]) ? $Format["Surrounding"] : NULL;
if ( $Radius == 0 ) { $Radius = 1; }
if ( $Surrounding != NULL ) { $BorderR = $R+$Surrounding; $BorderG = $G+$Surrounding; $BorderB = $B+$Surrounding; }
@@ -911,37 +911,37 @@
if ( $BorderR != -1 )
$this->drawCircle($X,$Y,$Radius,$Radius,array("R"=>$BorderR,"G"=>$BorderG,"B"=>$BorderB,"Alpha"=>$BorderAlpha,"Ticks"=>$Ticks));
- $this->Shadow = $RestoreShadow;
+ $this->Shadow = $RestoreShadow;
}
/* Write text */
function drawText($X,$Y,$Text,$Format="")
{
- $R = isset($Format["R"]) ? $Format["R"] : $this->FontColorR;
- $G = isset($Format["G"]) ? $Format["G"] : $this->FontColorG;
- $B = isset($Format["B"]) ? $Format["B"] : $this->FontColorB;
- $Angle = isset($Format["Angle"]) ? $Format["Angle"] : 0;
- $Align = isset($Format["Align"]) ? $Format["Align"] : TEXT_ALIGN_BOTTOMLEFT;
- $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : $this->FontColorA;
- $FontName = isset($Format["FontName"]) ? $Format["FontName"] : $this->FontName;
- $FontSize = isset($Format["FontSize"]) ? $Format["FontSize"] : $this->FontSize;
- $ShowOrigine = isset($Format["ShowOrigine"]) ? $Format["ShowOrigine"] : FALSE;
- $TOffset = isset($Format["TOffset"]) ? $Format["TOffset"] : 2;
- $DrawBox = isset($Format["DrawBox"]) ? $Format["DrawBox"] : FALSE;
- $DrawBoxBorder = isset($Format["DrawBoxBorder"]) ? $Format["DrawBoxBorder"] : TRUE;
- $BorderOffset = isset($Format["BorderOffset"]) ? $Format["BorderOffset"] : 6;
- $BoxRounded = isset($Format["BoxRounded"]) ? $Format["BoxRounded"] : FALSE;
- $RoundedRadius = isset($Format["RoundedRadius"]) ? $Format["RoundedRadius"] : 6;
- $BoxR = isset($Format["BoxR"]) ? $Format["BoxR"] : 255;
- $BoxG = isset($Format["BoxG"]) ? $Format["BoxG"] : 255;
- $BoxB = isset($Format["BoxB"]) ? $Format["BoxB"] : 255;
- $BoxAlpha = isset($Format["BoxAlpha"]) ? $Format["BoxAlpha"] : 50;
- $BoxSurrounding = isset($Format["BoxSurrounding"]) ? $Format["BoxSurrounding"] : "";
- $BoxBorderR = isset($Format["BoxR"]) ? $Format["BoxR"] : 0;
- $BoxBorderG = isset($Format["BoxG"]) ? $Format["BoxG"] : 0;
- $BoxBorderB = isset($Format["BoxB"]) ? $Format["BoxB"] : 0;
- $BoxBorderAlpha = isset($Format["BoxAlpha"]) ? $Format["BoxAlpha"] : 50;
- $NoShadow = isset($Format["NoShadow"]) ? $Format["NoShadow"] : FALSE;
+ $R = isset($Format["R"]) ? $Format["R"] : $this->FontColorR;
+ $G = isset($Format["G"]) ? $Format["G"] : $this->FontColorG;
+ $B = isset($Format["B"]) ? $Format["B"] : $this->FontColorB;
+ $Angle = isset($Format["Angle"]) ? $Format["Angle"] : 0;
+ $Align = isset($Format["Align"]) ? $Format["Align"] : TEXT_ALIGN_BOTTOMLEFT;
+ $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : $this->FontColorA;
+ $FontName = isset($Format["FontName"]) ? $Format["FontName"] : $this->FontName;
+ $FontSize = isset($Format["FontSize"]) ? $Format["FontSize"] : $this->FontSize;
+ $ShowOrigine = isset($Format["ShowOrigine"]) ? $Format["ShowOrigine"] : FALSE;
+ $TOffset = isset($Format["TOffset"]) ? $Format["TOffset"] : 2;
+ $DrawBox = isset($Format["DrawBox"]) ? $Format["DrawBox"] : FALSE;
+ $DrawBoxBorder = isset($Format["DrawBoxBorder"]) ? $Format["DrawBoxBorder"] : TRUE;
+ $BorderOffset = isset($Format["BorderOffset"]) ? $Format["BorderOffset"] : 6;
+ $BoxRounded = isset($Format["BoxRounded"]) ? $Format["BoxRounded"] : FALSE;
+ $RoundedRadius = isset($Format["RoundedRadius"]) ? $Format["RoundedRadius"] : 6;
+ $BoxR = isset($Format["BoxR"]) ? $Format["BoxR"] : 255;
+ $BoxG = isset($Format["BoxG"]) ? $Format["BoxG"] : 255;
+ $BoxB = isset($Format["BoxB"]) ? $Format["BoxB"] : 255;
+ $BoxAlpha = isset($Format["BoxAlpha"]) ? $Format["BoxAlpha"] : 50;
+ $BoxSurrounding = isset($Format["BoxSurrounding"]) ? $Format["BoxSurrounding"] : "";
+ $BoxBorderR = isset($Format["BoxR"]) ? $Format["BoxR"] : 0;
+ $BoxBorderG = isset($Format["BoxG"]) ? $Format["BoxG"] : 0;
+ $BoxBorderB = isset($Format["BoxB"]) ? $Format["BoxB"] : 0;
+ $BoxBorderAlpha = isset($Format["BoxAlpha"]) ? $Format["BoxAlpha"] : 50;
+ $NoShadow = isset($Format["NoShadow"]) ? $Format["NoShadow"] : FALSE;
$Shadow = $this->Shadow;
if ( $NoShadow ) { $this->Shadow = FALSE; }
@@ -999,14 +999,14 @@
/* Draw a gradient within a defined area */
function drawGradientArea($X1,$Y1,$X2,$Y2,$Direction,$Format="")
{
- $StartR = isset($Format["StartR"]) ? $Format["StartR"] : 90;
- $StartG = isset($Format["StartG"]) ? $Format["StartG"] : 90;
- $StartB = isset($Format["StartB"]) ? $Format["StartB"] : 90;
- $EndR = isset($Format["EndR"]) ? $Format["EndR"] : 0;
- $EndG = isset($Format["EndG"]) ? $Format["EndG"] : 0;
- $EndB = isset($Format["EndB"]) ? $Format["EndB"] : 0;
- $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 100;
- $Levels = isset($Format["Levels"]) ? $Format["Levels"] : NULL;
+ $StartR = isset($Format["StartR"]) ? $Format["StartR"] : 90;
+ $StartG = isset($Format["StartG"]) ? $Format["StartG"] : 90;
+ $StartB = isset($Format["StartB"]) ? $Format["StartB"] : 90;
+ $EndR = isset($Format["EndR"]) ? $Format["EndR"] : 0;
+ $EndG = isset($Format["EndG"]) ? $Format["EndG"] : 0;
+ $EndB = isset($Format["EndB"]) ? $Format["EndB"] : 0;
+ $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 100;
+ $Levels = isset($Format["Levels"]) ? $Format["Levels"] : NULL;
$Shadow = $this->Shadow;
$this->Shadow = FALSE;
@@ -1250,17 +1250,17 @@
/* Draw an arrow */
function drawArrow($X1,$Y1,$X2,$Y2,$Format="")
{
- $FillR = isset($Format["FillR"]) ? $Format["FillR"] : 0;
- $FillG = isset($Format["FillG"]) ? $Format["FillG"] : 0;
- $FillB = isset($Format["FillB"]) ? $Format["FillB"] : 0;
- $BorderR = isset($Format["BorderR"]) ? $Format["BorderR"] : $FillR;
- $BorderG = isset($Format["BorderG"]) ? $Format["BorderG"] : $FillG;
- $BorderB = isset($Format["BorderB"]) ? $Format["BorderB"] : $FillB;
- $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 100;
- $Size = isset($Format["Size"]) ? $Format["Size"] : 10;
- $Ratio = isset($Format["Ratio"]) ? $Format["Ratio"] : .5;
- $TwoHeads = isset($Format["TwoHeads"]) ? $Format["TwoHeads"] : FALSE;
- $Ticks = isset($Format["Ticks"]) ? $Format["Ticks"] : FALSE;
+ $FillR = isset($Format["FillR"]) ? $Format["FillR"] : 0;
+ $FillG = isset($Format["FillG"]) ? $Format["FillG"] : 0;
+ $FillB = isset($Format["FillB"]) ? $Format["FillB"] : 0;
+ $BorderR = isset($Format["BorderR"]) ? $Format["BorderR"] : $FillR;
+ $BorderG = isset($Format["BorderG"]) ? $Format["BorderG"] : $FillG;
+ $BorderB = isset($Format["BorderB"]) ? $Format["BorderB"] : $FillB;
+ $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 100;
+ $Size = isset($Format["Size"]) ? $Format["Size"] : 10;
+ $Ratio = isset($Format["Ratio"]) ? $Format["Ratio"] : .5;
+ $TwoHeads = isset($Format["TwoHeads"]) ? $Format["TwoHeads"] : FALSE;
+ $Ticks = isset($Format["Ticks"]) ? $Format["Ticks"] : FALSE;
/* Calculate the line angle */
$Angle = $this->getAngle($X1,$Y1,$X2,$Y2);
@@ -1277,10 +1277,10 @@
$TailX = cos(($Angle-180)*PI/180)*$Size+$X2;
$TailY = sin(($Angle-180)*PI/180)*$Size+$Y2;
- $Points = "";
+ $Points = "";
$Points[] = $X2; $Points[] = $Y2;
- $Points[] = cos(($Angle-90)*PI/180)*$Size*$Ratio+$TailX; $Points[] = sin(($Angle-90)*PI/180)*$Size*$Ratio+$TailY;
- $Points[] = cos(($Angle-270)*PI/180)*$Size*$Ratio+$TailX; $Points[] = sin(($Angle-270)*PI/180)*$Size*$Ratio+$TailY;
+ $Points[] = cos(($Angle-90)*PI/180)*$Size*$Ratio+$TailX; $Points[] = sin(($Angle-90)*PI/180)*$Size*$Ratio+$TailY;
+ $Points[] = cos(($Angle-270)*PI/180)*$Size*$Ratio+$TailX; $Points[] = sin(($Angle-270)*PI/180)*$Size*$Ratio+$TailY;
$Points[] = $X2; $Points[] = $Y2;
/* Visual correction */
@@ -1357,9 +1357,9 @@
$this->drawArrow($X2,$Y2,$X1,$Y1,$Format);
- $Size = imagettfbbox($FontSize,0,$FontName,$Text);
- $TxtWidth = max(abs($Size[2]-$Size[0]),abs($Size[0]-$Size[6]));
- $TxtHeight = max(abs($Size[1]-$Size[7]),abs($Size[3]-$Size[1]));
+ $Size = imagettfbbox($FontSize,0,$FontName,$Text);
+ $TxtWidth = max(abs($Size[2]-$Size[0]),abs($Size[0]-$Size[6]));
+ $TxtHeight = max(abs($Size[1]-$Size[7]),abs($Size[3]-$Size[1]));
if ( $Angle > 0 && $Angle < 180 )
{
@@ -1385,31 +1385,31 @@
if ( $Percent > 100 ) { $Percent = 100; }
if ( $Percent < 0 ) { $Percent = 0; }
- $Width = isset($Format["Width"]) ? $Format["Width"] : 200;
- $Height = isset($Format["Height"]) ? $Format["Height"] : 20;
+ $Width = isset($Format["Width"]) ? $Format["Width"] : 200;
+ $Height = isset($Format["Height"]) ? $Format["Height"] : 20;
$Orientation = isset($Format["Orientation"]) ? $Format["Orientation"] : ORIENTATION_HORIZONTAL;
$ShowLabel = isset($Format["ShowLabel"]) ? $Format["ShowLabel"] : FALSE;
- $LabelPos = isset($Format["LabelPos"]) ? $Format["LabelPos"] : LABEL_POS_INSIDE;
+ $LabelPos = isset($Format["LabelPos"]) ? $Format["LabelPos"] : LABEL_POS_INSIDE;
$Margin = isset($Format["Margin"]) ? $Format["Margin"] : 10;
- $R = isset($Format["R"]) ? $Format["R"] : 130;
- $G = isset($Format["G"]) ? $Format["G"] : 130;
- $B = isset($Format["B"]) ? $Format["B"] : 130;
- $RFade = isset($Format["RFade"]) ? $Format["RFade"] : -1;
- $GFade = isset($Format["GFade"]) ? $Format["GFade"] : -1;
- $BFade = isset($Format["BFade"]) ? $Format["BFade"] : -1;
- $BorderR = isset($Format["BorderR"]) ? $Format["BorderR"] : $R;
- $BorderG = isset($Format["BorderG"]) ? $Format["BorderG"] : $G;
- $BorderB = isset($Format["BorderB"]) ? $Format["BorderB"] : $B;
+ $R = isset($Format["R"]) ? $Format["R"] : 130;
+ $G = isset($Format["G"]) ? $Format["G"] : 130;
+ $B = isset($Format["B"]) ? $Format["B"] : 130;
+ $RFade = isset($Format["RFade"]) ? $Format["RFade"] : -1;
+ $GFade = isset($Format["GFade"]) ? $Format["GFade"] : -1;
+ $BFade = isset($Format["BFade"]) ? $Format["BFade"] : -1;
+ $BorderR = isset($Format["BorderR"]) ? $Format["BorderR"] : $R;
+ $BorderG = isset($Format["BorderG"]) ? $Format["BorderG"] : $G;
+ $BorderB = isset($Format["BorderB"]) ? $Format["BorderB"] : $B;
$BoxBorderR = isset($Format["BoxBorderR"]) ? $Format["BoxBorderR"] : 0;
$BoxBorderG = isset($Format["BoxBorderG"]) ? $Format["BoxBorderG"] : 0;
$BoxBorderB = isset($Format["BoxBorderB"]) ? $Format["BoxBorderB"] : 0;
- $BoxBackR = isset($Format["BoxBackR"]) ? $Format["BoxBackR"] : 255;
- $BoxBackG = isset($Format["BoxBackG"]) ? $Format["BoxBackG"] : 255;
- $BoxBackB = isset($Format["BoxBackB"]) ? $Format["BoxBackB"] : 255;
- $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 100;
+ $BoxBackR = isset($Format["BoxBackR"]) ? $Format["BoxBackR"] : 255;
+ $BoxBackG = isset($Format["BoxBackG"]) ? $Format["BoxBackG"] : 255;
+ $BoxBackB = isset($Format["BoxBackB"]) ? $Format["BoxBackB"] : 255;
+ $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 100;
$Surrounding = isset($Format["Surrounding"]) ? $Format["Surrounding"] : NULL;
$BoxSurrounding = isset($Format["BoxSurrounding"]) ? $Format["BoxSurrounding"] : NULL;
- $NoAngle = isset($Format["NoAngle"]) ? $Format["NoAngle"] : FALSE;
+ $NoAngle = isset($Format["NoAngle"]) ? $Format["NoAngle"] : FALSE;
if ( $RFade != -1 && $GFade != -1 && $BFade != -1 )
{
@@ -1440,10 +1440,10 @@
$this->Shadow = $RestoreShadow;
- if ( $ShowLabel && $LabelPos == LABEL_POS_BOTTOM ) { $this->drawText($X+($Width/2),$Y+$Margin,$Percent."%",array("Align"=>TEXT_ALIGN_TOPMIDDLE)); }
- if ( $ShowLabel && $LabelPos == LABEL_POS_TOP ) { $this->drawText($X+($Width/2),$Y-$Height-$Margin,$Percent."%",array("Align"=>TEXT_ALIGN_BOTTOMMIDDLE)); }
- if ( $ShowLabel && $LabelPos == LABEL_POS_INSIDE ) { $this->drawText($X+($Width/2),$Y-$InnerHeight-$Margin,$Percent."%",array("Align"=>TEXT_ALIGN_MIDDLELEFT,"Angle"=>90)); }
- if ( $ShowLabel && $LabelPos == LABEL_POS_CENTER ) { $this->drawText($X+($Width/2),$Y-($Height/2),$Percent."%",array("Align"=>TEXT_ALIGN_MIDDLEMIDDLE,"Angle"=>90)); }
+ if ( $ShowLabel && $LabelPos == LABEL_POS_BOTTOM ) { $this->drawText($X+($Width/2),$Y+$Margin,$Percent."%",array("Align"=>TEXT_ALIGN_TOPMIDDLE)); }
+ if ( $ShowLabel && $LabelPos == LABEL_POS_TOP ) { $this->drawText($X+($Width/2),$Y-$Height-$Margin,$Percent."%",array("Align"=>TEXT_ALIGN_BOTTOMMIDDLE)); }
+ if ( $ShowLabel && $LabelPos == LABEL_POS_INSIDE ) { $this->drawText($X+($Width/2),$Y-$InnerHeight-$Margin,$Percent."%",array("Align"=>TEXT_ALIGN_MIDDLELEFT,"Angle"=>90)); }
+ if ( $ShowLabel && $LabelPos == LABEL_POS_CENTER ) { $this->drawText($X+($Width/2),$Y-($Height/2),$Percent."%",array("Align"=>TEXT_ALIGN_MIDDLEMIDDLE,"Angle"=>90)); }
}
else
{
@@ -1468,27 +1468,27 @@
$this->Shadow = $RestoreShadow;
- if ( $ShowLabel && $LabelPos == LABEL_POS_LEFT ) { $this->drawText($X-$Margin,$Y+($Height/2),$Percent."%",array("Align"=>TEXT_ALIGN_MIDDLERIGHT)); }
- if ( $ShowLabel && $LabelPos == LABEL_POS_RIGHT ) { $this->drawText($X+$Width+$Margin,$Y+($Height/2),$Percent."%",array("Align"=>TEXT_ALIGN_MIDDLELEFT)); }
- if ( $ShowLabel && $LabelPos == LABEL_POS_CENTER ) { $this->drawText($X+($Width/2),$Y+($Height/2),$Percent."%",array("Align"=>TEXT_ALIGN_MIDDLEMIDDLE)); }
- if ( $ShowLabel && $LabelPos == LABEL_POS_INSIDE ) { $this->drawText($X+$InnerWidth+$Margin,$Y+($Height/2),$Percent."%",array("Align"=>TEXT_ALIGN_MIDDLELEFT)); }
+ if ( $ShowLabel && $LabelPos == LABEL_POS_LEFT ) { $this->drawText($X-$Margin,$Y+($Height/2),$Percent."%",array("Align"=>TEXT_ALIGN_MIDDLERIGHT)); }
+ if ( $ShowLabel && $LabelPos == LABEL_POS_RIGHT ) { $this->drawText($X+$Width+$Margin,$Y+($Height/2),$Percent."%",array("Align"=>TEXT_ALIGN_MIDDLELEFT)); }
+ if ( $ShowLabel && $LabelPos == LABEL_POS_CENTER ) { $this->drawText($X+($Width/2),$Y+($Height/2),$Percent."%",array("Align"=>TEXT_ALIGN_MIDDLEMIDDLE)); }
+ if ( $ShowLabel && $LabelPos == LABEL_POS_INSIDE ) { $this->drawText($X+$InnerWidth+$Margin,$Y+($Height/2),$Percent."%",array("Align"=>TEXT_ALIGN_MIDDLELEFT)); }
}
}
/* Get the legend box size */
function getLegendSize($Format="")
{
- $FontName = isset($Format["FontName"]) ? $Format["FontName"] : $this->FontName;
- $FontSize = isset($Format["FontSize"]) ? $Format["FontSize"] : $this->FontSize;
- $BoxSize = isset($Format["BoxSize"]) ? $Format["BoxSize"] : 5;
- $Margin = isset($Format["Margin"]) ? $Format["Margin"] : 5;
- $Style = isset($Format["Style"]) ? $Format["Style"] : LEGEND_ROUND;
- $Mode = isset($Format["Mode"]) ? $Format["Mode"] : LEGEND_VERTICAL;
- $BoxWidth = isset($Format["BoxWidth"]) ? $Format["BoxWidth"] : 5;
- $BoxHeight = isset($Format["BoxHeight"]) ? $Format["BoxHeight"] : 5;
- $IconAreaWidth = isset($Format["IconAreaWidth"]) ? $Format["IconAreaWidth"] : $BoxWidth;
- $IconAreaHeight = isset($Format["IconAreaHeight"]) ? $Format["IconAreaHeight"] : $BoxHeight;
- $XSpacing = isset($Format["XSpacing"]) ? $Format["XSpacing"] : 5;
+ $FontName = isset($Format["FontName"]) ? $Format["FontName"] : $this->FontName;
+ $FontSize = isset($Format["FontSize"]) ? $Format["FontSize"] : $this->FontSize;
+ $BoxSize = isset($Format["BoxSize"]) ? $Format["BoxSize"] : 5;
+ $Margin = isset($Format["Margin"]) ? $Format["Margin"] : 5;
+ $Style = isset($Format["Style"]) ? $Format["Style"] : LEGEND_ROUND;
+ $Mode = isset($Format["Mode"]) ? $Format["Mode"] : LEGEND_VERTICAL;
+ $BoxWidth = isset($Format["BoxWidth"]) ? $Format["BoxWidth"] : 5;
+ $BoxHeight = isset($Format["BoxHeight"]) ? $Format["BoxHeight"] : 5;
+ $IconAreaWidth = isset($Format["IconAreaWidth"]) ? $Format["IconAreaWidth"] : $BoxWidth;
+ $IconAreaHeight = isset($Format["IconAreaHeight"]) ? $Format["IconAreaHeight"] : $BoxHeight;
+ $XSpacing = isset($Format["XSpacing"]) ? $Format["XSpacing"] : 5;
$Data = $this->DataSet->getData();
@@ -1557,28 +1557,28 @@
/* Draw the legend of the active series */
function drawLegend($X,$Y,$Format="")
{
- $Family = isset($Format["Family"]) ? $Format["Family"] : LEGEND_FAMILY_BOX;
- $FontName = isset($Format["FontName"]) ? $Format["FontName"] : $this->FontName;
- $FontSize = isset($Format["FontSize"]) ? $Format["FontSize"] : $this->FontSize;
- $FontR = isset($Format["FontR"]) ? $Format["FontR"] : $this->FontColorR;
- $FontG = isset($Format["FontG"]) ? $Format["FontG"] : $this->FontColorG;
- $FontB = isset($Format["FontB"]) ? $Format["FontB"] : $this->FontColorB;
- $BoxWidth = isset($Format["BoxWidth"]) ? $Format["BoxWidth"] : 5;
- $BoxHeight = isset($Format["BoxHeight"]) ? $Format["BoxHeight"] : 5;
- $IconAreaWidth = isset($Format["IconAreaWidth"]) ? $Format["IconAreaWidth"] : $BoxWidth;
- $IconAreaHeight = isset($Format["IconAreaHeight"]) ? $Format["IconAreaHeight"] : $BoxHeight;
- $XSpacing = isset($Format["XSpacing"]) ? $Format["XSpacing"] : 5;
- $Margin = isset($Format["Margin"]) ? $Format["Margin"] : 5;
- $R = isset($Format["R"]) ? $Format["R"] : 200;
- $G = isset($Format["G"]) ? $Format["G"] : 200;
- $B = isset($Format["B"]) ? $Format["B"] : 200;
- $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 100;
- $BorderR = isset($Format["BorderR"]) ? $Format["BorderR"] : 255;
- $BorderG = isset($Format["BorderG"]) ? $Format["BorderG"] : 255;
- $BorderB = isset($Format["BorderB"]) ? $Format["BorderB"] : 255;
+ $Family = isset($Format["Family"]) ? $Format["Family"] : LEGEND_FAMILY_BOX;
+ $FontName = isset($Format["FontName"]) ? $Format["FontName"] : $this->FontName;
+ $FontSize = isset($Format["FontSize"]) ? $Format["FontSize"] : $this->FontSize;
+ $FontR = isset($Format["FontR"]) ? $Format["FontR"] : $this->FontColorR;
+ $FontG = isset($Format["FontG"]) ? $Format["FontG"] : $this->FontColorG;
+ $FontB = isset($Format["FontB"]) ? $Format["FontB"] : $this->FontColorB;
+ $BoxWidth = isset($Format["BoxWidth"]) ? $Format["BoxWidth"] : 5;
+ $BoxHeight = isset($Format["BoxHeight"]) ? $Format["BoxHeight"] : 5;
+ $IconAreaWidth = isset($Format["IconAreaWidth"]) ? $Format["IconAreaWidth"] : $BoxWidth;
+ $IconAreaHeight = isset($Format["IconAreaHeight"]) ? $Format["IconAreaHeight"] : $BoxHeight;
+ $XSpacing = isset($Format["XSpacing"]) ? $Format["XSpacing"] : 5;
+ $Margin = isset($Format["Margin"]) ? $Format["Margin"] : 5;
+ $R = isset($Format["R"]) ? $Format["R"] : 200;
+ $G = isset($Format["G"]) ? $Format["G"] : 200;
+ $B = isset($Format["B"]) ? $Format["B"] : 200;
+ $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 100;
+ $BorderR = isset($Format["BorderR"]) ? $Format["BorderR"] : 255;
+ $BorderG = isset($Format["BorderG"]) ? $Format["BorderG"] : 255;
+ $BorderB = isset($Format["BorderB"]) ? $Format["BorderB"] : 255;
$Surrounding = isset($Format["Surrounding"]) ? $Format["Surrounding"] : NULL;
- $Style = isset($Format["Style"]) ? $Format["Style"] : LEGEND_ROUND;
- $Mode = isset($Format["Mode"]) ? $Format["Mode"] : LEGEND_VERTICAL;
+ $Style = isset($Format["Style"]) ? $Format["Style"] : LEGEND_ROUND;
+ $Mode = isset($Format["Mode"]) ? $Format["Mode"] : LEGEND_VERTICAL;
if ( $Surrounding != NULL ) { $BorderR = $R + $Surrounding; $BorderG = $G + $Surrounding; $BorderB = $B + $Surrounding; }
@@ -1709,68 +1709,68 @@
function drawScale($Format="")
{
- $Pos = isset($Format["Pos"]) ? $Format["Pos"] : SCALE_POS_LEFTRIGHT;
- $Floating = isset($Format["Floating"]) ? $Format["Floating"] : FALSE;
- $Mode = isset($Format["Mode"]) ? $Format["Mode"] : SCALE_MODE_FLOATING;
- $RemoveXAxis = isset($Format["RemoveXAxis"]) ? $Format["RemoveXAxis"] : FALSE;
- $MinDivHeight = isset($Format["MinDivHeight"]) ? $Format["MinDivHeight"] : 20;
- $Factors = isset($Format["Factors"]) ? $Format["Factors"] : array(1,2,5);
- $ManualScale = isset($Format["ManualScale"]) ? $Format["ManualScale"] : array("0"=>array("Min"=>-100,"Max"=>100));
- $XMargin = isset($Format["XMargin"]) ? $Format["XMargin"] : AUTO;
- $YMargin = isset($Format["YMargin"]) ? $Format["YMargin"] : 0;
- $ScaleSpacing = isset($Format["ScaleSpacing"]) ? $Format["ScaleSpacing"] : 15;
- $InnerTickWidth = isset($Format["InnerTickWidth"]) ? $Format["InnerTickWidth"] : 2;
- $OuterTickWidth = isset($Format["OuterTickWidth"]) ? $Format["OuterTickWidth"] : 2;
- $DrawXLines = isset($Format["DrawXLines"]) ? $Format["DrawXLines"] : TRUE;
- $DrawYLines = isset($Format["DrawYLines"]) ? $Format["DrawYLines"] : ALL;
- $GridTicks = isset($Format["GridTicks"]) ? $Format["GridTicks"] : 4;
- $GridR = isset($Format["GridR"]) ? $Format["GridR"] : 255;
- $GridG = isset($Format["GridG"]) ? $Format["GridG"] : 255;
- $GridB = isset($Format["GridB"]) ? $Format["GridB"] : 255;
- $GridAlpha = isset($Format["GridAlpha"]) ? $Format["GridAlpha"] : 40;
- $AxisRo = isset($Format["AxisR"]) ? $Format["AxisR"] : 0;
- $AxisGo = isset($Format["AxisG"]) ? $Format["AxisG"] : 0;
- $AxisBo = isset($Format["AxisB"]) ? $Format["AxisB"] : 0;
- $AxisAlpha = isset($Format["AxisAlpha"]) ? $Format["AxisAlpha"] : 100;
- $TickRo = isset($Format["TickR"]) ? $Format["TickR"] : 0;
- $TickGo = isset($Format["TickG"]) ? $Format["TickG"] : 0;
- $TickBo = isset($Format["TickB"]) ? $Format["TickB"] : 0;
- $TickAlpha = isset($Format["TickAlpha"]) ? $Format["TickAlpha"] : 100;
- $DrawSubTicks = isset($Format["DrawSubTicks"]) ? $Format["DrawSubTicks"] : FALSE;
- $InnerSubTickWidth = isset($Format["InnerSubTickWidth"]) ? $Format["InnerSubTickWidth"] : 0;
- $OuterSubTickWidth = isset($Format["OuterSubTickWidth"]) ? $Format["OuterSubTickWidth"] : 2;
- $SubTickR = isset($Format["SubTickR"]) ? $Format["SubTickR"] : 255;
- $SubTickG = isset($Format["SubTickG"]) ? $Format["SubTickG"] : 0;
- $SubTickB = isset($Format["SubTickB"]) ? $Format["SubTickB"] : 0;
- $SubTickAlpha = isset($Format["SubTickAlpha"]) ? $Format["SubTickAlpha"] : 100;
- $AutoAxisLabels = isset($Format["AutoAxisLabels"]) ? $Format["AutoAxisLabels"] : TRUE;
- $XReleasePercent = isset($Format["XReleasePercent"]) ? $Format["XReleasePercent"] : 1;
- $DrawArrows = isset($Format["DrawArrows"]) ? $Format["DrawArrows"] : FALSE;
+ $Pos = isset($Format["Pos"]) ? $Format["Pos"] : SCALE_POS_LEFTRIGHT;
+ $Floating = isset($Format["Floating"]) ? $Format["Floating"] : FALSE;
+ $Mode = isset($Format["Mode"]) ? $Format["Mode"] : SCALE_MODE_FLOATING;
+ $RemoveXAxis = isset($Format["RemoveXAxis"]) ? $Format["RemoveXAxis"] : FALSE;
+ $MinDivHeight = isset($Format["MinDivHeight"]) ? $Format["MinDivHeight"] : 20;
+ $Factors = isset($Format["Factors"]) ? $Format["Factors"] : array(1,2,5);
+ $ManualScale = isset($Format["ManualScale"]) ? $Format["ManualScale"] : array("0"=>array("Min"=>-100,"Max"=>100));
+ $XMargin = isset($Format["XMargin"]) ? $Format["XMargin"] : AUTO;
+ $YMargin = isset($Format["YMargin"]) ? $Format["YMargin"] : 0;
+ $ScaleSpacing = isset($Format["ScaleSpacing"]) ? $Format["ScaleSpacing"] : 15;
+ $InnerTickWidth = isset($Format["InnerTickWidth"]) ? $Format["InnerTickWidth"] : 2;
+ $OuterTickWidth = isset($Format["OuterTickWidth"]) ? $Format["OuterTickWidth"] : 2;
+ $DrawXLines = isset($Format["DrawXLines"]) ? $Format["DrawXLines"] : TRUE;
+ $DrawYLines = isset($Format["DrawYLines"]) ? $Format["DrawYLines"] : ALL;
+ $GridTicks = isset($Format["GridTicks"]) ? $Format["GridTicks"] : 4;
+ $GridR = isset($Format["GridR"]) ? $Format["GridR"] : 255;
+ $GridG = isset($Format["GridG"]) ? $Format["GridG"] : 255;
+ $GridB = isset($Format["GridB"]) ? $Format["GridB"] : 255;
+ $GridAlpha = isset($Format["GridAlpha"]) ? $Format["GridAlpha"] : 40;
+ $AxisRo = isset($Format["AxisR"]) ? $Format["AxisR"] : 0;
+ $AxisGo = isset($Format["AxisG"]) ? $Format["AxisG"] : 0;
+ $AxisBo = isset($Format["AxisB"]) ? $Format["AxisB"] : 0;
+ $AxisAlpha = isset($Format["AxisAlpha"]) ? $Format["AxisAlpha"] : 100;
+ $TickRo = isset($Format["TickR"]) ? $Format["TickR"] : 0;
+ $TickGo = isset($Format["TickG"]) ? $Format["TickG"] : 0;
+ $TickBo = isset($Format["TickB"]) ? $Format["TickB"] : 0;
+ $TickAlpha = isset($Format["TickAlpha"]) ? $Format["TickAlpha"] : 100;
+ $DrawSubTicks = isset($Format["DrawSubTicks"]) ? $Format["DrawSubTicks"] : FALSE;
+ $InnerSubTickWidth = isset($Format["InnerSubTickWidth"]) ? $Format["InnerSubTickWidth"] : 0;
+ $OuterSubTickWidth = isset($Format["OuterSubTickWidth"]) ? $Format["OuterSubTickWidth"] : 2;
+ $SubTickR = isset($Format["SubTickR"]) ? $Format["SubTickR"] : 255;
+ $SubTickG = isset($Format["SubTickG"]) ? $Format["SubTickG"] : 0;
+ $SubTickB = isset($Format["SubTickB"]) ? $Format["SubTickB"] : 0;
+ $SubTickAlpha = isset($Format["SubTickAlpha"]) ? $Format["SubTickAlpha"] : 100;
+ $AutoAxisLabels = isset($Format["AutoAxisLabels"]) ? $Format["AutoAxisLabels"] : TRUE;
+ $XReleasePercent = isset($Format["XReleasePercent"]) ? $Format["XReleasePercent"] : 1;
+ $DrawArrows = isset($Format["DrawArrows"]) ? $Format["DrawArrows"] : FALSE;
$ArrowSize = isset($Format["ArrowSize"]) ? $Format["ArrowSize"] : 8;
- $CycleBackground = isset($Format["CycleBackground"]) ? $Format["CycleBackground"] : FALSE;
- $BackgroundR1 = isset($Format["BackgroundR1"]) ? $Format["BackgroundR1"] : 255;
- $BackgroundG1 = isset($Format["BackgroundG1"]) ? $Format["BackgroundG1"] : 255;
- $BackgroundB1 = isset($Format["BackgroundB1"]) ? $Format["BackgroundB1"] : 255;
- $BackgroundAlpha1 = isset($Format["BackgroundAlpha1"]) ? $Format["BackgroundAlpha1"] : 20;
- $BackgroundR2 = isset($Format["BackgroundR2"]) ? $Format["BackgroundR2"] : 230;
- $BackgroundG2 = isset($Format["BackgroundG2"]) ? $Format["BackgroundG2"] : 230;
- $BackgroundB2 = isset($Format["BackgroundB2"]) ? $Format["BackgroundB2"] : 230;
- $BackgroundAlpha2 = isset($Format["BackgroundAlpha2"]) ? $Format["BackgroundAlpha2"] : 20;
- $LabelingMethod = isset($Format["LabelingMethod"]) ? $Format["LabelingMethod"] : LABELING_ALL;
- $LabelSkip = isset($Format["LabelSkip"]) ? $Format["LabelSkip"] : 0;
- $LabelRotation = isset($Format["LabelRotation"]) ? $Format["LabelRotation"] : 0;
- $RemoveSkippedAxis = isset($Format["RemoveSkippedAxis"]) ? $Format["RemoveSkippedAxis"] : FALSE;
- $SkippedAxisTicks = isset($Format["SkippedAxisTicks"]) ? $Format["SkippedAxisTicks"] : $GridTicks+2;
- $SkippedAxisR = isset($Format["SkippedAxisR"]) ? $Format["SkippedAxisR"] : $GridR;
- $SkippedAxisG = isset($Format["SkippedAxisG"]) ? $Format["SkippedAxisG"] : $GridG;
- $SkippedAxisB = isset($Format["SkippedAxisB"]) ? $Format["SkippedAxisB"] : $GridB;
- $SkippedAxisAlpha = isset($Format["SkippedAxisAlpha"]) ? $Format["SkippedAxisAlpha"] : $GridAlpha-30;
- $SkippedTickR = isset($Format["SkippedTickR"]) ? $Format["SkippedTickR"] : $TickRo;
- $SkippedTickG = isset($Format["SkippedTickG"]) ? $Format["SkippedTickG"] : $TickGo;
- $SkippedTickB = isset($Format["SkippedTicksB"]) ? $Format["SkippedTickB"] : $TickBo;
- $SkippedTickAlpha = isset($Format["SkippedTickAlpha"]) ? $Format["SkippedTickAlpha"] : $TickAlpha-80;
- $SkippedInnerTickWidth = isset($Format["SkippedInnerTickWidth"]) ? $Format["SkippedInnerTickWidth"] : 0;
- $SkippedOuterTickWidth = isset($Format["SkippedOuterTickWidth"]) ? $Format["SkippedOuterTickWidth"] : 2;
+ $CycleBackground = isset($Format["CycleBackground"]) ? $Format["CycleBackground"] : FALSE;
+ $BackgroundR1 = isset($Format["BackgroundR1"]) ? $Format["BackgroundR1"] : 255;
+ $BackgroundG1 = isset($Format["BackgroundG1"]) ? $Format["BackgroundG1"] : 255;
+ $BackgroundB1 = isset($Format["BackgroundB1"]) ? $Format["BackgroundB1"] : 255;
+ $BackgroundAlpha1 = isset($Format["BackgroundAlpha1"]) ? $Format["BackgroundAlpha1"] : 20;
+ $BackgroundR2 = isset($Format["BackgroundR2"]) ? $Format["BackgroundR2"] : 230;
+ $BackgroundG2 = isset($Format["BackgroundG2"]) ? $Format["BackgroundG2"] : 230;
+ $BackgroundB2 = isset($Format["BackgroundB2"]) ? $Format["BackgroundB2"] : 230;
+ $BackgroundAlpha2 = isset($Format["BackgroundAlpha2"]) ? $Format["BackgroundAlpha2"] : 20;
+ $LabelingMethod = isset($Format["LabelingMethod"]) ? $Format["LabelingMethod"] : LABELING_ALL;
+ $LabelSkip = isset($Format["LabelSkip"]) ? $Format["LabelSkip"] : 0;
+ $LabelRotation = isset($Format["LabelRotation"]) ? $Format["LabelRotation"] : 0;
+ $RemoveSkippedAxis = isset($Format["RemoveSkippedAxis"]) ? $Format["RemoveSkippedAxis"] : FALSE;
+ $SkippedAxisTicks = isset($Format["SkippedAxisTicks"]) ? $Format["SkippedAxisTicks"] : $GridTicks+2;
+ $SkippedAxisR = isset($Format["SkippedAxisR"]) ? $Format["SkippedAxisR"] : $GridR;
+ $SkippedAxisG = isset($Format["SkippedAxisG"]) ? $Format["SkippedAxisG"] : $GridG;
+ $SkippedAxisB = isset($Format["SkippedAxisB"]) ? $Format["SkippedAxisB"] : $GridB;
+ $SkippedAxisAlpha = isset($Format["SkippedAxisAlpha"]) ? $Format["SkippedAxisAlpha"] : $GridAlpha-30;
+ $SkippedTickR = isset($Format["SkippedTickR"]) ? $Format["SkippedTickR"] : $TickRo;
+ $SkippedTickG = isset($Format["SkippedTickG"]) ? $Format["SkippedTickG"] : $TickGo;
+ $SkippedTickB = isset($Format["SkippedTicksB"]) ? $Format["SkippedTickB"] : $TickBo;
+ $SkippedTickAlpha = isset($Format["SkippedTickAlpha"]) ? $Format["SkippedTickAlpha"] : $TickAlpha-80;
+ $SkippedInnerTickWidth = isset($Format["SkippedInnerTickWidth"]) ? $Format["SkippedInnerTickWidth"] : 0;
+ $SkippedOuterTickWidth = isset($Format["SkippedOuterTickWidth"]) ? $Format["SkippedOuterTickWidth"] : 2;
/* Floating scale require X & Y margins to be set manually */
if ( $Floating && ( $XMargin == AUTO || $YMargin == 0 ) ) { $Floating = FALSE; }
@@ -1958,10 +1958,10 @@
{
if ( $Parameters["Position"] == AXIS_POSITION_BOTTOM )
{
- if ( $LabelRotation == 0 ) { $LabelAlign = TEXT_ALIGN_TOPMIDDLE; $YLabelOffset = 2; }
- if ( $LabelRotation > 0 && $LabelRotation < 190 ) { $LabelAlign = TEXT_ALIGN_MIDDLERIGHT; $YLabelOffset = 5; }
- if ( $LabelRotation == 180 ) { $LabelAlign = TEXT_ALIGN_BOTTOMMIDDLE; $YLabelOffset = 5; }
- if ( $LabelRotation > 180 && $LabelRotation < 360 ) { $LabelAlign = TEXT_ALIGN_MIDDLELEFT; $YLabelOffset = 2; }
+ if ( $LabelRotation == 0 ) { $LabelAlign = TEXT_ALIGN_TOPMIDDLE; $YLabelOffset = 2; }
+ if ( $LabelRotation > 0 && $LabelRotation < 190 ) { $LabelAlign = TEXT_ALIGN_MIDDLERIGHT; $YLabelOffset = 5; }
+ if ( $LabelRotation == 180 ) { $LabelAlign = TEXT_ALIGN_BOTTOMMIDDLE; $YLabelOffset = 5; }
+ if ( $LabelRotation > 180 && $LabelRotation < 360 ) { $LabelAlign = TEXT_ALIGN_MIDDLELEFT; $YLabelOffset = 2; }
if ( !$RemoveXAxis )
{
@@ -2031,10 +2031,10 @@
}
elseif ( $Parameters["Position"] == AXIS_POSITION_TOP )
{
- if ( $LabelRotation == 0 ) { $LabelAlign = TEXT_ALIGN_BOTTOMMIDDLE; $YLabelOffset = 2; }
- if ( $LabelRotation > 0 && $LabelRotation < 190 ) { $LabelAlign = TEXT_ALIGN_MIDDLELEFT; $YLabelOffset = 2; }
- if ( $LabelRotation == 180 ) { $LabelAlign = TEXT_ALIGN_TOPMIDDLE; $YLabelOffset = 5; }
- if ( $LabelRotation > 180 && $LabelRotation < 360 ) { $LabelAlign = TEXT_ALIGN_MIDDLERIGHT; $YLabelOffset = 5; }
+ if ( $LabelRotation == 0 ) { $LabelAlign = TEXT_ALIGN_BOTTOMMIDDLE; $YLabelOffset = 2; }
+ if ( $LabelRotation > 0 && $LabelRotation < 190 ) { $LabelAlign = TEXT_ALIGN_MIDDLELEFT; $YLabelOffset = 2; }
+ if ( $LabelRotation == 180 ) { $LabelAlign = TEXT_ALIGN_TOPMIDDLE; $YLabelOffset = 5; }
+ if ( $LabelRotation > 180 && $LabelRotation < 360 ) { $LabelAlign = TEXT_ALIGN_MIDDLERIGHT; $YLabelOffset = 5; }
if ( !$RemoveXAxis )
{
@@ -2108,10 +2108,10 @@
{
if ( $Parameters["Position"] == AXIS_POSITION_LEFT )
{
- if ( $LabelRotation == 0 ) { $LabelAlign = TEXT_ALIGN_MIDDLERIGHT; $XLabelOffset = -2; }
- if ( $LabelRotation > 0 && $LabelRotation < 190 ) { $LabelAlign = TEXT_ALIGN_MIDDLERIGHT; $XLabelOffset = -6; }
- if ( $LabelRotation == 180 ) { $LabelAlign = TEXT_ALIGN_MIDDLELEFT; $XLabelOffset = -2; }
- if ( $LabelRotation > 180 && $LabelRotation < 360 ) { $LabelAlign = TEXT_ALIGN_MIDDLELEFT; $XLabelOffset = -5; }
+ if ( $LabelRotation == 0 ) { $LabelAlign = TEXT_ALIGN_MIDDLERIGHT; $XLabelOffset = -2; }
+ if ( $LabelRotation > 0 && $LabelRotation < 190 ) { $LabelAlign = TEXT_ALIGN_MIDDLERIGHT; $XLabelOffset = -6; }
+ if ( $LabelRotation == 180 ) { $LabelAlign = TEXT_ALIGN_MIDDLELEFT; $XLabelOffset = -2; }
+ if ( $LabelRotation > 180 && $LabelRotation < 360 ) { $LabelAlign = TEXT_ALIGN_MIDDLELEFT; $XLabelOffset = -5; }
if ( !$RemoveXAxis )
{
@@ -2181,10 +2181,10 @@
}
elseif ( $Parameters["Position"] == AXIS_POSITION_RIGHT )
{
- if ( $LabelRotation == 0 ) { $LabelAlign = TEXT_ALIGN_MIDDLELEFT; $XLabelOffset = 2; }
- if ( $LabelRotation > 0 && $LabelRotation < 190 ) { $LabelAlign = TEXT_ALIGN_MIDDLELEFT; $XLabelOffset = 6; }
- if ( $LabelRotation == 180 ) { $LabelAlign = TEXT_ALIGN_MIDDLERIGHT; $XLabelOffset = 5; }
- if ( $LabelRotation > 180 && $LabelRotation < 360 ) { $LabelAlign = TEXT_ALIGN_MIDDLERIGHT; $XLabelOffset = 7; }
+ if ( $LabelRotation == 0 ) { $LabelAlign = TEXT_ALIGN_MIDDLELEFT; $XLabelOffset = 2; }
+ if ( $LabelRotation > 0 && $LabelRotation < 190 ) { $LabelAlign = TEXT_ALIGN_MIDDLELEFT; $XLabelOffset = 6; }
+ if ( $LabelRotation == 180 ) { $LabelAlign = TEXT_ALIGN_MIDDLERIGHT; $XLabelOffset = 5; }
+ if ( $LabelRotation > 180 && $LabelRotation < 360 ) { $LabelAlign = TEXT_ALIGN_MIDDLERIGHT; $XLabelOffset = 7; }
if ( !$RemoveXAxis )
{
@@ -2573,10 +2573,10 @@
return($Scale);
}
- /*
+ /*
function modulo($Value1,$Value2)
{
- if ($Value1 > $Value2) { return 0; }
+ if ($Value1 > $Value2) { return 0; }
if (floor($Value2) == 0) { return(0); }
if (floor($Value2) != 0) { return($Value1 % $Value2); }
@@ -2586,9 +2586,9 @@
return(($Value1*$Factor) % ($Value2*$Factor));
}
- */
- function modulo( $Value1, $Value2 ) {
- if ($Value1 > $Value2) { return 0; }
+ */
+ function modulo( $Value1, $Value2 ) {
+ if ($Value1 > $Value2) { return 0; }
if ($Value2 == 0) {
return 0;
@@ -2602,37 +2602,37 @@
/* Draw an X threshold */
function drawXThreshold($Value,$Format="")
{
- $R = isset($Format["R"]) ? $Format["R"] : 255;
- $G = isset($Format["G"]) ? $Format["G"] : 0;
- $B = isset($Format["B"]) ? $Format["B"] : 0;
- $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 50;
- $Weight = isset($Format["Weight"]) ? $Format["Weight"] : NULL;
- $Ticks = isset($Format["Ticks"]) ? $Format["Ticks"] : 6;
- $Wide = isset($Format["Wide"]) ? $Format["Wide"] : FALSE;
- $WideFactor = isset($Format["WideFactor"]) ? $Format["WideFactor"] : 5;
- $WriteCaption = isset($Format["WriteCaption"]) ? $Format["WriteCaption"] : FALSE;
- $Caption = isset($Format["Caption"]) ? $Format["Caption"] : NULL;
- $CaptionAlign = isset($Format["CaptionAlign"]) ? $Format["CaptionAlign"] : CAPTION_LEFT_TOP;
+ $R = isset($Format["R"]) ? $Format["R"] : 255;
+ $G = isset($Format["G"]) ? $Format["G"] : 0;
+ $B = isset($Format["B"]) ? $Format["B"] : 0;
+ $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 50;
+ $Weight = isset($Format["Weight"]) ? $Format["Weight"] : NULL;
+ $Ticks = isset($Format["Ticks"]) ? $Format["Ticks"] : 6;
+ $Wide = isset($Format["Wide"]) ? $Format["Wide"] : FALSE;
+ $WideFactor = isset($Format["WideFactor"]) ? $Format["WideFactor"] : 5;
+ $WriteCaption = isset($Format["WriteCaption"]) ? $Format["WriteCaption"] : FALSE;
+ $Caption = isset($Format["Caption"]) ? $Format["Caption"] : NULL;
+ $CaptionAlign = isset($Format["CaptionAlign"]) ? $Format["CaptionAlign"] : CAPTION_LEFT_TOP;
$CaptionOffset = isset($Format["CaptionOffset"]) ? $Format["CaptionOffset"] : 5;
- $CaptionR = isset($Format["CaptionR"]) ? $Format["CaptionR"] : 255;
- $CaptionG = isset($Format["CaptionG"]) ? $Format["CaptionG"] : 255;
- $CaptionB = isset($Format["CaptionB"]) ? $Format["CaptionB"] : 255;
- $CaptionAlpha = isset($Format["CaptionAlpha"]) ? $Format["CaptionAlpha"] : 100;
- $DrawBox = isset($Format["DrawBox"]) ? $Format["DrawBox"] : TRUE;
- $DrawBoxBorder = isset($Format["DrawBoxBorder"]) ? $Format["DrawBoxBorder"] : FALSE;
- $BorderOffset = isset($Format["BorderOffset"]) ? $Format["BorderOffset"] : 3;
- $BoxRounded = isset($Format["BoxRounded"]) ? $Format["BoxRounded"] : TRUE;
- $RoundedRadius = isset($Format["RoundedRadius"]) ? $Format["RoundedRadius"] : 3;
- $BoxR = isset($Format["BoxR"]) ? $Format["BoxR"] : 0;
- $BoxG = isset($Format["BoxG"]) ? $Format["BoxG"] : 0;
- $BoxB = isset($Format["BoxB"]) ? $Format["BoxB"] : 0;
- $BoxAlpha = isset($Format["BoxAlpha"]) ? $Format["BoxAlpha"] : 30;
- $BoxSurrounding = isset($Format["BoxSurrounding"]) ? $Format["BoxSurrounding"] : "";
- $BoxBorderR = isset($Format["BoxBorderR"]) ? $Format["BoxBorderR"] : 255;
- $BoxBorderG = isset($Format["BoxBorderG"]) ? $Format["BoxBorderG"] : 255;
- $BoxBorderB = isset($Format["BoxBorderB"]) ? $Format["BoxBorderB"] : 255;
- $BoxBorderAlpha = isset($Format["BoxBorderAlpha"]) ? $Format["BoxBorderAlpha"] : 100;
- $ValueIsLabel = isset($Format["ValueIsLabel"]) ? $Format["ValueIsLabel"] : FALSE;
+ $CaptionR = isset($Format["CaptionR"]) ? $Format["CaptionR"] : 255;
+ $CaptionG = isset($Format["CaptionG"]) ? $Format["CaptionG"] : 255;
+ $CaptionB = isset($Format["CaptionB"]) ? $Format["CaptionB"] : 255;
+ $CaptionAlpha = isset($Format["CaptionAlpha"]) ? $Format["CaptionAlpha"] : 100;
+ $DrawBox = isset($Format["DrawBox"]) ? $Format["DrawBox"] : TRUE;
+ $DrawBoxBorder = isset($Format["DrawBoxBorder"]) ? $Format["DrawBoxBorder"] : FALSE;
+ $BorderOffset = isset($Format["BorderOffset"]) ? $Format["BorderOffset"] : 3;
+ $BoxRounded = isset($Format["BoxRounded"]) ? $Format["BoxRounded"] : TRUE;
+ $RoundedRadius = isset($Format["RoundedRadius"]) ? $Format["RoundedRadius"] : 3;
+ $BoxR = isset($Format["BoxR"]) ? $Format["BoxR"] : 0;
+ $BoxG = isset($Format["BoxG"]) ? $Format["BoxG"] : 0;
+ $BoxB = isset($Format["BoxB"]) ? $Format["BoxB"] : 0;
+ $BoxAlpha = isset($Format["BoxAlpha"]) ? $Format["BoxAlpha"] : 30;
+ $BoxSurrounding = isset($Format["BoxSurrounding"]) ? $Format["BoxSurrounding"] : "";
+ $BoxBorderR = isset($Format["BoxBorderR"]) ? $Format["BoxBorderR"] : 255;
+ $BoxBorderG = isset($Format["BoxBorderG"]) ? $Format["BoxBorderG"] : 255;
+ $BoxBorderB = isset($Format["BoxBorderB"]) ? $Format["BoxBorderB"] : 255;
+ $BoxBorderAlpha = isset($Format["BoxBorderAlpha"]) ? $Format["BoxBorderAlpha"] : 100;
+ $ValueIsLabel = isset($Format["ValueIsLabel"]) ? $Format["ValueIsLabel"] : FALSE;
$Data = $this->DataSet->getData();
$AbscissaMargin = $this->getAbscissaMargin($Data);
@@ -2732,22 +2732,22 @@
/* Draw an X threshold area */
function drawXThresholdArea($Value1,$Value2,$Format="")
{
- $R = isset($Format["R"]) ? $Format["R"] : 255;
- $G = isset($Format["G"]) ? $Format["G"] : 0;
- $B = isset($Format["B"]) ? $Format["B"] : 0;
- $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 20;
+ $R = isset($Format["R"]) ? $Format["R"] : 255;
+ $G = isset($Format["G"]) ? $Format["G"] : 0;
+ $B = isset($Format["B"]) ? $Format["B"] : 0;
+ $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 20;
$Border = isset($Format["Border"]) ? $Format["Border"] : TRUE;
$BorderR = isset($Format["BorderR"]) ? $Format["BorderR"] : $R;
$BorderG = isset($Format["BorderG"]) ? $Format["BorderG"] : $G;
$BorderB = isset($Format["BorderB"]) ? $Format["BorderB"] : $B;
$BorderAlpha = isset($Format["BorderAlpha"]) ? $Format["BorderAlpha"] : $Alpha + 20;
$BorderTicks = isset($Format["BorderTicks"]) ? $Format["BorderTicks"] : 2;
- $AreaName = isset($Format["AreaName"]) ? $Format["AreaName"] : NULL;
- $NameAngle = isset($Format["NameAngle"]) ? $Format["NameAngle"] : ZONE_NAME_ANGLE_AUTO;
- $NameR = isset($Format["NameR"]) ? $Format["NameR"] : 255;
- $NameG = isset($Format["NameG"]) ? $Format["NameG"] : 255;
- $NameB = isset($Format["NameB"]) ? $Format["NameB"] : 255;
- $NameAlpha = isset($Format["NameAlpha"]) ? $Format["NameAlpha"] : 100;
+ $AreaName = isset($Format["AreaName"]) ? $Format["AreaName"] : NULL;
+ $NameAngle = isset($Format["NameAngle"]) ? $Format["NameAngle"] : ZONE_NAME_ANGLE_AUTO;
+ $NameR = isset($Format["NameR"]) ? $Format["NameR"] : 255;
+ $NameG = isset($Format["NameG"]) ? $Format["NameG"] : 255;
+ $NameB = isset($Format["NameB"]) ? $Format["NameB"] : 255;
+ $NameAlpha = isset($Format["NameAlpha"]) ? $Format["NameAlpha"] : 100;
$DisableShadowOnArea = isset($Format["DisableShadowOnArea"]) ? $Format["DisableShadowOnArea"] : TRUE;
$RestoreShadow = $this->Shadow;
@@ -2838,38 +2838,38 @@
/* Draw an Y threshold with the computed scale */
function drawThreshold($Value,$Format="")
{
- $AxisID = isset($Format["AxisID"]) ? $Format["AxisID"] : 0;
- $R = isset($Format["R"]) ? $Format["R"] : 255;
- $G = isset($Format["G"]) ? $Format["G"] : 0;
- $B = isset($Format["B"]) ? $Format["B"] : 0;
- $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 50;
- $Weight = isset($Format["Weight"]) ? $Format["Weight"] : NULL;
- $Ticks = isset($Format["Ticks"]) ? $Format["Ticks"] : 6;
- $Wide = isset($Format["Wide"]) ? $Format["Wide"] : FALSE;
- $WideFactor = isset($Format["WideFactor"]) ? $Format["WideFactor"] : 5;
- $WriteCaption = isset($Format["WriteCaption"]) ? $Format["WriteCaption"] : FALSE;
- $Caption = isset($Format["Caption"]) ? $Format["Caption"] : NULL;
- $CaptionAlign = isset($Format["CaptionAlign"]) ? $Format["CaptionAlign"] : CAPTION_LEFT_TOP;
+ $AxisID = isset($Format["AxisID"]) ? $Format["AxisID"] : 0;
+ $R = isset($Format["R"]) ? $Format["R"] : 255;
+ $G = isset($Format["G"]) ? $Format["G"] : 0;
+ $B = isset($Format["B"]) ? $Format["B"] : 0;
+ $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 50;
+ $Weight = isset($Format["Weight"]) ? $Format["Weight"] : NULL;
+ $Ticks = isset($Format["Ticks"]) ? $Format["Ticks"] : 6;
+ $Wide = isset($Format["Wide"]) ? $Format["Wide"] : FALSE;
+ $WideFactor = isset($Format["WideFactor"]) ? $Format["WideFactor"] : 5;
+ $WriteCaption = isset($Format["WriteCaption"]) ? $Format["WriteCaption"] : FALSE;
+ $Caption = isset($Format["Caption"]) ? $Format["Caption"] : NULL;
+ $CaptionAlign = isset($Format["CaptionAlign"]) ? $Format["CaptionAlign"] : CAPTION_LEFT_TOP;
$CaptionOffset = isset($Format["CaptionOffset"]) ? $Format["CaptionOffset"] : 10;
- $CaptionR = isset($Format["CaptionR"]) ? $Format["CaptionR"] : 255;
- $CaptionG = isset($Format["CaptionG"]) ? $Format["CaptionG"] : 255;
- $CaptionB = isset($Format["CaptionB"]) ? $Format["CaptionB"] : 255;
- $CaptionAlpha = isset($Format["CaptionAlpha"]) ? $Format["CaptionAlpha"] : 100;
- $DrawBox = isset($Format["DrawBox"]) ? $Format["DrawBox"] : TRUE;
- $DrawBoxBorder = isset($Format["DrawBoxBorder"]) ? $Format["DrawBoxBorder"] : FALSE;
- $BorderOffset = isset($Format["BorderOffset"]) ? $Format["BorderOffset"] : 5;
- $BoxRounded = isset($Format["BoxRounded"]) ? $Format["BoxRounded"] : TRUE;
- $RoundedRadius = isset($Format["RoundedRadius"]) ? $Format["RoundedRadius"] : 3;
- $BoxR = isset($Format["BoxR"]) ? $Format["BoxR"] : 0;
- $BoxG = isset($Format["BoxG"]) ? $Format["BoxG"] : 0;
- $BoxB = isset($Format["BoxB"]) ? $Format["BoxB"] : 0;
- $BoxAlpha = isset($Format["BoxAlpha"]) ? $Format["BoxAlpha"] : 20;
- $BoxSurrounding = isset($Format["BoxSurrounding"]) ? $Format["BoxSurrounding"] : "";
- $BoxBorderR = isset($Format["BoxBorderR"]) ? $Format["BoxBorderR"] : 255;
- $BoxBorderG = isset($Format["BoxBorderG"]) ? $Format["BoxBorderG"] : 255;
- $BoxBorderB = isset($Format["BoxBorderB"]) ? $Format["BoxBorderB"] : 255;
- $BoxBorderAlpha = isset($Format["BoxBorderAlpha"]) ? $Format["BoxBorderAlpha"] : 100;
- $NoMargin = isset($Format["NoMargin"]) ? $Format["NoMargin"] : FALSE;
+ $CaptionR = isset($Format["CaptionR"]) ? $Format["CaptionR"] : 255;
+ $CaptionG = isset($Format["CaptionG"]) ? $Format["CaptionG"] : 255;
+ $CaptionB = isset($Format["CaptionB"]) ? $Format["CaptionB"] : 255;
+ $CaptionAlpha = isset($Format["CaptionAlpha"]) ? $Format["CaptionAlpha"] : 100;
+ $DrawBox = isset($Format["DrawBox"]) ? $Format["DrawBox"] : TRUE;
+ $DrawBoxBorder = isset($Format["DrawBoxBorder"]) ? $Format["DrawBoxBorder"] : FALSE;
+ $BorderOffset = isset($Format["BorderOffset"]) ? $Format["BorderOffset"] : 5;
+ $BoxRounded = isset($Format["BoxRounded"]) ? $Format["BoxRounded"] : TRUE;
+ $RoundedRadius = isset($Format["RoundedRadius"]) ? $Format["RoundedRadius"] : 3;
+ $BoxR = isset($Format["BoxR"]) ? $Format["BoxR"] : 0;
+ $BoxG = isset($Format["BoxG"]) ? $Format["BoxG"] : 0;
+ $BoxB = isset($Format["BoxB"]) ? $Format["BoxB"] : 0;
+ $BoxAlpha = isset($Format["BoxAlpha"]) ? $Format["BoxAlpha"] : 20;
+ $BoxSurrounding = isset($Format["BoxSurrounding"]) ? $Format["BoxSurrounding"] : "";
+ $BoxBorderR = isset($Format["BoxBorderR"]) ? $Format["BoxBorderR"] : 255;
+ $BoxBorderG = isset($Format["BoxBorderG"]) ? $Format["BoxBorderG"] : 255;
+ $BoxBorderB = isset($Format["BoxBorderB"]) ? $Format["BoxBorderB"] : 255;
+ $BoxBorderAlpha = isset($Format["BoxBorderAlpha"]) ? $Format["BoxBorderAlpha"] : 100;
+ $NoMargin = isset($Format["NoMargin"]) ? $Format["NoMargin"] : FALSE;
if ( is_array($Value) ) { foreach ($Value as $Key => $ID) { $this->drawThreshold($ID,$Format); } return(0); }
@@ -2950,25 +2950,25 @@
/* Draw a threshold with the computed scale */
function drawThresholdArea($Value1,$Value2,$Format="")
{
- $AxisID = isset($Format["AxisID"]) ? $Format["AxisID"] : 0;
- $R = isset($Format["R"]) ? $Format["R"] : 255;
- $G = isset($Format["G"]) ? $Format["G"] : 0;
- $B = isset($Format["B"]) ? $Format["B"] : 0;
- $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 20;
+ $AxisID = isset($Format["AxisID"]) ? $Format["AxisID"] : 0;
+ $R = isset($Format["R"]) ? $Format["R"] : 255;
+ $G = isset($Format["G"]) ? $Format["G"] : 0;
+ $B = isset($Format["B"]) ? $Format["B"] : 0;
+ $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 20;
$Border = isset($Format["Border"]) ? $Format["Border"] : TRUE;
$BorderR = isset($Format["BorderR"]) ? $Format["BorderR"] : $R;
$BorderG = isset($Format["BorderG"]) ? $Format["BorderG"] : $G;
$BorderB = isset($Format["BorderB"]) ? $Format["BorderB"] : $B;
$BorderAlpha = isset($Format["BorderAlpha"]) ? $Format["BorderAlpha"] : $Alpha + 20;
$BorderTicks = isset($Format["BorderTicks"]) ? $Format["BorderTicks"] : 2;
- $AreaName = isset($Format["AreaName"]) ? $Format["AreaName"] : NULL;
- $NameAngle = isset($Format["NameAngle"]) ? $Format["NameAngle"] : ZONE_NAME_ANGLE_AUTO;
- $NameR = isset($Format["NameR"]) ? $Format["NameR"] : 255;
- $NameG = isset($Format["NameG"]) ? $Format["NameG"] : 255;
- $NameB = isset($Format["NameB"]) ? $Format["NameB"] : 255;
- $NameAlpha = isset($Format["NameAlpha"]) ? $Format["NameAlpha"] : 100;
+ $AreaName = isset($Format["AreaName"]) ? $Format["AreaName"] : NULL;
+ $NameAngle = isset($Format["NameAngle"]) ? $Format["NameAngle"] : ZONE_NAME_ANGLE_AUTO;
+ $NameR = isset($Format["NameR"]) ? $Format["NameR"] : 255;
+ $NameG = isset($Format["NameG"]) ? $Format["NameG"] : 255;
+ $NameB = isset($Format["NameB"]) ? $Format["NameB"] : 255;
+ $NameAlpha = isset($Format["NameAlpha"]) ? $Format["NameAlpha"] : 100;
$DisableShadowOnArea = isset($Format["DisableShadowOnArea"]) ? $Format["DisableShadowOnArea"] : TRUE;
- $NoMargin = isset($Format["NoMargin"]) ? $Format["NoMargin"] : FALSE;
+ $NoMargin = isset($Format["NoMargin"]) ? $Format["NoMargin"] : FALSE;
if ($Value1 > $Value2) { list($Value1, $Value2) = array($Value2, $Value1); }
@@ -3070,8 +3070,8 @@
function scaleComputeY($Values,$Option="",$ReturnOnly0Height=FALSE)
{
- $AxisID = isset($Option["AxisID"]) ? $Option["AxisID"] : 0;
- $SerieName = isset($Option["SerieName"]) ? $Option["SerieName"] : NULL;
+ $AxisID = isset($Option["AxisID"]) ? $Option["AxisID"] : 0;
+ $SerieName = isset($Option["SerieName"]) ? $Option["SerieName"] : NULL;
$Data = $this->DataSet->getData();
if ( !isset($Data["Axis"][$AxisID]) ) { return(-1); }
@@ -3096,11 +3096,11 @@
$Width = ($this->GraphAreaX2 - $this->GraphAreaX1) - $Data["Axis"][$AxisID]["Margin"]*2;
$ScaleWidth = $Data["Axis"][$AxisID]["ScaleMax"] - $Data["Axis"][$AxisID]["ScaleMin"];
- if ($ScaleWidth > 0) {
- $Step = $Width / $ScaleWidth;
- } else {
- $Step = 1; // or change this to 0 if it doesn't work, I am not sure what this line does.
- }
+ if ($ScaleWidth > 0) {
+ $Step = $Width / $ScaleWidth;
+ } else {
+ $Step = 1; // or change this to 0 if it doesn't work, I am not sure what this line does.
+ }
if ( $ReturnOnly0Height )
{ foreach($Values as $Key => $Value) { if ( $Value == VOID ) { $Result[] = VOID; } else { $Result[] = $Step * $Value; } } }
@@ -3157,34 +3157,34 @@
/* Write Max value on a chart */
function writeBounds($Type=BOUND_BOTH,$Format=NULL)
{
- $MaxLabelTxt = isset($Format["MaxLabelTxt"]) ? $Format["MaxLabelTxt"] : "max=";
- $MinLabelTxt = isset($Format["MinLabelTxt"]) ? $Format["MinLabelTxt"] : "min=";
- $Decimals = isset($Format["Decimals"]) ? $Format["Decimals"] : 1;
- $ExcludedSeries = isset($Format["ExcludedSeries"]) ? $Format["ExcludedSeries"] : "";
- $DisplayOffset = isset($Format["DisplayOffset"]) ? $Format["DisplayOffset"] : 4;
- $DisplayColor = isset($Format["DisplayColor"]) ? $Format["DisplayColor"] : DISPLAY_MANUAL;
- $MaxDisplayR = isset($Format["MaxDisplayR"]) ? $Format["MaxDisplayR"] : 0;
- $MaxDisplayG = isset($Format["MaxDisplayG"]) ? $Format["MaxDisplayG"] : 0;
- $MaxDisplayB = isset($Format["MaxDisplayB"]) ? $Format["MaxDisplayB"] : 0;
- $MinDisplayR = isset($Format["MinDisplayR"]) ? $Format["MinDisplayR"] : 255;
- $MinDisplayG = isset($Format["MinDisplayG"]) ? $Format["MinDisplayG"] : 255;
- $MinDisplayB = isset($Format["MinDisplayB"]) ? $Format["MinDisplayB"] : 255;
- $MinLabelPos = isset($Format["MinLabelPos"]) ? $Format["MinLabelPos"] : BOUND_LABEL_POS_AUTO;
- $MaxLabelPos = isset($Format["MaxLabelPos"]) ? $Format["MaxLabelPos"] : BOUND_LABEL_POS_AUTO;
- $DrawBox = isset($Format["DrawBox"]) ? $Format["DrawBox"] : TRUE;
- $DrawBoxBorder = isset($Format["DrawBoxBorder"]) ? $Format["DrawBoxBorder"] : FALSE;
- $BorderOffset = isset($Format["BorderOffset"]) ? $Format["BorderOffset"] : 5;
- $BoxRounded = isset($Format["BoxRounded"]) ? $Format["BoxRounded"] : TRUE;
- $RoundedRadius = isset($Format["RoundedRadius"]) ? $Format["RoundedRadius"] : 3;
- $BoxR = isset($Format["BoxR"]) ? $Format["BoxR"] : 0;
- $BoxG = isset($Format["BoxG"]) ? $Format["BoxG"] : 0;
- $BoxB = isset($Format["BoxB"]) ? $Format["BoxB"] : 0;
- $BoxAlpha = isset($Format["BoxAlpha"]) ? $Format["BoxAlpha"] : 20;
- $BoxSurrounding = isset($Format["BoxSurrounding"]) ? $Format["BoxSurrounding"] : "";
- $BoxBorderR = isset($Format["BoxBorderR"]) ? $Format["BoxBorderR"] : 255;
- $BoxBorderG = isset($Format["BoxBorderG"]) ? $Format["BoxBorderG"] : 255;
- $BoxBorderB = isset($Format["BoxBorderB"]) ? $Format["BoxBorderB"] : 255;
- $BoxBorderAlpha = isset($Format["BoxBorderAlpha"]) ? $Format["BoxBorderAlpha"] : 100;
+ $MaxLabelTxt = isset($Format["MaxLabelTxt"]) ? $Format["MaxLabelTxt"] : "max=";
+ $MinLabelTxt = isset($Format["MinLabelTxt"]) ? $Format["MinLabelTxt"] : "min=";
+ $Decimals = isset($Format["Decimals"]) ? $Format["Decimals"] : 1;
+ $ExcludedSeries = isset($Format["ExcludedSeries"]) ? $Format["ExcludedSeries"] : "";
+ $DisplayOffset = isset($Format["DisplayOffset"]) ? $Format["DisplayOffset"] : 4;
+ $DisplayColor = isset($Format["DisplayColor"]) ? $Format["DisplayColor"] : DISPLAY_MANUAL;
+ $MaxDisplayR = isset($Format["MaxDisplayR"]) ? $Format["MaxDisplayR"] : 0;
+ $MaxDisplayG = isset($Format["MaxDisplayG"]) ? $Format["MaxDisplayG"] : 0;
+ $MaxDisplayB = isset($Format["MaxDisplayB"]) ? $Format["MaxDisplayB"] : 0;
+ $MinDisplayR = isset($Format["MinDisplayR"]) ? $Format["MinDisplayR"] : 255;
+ $MinDisplayG = isset($Format["MinDisplayG"]) ? $Format["MinDisplayG"] : 255;
+ $MinDisplayB = isset($Format["MinDisplayB"]) ? $Format["MinDisplayB"] : 255;
+ $MinLabelPos = isset($Format["MinLabelPos"]) ? $Format["MinLabelPos"] : BOUND_LABEL_POS_AUTO;
+ $MaxLabelPos = isset($Format["MaxLabelPos"]) ? $Format["MaxLabelPos"] : BOUND_LABEL_POS_AUTO;
+ $DrawBox = isset($Format["DrawBox"]) ? $Format["DrawBox"] : TRUE;
+ $DrawBoxBorder = isset($Format["DrawBoxBorder"]) ? $Format["DrawBoxBorder"] : FALSE;
+ $BorderOffset = isset($Format["BorderOffset"]) ? $Format["BorderOffset"] : 5;
+ $BoxRounded = isset($Format["BoxRounded"]) ? $Format["BoxRounded"] : TRUE;
+ $RoundedRadius = isset($Format["RoundedRadius"]) ? $Format["RoundedRadius"] : 3;
+ $BoxR = isset($Format["BoxR"]) ? $Format["BoxR"] : 0;
+ $BoxG = isset($Format["BoxG"]) ? $Format["BoxG"] : 0;
+ $BoxB = isset($Format["BoxB"]) ? $Format["BoxB"] : 0;
+ $BoxAlpha = isset($Format["BoxAlpha"]) ? $Format["BoxAlpha"] : 20;
+ $BoxSurrounding = isset($Format["BoxSurrounding"]) ? $Format["BoxSurrounding"] : "";
+ $BoxBorderR = isset($Format["BoxBorderR"]) ? $Format["BoxBorderR"] : 255;
+ $BoxBorderG = isset($Format["BoxBorderG"]) ? $Format["BoxBorderG"] : 255;
+ $BoxBorderB = isset($Format["BoxBorderB"]) ? $Format["BoxBorderB"] : 255;
+ $BoxBorderAlpha = isset($Format["BoxBorderAlpha"]) ? $Format["BoxBorderAlpha"] : 100;
$CaptionSettings = array("DrawBox"=>$DrawBox,"DrawBoxBorder"=>$DrawBoxBorder,"BorderOffset"=>$BorderOffset,"BoxRounded"=>$BoxRounded,"RoundedRadius"=>$RoundedRadius,
"BoxR"=>$BoxR,"BoxG"=>$BoxG,"BoxB"=>$BoxB,"BoxAlpha"=>$BoxAlpha,"BoxSurrounding"=>$BoxSurrounding,
@@ -3210,10 +3210,10 @@
if ( $Value == $MaxValue ) { $MaxPos = $Key; }
}
- $AxisID = $Serie["Axis"];
- $Mode = $Data["Axis"][$AxisID]["Display"];
- $Format = $Data["Axis"][$AxisID]["Format"];
- $Unit = $Data["Axis"][$AxisID]["Unit"];
+ $AxisID = $Serie["Axis"];
+ $Mode = $Data["Axis"][$AxisID]["Display"];
+ $Format = $Data["Axis"][$AxisID]["Format"];
+ $Unit = $Data["Axis"][$AxisID]["Unit"];
$PosArray = $this->scaleComputeY($Serie["Data"],array("AxisID"=>$Serie["Axis"]));
@@ -3320,21 +3320,21 @@
/* Draw a plot chart */
function drawPlotChart($Format=NULL)
{
- $PlotSize = isset($Format["PlotSize"]) ? $Format["PlotSize"] : NULL;
- $PlotBorder = isset($Format["PlotBorder"]) ? $Format["PlotBorder"] : FALSE;
- $BorderR = isset($Format["BorderR"]) ? $Format["BorderR"] : 50;
- $BorderG = isset($Format["BorderG"]) ? $Format["BorderG"] : 50;
- $BorderB = isset($Format["BorderB"]) ? $Format["BorderB"] : 50;
- $BorderAlpha = isset($Format["BorderAlpha"]) ? $Format["BorderAlpha"] : 30;
- $BorderSize = isset($Format["BorderSize"]) ? $Format["BorderSize"] : 2;
- $Surrounding = isset($Format["Surrounding"]) ? $Format["Surrounding"] : NULL;
- $DisplayValues = isset($Format["DisplayValues"]) ? $Format["DisplayValues"] : FALSE;
- $DisplayOffset = isset($Format["DisplayOffset"]) ? $Format["DisplayOffset"] : 4;
- $DisplayColor = isset($Format["DisplayColor"]) ? $Format["DisplayColor"] : DISPLAY_MANUAL;
- $DisplayR = isset($Format["DisplayR"]) ? $Format["DisplayR"] : 0;
- $DisplayG = isset($Format["DisplayG"]) ? $Format["DisplayG"] : 0;
- $DisplayB = isset($Format["DisplayB"]) ? $Format["DisplayB"] : 0;
- $RecordImageMap = isset($Format["RecordImageMap"]) ? $Format["RecordImageMap"] : FALSE;
+ $PlotSize = isset($Format["PlotSize"]) ? $Format["PlotSize"] : NULL;
+ $PlotBorder = isset($Format["PlotBorder"]) ? $Format["PlotBorder"] : FALSE;
+ $BorderR = isset($Format["BorderR"]) ? $Format["BorderR"] : 50;
+ $BorderG = isset($Format["BorderG"]) ? $Format["BorderG"] : 50;
+ $BorderB = isset($Format["BorderB"]) ? $Format["BorderB"] : 50;
+ $BorderAlpha = isset($Format["BorderAlpha"]) ? $Format["BorderAlpha"] : 30;
+ $BorderSize = isset($Format["BorderSize"]) ? $Format["BorderSize"] : 2;
+ $Surrounding = isset($Format["Surrounding"]) ? $Format["Surrounding"] : NULL;
+ $DisplayValues = isset($Format["DisplayValues"]) ? $Format["DisplayValues"] : FALSE;
+ $DisplayOffset = isset($Format["DisplayOffset"]) ? $Format["DisplayOffset"] : 4;
+ $DisplayColor = isset($Format["DisplayColor"]) ? $Format["DisplayColor"] : DISPLAY_MANUAL;
+ $DisplayR = isset($Format["DisplayR"]) ? $Format["DisplayR"] : 0;
+ $DisplayG = isset($Format["DisplayG"]) ? $Format["DisplayG"] : 0;
+ $DisplayB = isset($Format["DisplayB"]) ? $Format["DisplayB"] : 0;
+ $RecordImageMap = isset($Format["RecordImageMap"]) ? $Format["RecordImageMap"] : FALSE;
$this->LastChartLayout = CHART_LAST_LAYOUT_REGULAR;
@@ -3356,11 +3356,11 @@
if ( $DisplayColor == DISPLAY_AUTO ) { $DisplayR = $R; $DisplayG = $G; $DisplayB = $B; }
- $AxisID = $Serie["Axis"];
- $Shape = $Serie["Shape"];
- $Mode = $Data["Axis"][$AxisID]["Display"];
- $Format = $Data["Axis"][$AxisID]["Format"];
- $Unit = $Data["Axis"][$AxisID]["Unit"];
+ $AxisID = $Serie["Axis"];
+ $Shape = $Serie["Shape"];
+ $Mode = $Data["Axis"][$AxisID]["Display"];
+ $Format = $Data["Axis"][$AxisID]["Format"];
+ $Unit = $Data["Axis"][$AxisID]["Unit"];
if (isset($Serie["Description"])) { $SerieDescription = $Serie["Description"]; } else { $SerieDescription = $SerieName; }
@@ -3423,18 +3423,18 @@
/* Draw a spline chart */
function drawSplineChart($Format=NULL)
{
- $BreakVoid = isset($Format["BreakVoid"]) ? $Format["BreakVoid"] : TRUE;
- $VoidTicks = isset($Format["VoidTicks"]) ? $Format["VoidTicks"] : 4;
- $BreakR = isset($Format["BreakR"]) ? $Format["BreakR"] : NULL; // 234
- $BreakG = isset($Format["BreakG"]) ? $Format["BreakG"] : NULL; // 55
- $BreakB = isset($Format["BreakB"]) ? $Format["BreakB"] : NULL; // 26
- $DisplayValues = isset($Format["DisplayValues"]) ? $Format["DisplayValues"] : FALSE;
- $DisplayOffset = isset($Format["DisplayOffset"]) ? $Format["DisplayOffset"] : 2;
- $DisplayColor = isset($Format["DisplayColor"]) ? $Format["DisplayColor"] : DISPLAY_MANUAL;
- $DisplayR = isset($Format["DisplayR"]) ? $Format["DisplayR"] : 0;
- $DisplayG = isset($Format["DisplayG"]) ? $Format["DisplayG"] : 0;
- $DisplayB = isset($Format["DisplayB"]) ? $Format["DisplayB"] : 0;
- $RecordImageMap = isset($Format["RecordImageMap"]) ? $Format["RecordImageMap"] : FALSE;
+ $BreakVoid = isset($Format["BreakVoid"]) ? $Format["BreakVoid"] : TRUE;
+ $VoidTicks = isset($Format["VoidTicks"]) ? $Format["VoidTicks"] : 4;
+ $BreakR = isset($Format["BreakR"]) ? $Format["BreakR"] : NULL; // 234
+ $BreakG = isset($Format["BreakG"]) ? $Format["BreakG"] : NULL; // 55
+ $BreakB = isset($Format["BreakB"]) ? $Format["BreakB"] : NULL; // 26
+ $DisplayValues = isset($Format["DisplayValues"]) ? $Format["DisplayValues"] : FALSE;
+ $DisplayOffset = isset($Format["DisplayOffset"]) ? $Format["DisplayOffset"] : 2;
+ $DisplayColor = isset($Format["DisplayColor"]) ? $Format["DisplayColor"] : DISPLAY_MANUAL;
+ $DisplayR = isset($Format["DisplayR"]) ? $Format["DisplayR"] : 0;
+ $DisplayG = isset($Format["DisplayG"]) ? $Format["DisplayG"] : 0;
+ $DisplayB = isset($Format["DisplayB"]) ? $Format["DisplayB"] : 0;
+ $RecordImageMap = isset($Format["RecordImageMap"]) ? $Format["RecordImageMap"] : FALSE;
$ImageMapPlotSize = isset($Format["ImageMapPlotSize"]) ? $Format["ImageMapPlotSize"] : 5;
$this->LastChartLayout = CHART_LAST_LAYOUT_REGULAR;
@@ -3454,10 +3454,10 @@
if ( $DisplayColor == DISPLAY_AUTO ) { $DisplayR = $R; $DisplayG = $G; $DisplayB = $B; }
- $AxisID = $Serie["Axis"];
- $Mode = $Data["Axis"][$AxisID]["Display"];
- $Format = $Data["Axis"][$AxisID]["Format"];
- $Unit = $Data["Axis"][$AxisID]["Unit"];
+ $AxisID = $Serie["Axis"];
+ $Mode = $Data["Axis"][$AxisID]["Display"];
+ $Format = $Data["Axis"][$AxisID]["Format"];
+ $Unit = $Data["Axis"][$AxisID]["Unit"];
if (isset($Serie["Description"])) { $SerieDescription = $Serie["Description"]; } else { $SerieDescription = $SerieName; }
@@ -3477,7 +3477,7 @@
{
if ( $DisplayValues )
$this->drawText($X,$Y-$DisplayOffset,$this->scaleFormat($Serie["Data"][$Key],$Mode,$Format,$Unit),array("R"=>$DisplayR,"G"=>$DisplayG,"B"=>$DisplayB,"Align"=>TEXT_ALIGN_BOTTOMMIDDLE));
-
+
if ( $RecordImageMap && $Y != VOID ) { $this->addToImageMap("CIRCLE",floor($X).",".floor($Y).",".$ImageMapPlotSize,$this->toHTMLColor($R,$G,$B),$SerieDescription,$this->scaleFormat($Serie["Data"][$Key],$Mode,$Format,$Unit)); }
if ( $Y == VOID && $LastY != NULL )
@@ -3536,14 +3536,14 @@
/* Draw a filled spline chart */
function drawFilledSplineChart($Format=NULL)
{
- $DisplayValues = isset($Format["DisplayValues"]) ? $Format["DisplayValues"] : FALSE;
- $DisplayOffset = isset($Format["DisplayOffset"]) ? $Format["DisplayOffset"] : 2;
- $DisplayColor = isset($Format["DisplayColor"]) ? $Format["DisplayColor"] : DISPLAY_MANUAL;
- $DisplayR = isset($Format["DisplayR"]) ? $Format["DisplayR"] : 0;
- $DisplayG = isset($Format["DisplayG"]) ? $Format["DisplayG"] : 0;
- $DisplayB = isset($Format["DisplayB"]) ? $Format["DisplayB"] : 0;
- $AroundZero = isset($Format["AroundZero"]) ? $Format["AroundZero"] : TRUE;
- $Threshold = isset($Format["Threshold"]) ? $Format["Threshold"] : NULL;
+ $DisplayValues = isset($Format["DisplayValues"]) ? $Format["DisplayValues"] : FALSE;
+ $DisplayOffset = isset($Format["DisplayOffset"]) ? $Format["DisplayOffset"] : 2;
+ $DisplayColor = isset($Format["DisplayColor"]) ? $Format["DisplayColor"] : DISPLAY_MANUAL;
+ $DisplayR = isset($Format["DisplayR"]) ? $Format["DisplayR"] : 0;
+ $DisplayG = isset($Format["DisplayG"]) ? $Format["DisplayG"] : 0;
+ $DisplayB = isset($Format["DisplayB"]) ? $Format["DisplayB"] : 0;
+ $AroundZero = isset($Format["AroundZero"]) ? $Format["AroundZero"] : TRUE;
+ $Threshold = isset($Format["Threshold"]) ? $Format["Threshold"] : NULL;
$this->LastChartLayout = CHART_LAST_LAYOUT_REGULAR;
@@ -3556,10 +3556,10 @@
$R = $Serie["Color"]["R"]; $G = $Serie["Color"]["G"]; $B = $Serie["Color"]["B"]; $Alpha = $Serie["Color"]["Alpha"]; $Ticks = $Serie["Ticks"];
if ( $DisplayColor == DISPLAY_AUTO ) { $DisplayR = $R; $DisplayG = $G; $DisplayB = $B; }
- $AxisID = $Serie["Axis"];
- $Mode = $Data["Axis"][$AxisID]["Display"];
- $Format = $Data["Axis"][$AxisID]["Format"];
- $Unit = $Data["Axis"][$AxisID]["Unit"];
+ $AxisID = $Serie["Axis"];
+ $Mode = $Data["Axis"][$AxisID]["Display"];
+ $Format = $Data["Axis"][$AxisID]["Format"];
+ $Unit = $Data["Axis"][$AxisID]["Unit"];
$PosArray = $this->scaleComputeY($Serie["Data"],array("AxisID"=>$Serie["Axis"]));
if ( $AroundZero ) { $YZero = $this->scaleComputeY(0,array("AxisID"=>$Serie["Axis"])); }
@@ -3710,24 +3710,24 @@
/* Draw a line chart */
function drawLineChart($Format=NULL)
{
- $BreakVoid = isset($Format["BreakVoid"]) ? $Format["BreakVoid"] : TRUE;
- $VoidTicks = isset($Format["VoidTicks"]) ? $Format["VoidTicks"] : 4;
- $BreakR = isset($Format["BreakR"]) ? $Format["BreakR"] : NULL;
- $BreakG = isset($Format["BreakG"]) ? $Format["BreakG"] : NULL;
- $BreakB = isset($Format["BreakB"]) ? $Format["BreakB"] : NULL;
- $DisplayValues = isset($Format["DisplayValues"]) ? $Format["DisplayValues"] : FALSE;
- $DisplayOffset = isset($Format["DisplayOffset"]) ? $Format["DisplayOffset"] : 2;
- $DisplayColor = isset($Format["DisplayColor"]) ? $Format["DisplayColor"] : DISPLAY_MANUAL;
- $DisplayR = isset($Format["DisplayR"]) ? $Format["DisplayR"] : 0;
- $DisplayG = isset($Format["DisplayG"]) ? $Format["DisplayG"] : 0;
- $DisplayB = isset($Format["DisplayB"]) ? $Format["DisplayB"] : 0;
- $RecordImageMap = isset($Format["RecordImageMap"]) ? $Format["RecordImageMap"] : FALSE;
+ $BreakVoid = isset($Format["BreakVoid"]) ? $Format["BreakVoid"] : TRUE;
+ $VoidTicks = isset($Format["VoidTicks"]) ? $Format["VoidTicks"] : 4;
+ $BreakR = isset($Format["BreakR"]) ? $Format["BreakR"] : NULL;
+ $BreakG = isset($Format["BreakG"]) ? $Format["BreakG"] : NULL;
+ $BreakB = isset($Format["BreakB"]) ? $Format["BreakB"] : NULL;
+ $DisplayValues = isset($Format["DisplayValues"]) ? $Format["DisplayValues"] : FALSE;
+ $DisplayOffset = isset($Format["DisplayOffset"]) ? $Format["DisplayOffset"] : 2;
+ $DisplayColor = isset($Format["DisplayColor"]) ? $Format["DisplayColor"] : DISPLAY_MANUAL;
+ $DisplayR = isset($Format["DisplayR"]) ? $Format["DisplayR"] : 0;
+ $DisplayG = isset($Format["DisplayG"]) ? $Format["DisplayG"] : 0;
+ $DisplayB = isset($Format["DisplayB"]) ? $Format["DisplayB"] : 0;
+ $RecordImageMap = isset($Format["RecordImageMap"]) ? $Format["RecordImageMap"] : FALSE;
$ImageMapPlotSize = isset($Format["ImageMapPlotSize"]) ? $Format["ImageMapPlotSize"] : 5;
- $ForceColor = isset($Format["ForceColor"]) ? $Format["ForceColor"] : FALSE;
- $ForceR = isset($Format["ForceR"]) ? $Format["ForceR"] : 0;
- $ForceG = isset($Format["ForceG"]) ? $Format["ForceG"] : 0;
- $ForceB = isset($Format["ForceB"]) ? $Format["ForceB"] : 0;
- $ForceAlpha = isset($Format["ForceAlpha"]) ? $Format["ForceAlpha"] : 100;
+ $ForceColor = isset($Format["ForceColor"]) ? $Format["ForceColor"] : FALSE;
+ $ForceR = isset($Format["ForceR"]) ? $Format["ForceR"] : 0;
+ $ForceG = isset($Format["ForceG"]) ? $Format["ForceG"] : 0;
+ $ForceB = isset($Format["ForceB"]) ? $Format["ForceB"] : 0;
+ $ForceAlpha = isset($Format["ForceAlpha"]) ? $Format["ForceAlpha"] : 100;
$this->LastChartLayout = CHART_LAST_LAYOUT_REGULAR;
@@ -3749,10 +3749,10 @@
if ( $DisplayColor == DISPLAY_AUTO ) { $DisplayR = $R; $DisplayG = $G; $DisplayB = $B; }
- $AxisID = $Serie["Axis"];
- $Mode = $Data["Axis"][$AxisID]["Display"];
- $Format = $Data["Axis"][$AxisID]["Format"];
- $Unit = $Data["Axis"][$AxisID]["Unit"];
+ $AxisID = $Serie["Axis"];
+ $Mode = $Data["Axis"][$AxisID]["Display"];
+ $Format = $Data["Axis"][$AxisID]["Format"];
+ $Unit = $Data["Axis"][$AxisID]["Unit"];
if (isset($Serie["Description"])) { $SerieDescription = $Serie["Description"]; } else { $SerieDescription = $SerieName; }
@@ -3824,29 +3824,29 @@
/* Draw a line chart */
function drawZoneChart($SerieA,$SerieB,$Format=NULL)
{
- $AxisID = isset($Format["AxisID"]) ? $Format["AxisID"] : 0;
- $LineR = isset($Format["LineR"]) ? $Format["LineR"] : 150;
- $LineG = isset($Format["LineG"]) ? $Format["LineG"] : 150;
- $LineB = isset($Format["LineB"]) ? $Format["LineB"] : 150;
- $LineAlpha = isset($Format["LineAlpha"]) ? $Format["LineAlpha"] : 50;
- $LineTicks = isset($Format["LineTicks"]) ? $Format["LineTicks"] : 1;
- $AreaR = isset($Format["AreaR"]) ? $Format["AreaR"] : 150;
- $AreaG = isset($Format["AreaG"]) ? $Format["AreaG"] : 150;
- $AreaB = isset($Format["AreaB"]) ? $Format["AreaB"] : 150;
- $AreaAlpha = isset($Format["AreaAlpha"]) ? $Format["AreaAlpha"] : 5;
+ $AxisID = isset($Format["AxisID"]) ? $Format["AxisID"] : 0;
+ $LineR = isset($Format["LineR"]) ? $Format["LineR"] : 150;
+ $LineG = isset($Format["LineG"]) ? $Format["LineG"] : 150;
+ $LineB = isset($Format["LineB"]) ? $Format["LineB"] : 150;
+ $LineAlpha = isset($Format["LineAlpha"]) ? $Format["LineAlpha"] : 50;
+ $LineTicks = isset($Format["LineTicks"]) ? $Format["LineTicks"] : 1;
+ $AreaR = isset($Format["AreaR"]) ? $Format["AreaR"] : 150;
+ $AreaG = isset($Format["AreaG"]) ? $Format["AreaG"] : 150;
+ $AreaB = isset($Format["AreaB"]) ? $Format["AreaB"] : 150;
+ $AreaAlpha = isset($Format["AreaAlpha"]) ? $Format["AreaAlpha"] : 5;
$this->LastChartLayout = CHART_LAST_LAYOUT_REGULAR;
- $Data = $this->DataSet->getData();
+ $Data = $this->DataSet->getData();
if ( !isset($Data["Series"][$SerieA]["Data"]) || !isset($Data["Series"][$SerieB]["Data"]) ) { return(0); }
$SerieAData = $Data["Series"][$SerieA]["Data"];
$SerieBData = $Data["Series"][$SerieB]["Data"];
list($XMargin,$XDivs) = $this->scaleGetXSettings();
- $Mode = $Data["Axis"][$AxisID]["Display"];
- $Format = $Data["Axis"][$AxisID]["Format"];
- $Unit = $Data["Axis"][$AxisID]["Unit"];
+ $Mode = $Data["Axis"][$AxisID]["Display"];
+ $Format = $Data["Axis"][$AxisID]["Format"];
+ $Unit = $Data["Axis"][$AxisID]["Unit"];
$PosArrayA = $this->scaleComputeY($SerieAData,array("AxisID"=>$AxisID));
$PosArrayB = $this->scaleComputeY($SerieBData,array("AxisID"=>$AxisID));
@@ -3913,19 +3913,19 @@
/* Draw a step chart */
function drawStepChart($Format=NULL)
{
- $BreakVoid = isset($Format["BreakVoid"]) ? $Format["BreakVoid"] : FALSE;
- $ReCenter = isset($Format["ReCenter"]) ? $Format["ReCenter"] : TRUE;
- $VoidTicks = isset($Format["VoidTicks"]) ? $Format["VoidTicks"] : 4;
- $BreakR = isset($Format["BreakR"]) ? $Format["BreakR"] : NULL;
- $BreakG = isset($Format["BreakG"]) ? $Format["BreakG"] : NULL;
- $BreakB = isset($Format["BreakB"]) ? $Format["BreakB"] : NULL;
- $DisplayValues = isset($Format["DisplayValues"]) ? $Format["DisplayValues"] :FALSE;
- $DisplayOffset = isset($Format["DisplayOffset"]) ? $Format["DisplayOffset"] : 2;
- $DisplayColor = isset($Format["DisplayColor"]) ? $Format["DisplayColor"] : DISPLAY_MANUAL;
- $DisplayR = isset($Format["DisplayR"]) ? $Format["DisplayR"] : 0;
- $DisplayG = isset($Format["DisplayG"]) ? $Format["DisplayG"] : 0;
- $DisplayB = isset($Format["DisplayB"]) ? $Format["DisplayB"] : 0;
- $RecordImageMap = isset($Format["RecordImageMap"]) ? $Format["RecordImageMap"] : FALSE;
+ $BreakVoid = isset($Format["BreakVoid"]) ? $Format["BreakVoid"] : FALSE;
+ $ReCenter = isset($Format["ReCenter"]) ? $Format["ReCenter"] : TRUE;
+ $VoidTicks = isset($Format["VoidTicks"]) ? $Format["VoidTicks"] : 4;
+ $BreakR = isset($Format["BreakR"]) ? $Format["BreakR"] : NULL;
+ $BreakG = isset($Format["BreakG"]) ? $Format["BreakG"] : NULL;
+ $BreakB = isset($Format["BreakB"]) ? $Format["BreakB"] : NULL;
+ $DisplayValues = isset($Format["DisplayValues"]) ? $Format["DisplayValues"] :FALSE;
+ $DisplayOffset = isset($Format["DisplayOffset"]) ? $Format["DisplayOffset"] : 2;
+ $DisplayColor = isset($Format["DisplayColor"]) ? $Format["DisplayColor"] : DISPLAY_MANUAL;
+ $DisplayR = isset($Format["DisplayR"]) ? $Format["DisplayR"] : 0;
+ $DisplayG = isset($Format["DisplayG"]) ? $Format["DisplayG"] : 0;
+ $DisplayB = isset($Format["DisplayB"]) ? $Format["DisplayB"] : 0;
+ $RecordImageMap = isset($Format["RecordImageMap"]) ? $Format["RecordImageMap"] : FALSE;
$ImageMapPlotSize = isset($Format["ImageMapPlotSize"]) ? $Format["ImageMapPlotSize"] : 5;
$this->LastChartLayout = CHART_LAST_LAYOUT_REGULAR;
@@ -3947,11 +3947,11 @@
if ( $DisplayColor == DISPLAY_AUTO ) { $DisplayR = $R; $DisplayG = $G; $DisplayB = $B; }
- $AxisID = $Serie["Axis"];
- $Mode = $Data["Axis"][$AxisID]["Display"];
- $Format = $Data["Axis"][$AxisID]["Format"];
- $Unit = $Data["Axis"][$AxisID]["Unit"];
- $Color = array("R"=>$R,"G"=>$G,"B"=>$B,"Alpha"=>$Alpha,"Ticks"=>$Ticks,"Weight"=>$Weight);
+ $AxisID = $Serie["Axis"];
+ $Mode = $Data["Axis"][$AxisID]["Display"];
+ $Format = $Data["Axis"][$AxisID]["Format"];
+ $Unit = $Data["Axis"][$AxisID]["Unit"];
+ $Color = array("R"=>$R,"G"=>$G,"B"=>$B,"Alpha"=>$Alpha,"Ticks"=>$Ticks,"Weight"=>$Weight);
$PosArray = $this->scaleComputeY($Serie["Data"],array("AxisID"=>$Serie["Axis"]));
@@ -4082,15 +4082,15 @@
/* Draw a step chart */
function drawFilledStepChart($Format=NULL)
{
- $ReCenter = isset($Format["ReCenter"]) ? $Format["ReCenter"] : TRUE;
- $DisplayValues = isset($Format["DisplayValues"]) ? $Format["DisplayValues"] :FALSE;
- $DisplayOffset = isset($Format["DisplayOffset"]) ? $Format["DisplayOffset"] : 2;
- $DisplayColor = isset($Format["DisplayColor"]) ? $Format["DisplayColor"] : DISPLAY_MANUAL;
- $ForceTransparency = isset($Format["ForceTransparency"]) ? $Format["ForceTransparency"] : NULL;
- $DisplayR = isset($Format["DisplayR"]) ? $Format["DisplayR"] : 0;
- $DisplayG = isset($Format["DisplayG"]) ? $Format["DisplayG"] : 0;
- $DisplayB = isset($Format["DisplayB"]) ? $Format["DisplayB"] : 0;
- $AroundZero = isset($Format["AroundZero"]) ? $Format["AroundZero"] : TRUE;
+ $ReCenter = isset($Format["ReCenter"]) ? $Format["ReCenter"] : TRUE;
+ $DisplayValues = isset($Format["DisplayValues"]) ? $Format["DisplayValues"] :FALSE;
+ $DisplayOffset = isset($Format["DisplayOffset"]) ? $Format["DisplayOffset"] : 2;
+ $DisplayColor = isset($Format["DisplayColor"]) ? $Format["DisplayColor"] : DISPLAY_MANUAL;
+ $ForceTransparency = isset($Format["ForceTransparency"]) ? $Format["ForceTransparency"] : NULL;
+ $DisplayR = isset($Format["DisplayR"]) ? $Format["DisplayR"] : 0;
+ $DisplayG = isset($Format["DisplayG"]) ? $Format["DisplayG"] : 0;
+ $DisplayB = isset($Format["DisplayB"]) ? $Format["DisplayB"] : 0;
+ $AroundZero = isset($Format["AroundZero"]) ? $Format["AroundZero"] : TRUE;
$this->LastChartLayout = CHART_LAST_LAYOUT_REGULAR;
@@ -4104,12 +4104,12 @@
if ( $DisplayColor == DISPLAY_AUTO ) { $DisplayR = $R; $DisplayG = $G; $DisplayB = $B; }
- $AxisID = $Serie["Axis"];
- $Mode = $Data["Axis"][$AxisID]["Display"];
- $Format = $Data["Axis"][$AxisID]["Format"];
- $Unit = $Data["Axis"][$AxisID]["Unit"];
+ $AxisID = $Serie["Axis"];
+ $Mode = $Data["Axis"][$AxisID]["Display"];
+ $Format = $Data["Axis"][$AxisID]["Format"];
+ $Unit = $Data["Axis"][$AxisID]["Unit"];
- $Color = array("R"=>$R,"G"=>$G,"B"=>$B);
+ $Color = array("R"=>$R,"G"=>$G,"B"=>$B);
if ( $ForceTransparency != NULL ) { $Color["Alpha"] = $ForceTransparency; } else { $Color["Alpha"] = $Alpha; }
$PosArray = $this->scaleComputeY($Serie["Data"],array("AxisID"=>$Serie["Axis"]));
@@ -4222,15 +4222,15 @@
/* Draw an area chart */
function drawAreaChart($Format=NULL)
{
- $DisplayValues = isset($Format["DisplayValues"]) ? $Format["DisplayValues"] : FALSE;
- $DisplayOffset = isset($Format["DisplayOffset"]) ? $Format["DisplayOffset"] : 2;
- $DisplayColor = isset($Format["DisplayColor"]) ? $Format["DisplayColor"] : DISPLAY_MANUAL;
- $DisplayR = isset($Format["DisplayR"]) ? $Format["DisplayR"] : 0;
- $DisplayG = isset($Format["DisplayG"]) ? $Format["DisplayG"] : 0;
- $DisplayB = isset($Format["DisplayB"]) ? $Format["DisplayB"] : 0;
- $ForceTransparency = isset($Format["ForceTransparency"]) ? $Format["ForceTransparency"] : 25;
- $AroundZero = isset($Format["AroundZero"]) ? $Format["AroundZero"] : TRUE;
- $Threshold = isset($Format["Threshold"]) ? $Format["Threshold"] : NULL;
+ $DisplayValues = isset($Format["DisplayValues"]) ? $Format["DisplayValues"] : FALSE;
+ $DisplayOffset = isset($Format["DisplayOffset"]) ? $Format["DisplayOffset"] : 2;
+ $DisplayColor = isset($Format["DisplayColor"]) ? $Format["DisplayColor"] : DISPLAY_MANUAL;
+ $DisplayR = isset($Format["DisplayR"]) ? $Format["DisplayR"] : 0;
+ $DisplayG = isset($Format["DisplayG"]) ? $Format["DisplayG"] : 0;
+ $DisplayB = isset($Format["DisplayB"]) ? $Format["DisplayB"] : 0;
+ $ForceTransparency = isset($Format["ForceTransparency"]) ? $Format["ForceTransparency"] : 25;
+ $AroundZero = isset($Format["AroundZero"]) ? $Format["AroundZero"] : TRUE;
+ $Threshold = isset($Format["Threshold"]) ? $Format["Threshold"] : NULL;
$this->LastChartLayout = CHART_LAST_LAYOUT_REGULAR;
@@ -4244,10 +4244,10 @@
$R = $Serie["Color"]["R"]; $G = $Serie["Color"]["G"]; $B = $Serie["Color"]["B"]; $Alpha = $Serie["Color"]["Alpha"]; $Ticks = $Serie["Ticks"];
if ( $DisplayColor == DISPLAY_AUTO ) { $DisplayR = $R; $DisplayG = $G; $DisplayB = $B; }
- $AxisID = $Serie["Axis"];
- $Mode = $Data["Axis"][$AxisID]["Display"];
- $Format = $Data["Axis"][$AxisID]["Format"];
- $Unit = $Data["Axis"][$AxisID]["Unit"];
+ $AxisID = $Serie["Axis"];
+ $Mode = $Data["Axis"][$AxisID]["Display"];
+ $Format = $Data["Axis"][$AxisID]["Format"];
+ $Unit = $Data["Axis"][$AxisID]["Unit"];
$PosArray = $this->scaleComputeY($Serie["Data"],array("AxisID"=>$Serie["Axis"]));
$YZero = $this->scaleComputeY(0,array("AxisID"=>$Serie["Axis"]));
@@ -4421,45 +4421,45 @@
/* Draw a bar chart */
function drawBarChart($Format=NULL)
{
- $Floating0Serie = isset($Format["Floating0Serie"]) ? $Format["Floating0Serie"] : NULL;
- $Floating0Value = isset($Format["Floating0Value"]) ? $Format["Floating0Value"] : NULL;
- $Draw0Line = isset($Format["Draw0Line"]) ? $Format["Draw0Line"] : FALSE;
- $DisplayValues = isset($Format["DisplayValues"]) ? $Format["DisplayValues"] : FALSE;
+ $Floating0Serie = isset($Format["Floating0Serie"]) ? $Format["Floating0Serie"] : NULL;
+ $Floating0Value = isset($Format["Floating0Value"]) ? $Format["Floating0Value"] : NULL;
+ $Draw0Line = isset($Format["Draw0Line"]) ? $Format["Draw0Line"] : FALSE;
+ $DisplayValues = isset($Format["DisplayValues"]) ? $Format["DisplayValues"] : FALSE;
$DisplayOrientation = isset($Format["DisplayOrientation"]) ? $Format["DisplayOrientation"] : ORIENTATION_HORIZONTAL;
- $DisplayOffset = isset($Format["DisplayOffset"]) ? $Format["DisplayOffset"] : 2;
- $DisplayColor = isset($Format["DisplayColor"]) ? $Format["DisplayColor"] : DISPLAY_MANUAL;
- $DisplayFont = isset($Format["DisplaySize"]) ? $Format["DisplaySize"] : $this->FontName;
- $DisplaySize = isset($Format["DisplaySize"]) ? $Format["DisplaySize"] : $this->FontSize;
- $DisplayPos = isset($Format["DisplayPos"]) ? $Format["DisplayPos"] : LABEL_POS_OUTSIDE;
- $DisplayShadow = isset($Format["DisplayShadow"]) ? $Format["DisplayShadow"] : TRUE;
- $DisplayR = isset($Format["DisplayR"]) ? $Format["DisplayR"] : 0;
- $DisplayG = isset($Format["DisplayG"]) ? $Format["DisplayG"] : 0;
- $DisplayB = isset($Format["DisplayB"]) ? $Format["DisplayB"] : 0;
- $AroundZero = isset($Format["AroundZero"]) ? $Format["AroundZero"] : TRUE;
- $Interleave = isset($Format["Interleave"]) ? $Format["Interleave"] : .5;
- $Rounded = isset($Format["Rounded"]) ? $Format["Rounded"] : FALSE;
- $RoundRadius = isset($Format["RoundRadius"]) ? $Format["RoundRadius"] : 4;
- $Surrounding = isset($Format["Surrounding"]) ? $Format["Surrounding"] : NULL;
- $BorderR = isset($Format["BorderR"]) ? $Format["BorderR"] : -1;
- $BorderG = isset($Format["BorderG"]) ? $Format["BorderG"] : -1;
- $BorderB = isset($Format["BorderB"]) ? $Format["BorderB"] : -1;
- $Gradient = isset($Format["Gradient"]) ? $Format["Gradient"] : FALSE;
- $GradientMode = isset($Format["GradientMode"]) ? $Format["GradientMode"] : GRADIENT_SIMPLE;
- $GradientAlpha = isset($Format["GradientAlpha"]) ? $Format["GradientAlpha"] : 20;
- $GradientStartR = isset($Format["GradientStartR"]) ? $Format["GradientStartR"] : 255;
- $GradientStartG = isset($Format["GradientStartG"]) ? $Format["GradientStartG"] : 255;
- $GradientStartB = isset($Format["GradientStartB"]) ? $Format["GradientStartB"] : 255;
- $GradientEndR = isset($Format["GradientEndR"]) ? $Format["GradientEndR"] : 0;
- $GradientEndG = isset($Format["GradientEndG"]) ? $Format["GradientEndG"] : 0;
- $GradientEndB = isset($Format["GradientEndB"]) ? $Format["GradientEndB"] : 0;
- $TxtMargin = isset($Format["TxtMargin"]) ? $Format["TxtMargin"] : 6;
- $OverrideColors = isset($Format["OverrideColors"]) ? $Format["OverrideColors"] : NULL;
+ $DisplayOffset = isset($Format["DisplayOffset"]) ? $Format["DisplayOffset"] : 2;
+ $DisplayColor = isset($Format["DisplayColor"]) ? $Format["DisplayColor"] : DISPLAY_MANUAL;
+ $DisplayFont = isset($Format["DisplaySize"]) ? $Format["DisplaySize"] : $this->FontName;
+ $DisplaySize = isset($Format["DisplaySize"]) ? $Format["DisplaySize"] : $this->FontSize;
+ $DisplayPos = isset($Format["DisplayPos"]) ? $Format["DisplayPos"] : LABEL_POS_OUTSIDE;
+ $DisplayShadow = isset($Format["DisplayShadow"]) ? $Format["DisplayShadow"] : TRUE;
+ $DisplayR = isset($Format["DisplayR"]) ? $Format["DisplayR"] : 0;
+ $DisplayG = isset($Format["DisplayG"]) ? $Format["DisplayG"] : 0;
+ $DisplayB = isset($Format["DisplayB"]) ? $Format["DisplayB"] : 0;
+ $AroundZero = isset($Format["AroundZero"]) ? $Format["AroundZero"] : TRUE;
+ $Interleave = isset($Format["Interleave"]) ? $Format["Interleave"] : .5;
+ $Rounded = isset($Format["Rounded"]) ? $Format["Rounded"] : FALSE;
+ $RoundRadius = isset($Format["RoundRadius"]) ? $Format["RoundRadius"] : 4;
+ $Surrounding = isset($Format["Surrounding"]) ? $Format["Surrounding"] : NULL;
+ $BorderR = isset($Format["BorderR"]) ? $Format["BorderR"] : -1;
+ $BorderG = isset($Format["BorderG"]) ? $Format["BorderG"] : -1;
+ $BorderB = isset($Format["BorderB"]) ? $Format["BorderB"] : -1;
+ $Gradient = isset($Format["Gradient"]) ? $Format["Gradient"] : FALSE;
+ $GradientMode = isset($Format["GradientMode"]) ? $Format["GradientMode"] : GRADIENT_SIMPLE;
+ $GradientAlpha = isset($Format["GradientAlpha"]) ? $Format["GradientAlpha"] : 20;
+ $GradientStartR = isset($Format["GradientStartR"]) ? $Format["GradientStartR"] : 255;
+ $GradientStartG = isset($Format["GradientStartG"]) ? $Format["GradientStartG"] : 255;
+ $GradientStartB = isset($Format["GradientStartB"]) ? $Format["GradientStartB"] : 255;
+ $GradientEndR = isset($Format["GradientEndR"]) ? $Format["GradientEndR"] : 0;
+ $GradientEndG = isset($Format["GradientEndG"]) ? $Format["GradientEndG"] : 0;
+ $GradientEndB = isset($Format["GradientEndB"]) ? $Format["GradientEndB"] : 0;
+ $TxtMargin = isset($Format["TxtMargin"]) ? $Format["TxtMargin"] : 6;
+ $OverrideColors = isset($Format["OverrideColors"]) ? $Format["OverrideColors"] : NULL;
$OverrideSurrounding = isset($Format["OverrideSurrounding"]) ? $Format["OverrideSurrounding"] : 30;
- $InnerSurrounding = isset($Format["InnerSurrounding"]) ? $Format["InnerSurrounding"] : NULL;
- $InnerBorderR = isset($Format["InnerBorderR"]) ? $Format["InnerBorderR"] : -1;
- $InnerBorderG = isset($Format["InnerBorderG"]) ? $Format["InnerBorderG"] : -1;
- $InnerBorderB = isset($Format["InnerBorderB"]) ? $Format["InnerBorderB"] : -1;
- $RecordImageMap = isset($Format["RecordImageMap"]) ? $Format["RecordImageMap"] : FALSE;
+ $InnerSurrounding = isset($Format["InnerSurrounding"]) ? $Format["InnerSurrounding"] : NULL;
+ $InnerBorderR = isset($Format["InnerBorderR"]) ? $Format["InnerBorderR"] : -1;
+ $InnerBorderG = isset($Format["InnerBorderG"]) ? $Format["InnerBorderG"] : -1;
+ $InnerBorderB = isset($Format["InnerBorderB"]) ? $Format["InnerBorderB"] : -1;
+ $RecordImageMap = isset($Format["RecordImageMap"]) ? $Format["RecordImageMap"] : FALSE;
$this->LastChartLayout = CHART_LAST_LAYOUT_REGULAR;
@@ -4487,10 +4487,10 @@
if ( $InnerBorderR == -1 ) { $InnerColor = NULL; } else { $InnerColor = array("R"=>$InnerBorderR,"G"=>$InnerBorderG,"B"=>$InnerBorderB); }
$Color = array("R"=>$R,"G"=>$G,"B"=>$B,"Alpha"=>$Alpha,"BorderR"=>$BorderR,"BorderG"=>$BorderG,"BorderB"=>$BorderB);
- $AxisID = $Serie["Axis"];
- $Mode = $Data["Axis"][$AxisID]["Display"];
- $Format = $Data["Axis"][$AxisID]["Format"];
- $Unit = $Data["Axis"][$AxisID]["Unit"];
+ $AxisID = $Serie["Axis"];
+ $Mode = $Data["Axis"][$AxisID]["Display"];
+ $Format = $Data["Axis"][$AxisID]["Format"];
+ $Unit = $Data["Axis"][$AxisID]["Unit"];
if (isset($Serie["Description"])) { $SerieDescription = $Serie["Description"]; } else { $SerieDescription = $SerieName; }
@@ -4763,37 +4763,37 @@
/* Draw a bar chart */
function drawStackedBarChart($Format=NULL)
{
- $DisplayValues = isset($Format["DisplayValues"]) ? $Format["DisplayValues"] : FALSE;
+ $DisplayValues = isset($Format["DisplayValues"]) ? $Format["DisplayValues"] : FALSE;
$DisplayOrientation = isset($Format["DisplayOrientation"]) ? $Format["DisplayOrientation"] : ORIENTATION_AUTO;
$DisplayRound = isset($Format["DisplayRound"]) ? $Format["DisplayRound"] : 0;
- $DisplayColor = isset($Format["DisplayColor"]) ? $Format["DisplayColor"] : DISPLAY_MANUAL;
- $DisplayFont = isset($Format["DisplayFont"]) ? $Format["DisplayFont"] : $this->FontName;
- $DisplaySize = isset($Format["DisplaySize"]) ? $Format["DisplaySize"] : $this->FontSize;
- $DisplayR = isset($Format["DisplayR"]) ? $Format["DisplayR"] : 0;
- $DisplayG = isset($Format["DisplayG"]) ? $Format["DisplayG"] : 0;
- $DisplayB = isset($Format["DisplayB"]) ? $Format["DisplayB"] : 0;
- $Interleave = isset($Format["Interleave"]) ? $Format["Interleave"] : .5;
- $Rounded = isset($Format["Rounded"]) ? $Format["Rounded"] : FALSE;
- $RoundRadius = isset($Format["RoundRadius"]) ? $Format["RoundRadius"] : 4;
- $Surrounding = isset($Format["Surrounding"]) ? $Format["Surrounding"] : NULL;
- $BorderR = isset($Format["BorderR"]) ? $Format["BorderR"] : -1;
- $BorderG = isset($Format["BorderG"]) ? $Format["BorderG"] : -1;
- $BorderB = isset($Format["BorderB"]) ? $Format["BorderB"] : -1;
- $Gradient = isset($Format["Gradient"]) ? $Format["Gradient"] : FALSE;
- $GradientMode = isset($Format["GradientMode"]) ? $Format["GradientMode"] : GRADIENT_SIMPLE;
- $GradientAlpha = isset($Format["GradientAlpha"]) ? $Format["GradientAlpha"] : 20;
- $GradientStartR = isset($Format["GradientStartR"]) ? $Format["GradientStartR"] : 255;
- $GradientStartG = isset($Format["GradientStartG"]) ? $Format["GradientStartG"] : 255;
- $GradientStartB = isset($Format["GradientStartB"]) ? $Format["GradientStartB"] : 255;
- $GradientEndR = isset($Format["GradientEndR"]) ? $Format["GradientEndR"] : 0;
- $GradientEndG = isset($Format["GradientEndG"]) ? $Format["GradientEndG"] : 0;
- $GradientEndB = isset($Format["GradientEndB"]) ? $Format["GradientEndB"] : 0;
- $InnerSurrounding = isset($Format["InnerSurrounding"]) ? $Format["InnerSurrounding"] : NULL;
- $InnerBorderR = isset($Format["InnerBorderR"]) ? $Format["InnerBorderR"] : -1;
- $InnerBorderG = isset($Format["InnerBorderG"]) ? $Format["InnerBorderG"] : -1;
- $InnerBorderB = isset($Format["InnerBorderB"]) ? $Format["InnerBorderB"] : -1;
- $RecordImageMap = isset($Format["RecordImageMap"]) ? $Format["RecordImageMap"] : FALSE;
- $FontFactor = isset($Format["FontFactor"]) ? $Format["FontFactor"] : 8;
+ $DisplayColor = isset($Format["DisplayColor"]) ? $Format["DisplayColor"] : DISPLAY_MANUAL;
+ $DisplayFont = isset($Format["DisplayFont"]) ? $Format["DisplayFont"] : $this->FontName;
+ $DisplaySize = isset($Format["DisplaySize"]) ? $Format["DisplaySize"] : $this->FontSize;
+ $DisplayR = isset($Format["DisplayR"]) ? $Format["DisplayR"] : 0;
+ $DisplayG = isset($Format["DisplayG"]) ? $Format["DisplayG"] : 0;
+ $DisplayB = isset($Format["DisplayB"]) ? $Format["DisplayB"] : 0;
+ $Interleave = isset($Format["Interleave"]) ? $Format["Interleave"] : .5;
+ $Rounded = isset($Format["Rounded"]) ? $Format["Rounded"] : FALSE;
+ $RoundRadius = isset($Format["RoundRadius"]) ? $Format["RoundRadius"] : 4;
+ $Surrounding = isset($Format["Surrounding"]) ? $Format["Surrounding"] : NULL;
+ $BorderR = isset($Format["BorderR"]) ? $Format["BorderR"] : -1;
+ $BorderG = isset($Format["BorderG"]) ? $Format["BorderG"] : -1;
+ $BorderB = isset($Format["BorderB"]) ? $Format["BorderB"] : -1;
+ $Gradient = isset($Format["Gradient"]) ? $Format["Gradient"] : FALSE;
+ $GradientMode = isset($Format["GradientMode"]) ? $Format["GradientMode"] : GRADIENT_SIMPLE;
+ $GradientAlpha = isset($Format["GradientAlpha"]) ? $Format["GradientAlpha"] : 20;
+ $GradientStartR = isset($Format["GradientStartR"]) ? $Format["GradientStartR"] : 255;
+ $GradientStartG = isset($Format["GradientStartG"]) ? $Format["GradientStartG"] : 255;
+ $GradientStartB = isset($Format["GradientStartB"]) ? $Format["GradientStartB"] : 255;
+ $GradientEndR = isset($Format["GradientEndR"]) ? $Format["GradientEndR"] : 0;
+ $GradientEndG = isset($Format["GradientEndG"]) ? $Format["GradientEndG"] : 0;
+ $GradientEndB = isset($Format["GradientEndB"]) ? $Format["GradientEndB"] : 0;
+ $InnerSurrounding = isset($Format["InnerSurrounding"]) ? $Format["InnerSurrounding"] : NULL;
+ $InnerBorderR = isset($Format["InnerBorderR"]) ? $Format["InnerBorderR"] : -1;
+ $InnerBorderG = isset($Format["InnerBorderG"]) ? $Format["InnerBorderG"] : -1;
+ $InnerBorderB = isset($Format["InnerBorderB"]) ? $Format["InnerBorderB"] : -1;
+ $RecordImageMap = isset($Format["RecordImageMap"]) ? $Format["RecordImageMap"] : FALSE;
+ $FontFactor = isset($Format["FontFactor"]) ? $Format["FontFactor"] : 8;
$this->LastChartLayout = CHART_LAST_LAYOUT_STACKED;
@@ -4813,10 +4813,10 @@
if ( $InnerSurrounding != NULL ) { $InnerBorderR = $R+$InnerSurrounding; $InnerBorderG = $G+$InnerSurrounding; $InnerBorderB = $B+$InnerSurrounding; }
if ( $InnerBorderR == -1 ) { $InnerColor = NULL; } else { $InnerColor = array("R"=>$InnerBorderR,"G"=>$InnerBorderG,"B"=>$InnerBorderB); }
- $AxisID = $Serie["Axis"];
- $Mode = $Data["Axis"][$AxisID]["Display"];
- $Format = $Data["Axis"][$AxisID]["Format"];
- $Unit = $Data["Axis"][$AxisID]["Unit"];
+ $AxisID = $Serie["Axis"];
+ $Mode = $Data["Axis"][$AxisID]["Display"];
+ $Format = $Data["Axis"][$AxisID]["Format"];
+ $Unit = $Data["Axis"][$AxisID]["Unit"];
if (isset($Serie["Description"])) { $SerieDescription = $Serie["Description"]; } else { $SerieDescription = $SerieName; }
@@ -5023,21 +5023,21 @@
/* Draw a stacked area chart */
function drawStackedAreaChart($Format=NULL)
{
- $DrawLine = isset($Format["DrawLine"]) ? $Format["DrawLine"] : FALSE;
- $LineSurrounding = isset($Format["LineSurrounding"]) ? $Format["LineSurrounding"] : NULL;
- $LineR = isset($Format["LineR"]) ? $Format["LineR"] : VOID;
- $LineG = isset($Format["LineG"]) ? $Format["LineG"] : VOID;
- $LineB = isset($Format["LineB"]) ? $Format["LineB"] : VOID;
- $LineAlpha = isset($Format["LineAlpha"]) ? $Format["LineAlpha"] : 100;
- $DrawPlot = isset($Format["DrawPlot"]) ? $Format["DrawPlot"] : FALSE;
- $PlotRadius = isset($Format["PlotRadius"]) ? $Format["PlotRadius"] : 2;
- $PlotBorder = isset($Format["PlotBorder"]) ? $Format["PlotBorder"] : 1;
+ $DrawLine = isset($Format["DrawLine"]) ? $Format["DrawLine"] : FALSE;
+ $LineSurrounding = isset($Format["LineSurrounding"]) ? $Format["LineSurrounding"] : NULL;
+ $LineR = isset($Format["LineR"]) ? $Format["LineR"] : VOID;
+ $LineG = isset($Format["LineG"]) ? $Format["LineG"] : VOID;
+ $LineB = isset($Format["LineB"]) ? $Format["LineB"] : VOID;
+ $LineAlpha = isset($Format["LineAlpha"]) ? $Format["LineAlpha"] : 100;
+ $DrawPlot = isset($Format["DrawPlot"]) ? $Format["DrawPlot"] : FALSE;
+ $PlotRadius = isset($Format["PlotRadius"]) ? $Format["PlotRadius"] : 2;
+ $PlotBorder = isset($Format["PlotBorder"]) ? $Format["PlotBorder"] : 1;
$PlotBorderSurrounding = isset($Format["PlotBorderSurrounding"]) ? $Format["PlotBorderSurrounding"] : NULL;
- $PlotBorderR = isset($Format["PlotBorderR"]) ? $Format["PlotBorderR"] : 0;
- $PlotBorderG = isset($Format["PlotBorderG"]) ? $Format["PlotBorderG"] : 0;
- $PlotBorderB = isset($Format["PlotBorderB"]) ? $Format["PlotBorderB"] : 0;
- $PlotBorderAlpha = isset($Format["PlotBorderAlpha"]) ? $Format["PlotBorderAlpha"] : 50;
- $ForceTransparency = isset($Format["ForceTransparency"]) ? $Format["ForceTransparency"] : NULL;
+ $PlotBorderR = isset($Format["PlotBorderR"]) ? $Format["PlotBorderR"] : 0;
+ $PlotBorderG = isset($Format["PlotBorderG"]) ? $Format["PlotBorderG"] : 0;
+ $PlotBorderB = isset($Format["PlotBorderB"]) ? $Format["PlotBorderB"] : 0;
+ $PlotBorderAlpha = isset($Format["PlotBorderAlpha"]) ? $Format["PlotBorderAlpha"] : 50;
+ $ForceTransparency = isset($Format["ForceTransparency"]) ? $Format["ForceTransparency"] : NULL;
$this->LastChartLayout = CHART_LAST_LAYOUT_STACKED;
@@ -5097,10 +5097,10 @@
else
$PlotBorderColor = array("R"=>$PlotBorderR,"G"=>$PlotBorderG,"B"=>$PlotBorderB,"Alpha"=>$PlotBorderAlpha);
- $AxisID = $Serie["Axis"];
- $Mode = $Data["Axis"][$AxisID]["Display"];
- $Format = $Data["Axis"][$AxisID]["Format"];
- $Unit = $Data["Axis"][$AxisID]["Unit"];
+ $AxisID = $Serie["Axis"];
+ $Mode = $Data["Axis"][$AxisID]["Display"];
+ $Format = $Data["Axis"][$AxisID]["Format"];
+ $Unit = $Data["Axis"][$AxisID]["Unit"];
$PosArray = $this->scaleComputeY($Serie["Data"],array("AxisID"=>$Serie["Axis"]),TRUE);
$YZero = $this->scaleComputeY(0,array("AxisID"=>$Serie["Axis"]));
@@ -5219,45 +5219,45 @@
/* Draw the derivative chart associated to the data series */
function drawDerivative($Format=NULL)
{
- $Offset = isset($Format["Offset"]) ? $Format["Offset"] : 10;
- $SerieSpacing = isset($Format["SerieSpacing"]) ? $Format["SerieSpacing"] : 3;
- $DerivativeHeight = isset($Format["DerivativeHeight"]) ? $Format["DerivativeHeight"] : 4;
- $ShadedSlopeBox = isset($Format["ShadedSlopeBox"]) ? $Format["ShadedSlopeBox"] : FALSE;
- $DrawBackground = isset($Format["DrawBackground"]) ? $Format["DrawBackground"] : TRUE;
- $BackgroundR = isset($Format["BackgroundR"]) ? $Format["BackgroundR"] : 255;
- $BackgroundG = isset($Format["BackgroundG"]) ? $Format["BackgroundG"] : 255;
- $BackgroundB = isset($Format["BackgroundB"]) ? $Format["BackgroundB"] : 255;
- $BackgroundAlpha = isset($Format["BackgroundAlpha"]) ? $Format["BackgroundAlpha"] : 20;
- $DrawBorder = isset($Format["DrawBorder"]) ? $Format["DrawBorder"] : TRUE;
- $BorderR = isset($Format["BorderR"]) ? $Format["BorderR"] : 0;
- $BorderG = isset($Format["BorderG"]) ? $Format["BorderG"] : 0;
- $BorderB = isset($Format["BorderB"]) ? $Format["BorderB"] : 0;
- $BorderAlpha = isset($Format["BorderAlpha"]) ? $Format["BorderAlpha"] : 100;
- $Caption = isset($Format["Caption"]) ? $Format["Caption"] : TRUE;
- $CaptionHeight = isset($Format["CaptionHeight"]) ? $Format["CaptionHeight"] : 10;
- $CaptionWidth = isset($Format["CaptionWidth"]) ? $Format["CaptionWidth"] : 20;
- $CaptionMargin = isset($Format["CaptionMargin"]) ? $Format["CaptionMargin"] : 4;
- $CaptionLine = isset($Format["CaptionLine"]) ? $Format["CaptionLine"] : FALSE;
- $CaptionBox = isset($Format["CaptionBox"]) ? $Format["CaptionBox"] : FALSE;
- $CaptionBorderR = isset($Format["CaptionBorderR"]) ? $Format["CaptionBorderR"] : 0;
- $CaptionBorderG = isset($Format["CaptionBorderG"]) ? $Format["CaptionBorderG"] : 0;
- $CaptionBorderB = isset($Format["CaptionBorderB"]) ? $Format["CaptionBorderB"] : 0;
- $CaptionFillR = isset($Format["CaptionFillR"]) ? $Format["CaptionFillR"] : 255;
- $CaptionFillG = isset($Format["CaptionFillG"]) ? $Format["CaptionFillG"] : 255;
- $CaptionFillB = isset($Format["CaptionFillB"]) ? $Format["CaptionFillB"] : 255;
- $CaptionFillAlpha = isset($Format["CaptionFillAlpha"]) ? $Format["CaptionFillAlpha"] : 80;
- $PositiveSlopeStartR = isset($Format["PositiveSlopeStartR"]) ? $Format["PositiveSlopeStartR"] : 184;
- $PositiveSlopeStartG = isset($Format["PositiveSlopeStartG"]) ? $Format["PositiveSlopeStartG"] : 234;
- $PositiveSlopeStartB = isset($Format["PositiveSlopeStartB"]) ? $Format["PositiveSlopeStartB"] : 88;
- $PositiveSlopeEndR = isset($Format["PositiveSlopeStartR"]) ? $Format["PositiveSlopeStartR"] : 239;
- $PositiveSlopeEndG = isset($Format["PositiveSlopeStartG"]) ? $Format["PositiveSlopeStartG"] : 31;
- $PositiveSlopeEndB = isset($Format["PositiveSlopeStartB"]) ? $Format["PositiveSlopeStartB"] : 36;
- $NegativeSlopeStartR = isset($Format["NegativeSlopeStartR"]) ? $Format["NegativeSlopeStartR"] : 184;
- $NegativeSlopeStartG = isset($Format["NegativeSlopeStartG"]) ? $Format["NegativeSlopeStartG"] : 234;
- $NegativeSlopeStartB = isset($Format["NegativeSlopeStartB"]) ? $Format["NegativeSlopeStartB"] : 88;
- $NegativeSlopeEndR = isset($Format["NegativeSlopeStartR"]) ? $Format["NegativeSlopeStartR"] : 67;
- $NegativeSlopeEndG = isset($Format["NegativeSlopeStartG"]) ? $Format["NegativeSlopeStartG"] : 124;
- $NegativeSlopeEndB = isset($Format["NegativeSlopeStartB"]) ? $Format["NegativeSlopeStartB"] : 227;
+ $Offset = isset($Format["Offset"]) ? $Format["Offset"] : 10;
+ $SerieSpacing = isset($Format["SerieSpacing"]) ? $Format["SerieSpacing"] : 3;
+ $DerivativeHeight = isset($Format["DerivativeHeight"]) ? $Format["DerivativeHeight"] : 4;
+ $ShadedSlopeBox = isset($Format["ShadedSlopeBox"]) ? $Format["ShadedSlopeBox"] : FALSE;
+ $DrawBackground = isset($Format["DrawBackground"]) ? $Format["DrawBackground"] : TRUE;
+ $BackgroundR = isset($Format["BackgroundR"]) ? $Format["BackgroundR"] : 255;
+ $BackgroundG = isset($Format["BackgroundG"]) ? $Format["BackgroundG"] : 255;
+ $BackgroundB = isset($Format["BackgroundB"]) ? $Format["BackgroundB"] : 255;
+ $BackgroundAlpha = isset($Format["BackgroundAlpha"]) ? $Format["BackgroundAlpha"] : 20;
+ $DrawBorder = isset($Format["DrawBorder"]) ? $Format["DrawBorder"] : TRUE;
+ $BorderR = isset($Format["BorderR"]) ? $Format["BorderR"] : 0;
+ $BorderG = isset($Format["BorderG"]) ? $Format["BorderG"] : 0;
+ $BorderB = isset($Format["BorderB"]) ? $Format["BorderB"] : 0;
+ $BorderAlpha = isset($Format["BorderAlpha"]) ? $Format["BorderAlpha"] : 100;
+ $Caption = isset($Format["Caption"]) ? $Format["Caption"] : TRUE;
+ $CaptionHeight = isset($Format["CaptionHeight"]) ? $Format["CaptionHeight"] : 10;
+ $CaptionWidth = isset($Format["CaptionWidth"]) ? $Format["CaptionWidth"] : 20;
+ $CaptionMargin = isset($Format["CaptionMargin"]) ? $Format["CaptionMargin"] : 4;
+ $CaptionLine = isset($Format["CaptionLine"]) ? $Format["CaptionLine"] : FALSE;
+ $CaptionBox = isset($Format["CaptionBox"]) ? $Format["CaptionBox"] : FALSE;
+ $CaptionBorderR = isset($Format["CaptionBorderR"]) ? $Format["CaptionBorderR"] : 0;
+ $CaptionBorderG = isset($Format["CaptionBorderG"]) ? $Format["CaptionBorderG"] : 0;
+ $CaptionBorderB = isset($Format["CaptionBorderB"]) ? $Format["CaptionBorderB"] : 0;
+ $CaptionFillR = isset($Format["CaptionFillR"]) ? $Format["CaptionFillR"] : 255;
+ $CaptionFillG = isset($Format["CaptionFillG"]) ? $Format["CaptionFillG"] : 255;
+ $CaptionFillB = isset($Format["CaptionFillB"]) ? $Format["CaptionFillB"] : 255;
+ $CaptionFillAlpha = isset($Format["CaptionFillAlpha"]) ? $Format["CaptionFillAlpha"] : 80;
+ $PositiveSlopeStartR = isset($Format["PositiveSlopeStartR"]) ? $Format["PositiveSlopeStartR"] : 184;
+ $PositiveSlopeStartG = isset($Format["PositiveSlopeStartG"]) ? $Format["PositiveSlopeStartG"] : 234;
+ $PositiveSlopeStartB = isset($Format["PositiveSlopeStartB"]) ? $Format["PositiveSlopeStartB"] : 88;
+ $PositiveSlopeEndR = isset($Format["PositiveSlopeStartR"]) ? $Format["PositiveSlopeStartR"] : 239;
+ $PositiveSlopeEndG = isset($Format["PositiveSlopeStartG"]) ? $Format["PositiveSlopeStartG"] : 31;
+ $PositiveSlopeEndB = isset($Format["PositiveSlopeStartB"]) ? $Format["PositiveSlopeStartB"] : 36;
+ $NegativeSlopeStartR = isset($Format["NegativeSlopeStartR"]) ? $Format["NegativeSlopeStartR"] : 184;
+ $NegativeSlopeStartG = isset($Format["NegativeSlopeStartG"]) ? $Format["NegativeSlopeStartG"] : 234;
+ $NegativeSlopeStartB = isset($Format["NegativeSlopeStartB"]) ? $Format["NegativeSlopeStartB"] : 88;
+ $NegativeSlopeEndR = isset($Format["NegativeSlopeStartR"]) ? $Format["NegativeSlopeStartR"] : 67;
+ $NegativeSlopeEndG = isset($Format["NegativeSlopeStartG"]) ? $Format["NegativeSlopeStartG"] : 124;
+ $NegativeSlopeEndB = isset($Format["NegativeSlopeStartB"]) ? $Format["NegativeSlopeStartB"] : 227;
$Data = $this->DataSet->getData();
@@ -5471,11 +5471,11 @@
/* Draw the line of best fit */
function drawBestFit($Format="")
{
- $OverrideTicks = isset($Format["Ticks"]) ? $Format["Ticks"] : NULL;
- $OverrideR = isset($Format["R"]) ? $Format["R"] : VOID;
- $OverrideG = isset($Format["G"]) ? $Format["G"] : VOID;
- $OverrideB = isset($Format["B"]) ? $Format["B"] : VOID;
- $OverrideAlpha = isset($Format["Alpha"]) ? $Format["Alpha"] : VOID;
+ $OverrideTicks = isset($Format["Ticks"]) ? $Format["Ticks"] : NULL;
+ $OverrideR = isset($Format["R"]) ? $Format["R"] : VOID;
+ $OverrideG = isset($Format["G"]) ? $Format["G"] : VOID;
+ $OverrideB = isset($Format["B"]) ? $Format["B"] : VOID;
+ $OverrideAlpha = isset($Format["Alpha"]) ? $Format["Alpha"] : VOID;
$Data = $this->DataSet->getData();
list($XMargin,$XDivs) = $this->scaleGetXSettings();
@@ -5570,15 +5570,15 @@
/* Write labels */
function writeLabel($SeriesName,$Indexes,$Format="")
{
- $OverrideTitle = isset($Format["OverrideTitle"]) ? $Format["OverrideTitle"] : NULL;
- $ForceLabels = isset($Format["ForceLabels"]) ? $Format["ForceLabels"] : NULL;
- $DrawPoint = isset($Format["DrawPoint"]) ? $Format["DrawPoint"] : LABEL_POINT_BOX;
- $DrawVerticalLine = isset($Format["DrawVerticalLine"]) ? $Format["DrawVerticalLine"] : FALSE;
- $VerticalLineR = isset($Format["VerticalLineR"]) ? $Format["VerticalLineR"] : 0;
- $VerticalLineG = isset($Format["VerticalLineG"]) ? $Format["VerticalLineG"] : 0;
- $VerticalLineB = isset($Format["VerticalLineB"]) ? $Format["VerticalLineB"] : 0;
- $VerticalLineAlpha = isset($Format["VerticalLineAlpha"]) ? $Format["VerticalLineAlpha"] : 40;
- $VerticalLineTicks = isset($Format["VerticalLineTicks"]) ? $Format["VerticalLineTicks"] : 2;
+ $OverrideTitle = isset($Format["OverrideTitle"]) ? $Format["OverrideTitle"] : NULL;
+ $ForceLabels = isset($Format["ForceLabels"]) ? $Format["ForceLabels"] : NULL;
+ $DrawPoint = isset($Format["DrawPoint"]) ? $Format["DrawPoint"] : LABEL_POINT_BOX;
+ $DrawVerticalLine = isset($Format["DrawVerticalLine"]) ? $Format["DrawVerticalLine"] : FALSE;
+ $VerticalLineR = isset($Format["VerticalLineR"]) ? $Format["VerticalLineR"] : 0;
+ $VerticalLineG = isset($Format["VerticalLineG"]) ? $Format["VerticalLineG"] : 0;
+ $VerticalLineB = isset($Format["VerticalLineB"]) ? $Format["VerticalLineB"] : 0;
+ $VerticalLineAlpha = isset($Format["VerticalLineAlpha"]) ? $Format["VerticalLineAlpha"] : 40;
+ $VerticalLineTicks = isset($Format["VerticalLineTicks"]) ? $Format["VerticalLineTicks"] : 2;
$Data = $this->DataSet->getData();
list($XMargin,$XDivs) = $this->scaleGetXSettings();
@@ -5783,39 +5783,39 @@
/* Draw a label box */
function drawLabelBox($X,$Y,$Title,$Captions,$Format="")
{
- $NoTitle = isset($Format["NoTitle"]) ? $Format["NoTitle"] : NULL;
- $BoxWidth = isset($Format["BoxWidth"]) ? $Format["BoxWidth"] : 50;
- $DrawSerieColor = isset($Format["DrawSerieColor"]) ? $Format["DrawSerieColor"] : TRUE;
- $SerieR = isset($Format["SerieR"]) ? $Format["SerieR"] : NULL;
- $SerieG = isset($Format["SerieG"]) ? $Format["SerieG"] : NULL;
- $SerieB = isset($Format["SerieB"]) ? $Format["SerieB"] : NULL;
- $SerieAlpha = isset($Format["SerieAlpha"]) ? $Format["SerieAlpha"] : NULL;
- $SerieBoxSize = isset($Format["SerieBoxSize"]) ? $Format["SerieBoxSize"] : 6;
- $SerieBoxSpacing = isset($Format["SerieBoxSpacing"]) ? $Format["SerieBoxSpacing"] : 4;
- $VerticalMargin = isset($Format["VerticalMargin"]) ? $Format["VerticalMargin"] : 10;
- $HorizontalMargin = isset($Format["HorizontalMargin"]) ? $Format["HorizontalMargin"] : 8;
- $R = isset($Format["R"]) ? $Format["R"] : $this->FontColorR;
- $G = isset($Format["G"]) ? $Format["G"] : $this->FontColorG;
- $B = isset($Format["B"]) ? $Format["B"] : $this->FontColorB;
- $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : $this->FontColorA;
- $FontName = isset($Format["FontName"]) ? $Format["FontName"] : $this->FontName;
- $FontSize = isset($Format["FontSize"]) ? $Format["FontSize"] : $this->FontSize;
- $TitleMode = isset($Format["TitleMode"]) ? $Format["TitleMode"] : LABEL_TITLE_NOBACKGROUND;
- $TitleR = isset($Format["TitleR"]) ? $Format["TitleR"] : $R;
- $TitleG = isset($Format["TitleG"]) ? $Format["TitleG"] : $G;
- $TitleB = isset($Format["TitleB"]) ? $Format["TitleB"] : $B;
- $TitleAlpha = isset($Format["TitleAlpha"]) ? $Format["TitleAlpha"] : 100;
- $TitleBackgroundR = isset($Format["TitleBackgroundR"]) ? $Format["TitleBackgroundR"] : 0;
- $TitleBackgroundG = isset($Format["TitleBackgroundG"]) ? $Format["TitleBackgroundG"] : 0;
- $TitleBackgroundB = isset($Format["TitleBackgroundB"]) ? $Format["TitleBackgroundB"] : 0;
- $TitleBackgroundAlpha = isset($Format["TitleBackgroundAlpha"]) ? $Format["TitleBackgroundAlpha"] : 100;
- $GradientStartR = isset($Format["GradientStartR"]) ? $Format["GradientStartR"] : 255;
- $GradientStartG = isset($Format["GradientStartG"]) ? $Format["GradientStartG"] : 255;
- $GradientStartB = isset($Format["GradientStartB"]) ? $Format["GradientStartB"] : 255;
- $GradientEndR = isset($Format["GradientEndR"]) ? $Format["GradientEndR"] : 220;
- $GradientEndG = isset($Format["GradientEndG"]) ? $Format["GradientEndG"] : 220;
- $GradientEndB = isset($Format["GradientEndB"]) ? $Format["GradientEndB"] : 220;
- $BoxAlpha = isset($Format["BoxAlpha"]) ? $Format["BoxAlpha"] : 100;
+ $NoTitle = isset($Format["NoTitle"]) ? $Format["NoTitle"] : NULL;
+ $BoxWidth = isset($Format["BoxWidth"]) ? $Format["BoxWidth"] : 50;
+ $DrawSerieColor = isset($Format["DrawSerieColor"]) ? $Format["DrawSerieColor"] : TRUE;
+ $SerieR = isset($Format["SerieR"]) ? $Format["SerieR"] : NULL;
+ $SerieG = isset($Format["SerieG"]) ? $Format["SerieG"] : NULL;
+ $SerieB = isset($Format["SerieB"]) ? $Format["SerieB"] : NULL;
+ $SerieAlpha = isset($Format["SerieAlpha"]) ? $Format["SerieAlpha"] : NULL;
+ $SerieBoxSize = isset($Format["SerieBoxSize"]) ? $Format["SerieBoxSize"] : 6;
+ $SerieBoxSpacing = isset($Format["SerieBoxSpacing"]) ? $Format["SerieBoxSpacing"] : 4;
+ $VerticalMargin = isset($Format["VerticalMargin"]) ? $Format["VerticalMargin"] : 10;
+ $HorizontalMargin = isset($Format["HorizontalMargin"]) ? $Format["HorizontalMargin"] : 8;
+ $R = isset($Format["R"]) ? $Format["R"] : $this->FontColorR;
+ $G = isset($Format["G"]) ? $Format["G"] : $this->FontColorG;
+ $B = isset($Format["B"]) ? $Format["B"] : $this->FontColorB;
+ $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : $this->FontColorA;
+ $FontName = isset($Format["FontName"]) ? $Format["FontName"] : $this->FontName;
+ $FontSize = isset($Format["FontSize"]) ? $Format["FontSize"] : $this->FontSize;
+ $TitleMode = isset($Format["TitleMode"]) ? $Format["TitleMode"] : LABEL_TITLE_NOBACKGROUND;
+ $TitleR = isset($Format["TitleR"]) ? $Format["TitleR"] : $R;
+ $TitleG = isset($Format["TitleG"]) ? $Format["TitleG"] : $G;
+ $TitleB = isset($Format["TitleB"]) ? $Format["TitleB"] : $B;
+ $TitleAlpha = isset($Format["TitleAlpha"]) ? $Format["TitleAlpha"] : 100;
+ $TitleBackgroundR = isset($Format["TitleBackgroundR"]) ? $Format["TitleBackgroundR"] : 0;
+ $TitleBackgroundG = isset($Format["TitleBackgroundG"]) ? $Format["TitleBackgroundG"] : 0;
+ $TitleBackgroundB = isset($Format["TitleBackgroundB"]) ? $Format["TitleBackgroundB"] : 0;
+ $TitleBackgroundAlpha = isset($Format["TitleBackgroundAlpha"]) ? $Format["TitleBackgroundAlpha"] : 100;
+ $GradientStartR = isset($Format["GradientStartR"]) ? $Format["GradientStartR"] : 255;
+ $GradientStartG = isset($Format["GradientStartG"]) ? $Format["GradientStartG"] : 255;
+ $GradientStartB = isset($Format["GradientStartB"]) ? $Format["GradientStartB"] : 255;
+ $GradientEndR = isset($Format["GradientEndR"]) ? $Format["GradientEndR"] : 220;
+ $GradientEndG = isset($Format["GradientEndG"]) ? $Format["GradientEndG"] : 220;
+ $GradientEndB = isset($Format["GradientEndB"]) ? $Format["GradientEndB"] : 220;
+ $BoxAlpha = isset($Format["BoxAlpha"]) ? $Format["BoxAlpha"] : 100;
if ( !$DrawSerieColor ) { $SerieBoxSize = 0; $SerieBoxSpacing = 0; }
@@ -6010,17 +6010,17 @@
function drawPolygonChart($Points,$Format="")
{
- $R = isset($Format["R"]) ? $Format["R"] : 0;
- $G = isset($Format["G"]) ? $Format["G"] : 0;
- $B = isset($Format["B"]) ? $Format["B"] : 0;
- $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 100;
- $NoFill = isset($Format["NoFill"]) ? $Format["NoFill"] : FALSE;
- $NoBorder = isset($Format["NoBorder"]) ? $Format["NoBorder"] : FALSE;
- $BorderR = isset($Format["BorderR"]) ? $Format["BorderR"] : $R;
- $BorderG = isset($Format["BorderG"]) ? $Format["BorderG"] : $G;
- $BorderB = isset($Format["BorderB"]) ? $Format["BorderB"] : $B;
- $BorderAlpha = isset($Format["BorderAlpha"]) ? $Format["BorderAlpha"] : $Alpha / 2;
- $Surrounding = isset($Format["Surrounding"]) ? $Format["Surrounding"] : NULL;
+ $R = isset($Format["R"]) ? $Format["R"] : 0;
+ $G = isset($Format["G"]) ? $Format["G"] : 0;
+ $B = isset($Format["B"]) ? $Format["B"] : 0;
+ $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 100;
+ $NoFill = isset($Format["NoFill"]) ? $Format["NoFill"] : FALSE;
+ $NoBorder = isset($Format["NoBorder"]) ? $Format["NoBorder"] : FALSE;
+ $BorderR = isset($Format["BorderR"]) ? $Format["BorderR"] : $R;
+ $BorderG = isset($Format["BorderG"]) ? $Format["BorderG"] : $G;
+ $BorderB = isset($Format["BorderB"]) ? $Format["BorderB"] : $B;
+ $BorderAlpha = isset($Format["BorderAlpha"]) ? $Format["BorderAlpha"] : $Alpha / 2;
+ $Surrounding = isset($Format["Surrounding"]) ? $Format["Surrounding"] : NULL;
$Threshold = isset($Format["Threshold"]) ? $Format["Threshold"] : NULL;
if ( $Surrounding != NULL ) { $BorderR = $R+$Surrounding; $BorderG = $G+$Surrounding; $BorderB = $B+$Surrounding; }
diff --git a/system/library/games/graph/pImage.php b/system/library/games/graph/pImage.php
index 99b6cae..cb9a3cc 100644
--- a/system/library/games/graph/pImage.php
+++ b/system/library/games/graph/pImage.php
@@ -1,6 +1,6 @@
Shadow = $Enabled;
@@ -188,8 +188,8 @@
$RealPos[2]["X"] = cos((270-$Angle)*PI/180)*$Height + $RealPos[1]["X"]; $RealPos[2]["Y"] = sin((270-$Angle)*PI/180)*$Height + $RealPos[1]["Y"];
$RealPos[3]["X"] = cos((180-$Angle)*PI/180)*$Width + $RealPos[2]["X"]; $RealPos[3]["Y"] = sin((180-$Angle)*PI/180)*$Width + $RealPos[2]["Y"];
- $RealPos[TEXT_ALIGN_BOTTOMLEFT]["X"] = $RealPos[0]["X"]; $RealPos[TEXT_ALIGN_BOTTOMLEFT]["Y"] = $RealPos[0]["Y"];
- $RealPos[TEXT_ALIGN_BOTTOMRIGHT]["X"] = $RealPos[1]["X"]; $RealPos[TEXT_ALIGN_BOTTOMRIGHT]["Y"] = $RealPos[1]["Y"];
+ $RealPos[TEXT_ALIGN_BOTTOMLEFT]["X"] = $RealPos[0]["X"]; $RealPos[TEXT_ALIGN_BOTTOMLEFT]["Y"] = $RealPos[0]["Y"];
+ $RealPos[TEXT_ALIGN_BOTTOMRIGHT]["X"] = $RealPos[1]["X"]; $RealPos[TEXT_ALIGN_BOTTOMRIGHT]["Y"] = $RealPos[1]["Y"];
return($RealPos);
}
@@ -206,15 +206,15 @@
$RealPos[$i/2]["Y"] = $Y + round($coords[$i+1] * $ca - $coords[$i] * $sa);
}
- $RealPos[TEXT_ALIGN_BOTTOMLEFT]["X"] = $RealPos[0]["X"]; $RealPos[TEXT_ALIGN_BOTTOMLEFT]["Y"] = $RealPos[0]["Y"];
- $RealPos[TEXT_ALIGN_BOTTOMRIGHT]["X"] = $RealPos[1]["X"]; $RealPos[TEXT_ALIGN_BOTTOMRIGHT]["Y"] = $RealPos[1]["Y"];
- $RealPos[TEXT_ALIGN_TOPLEFT]["X"] = $RealPos[3]["X"]; $RealPos[TEXT_ALIGN_TOPLEFT]["Y"] = $RealPos[3]["Y"];
- $RealPos[TEXT_ALIGN_TOPRIGHT]["X"] = $RealPos[2]["X"]; $RealPos[TEXT_ALIGN_TOPRIGHT]["Y"] = $RealPos[2]["Y"];
- $RealPos[TEXT_ALIGN_BOTTOMMIDDLE]["X"] = ($RealPos[1]["X"]-$RealPos[0]["X"])/2+$RealPos[0]["X"]; $RealPos[TEXT_ALIGN_BOTTOMMIDDLE]["Y"] = ($RealPos[0]["Y"]-$RealPos[1]["Y"])/2+$RealPos[1]["Y"];
- $RealPos[TEXT_ALIGN_TOPMIDDLE]["X"] = ($RealPos[2]["X"]-$RealPos[3]["X"])/2+$RealPos[3]["X"]; $RealPos[TEXT_ALIGN_TOPMIDDLE]["Y"] = ($RealPos[3]["Y"]-$RealPos[2]["Y"])/2+$RealPos[2]["Y"];
- $RealPos[TEXT_ALIGN_MIDDLELEFT]["X"] = ($RealPos[0]["X"]-$RealPos[3]["X"])/2+$RealPos[3]["X"]; $RealPos[TEXT_ALIGN_MIDDLELEFT]["Y"] = ($RealPos[0]["Y"]-$RealPos[3]["Y"])/2+$RealPos[3]["Y"];
- $RealPos[TEXT_ALIGN_MIDDLERIGHT]["X"] = ($RealPos[1]["X"]-$RealPos[2]["X"])/2+$RealPos[2]["X"]; $RealPos[TEXT_ALIGN_MIDDLERIGHT]["Y"] = ($RealPos[1]["Y"]-$RealPos[2]["Y"])/2+$RealPos[2]["Y"];
- $RealPos[TEXT_ALIGN_MIDDLEMIDDLE]["X"] = ($RealPos[1]["X"]-$RealPos[3]["X"])/2+$RealPos[3]["X"]; $RealPos[TEXT_ALIGN_MIDDLEMIDDLE]["Y"] = ($RealPos[0]["Y"]-$RealPos[2]["Y"])/2+$RealPos[2]["Y"];
+ $RealPos[TEXT_ALIGN_BOTTOMLEFT]["X"] = $RealPos[0]["X"]; $RealPos[TEXT_ALIGN_BOTTOMLEFT]["Y"] = $RealPos[0]["Y"];
+ $RealPos[TEXT_ALIGN_BOTTOMRIGHT]["X"] = $RealPos[1]["X"]; $RealPos[TEXT_ALIGN_BOTTOMRIGHT]["Y"] = $RealPos[1]["Y"];
+ $RealPos[TEXT_ALIGN_TOPLEFT]["X"] = $RealPos[3]["X"]; $RealPos[TEXT_ALIGN_TOPLEFT]["Y"] = $RealPos[3]["Y"];
+ $RealPos[TEXT_ALIGN_TOPRIGHT]["X"] = $RealPos[2]["X"]; $RealPos[TEXT_ALIGN_TOPRIGHT]["Y"] = $RealPos[2]["Y"];
+ $RealPos[TEXT_ALIGN_BOTTOMMIDDLE]["X"] = ($RealPos[1]["X"]-$RealPos[0]["X"])/2+$RealPos[0]["X"]; $RealPos[TEXT_ALIGN_BOTTOMMIDDLE]["Y"] = ($RealPos[0]["Y"]-$RealPos[1]["Y"])/2+$RealPos[1]["Y"];
+ $RealPos[TEXT_ALIGN_TOPMIDDLE]["X"] = ($RealPos[2]["X"]-$RealPos[3]["X"])/2+$RealPos[3]["X"]; $RealPos[TEXT_ALIGN_TOPMIDDLE]["Y"] = ($RealPos[3]["Y"]-$RealPos[2]["Y"])/2+$RealPos[2]["Y"];
+ $RealPos[TEXT_ALIGN_MIDDLELEFT]["X"] = ($RealPos[0]["X"]-$RealPos[3]["X"])/2+$RealPos[3]["X"]; $RealPos[TEXT_ALIGN_MIDDLELEFT]["Y"] = ($RealPos[0]["Y"]-$RealPos[3]["Y"])/2+$RealPos[3]["Y"];
+ $RealPos[TEXT_ALIGN_MIDDLERIGHT]["X"] = ($RealPos[1]["X"]-$RealPos[2]["X"])/2+$RealPos[2]["X"]; $RealPos[TEXT_ALIGN_MIDDLERIGHT]["Y"] = ($RealPos[1]["Y"]-$RealPos[2]["Y"])/2+$RealPos[2]["Y"];
+ $RealPos[TEXT_ALIGN_MIDDLEMIDDLE]["X"] = ($RealPos[1]["X"]-$RealPos[3]["X"])/2+$RealPos[3]["X"]; $RealPos[TEXT_ALIGN_MIDDLEMIDDLE]["Y"] = ($RealPos[0]["Y"]-$RealPos[2]["Y"])/2+$RealPos[2]["Y"];
return($RealPos);
}
@@ -222,12 +222,12 @@
/* Set current font properties */
function setFontProperties($Format="")
{
- $R = isset($Format["R"]) ? $Format["R"] : -1;
- $G = isset($Format["G"]) ? $Format["G"] : -1;
- $B = isset($Format["B"]) ? $Format["B"] : -1;
- $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 100;
- $FontName = isset($Format["FontName"]) ? $Format["FontName"] : NULL;
- $FontSize = isset($Format["FontSize"]) ? $Format["FontSize"] : NULL;
+ $R = isset($Format["R"]) ? $Format["R"] : -1;
+ $G = isset($Format["G"]) ? $Format["G"] : -1;
+ $B = isset($Format["B"]) ? $Format["B"] : -1;
+ $Alpha = isset($Format["Alpha"]) ? $Format["Alpha"] : 100;
+ $FontName = isset($Format["FontName"]) ? $Format["FontName"] : NULL;
+ $FontSize = isset($Format["FontSize"]) ? $Format["FontSize"] : NULL;
if ( $R != -1) { $this->FontColorR = $R; }
if ( $G != -1) { $this->FontColorG = $G; }
@@ -259,8 +259,8 @@
/* Initialise the image map methods */
function initialiseImageMap($Name="pChart",$StorageMode=IMAGE_MAP_STORAGE_SESSION,$UniqueID="imageMap",$StorageFolder="tmp")
{
- $this->ImageMapIndex = $Name;
- $this->ImageMapStorageMode = $StorageMode;
+ $this->ImageMapIndex = $Name;
+ $this->ImageMapStorageMode = $StorageMode;
if ($StorageMode == IMAGE_MAP_STORAGE_SESSION)
{
@@ -269,8 +269,8 @@
}
elseif($StorageMode == IMAGE_MAP_STORAGE_FILE)
{
- $this->ImageMapFileName = $UniqueID;
- $this->ImageMapStorageFolder = $StorageFolder;
+ $this->ImageMapFileName = $UniqueID;
+ $this->ImageMapStorageFolder = $StorageFolder;
if (file_exists($StorageFolder."/".$UniqueID.".map")) { unlink($StorageFolder."/".$UniqueID.".map"); }
}
@@ -394,8 +394,8 @@
/* Dump the image map */
function dumpImageMap($Name="pChart",$StorageMode=IMAGE_MAP_STORAGE_SESSION,$UniqueID="imageMap",$StorageFolder="tmp")
{
- $this->ImageMapIndex = $Name;
- $this->ImageMapStorageMode = $StorageMode;
+ $this->ImageMapIndex = $Name;
+ $this->ImageMapStorageMode = $StorageMode;
if ( $this->ImageMapStorageMode == IMAGE_MAP_STORAGE_SESSION )
{
@@ -442,8 +442,8 @@
/* Mirror Effect */
function drawAreaMirror($X,$Y,$Width,$Height,$Format="")
{
- $StartAlpha = isset($Format["StartAlpha"]) ? $Format["StartAlpha"] : 80;
- $EndAlpha = isset($Format["EndAlpha"]) ? $Format["EndAlpha"] : 0;
+ $StartAlpha = isset($Format["StartAlpha"]) ? $Format["StartAlpha"] : 80;
+ $EndAlpha = isset($Format["EndAlpha"]) ? $Format["EndAlpha"] : 0;
$AlphaStep = ($StartAlpha-$EndAlpha)/$Height;
diff --git a/system/library/games/mc/action.php b/system/library/games/mc/action.php
index 003c3ac..cf24a8e 100644
--- a/system/library/games/mc/action.php
+++ b/system/library/games/mc/action.php
@@ -1,110 +1,110 @@
query('SELECT `uid`, `unit`, `tarif`, `game`, `address`, `slots_start`, `name`, `ram`, `time_start` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `uid`, `unit`, `tarif`, `game`, `address`, `slots_start`, `name`, `ram`, `time_start` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
+ $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
$tarif = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return array('e' => sys::text('error', 'ssh'));
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return array('e' => sys::text('error', 'ssh'));
- list($ip, $port) = explode(':', $server['address']);
+ list($ip, $port) = explode(':', $server['address']);
- // Убить процессы
- $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
- .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe;');
+ // Убить процессы
+ $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
+ .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe;');
- // Временный файл
- $temp = sys::temp(action::config($ip, $port, $server['slots_start'], $ssh->get('cat '.$tarif['install'].'/'.$server['uid'].'/server.properties')));
+ // Временный файл
+ $temp = sys::temp(action::config($ip, $port, $server['slots_start'], $ssh->get('cat '.$tarif['install'].'/'.$server['uid'].'/server.properties')));
- // Обновление файла server.cfg
- $ssh->setfile($temp, $tarif['install'].$server['uid'].'/server.properties', 0644);
+ // Обновление файла server.cfg
+ $ssh->setfile($temp, $tarif['install'].$server['uid'].'/server.properties', 0644);
- unlink($temp);
+ unlink($temp);
- // Параметры запуска
- $bash = 'java -Xmx'.$server['ram'].'M -Xms'.$server['ram'].'M -jar start.jar nogui';
+ // Параметры запуска
+ $bash = 'java -Xmx'.$server['ram'].'M -Xms'.$server['ram'].'M -jar start.jar nogui';
- // Временный файл
- $temp = sys::temp($bash);
+ // Временный файл
+ $temp = sys::temp($bash);
- // Обновление файла start.sh
- $ssh->setfile($temp, $tarif['install'].$server['uid'].'/start.sh', 0500);
+ // Обновление файла start.sh
+ $ssh->setfile($temp, $tarif['install'].$server['uid'].'/start.sh', 0500);
- // Строка запуска
- $ssh->set('cd '.$tarif['install'].$server['uid'].';' // переход в директорию игрового сервера
- .'sudo -u server'.$server['uid'].' mkdir -p oldstart;' // Создание папки логов
- .'cat console.log >> oldstart/'.date('d.m.Y_H:i:s', $server['time_start']).'.log; rm console.log; rm oldstart/01.01.1970_03:00:00.log;' // Перемещение лога предыдущего запуска
- .'chown server'.$server['uid'].':1000 server.properties start.sh;' // Обновление владельца файлов
- .'sudo -u server'.$server['uid'].' screen -dmS s_'.$server['uid'].' '.$taskset.' sh -c "./start.sh > console.log"'); // Запуск игровго сервера
+ // Строка запуска
+ $ssh->set('cd '.$tarif['install'].$server['uid'].';' // переход в директорию игрового сервера
+ .'sudo -u server'.$server['uid'].' mkdir -p oldstart;' // Создание папки логов
+ .'cat console.log >> oldstart/'.date('d.m.Y_H:i:s', $server['time_start']).'.log; rm console.log; rm oldstart/01.01.1970_03:00:00.log;' // Перемещение лога предыдущего запуска
+ .'chown server'.$server['uid'].':1000 server.properties start.sh;' // Обновление владельца файлов
+ .'sudo -u server'.$server['uid'].' screen -dmS s_'.$server['uid'].' '.$taskset.' sh -c "./start.sh > console.log"'); // Запуск игровго сервера
- // Обновление информации в базе
- $sql->query('UPDATE `servers` set `status`="'.$type.'", `online`="0", `players`="", `time_start`="'.$start_point.'", `stop`="1" WHERE `id`="'.$id.'" LIMIT 1');
+ // Обновление информации в базе
+ $sql->query('UPDATE `servers` set `status`="'.$type.'", `online`="0", `players`="", `time_start`="'.$start_point.'", `stop`="1" WHERE `id`="'.$id.'" LIMIT 1');
- unlink($temp);
+ unlink($temp);
- // Сброс кеша
- actions::clmcache($id);
+ // Сброс кеша
+ actions::clmcache($id);
- sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0, 'players' => ''));
- sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0));
+ sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0, 'players' => ''));
+ sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0));
- return array('s' => 'ok');
- }
+ return array('s' => 'ok');
+ }
- public static function config($ip, $port, $slots, $config)
- {
- $aLine = explode("\n", $config);
+ public static function config($ip, $port, $slots, $config)
+ {
+ $aLine = explode("\n", $config);
- $search = array(
- "#^server-ip=(.*?)$#is",
- "#^server-port=(.*?)$#is",
- "#^rcon\.port=(.*?)$#is",
- "#^query\.port=(.*?)$#is",
- "#^max-players=(.*?)$#is",
- "#^enable-query=(.*?)$#is",
- "#^debug=(.*?)$#is"
- );
+ $search = array(
+ "#^server-ip=(.*?)$#is",
+ "#^server-port=(.*?)$#is",
+ "#^rcon\.port=(.*?)$#is",
+ "#^query\.port=(.*?)$#is",
+ "#^max-players=(.*?)$#is",
+ "#^enable-query=(.*?)$#is",
+ "#^debug=(.*?)$#is"
+ );
- $config = '';
+ $config = '';
- foreach($aLine as $line)
- {
- if(str_replace(array(' ', "\t"), '', $line) != '')
- $edit = trim(preg_replace($search, array('','','','','','',''), $line));
+ foreach($aLine as $line)
+ {
+ if(str_replace(array(' ', "\t"), '', $line) != '')
+ $edit = trim(preg_replace($search, array('','','','','','',''), $line));
- if($edit != '')
- $config .= $edit.PHP_EOL;
+ if($edit != '')
+ $config .= $edit.PHP_EOL;
- $edit = '';
- }
+ $edit = '';
+ }
- $config .= 'server-ip='.$ip.PHP_EOL
- .'server-port='.$port.PHP_EOL
- .'rcon.port='.($port+10000).PHP_EOL
- .'query.port='.($port).PHP_EOL
- .'max-players='.$slots.PHP_EOL
- .'enable-query=true'.PHP_EOL
- .'debug=false';
+ $config .= 'server-ip='.$ip.PHP_EOL
+ .'server-port='.$port.PHP_EOL
+ .'rcon.port='.($port+10000).PHP_EOL
+ .'query.port='.($port).PHP_EOL
+ .'max-players='.$slots.PHP_EOL
+ .'enable-query=true'.PHP_EOL
+ .'debug=false';
- return $config;
- }
+ return $config;
+ }
}
?>
\ No newline at end of file
diff --git a/system/library/games/mc/scan.php b/system/library/games/mc/scan.php
index ed18502..48829a2 100644
--- a/system/library/games/mc/scan.php
+++ b/system/library/games/mc/scan.php
@@ -1,113 +1,113 @@
query('SELECT `address`, `game`, `name`, `map`, `online`, `players`, `status`, `time`, `overdue` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `address`, `game`, `name`, `map`, `online`, `players`, `status`, `time`, `overdue` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- list($ip, $port) = explode(':', $server['address']);
+ list($ip, $port) = explode(':', $server['address']);
- include(LIB.'games/query/McQuery.php');
+ include(LIB.'games/query/McQuery.php');
- $sq = new McQuery($ip, $port);
+ $sq = new McQuery($ip, $port);
- if($players_get)
- $nmch = 'server_scan_mon_pl_'.$id;
- else
- $nmch = 'server_scan_mon_'.$id;
+ if($players_get)
+ $nmch = 'server_scan_mon_pl_'.$id;
+ else
+ $nmch = 'server_scan_mon_'.$id;
- if(is_array($mcache->get($nmch)))
- return $mcache->get($nmch);
+ if(is_array($mcache->get($nmch)))
+ return $mcache->get($nmch);
- $out = array();
+ $out = array();
- $out['time'] = 'Арендован до: '.date('d.m.Y - H:i', $server['time']);
+ $out['time'] = 'Арендован до: '.date('d.m.Y - H:i', $server['time']);
- if($server['status'] == 'overdue')
- $out['time_end'] = 'Удаление через: '.sys::date('min', $server['overdue']+$cfg['server_delete']*86400);
- else
- $out['time_end'] = 'Осталось: '.sys::date('min', $server['time']);
+ if($server['status'] == 'overdue')
+ $out['time_end'] = 'Удаление через: '.sys::date('min', $server['overdue']+$cfg['server_delete']*86400);
+ else
+ $out['time_end'] = 'Осталось: '.sys::date('min', $server['time']);
- $info = $sq->getInfo($players_get);
+ $info = $sq->getInfo($players_get);
- if(!is_array($info))
- {
- $out['name'] = $server['name'];
- $out['status'] = sys::status($server['status'], $server['game'], $server['map']);
- $out['online'] = $server['online'];
- $out['image'] = ' ';
- $out['buttons'] = sys::buttons($id, $server['status'], $server['game']);
+ if(!is_array($info))
+ {
+ $out['name'] = $server['name'];
+ $out['status'] = sys::status($server['status'], $server['game'], $server['map']);
+ $out['online'] = $server['online'];
+ $out['image'] = ' ';
+ $out['buttons'] = sys::buttons($id, $server['status'], $server['game']);
- if($players_get)
- $out['players'] = base64_decode($server['players']);
+ if($players_get)
+ $out['players'] = base64_decode($server['players']);
- $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
+ $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
- return $out;
- }
+ return $out;
+ }
- $players = scan::players($info['players_list']);
+ $players = scan::players($info['players_list']);
- $info['map'] = htmlspecialchars(mb_convert_encoding($info['map'], 'UTF-8', 'WINDOWS-1251'));
- $out['name'] = htmlspecialchars(mb_convert_encoding($info['hostname'], 'UTF-8', 'WINDOWS-1251'));
- $out['status'] = sys::status('working', $server['game'], $info['map']);
- $out['online'] = sys::int($info['online']);
- $out['image'] = ' ';
- $out['buttons'] = sys::buttons($id, 'working', $server['game']);
- $out['players'] = '';
+ $info['map'] = htmlspecialchars(mb_convert_encoding($info['map'], 'UTF-8', 'WINDOWS-1251'));
+ $out['name'] = htmlspecialchars(mb_convert_encoding($info['hostname'], 'UTF-8', 'WINDOWS-1251'));
+ $out['status'] = sys::status('working', $server['game'], $info['map']);
+ $out['online'] = sys::int($info['online']);
+ $out['image'] = ' ';
+ $out['buttons'] = sys::buttons($id, 'working', $server['game']);
+ $out['players'] = '';
- if($players_get)
- {
- foreach($players as $index => $player)
- {
- $html->get($server['game'], 'sections/servers/players');
+ if($players_get)
+ {
+ foreach($players as $index => $player)
+ {
+ $html->get($server['game'], 'sections/servers/players');
- $html->set('i', $player['i']);
- $html->set('name', $player['name']);
- $html->set('ping', $player['ping']);
+ $html->set('i', $player['i']);
+ $html->set('name', $player['name']);
+ $html->set('ping', $player['ping']);
- $html->pack('list');
- }
+ $html->pack('list');
+ }
- $out['players'] = isset($html->arr['list']) ? $html->arr['list'] : '';
- }
+ $out['players'] = isset($html->arr['list']) ? $html->arr['list'] : '';
+ }
- $sql->query('UPDATE `servers` set '
- .'`name`="'.$out['name'].'", '
- .'`online`="'.$out['online'].'", '
- .'`map`="'.$info['map'].'", '
- .'`status`="working" WHERE `id`="'.$id.'" LIMIT 1');
+ $sql->query('UPDATE `servers` set '
+ .'`name`="'.$out['name'].'", '
+ .'`online`="'.$out['online'].'", '
+ .'`map`="'.$info['map'].'", '
+ .'`status`="working" WHERE `id`="'.$id.'" LIMIT 1');
- if($players_get)
- $sql->query('UPDATE `servers` set `players`="'.base64_encode($out['players']).'" WHERE `id`="'.$id.'" LIMIT 1');
+ if($players_get)
+ $sql->query('UPDATE `servers` set `players`="'.base64_encode($out['players']).'" WHERE `id`="'.$id.'" LIMIT 1');
- $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
+ $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
- return $out;
- }
+ return $out;
+ }
- public static function players($aPlayrs)
- {
- $i = 1;
- $aData = array();
+ public static function players($aPlayrs)
+ {
+ $i = 1;
+ $aData = array();
- foreach($aPlayrs as $n => $player)
- {
- $aData[$i]['i'] = $i;
- $aData[$i]['name'] = $player['nickname'] == '' ? 'Подключается' : htmlspecialchars($player['nickname']);
+ foreach($aPlayrs as $n => $player)
+ {
+ $aData[$i]['i'] = $i;
+ $aData[$i]['name'] = $player['nickname'] == '' ? 'Подключается' : htmlspecialchars($player['nickname']);
- $i+=1;
- }
+ $i+=1;
+ }
- return $aData;
- }
- }
+ return $aData;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/games/mc/service.php b/system/library/games/mc/service.php
index 38745a8..97337dd 100644
--- a/system/library/games/mc/service.php
+++ b/system/library/games/mc/service.php
@@ -1,369 +1,369 @@
query('SELECT `address`, `test` FROM `units` WHERE `id`="'.$aData['unit'].'" AND `mc`="1" AND `show`="1" LIMIT 1');
- if(!$sql->num())
- sys::outjs(array('e' => 'Локация не найдена.'));
+ // Проверка локации
+ $sql->query('SELECT `address`, `test` FROM `units` WHERE `id`="'.$aData['unit'].'" AND `mc`="1" AND `show`="1" LIMIT 1');
+ if(!$sql->num())
+ sys::outjs(array('e' => 'Локация не найдена.'));
- $unit = $sql->get();
+ $unit = $sql->get();
- // Проверка тарифа
- $sql->query('SELECT `id` FROM `tarifs` WHERE `id`="'.$aData['tarif'].'" AND `unit`="'.$aData['unit'].'" AND `show`="1" LIMIT 1');
- if(!$sql->num())
- sys::outjs(array('e' => 'Тариф не найден.'));
+ // Проверка тарифа
+ $sql->query('SELECT `id` FROM `tarifs` WHERE `id`="'.$aData['tarif'].'" AND `unit`="'.$aData['unit'].'" AND `show`="1" LIMIT 1');
+ if(!$sql->num())
+ sys::outjs(array('e' => 'Тариф не найден.'));
- $sql->query('SELECT '
- .'`slots_min`,'
- .'`slots_max`,'
- .'`port_min`,'
- .'`port_max`,'
- .'`hostname`,'
- .'`packs`,'
- .'`ram`,'
- .'`param_fix`,'
- .'`time`,'
- .'`test`,'
- .'`tests`,'
- .'`discount`,'
- .'`map`,'
- .'`ftp`,'
- .'`plugins`,'
- .'`console`,'
- .'`stats`,'
- .'`copy`,'
- .'`web`,'
- .'`plugins_install`,'
- .'`hdd`,'
- .'`autostop`,'
- .'`core_fix`,'
- .'`ip`,'
- .'`price`'
- .' FROM `tarifs` WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
+ $sql->query('SELECT '
+ .'`slots_min`,'
+ .'`slots_max`,'
+ .'`port_min`,'
+ .'`port_max`,'
+ .'`hostname`,'
+ .'`packs`,'
+ .'`ram`,'
+ .'`param_fix`,'
+ .'`time`,'
+ .'`test`,'
+ .'`tests`,'
+ .'`discount`,'
+ .'`map`,'
+ .'`ftp`,'
+ .'`plugins`,'
+ .'`console`,'
+ .'`stats`,'
+ .'`copy`,'
+ .'`web`,'
+ .'`plugins_install`,'
+ .'`hdd`,'
+ .'`autostop`,'
+ .'`core_fix`,'
+ .'`ip`,'
+ .'`price`'
+ .' FROM `tarifs` WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
- $tarif = $sql->get();
+ $tarif = $sql->get();
- // Проверка сборки
- if(!array_key_exists($aData['pack'], sys::b64djs($tarif['packs'], true)))
- sys::outjs(array('e' => 'Сборка не найдена.'));
+ // Проверка сборки
+ if(!array_key_exists($aData['pack'], sys::b64djs($tarif['packs'], true)))
+ sys::outjs(array('e' => 'Сборка не найдена.'));
- // Проверка RAM
- if(!in_array($aData['ram'], explode(':', $tarif['ram'])))
- sys::outjs(array('e' => 'Переданные данные ram неверны.'));
+ // Проверка RAM
+ if(!in_array($aData['ram'], explode(':', $tarif['ram'])))
+ sys::outjs(array('e' => 'Переданные данные ram неверны.'));
- $test = 0;
+ $test = 0;
- // Проверка периода на тест
- if($aData['test'])
- {
- if(!$tarif['test'] || !$unit['test'])
- sys::outjs(array('e' => 'Тестовый период недоступен.'));
+ // Проверка периода на тест
+ if($aData['test'])
+ {
+ if(!$tarif['test'] || !$unit['test'])
+ sys::outjs(array('e' => 'Тестовый период недоступен.'));
- // Проверка на повторный запрос
- $sql->query('SELECT `id`, `game` FROM `tests` WHERE `user`="'.$user['id'].'" LIMIT 1');
- if($sql->num())
- {
- $test_info = $sql->get();
+ // Проверка на повторный запрос
+ $sql->query('SELECT `id`, `game` FROM `tests` WHERE `user`="'.$user['id'].'" LIMIT 1');
+ if($sql->num())
+ {
+ $test_info = $sql->get();
- if(!$cfg['tests']['game'] || $test_info['game'] == 'mc')
- sys::outjs(array('e' => 'Тестовый период предоставляется один раз.'));
+ if(!$cfg['tests']['game'] || $test_info['game'] == 'mc')
+ sys::outjs(array('e' => 'Тестовый период предоставляется один раз.'));
- $sql->query('SELECT `id` FROM `servers` WHERE `user`="'.$user['id'].'" AND `test`="1" LIMIT 1');
- if($sql->num() AND !$cfg['tests']['sametime'])
- sys::outjs(array('e' => 'Чтобы получить тестовый период другой игры, дождитесь окончания текущего.'));
- }
+ $sql->query('SELECT `id` FROM `servers` WHERE `user`="'.$user['id'].'" AND `test`="1" LIMIT 1');
+ if($sql->num() AND !$cfg['tests']['sametime'])
+ sys::outjs(array('e' => 'Чтобы получить тестовый период другой игры, дождитесь окончания текущего.'));
+ }
- // Проверка наличия мест на локации
- $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `test`="1" AND `time`>"'.$start_point.'" LIMIT '.$unit['test']);
- if($sql->num() == $unit['test'])
- sys::outjs(array('e' => 'Свободного места для тестового периода нет.'));
+ // Проверка наличия мест на локации
+ $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `test`="1" AND `time`>"'.$start_point.'" LIMIT '.$unit['test']);
+ if($sql->num() == $unit['test'])
+ sys::outjs(array('e' => 'Свободного места для тестового периода нет.'));
- // Проверка наличия мест для выбранного тарифа
- $sql->query('SELECT `id` FROM `servers` WHERE `tarif`="'.$aData['tarif'].'" AND `test`="1" AND `time`>"'.$start_point.'" LIMIT '.$tarif['tests']);
- if($sql->num() == $tarif['tests'])
- sys::outjs(array('e' => 'Свободного места для тестового периода выбранного тарифа нет.'));
+ // Проверка наличия мест для выбранного тарифа
+ $sql->query('SELECT `id` FROM `servers` WHERE `tarif`="'.$aData['tarif'].'" AND `test`="1" AND `time`>"'.$start_point.'" LIMIT '.$tarif['tests']);
+ if($sql->num() == $tarif['tests'])
+ sys::outjs(array('e' => 'Свободного места для тестового периода выбранного тарифа нет.'));
- $test = 1;
- }else
- // Проверка периода
- if(!$cfg['settlement_period'] AND !in_array($aData['time'], explode(':', $tarif['time'])))
- sys::outjs(array('e' => 'Переданные данные периода неверны.'));
+ $test = 1;
+ }else
+ // Проверка периода
+ if(!$cfg['settlement_period'] AND !in_array($aData['time'], explode(':', $tarif['time'])))
+ sys::outjs(array('e' => 'Переданные данные периода неверны.'));
- // Проверка слот
- if($aData['slots'] < $tarif['slots_min'] || $aData['slots'] > $tarif['slots_max'])
- sys::outjs(array('e' => 'Переданные данные слот неверны.'));
+ // Проверка слот
+ if($aData['slots'] < $tarif['slots_min'] || $aData['slots'] > $tarif['slots_max'])
+ sys::outjs(array('e' => 'Переданные данные слот неверны.'));
- // Определение цены
- $aPrice = explode(':', $tarif['price']);
- $price = $aPrice[array_search($aData['ram'], explode(':', $tarif['ram']))];
+ // Определение цены
+ $aPrice = explode(':', $tarif['price']);
+ $price = $aPrice[array_search($aData['ram'], explode(':', $tarif['ram']))];
- // Определение суммы
- if($cfg['settlement_period'])
- {
- // Цена аренды за расчетный период
- $sum = games::define_sum($tarif['discount'], $price, $aData['slots'], $start_point);
+ // Определение суммы
+ if($cfg['settlement_period'])
+ {
+ // Цена аренды за расчетный период
+ $sum = games::define_sum($tarif['discount'], $price, $aData['slots'], $start_point);
- $aData['time'] = games::define_period('buy', params::$aDayMonth);
- }else
- $sum = games::define_sum($tarif['discount'], $price, $aData['slots'], $aData['time']);
+ $aData['time'] = games::define_period('buy', params::$aDayMonth);
+ }else
+ $sum = games::define_sum($tarif['discount'], $price, $aData['slots'], $aData['time']);
- // Проверка промо-кода
- $promo = games::define_promo(
- $aData['promo'],
- array(
- 'tarif' => $aData['tarif'],
- 'ram' => $aData['ram'],
- 'slots' => $aData['slots'],
- 'time' => $aData['time'],
- 'user' => $user['id']
- ),
- $tarif['discount'],
- $sum
- );
+ // Проверка промо-кода
+ $promo = games::define_promo(
+ $aData['promo'],
+ array(
+ 'tarif' => $aData['tarif'],
+ 'ram' => $aData['ram'],
+ 'slots' => $aData['slots'],
+ 'time' => $aData['time'],
+ 'user' => $user['id']
+ ),
+ $tarif['discount'],
+ $sum
+ );
- $days = $aData['time']; // Кол-во дней аренды
+ $days = $aData['time']; // Кол-во дней аренды
- // Использование промо-кода
- if(is_array($promo))
- {
- if(array_key_exists('sum', $promo))
- $sum = $promo['sum'];
- else
- $days += $promo['days']; // Кол-во дней аренды с учетом подарочных (промо-код)
- }
+ // Использование промо-кода
+ if(is_array($promo))
+ {
+ if(array_key_exists('sum', $promo))
+ $sum = $promo['sum'];
+ else
+ $days += $promo['days']; // Кол-во дней аренды с учетом подарочных (промо-код)
+ }
- // Проверка баланса
- if($user['balance'] < $sum)
- sys::outjs(array('e' => 'У вас не хватает '.(round($sum-$user['balance'], 2)).' '.$cfg['currency']));
+ // Проверка баланса
+ if($user['balance'] < $sum)
+ sys::outjs(array('e' => 'У вас не хватает '.(round($sum-$user['balance'], 2)).' '.$cfg['currency']));
- // Выделенный адрес игрового сервера
- if(!empty($tarif['ip']))
- {
- $aIp = explode(':', $tarif['ip']);
+ // Выделенный адрес игрового сервера
+ if(!empty($tarif['ip']))
+ {
+ $aIp = explode(':', $tarif['ip']);
- $ip = false;
- $port = params::$aDefPort['mc'];
+ $ip = false;
+ $port = params::$aDefPort['mc'];
- // Проверка наличия свободного адреса
- foreach($aIp as $adr)
- {
- $adr = trim($adr);
+ // Проверка наличия свободного адреса
+ foreach($aIp as $adr)
+ {
+ $adr = trim($adr);
- $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `address` LIKE "'.$adr.':%" LIMIT 1');
- if(!$sql->num())
- {
- $ip = $adr;
+ $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `address` LIKE "'.$adr.':%" LIMIT 1');
+ if(!$sql->num())
+ {
+ $ip = $adr;
- break;
- }
- }
- }else{
- $ip = sys::first(explode(':', $unit['address']));
- $port = false;
+ break;
+ }
+ }
+ }else{
+ $ip = sys::first(explode(':', $unit['address']));
+ $port = false;
- // Проверка наличия свободного порта
- for($tarif['port_min']; $tarif['port_min'] <= $tarif['port_max']; $tarif['port_min']+=1)
- {
- $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND (`address`="'.$ip.':'.$tarif['port_min'].'" OR `port`="'.$tarif['port_min'].'") LIMIT 1');
- if(!$sql->num())
- {
- $port = $tarif['port_min'];
+ // Проверка наличия свободного порта
+ for($tarif['port_min']; $tarif['port_min'] <= $tarif['port_max']; $tarif['port_min']+=1)
+ {
+ $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND (`address`="'.$ip.':'.$tarif['port_min'].'" OR `port`="'.$tarif['port_min'].'") LIMIT 1');
+ if(!$sql->num())
+ {
+ $port = $tarif['port_min'];
- break;
- }
- }
- }
+ break;
+ }
+ }
+ }
- if(!$ip || !$port)
- {
- $sql->query('UPDATE `tarifs` set `show`="0" WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
+ if(!$ip || !$port)
+ {
+ $sql->query('UPDATE `tarifs` set `show`="0" WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
- sys::outjs(array('e' => 'К сожалению нет доступных мест, обратитесь в тех.поддержку.'));
- }
+ sys::outjs(array('e' => 'К сожалению нет доступных мест, обратитесь в тех.поддержку.'));
+ }
- if($test)
- $aData['time'] = games::time($start_point, $tarif['test']);
- else
- $aData['time'] = games::time($start_point, $days);
+ if($test)
+ $aData['time'] = games::time($start_point, $tarif['test']);
+ else
+ $aData['time'] = games::time($start_point, $days);
- $fix_one = 0;
- $core = 0;
+ $fix_one = 0;
+ $core = 0;
- if($tarif['core_fix'] != '')
- {
- $aCore = explode(',', $tarif['core_fix']);
+ if($tarif['core_fix'] != '')
+ {
+ $aCore = explode(',', $tarif['core_fix']);
- foreach($aCore as $cpu)
- {
- $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `tarif`="'.$aData['tarif'].'" AND `core_fix`="'.$cpu.'" AND `core_fix_one`="1" LIMIT 1');
+ foreach($aCore as $cpu)
+ {
+ $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `tarif`="'.$aData['tarif'].'" AND `core_fix`="'.$cpu.'" AND `core_fix_one`="1" LIMIT 1');
- if($sql->num())
- continue;
+ if($sql->num())
+ continue;
- $fix_one = 1;
- $core = $cpu;
+ $fix_one = 1;
+ $core = $cpu;
- break;
- }
+ break;
+ }
- if(!$core)
- {
- $sql->query('UPDATE `tarifs` set `show`="0" WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
+ if(!$core)
+ {
+ $sql->query('UPDATE `tarifs` set `show`="0" WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
- sys::outjs(array('e' => 'К сожалению нет доступных мест, обратитесь в тех.поддержку.'));
- }
- }
+ sys::outjs(array('e' => 'К сожалению нет доступных мест, обратитесь в тех.поддержку.'));
+ }
+ }
- $ram = $tarif['param_fix'] ? $aData['ram'] : $aData['ram']*$aData['slots'];
+ $ram = $tarif['param_fix'] ? $aData['ram'] : $aData['ram']*$aData['slots'];
- // Массив данных
- $aSDATA = array(
- 'unit' => $aData['unit'], // идентификатор локации
- 'tarif' => $aData['tarif'], // идентификатор тарифа
- 'ram' => $ram, // значение ram
- 'param_fix' => $tarif['param_fix'], // фиксированные параметры
- 'pack' => $aData['pack'], // Выбранная сборка для установки
- 'time' => $aData['time'], // Время аренды
- 'days' => $days, // Число дней
- 'sum' => $sum, // Сумма списания
- 'test' => $test, // тестовый период
- 'address' => $ip.':'.$port, // адрес игрового сервера
- 'port' => $port, // порт игрового сервера
- 'slots' => $aData['slots'], // Кол-во слот
- 'map' => $tarif['map'], // Фиксированное значение слот
- 'autostop' => $tarif['autostop'], // Выключение при 0 онлайне
- 'ftp' => $tarif['ftp'], // Использование ftp
- 'plugins' => $tarif['plugins'], // Использование плагинов
- 'console' => $tarif['console'], // Использование консоли
- 'stats' => $tarif['stats'], // Использование графиков (ведение статистики)
- 'copy' => $tarif['copy'], // Использование резервных копий
- 'web' => $tarif['web'], // Использование доп услуг
- 'plugins_install' => $tarif['plugins_install'], // Список установленных плагинов
- 'hdd' => $tarif['hdd'], // Дисковое пространство
- 'core_fix' => $core, // Выделенный поток
- 'core_fix_one' => $fix_one, // Выделенный поток
- 'promo' => $promo // Использование промо-кода
- );
+ // Массив данных
+ $aSDATA = array(
+ 'unit' => $aData['unit'], // идентификатор локации
+ 'tarif' => $aData['tarif'], // идентификатор тарифа
+ 'ram' => $ram, // значение ram
+ 'param_fix' => $tarif['param_fix'], // фиксированные параметры
+ 'pack' => $aData['pack'], // Выбранная сборка для установки
+ 'time' => $aData['time'], // Время аренды
+ 'days' => $days, // Число дней
+ 'sum' => $sum, // Сумма списания
+ 'test' => $test, // тестовый период
+ 'address' => $ip.':'.$port, // адрес игрового сервера
+ 'port' => $port, // порт игрового сервера
+ 'slots' => $aData['slots'], // Кол-во слот
+ 'map' => $tarif['map'], // Фиксированное значение слот
+ 'autostop' => $tarif['autostop'], // Выключение при 0 онлайне
+ 'ftp' => $tarif['ftp'], // Использование ftp
+ 'plugins' => $tarif['plugins'], // Использование плагинов
+ 'console' => $tarif['console'], // Использование консоли
+ 'stats' => $tarif['stats'], // Использование графиков (ведение статистики)
+ 'copy' => $tarif['copy'], // Использование резервных копий
+ 'web' => $tarif['web'], // Использование доп услуг
+ 'plugins_install' => $tarif['plugins_install'], // Список установленных плагинов
+ 'hdd' => $tarif['hdd'], // Дисковое пространство
+ 'core_fix' => $core, // Выделенный поток
+ 'core_fix_one' => $fix_one, // Выделенный поток
+ 'promo' => $promo // Использование промо-кода
+ );
- return $aSDATA;
- }
+ return $aSDATA;
+ }
- public static function install($aSDATA = array())
- {
- global $cfg, $sql, $user, $start_point;
+ public static function install($aSDATA = array())
+ {
+ global $cfg, $sql, $user, $start_point;
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- // Массив данных локации (адрес,пароль)
- $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$aSDATA['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ // Массив данных локации (адрес,пароль)
+ $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$aSDATA['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- // Проверка ssh соединения с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- sys::outjs(array('e' => sys::text('error', 'ssh')));
+ // Проверка ssh соединения с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ sys::outjs(array('e' => sys::text('error', 'ssh')));
- // Массив данных тарифа (путь сборки,путь установки)
- $sql->query('SELECT `path`, `install`, `hostname` FROM `tarifs` WHERE `id`="'.$aSDATA['tarif'].'" LIMIT 1');
- $tarif = $sql->get();
+ // Массив данных тарифа (путь сборки,путь установки)
+ $sql->query('SELECT `path`, `install`, `hostname` FROM `tarifs` WHERE `id`="'.$aSDATA['tarif'].'" LIMIT 1');
+ $tarif = $sql->get();
- // Получение идентификаторов игрового сервера
- $sql->query('INSERT INTO `servers` set uid="1"');
- $id = $sql->id();
- $uid = $id+1000;
+ // Получение идентификаторов игрового сервера
+ $sql->query('INSERT INTO `servers` set uid="1"');
+ $id = $sql->id();
+ $uid = $id+1000;
- // Директория сборки
- $path = $tarif['path'].$aSDATA['pack'];
+ // Директория сборки
+ $path = $tarif['path'].$aSDATA['pack'];
- // Директория игрового сервера
- $install = $tarif['install'].$uid;
+ // Директория игрового сервера
+ $install = $tarif['install'].$uid;
- $ssh->set('mkdir '.$install.';' // Создание директории
- .'useradd -s /bin/false -d '.$install.' -g servers -u '.$uid.' server'.$uid.';' // Создание пользователя сервера на локации
- .'chown server'.$uid.':1000 '.$install.';' // Изменение владельца и группы директории
- .'cd '.$install.' && sudo -u server'.$uid.' screen -dmS i_'.$uid.' sh -c "cp -r '.$path.'/. .;' // Копирование файлов сборки для сервера
- .'find . -type d -exec chmod 700 {} \;;'
- .'find . -type f -exec chmod 600 {} \;;'
- .'chmod 500 '.params::$aFileGame['mc'].'"');
+ $ssh->set('mkdir '.$install.';' // Создание директории
+ .'useradd -s /bin/false -d '.$install.' -g servers -u '.$uid.' server'.$uid.';' // Создание пользователя сервера на локации
+ .'chown server'.$uid.':1000 '.$install.';' // Изменение владельца и группы директории
+ .'cd '.$install.' && sudo -u server'.$uid.' screen -dmS i_'.$uid.' sh -c "cp -r '.$path.'/. .;' // Копирование файлов сборки для сервера
+ .'find . -type d -exec chmod 700 {} \;;'
+ .'find . -type f -exec chmod 600 {} \;;'
+ .'chmod 500 '.params::$aFileGame['mc'].'"');
- // Запись данных нового сервера
- $sql->query('UPDATE `servers` set
- `uid`="'.$uid.'",
- `unit`="'.$aSDATA['unit'].'",
- `tarif`="'.$aSDATA['tarif'].'",
- `user`="'.$user['id'].'",
- `address`="'.$aSDATA['address'].'",
- `port`="'.$aSDATA['port'].'",
- `game`="mc",
- `slots`="'.$aSDATA['slots'].'",
- `slots_start`="'.$aSDATA['slots'].'",
- `status`="install",
- `name`="'.$tarif['hostname'].'",
- `pack`="'.$aSDATA['pack'].'",
- `plugins_use`="'.$aSDATA['plugins'].'",
- `ftp_use`="'.$aSDATA['ftp'].'",
- `console_use`="'.$aSDATA['console'].'",
- `stats_use`="'.$aSDATA['stats'].'",
- `copy_use`="'.$aSDATA['copy'].'",
- `web_use`="'.$aSDATA['web'].'",
- `ram`="'.$aSDATA['ram'].'",
- `ram_fix`="'.$aSDATA['param_fix'].'",
- `map_start`="'.$aSDATA['map'].'",
- `vac`="1",
- `hdd`="'.$aSDATA['hdd'].'",
- `time`="'.$aSDATA['time'].'",
- `date`="'.$start_point.'",
- `test`="'.$aSDATA['test'].'",
- `core_fix`="'.$aSDATA['core_fix'].'",
- `core_fix_one`="'.$aSDATA['core_fix_one'].'",
- `autostop`="'.$aSDATA['autostop'].'" WHERE `id`="'.$id.'" LIMIT 1');
+ // Запись данных нового сервера
+ $sql->query('UPDATE `servers` set
+ `uid`="'.$uid.'",
+ `unit`="'.$aSDATA['unit'].'",
+ `tarif`="'.$aSDATA['tarif'].'",
+ `user`="'.$user['id'].'",
+ `address`="'.$aSDATA['address'].'",
+ `port`="'.$aSDATA['port'].'",
+ `game`="mc",
+ `slots`="'.$aSDATA['slots'].'",
+ `slots_start`="'.$aSDATA['slots'].'",
+ `status`="install",
+ `name`="'.$tarif['hostname'].'",
+ `pack`="'.$aSDATA['pack'].'",
+ `plugins_use`="'.$aSDATA['plugins'].'",
+ `ftp_use`="'.$aSDATA['ftp'].'",
+ `console_use`="'.$aSDATA['console'].'",
+ `stats_use`="'.$aSDATA['stats'].'",
+ `copy_use`="'.$aSDATA['copy'].'",
+ `web_use`="'.$aSDATA['web'].'",
+ `ram`="'.$aSDATA['ram'].'",
+ `ram_fix`="'.$aSDATA['param_fix'].'",
+ `map_start`="'.$aSDATA['map'].'",
+ `vac`="1",
+ `hdd`="'.$aSDATA['hdd'].'",
+ `time`="'.$aSDATA['time'].'",
+ `date`="'.$start_point.'",
+ `test`="'.$aSDATA['test'].'",
+ `core_fix`="'.$aSDATA['core_fix'].'",
+ `core_fix_one`="'.$aSDATA['core_fix_one'].'",
+ `autostop`="'.$aSDATA['autostop'].'" WHERE `id`="'.$id.'" LIMIT 1');
- // Запись установленных плагинов
- if($aSDATA['plugins'])
- {
- // Массив идентификаторов плагинов
- $aPlugins = sys::b64djs($aSDATA['plugins_install']);
+ // Запись установленных плагинов
+ if($aSDATA['plugins'])
+ {
+ // Массив идентификаторов плагинов
+ $aPlugins = sys::b64djs($aSDATA['plugins_install']);
- if(isset($aPlugins[$aSDATA['pack']]))
- {
- $plugins = explode(',', $aPlugins[$aSDATA['pack']]);
+ if(isset($aPlugins[$aSDATA['pack']]))
+ {
+ $plugins = explode(',', $aPlugins[$aSDATA['pack']]);
- foreach($plugins as $plugin)
- if($plugin)
- $sql->query('INSERT INTO `plugins_install` set `server`="'.$id.'", `plugin`="'.$plugin.'", `time`="'.$start_point.'"');
- }
- }
+ foreach($plugins as $plugin)
+ if($plugin)
+ $sql->query('INSERT INTO `plugins_install` set `server`="'.$id.'", `plugin`="'.$plugin.'", `time`="'.$start_point.'"');
+ }
+ }
- // Списание средств с баланса пользователя
- $sql->query('UPDATE `users` set `balance`="'.($user['balance']-$aSDATA['sum']).'" WHERE `id`="'.$user['id'].'" LIMIT 1');
+ // Списание средств с баланса пользователя
+ $sql->query('UPDATE `users` set `balance`="'.($user['balance']-$aSDATA['sum']).'" WHERE `id`="'.$user['id'].'" LIMIT 1');
- // Запись получения тестового периода
- if($aSDATA['test'])
- {
- $sql->query('INSERT INTO `tests` set `server`="'.$id.'", `unit`="'.$aSDATA['unit'].'", `game`="mc", `user`="'.$user['id'].'", `time`="'.$start_point.'"');
- $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server_test'), array('id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="0"');
- }else{
- // Реф. система
- games::part($user['id'], $aSDATA['sum']);
+ // Запись получения тестового периода
+ if($aSDATA['test'])
+ {
+ $sql->query('INSERT INTO `tests` set `server`="'.$id.'", `unit`="'.$aSDATA['unit'].'", `game`="mc", `user`="'.$user['id'].'", `time`="'.$start_point.'"');
+ $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server_test'), array('id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="0"');
+ }else{
+ // Реф. система
+ games::part($user['id'], $aSDATA['sum']);
- // Запись логов
- if(!is_array($aSDATA['promo']))
- $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server'), array('days' => games::parse_day($aSDATA['days'], true), 'money' => $aSDATA['sum'], 'id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="'.$aSDATA['sum'].'"');
- else{
- $sql->query('UPDATE `servers` set `benefit`="'.$aSDATA['time'].'" WHERE `id`="'.$id.'" LIMIT 1');
- $sql->query('INSERT INTO `promo_use` set `promo`="'.$aSDATA['promo']['id'].'", `user`="'.$user['id'].'", `time`="'.$start_point.'"');
- $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server_promo'), array('days' => games::parse_day($aSDATA['days'], true), 'money' => $aSDATA['sum'], 'promo' => $aSDATA['promo']['cod'], 'id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="'.$aSDATA['sum'].'"');
- }
- }
+ // Запись логов
+ if(!is_array($aSDATA['promo']))
+ $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server'), array('days' => games::parse_day($aSDATA['days'], true), 'money' => $aSDATA['sum'], 'id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="'.$aSDATA['sum'].'"');
+ else{
+ $sql->query('UPDATE `servers` set `benefit`="'.$aSDATA['time'].'" WHERE `id`="'.$id.'" LIMIT 1');
+ $sql->query('INSERT INTO `promo_use` set `promo`="'.$aSDATA['promo']['id'].'", `user`="'.$user['id'].'", `time`="'.$start_point.'"');
+ $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server_promo'), array('days' => games::parse_day($aSDATA['days'], true), 'money' => $aSDATA['sum'], 'promo' => $aSDATA['promo']['cod'], 'id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="'.$aSDATA['sum'].'"');
+ }
+ }
- return $id;
- }
+ return $id;
+ }
}
?>
\ No newline at end of file
diff --git a/system/library/games/mc/tarif.php b/system/library/games/mc/tarif.php
index 923aa1f..dbb33c8 100644
--- a/system/library/games/mc/tarif.php
+++ b/system/library/games/mc/tarif.php
@@ -1,231 +1,231 @@
get('extend', 'sections/servers/games/tarif');
+ $html->get('extend', 'sections/servers/games/tarif');
- if(isset($html->arr['extend_address']))
- {
- $html->unit('extend_address', 1);
- $html->set('extend_address', $html->arr['extend_address']);
- }else
- $html->unit('extend_address');
+ if(isset($html->arr['extend_address']))
+ {
+ $html->unit('extend_address', 1);
+ $html->set('extend_address', $html->arr['extend_address']);
+ }else
+ $html->unit('extend_address');
- $html->set('id', $sid);
- $html->set('time', sys::date('min', $server['time']));
- $html->set('options', 'Выберете период продления '.$options);
- $html->set('slots', $server['slots']);
- $html->set('info', $server['ram'].' RAM');
- $html->set('tarif', $tarif_name);
- $html->set('cur', $cfg['currency']);
+ $html->set('id', $sid);
+ $html->set('time', sys::date('min', $server['time']));
+ $html->set('options', 'Выберете период продления '.$options);
+ $html->set('slots', $server['slots']);
+ $html->set('info', $server['ram'].' RAM');
+ $html->set('tarif', $tarif_name);
+ $html->set('cur', $cfg['currency']);
- $html->pack('main');
+ $html->pack('main');
- return NULL;
- }
+ return NULL;
+ }
public static function extend_sp($server, $tarif, $sid)
{
- global $cfg, $sql, $html, $start_point;
+ global $cfg, $sql, $html, $start_point;
- tarifs::extend_address($server['game'], $sid);
+ tarifs::extend_address($server['game'], $sid);
- $aPrice = explode(':', $tarif['price']);
- $aRAM = explode(':', $tarif['ram']);
+ $aPrice = explode(':', $tarif['price']);
+ $aRAM = explode(':', $tarif['ram']);
- $ram = $server['ram_fix'] ? $server['ram'] : $server['ram']/$server['slots'];
+ $ram = $server['ram_fix'] ? $server['ram'] : $server['ram']/$server['slots'];
- $sum = $tarif['slots'] ? $aPrice[array_search($ram, $aRAM)] : $aPrice[array_search($ram, $aRAM)]*$server['slots'];
+ $sum = $tarif['slots'] ? $aPrice[array_search($ram, $aRAM)] : $aPrice[array_search($ram, $aRAM)]*$server['slots'];
- $html->get('extend_sp', 'sections/servers/games/tarif');
+ $html->get('extend_sp', 'sections/servers/games/tarif');
- if(isset($html->arr['extend_address']))
- {
- $html->unit('extend_address', 1);
- $html->set('extend_address', $html->arr['extend_address']);
- }else
- $html->unit('extend_address');
+ if(isset($html->arr['extend_address']))
+ {
+ $html->unit('extend_address', 1);
+ $html->set('extend_address', $html->arr['extend_address']);
+ }else
+ $html->unit('extend_address');
- $html->set('id', $sid);
- $html->set('time', sys::date('min', $server['time']));
- $html->set('date', $server['time'] > $start_point ? 'Сервер продлен до: '.date('d.m.Y', $server['time']) : 'Текущая дата: '.date('d.m.Y', $start_point));
- $html->set('options', 'Выберете период продления '.$options);
- $html->set('slots', $server['slots']);
- $html->set('info', $server['ram'].' RAM');
- $html->set('tarif', $tarif['name']);
- $html->set('sum', $sum);
- $html->set('cur', $cfg['currency']);
+ $html->set('id', $sid);
+ $html->set('time', sys::date('min', $server['time']));
+ $html->set('date', $server['time'] > $start_point ? 'Сервер продлен до: '.date('d.m.Y', $server['time']) : 'Текущая дата: '.date('d.m.Y', $start_point));
+ $html->set('options', 'Выберете период продления '.$options);
+ $html->set('slots', $server['slots']);
+ $html->set('info', $server['ram'].' RAM');
+ $html->set('tarif', $tarif['name']);
+ $html->set('sum', $sum);
+ $html->set('cur', $cfg['currency']);
- $html->pack('main');
+ $html->pack('main');
- return NULL;
- }
+ return NULL;
+ }
public static function plan($server, $tarif_name, $sid)
{
- global $cfg, $sql, $html;
+ global $cfg, $sql, $html;
- $sql->query('SELECT `ram`, `price` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
+ $sql->query('SELECT `ram`, `price` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
- if(!$sql->num())
- return NULL;
+ if(!$sql->num())
+ return NULL;
- $tarif = $sql->get();
+ $tarif = $sql->get();
- $options = 'Выберете тарифный план ';
+ $options = 'Выберете тарифный план ';
- $aPrice = explode(':', $tarif['price']);
- $aRAM = explode(':', $tarif['ram']);
+ $aPrice = explode(':', $tarif['price']);
+ $aRAM = explode(':', $tarif['ram']);
- $ram = $server['ram_fix'] ? $server['ram'] : $server['ram']/$server['slots'];
+ $ram = $server['ram_fix'] ? $server['ram'] : $server['ram']/$server['slots'];
- // Если есть выбор
- if(count($aRAM) > 1)
- {
- // Удалить при наличии ram сервера из выбора
- if(in_array($ram, $aRAM))
- unset($aRAM[array_search($ram, $aRAM)]);
+ // Если есть выбор
+ if(count($aRAM) > 1)
+ {
+ // Удалить при наличии ram сервера из выбора
+ if(in_array($ram, $aRAM))
+ unset($aRAM[array_search($ram, $aRAM)]);
- foreach($aRAM as $index => $ram)
- $options .= ''
- .$ram.' RAM '
- .'('.$aPrice[$index].' '.$cfg['currency'].'/слот | '
- .($aPrice[$index]*$server['slots']).' '.$cfg['currency'].'/месяц)'
- .' ';
- }else
- return NULL;
+ foreach($aRAM as $index => $ram)
+ $options .= ''
+ .$ram.' RAM '
+ .'('.$aPrice[$index].' '.$cfg['currency'].'/слот | '
+ .($aPrice[$index]*$server['slots']).' '.$cfg['currency'].'/месяц)'
+ .' ';
+ }else
+ return NULL;
- $html->get('plan', 'sections/servers/games/tarif');
+ $html->get('plan', 'sections/servers/games/tarif');
- $html->set('id', $sid);
- $html->set('options', $options);
- $html->set('info', $server['ram'].' RAM');
- $html->set('tarif', $tarif_name);
+ $html->set('id', $sid);
+ $html->set('options', $options);
+ $html->set('info', $server['ram'].' RAM');
+ $html->set('tarif', $tarif_name);
- $html->pack('main');
+ $html->pack('main');
- return NULL;
- }
+ return NULL;
+ }
- public static function unit($server, $unit_name, $tarif_name, $sid)
+ public static function unit($server, $unit_name, $tarif_name, $sid)
{
- global $cfg, $sql, $html;
+ global $cfg, $sql, $html;
- if(!$cfg['change_unit'][$server['game']])
- return NULL;
+ if(!$cfg['change_unit'][$server['game']])
+ return NULL;
- $tarifs = $sql->query('SELECT `unit`, `ram` FROM `tarifs` WHERE `game`="'.$server['game'].'" AND `name`="'.$tarif_name.'" AND `id`!="'.$server['tarif'].'" AND `show`="1" ORDER BY `unit`');
- if(!$sql->num($tarifs))
- return NULL;
+ $tarifs = $sql->query('SELECT `unit`, `ram` FROM `tarifs` WHERE `game`="'.$server['game'].'" AND `name`="'.$tarif_name.'" AND `id`!="'.$server['tarif'].'" AND `show`="1" ORDER BY `unit`');
+ if(!$sql->num($tarifs))
+ return NULL;
- $units = 0;
+ $units = 0;
- $options = 'Выберете новую локацию ';
+ $options = 'Выберете новую локацию ';
- $ram = $server['ram_fix'] ? $server['ram'] : $server['ram']/$server['slots'];
+ $ram = $server['ram_fix'] ? $server['ram'] : $server['ram']/$server['slots'];
- while($tarif = $sql->get($tarifs))
- {
- if(!in_array($ram, explode(':', $tarif['ram'])))
- continue;
+ while($tarif = $sql->get($tarifs))
+ {
+ if(!in_array($ram, explode(':', $tarif['ram'])))
+ continue;
- $sql->query('SELECT `id`, `name` FROM `units` WHERE `id`="'.$tarif['unit'].'" AND `show`="1" LIMIT 1');
- if(!$sql->num())
- continue;
+ $sql->query('SELECT `id`, `name` FROM `units` WHERE `id`="'.$tarif['unit'].'" AND `show`="1" LIMIT 1');
+ if(!$sql->num())
+ continue;
- $unit = $sql->get();
+ $unit = $sql->get();
- $options .= ''.$unit['name'].' ';
+ $options .= ''.$unit['name'].' ';
- $units+=1;
- }
+ $units+=1;
+ }
- if(!$units)
- return NULL;
+ if(!$units)
+ return NULL;
- $html->get('unit', 'sections/servers/games/tarif');
+ $html->get('unit', 'sections/servers/games/tarif');
- $html->set('id', $sid);
- $html->set('options', $options);
- $html->set('slots', $server['slots']);
- $html->set('info', $server['ram'].' RAM');
- $html->set('unit', $unit_name);
- $html->set('tarif', $tarif_name);
+ $html->set('id', $sid);
+ $html->set('options', $options);
+ $html->set('slots', $server['slots']);
+ $html->set('info', $server['ram'].' RAM');
+ $html->set('unit', $unit_name);
+ $html->set('tarif', $tarif_name);
- $html->pack('main');
+ $html->pack('main');
- return NULL;
- }
+ return NULL;
+ }
- public static function unit_new($tarif, $unit, $server, $mcache)
- {
- global $ssh, $sql, $user, $start_point;
+ public static function unit_new($tarif, $unit, $server, $mcache)
+ {
+ global $ssh, $sql, $user, $start_point;
- // Проверка ssh соединения с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- sys::outjs(array('e' => sys::text('error', 'ssh')));
+ // Проверка ssh соединения с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ sys::outjs(array('e' => sys::text('error', 'ssh')));
- // Директория сборки
- $path = $tarif['path'].$tarif['pack'];
+ // Директория сборки
+ $path = $tarif['path'].$tarif['pack'];
- // Директория игрового сервера
- $install = $tarif['install'].$server['uid'];
+ // Директория игрового сервера
+ $install = $tarif['install'].$server['uid'];
- // Пользователь сервера
- $uS = 'server'.$server['uid'];
+ // Пользователь сервера
+ $uS = 'server'.$server['uid'];
- $ssh->set('mkdir '.$install.';' // Создание директории
- .'useradd -d '.$install.' -g servers -u '.$server['uid'].' '.$uS.';' // Создание пользователя сервера на локации
- .'chown '.$uS.':1000 '.$install.';' // Изменение владельца и группы директории
- .'cd '.$install.' && sudo -u '.$uS.' screen -dmS i_'.$server['uid'].' cp -r '.$path.'/. .'); // Копирование файлов сборки для сервера
+ $ssh->set('mkdir '.$install.';' // Создание директории
+ .'useradd -d '.$install.' -g servers -u '.$server['uid'].' '.$uS.';' // Создание пользователя сервера на локации
+ .'chown '.$uS.':1000 '.$install.';' // Изменение владельца и группы директории
+ .'cd '.$install.' && sudo -u '.$uS.' screen -dmS i_'.$server['uid'].' cp -r '.$path.'/. .'); // Копирование файлов сборки для сервера
- $address = explode(':', $server['address']);
+ $address = explode(':', $server['address']);
- $fix_one = $tarif['core_fix'] ? 1 : 0;
+ $fix_one = $tarif['core_fix'] ? 1 : 0;
- // Обновление данных нового сервера
- $sql->query('UPDATE `servers` set
- `unit`="'.$tarif['unit'].'",
- `tarif`="'.$tarif['id'].'",
- `address`="'.$server['address'].'",
- `port`="'.$address[1].'",
- `status`="install",
- `name`="'.$tarif['hostname'].'",
- `pack`="'.$tarif['pack'].'",
- `map_start`="'.$tarif['map'].'",
- `vac`="1",
- `hdd`="'.$tarif['hdd'].'",
- `time`="'.$tarif['time'].'",
- `autostop`="'.$tarif['autostop'].'",
- `core_fix`="'.$tarif['core_fix'].'",
- `core_fix_one`="'.$fix_one.'",
- `reinstall`="'.$start_point.'" WHERE `id`="'.$server['id'].'" LIMIT 1');
+ // Обновление данных нового сервера
+ $sql->query('UPDATE `servers` set
+ `unit`="'.$tarif['unit'].'",
+ `tarif`="'.$tarif['id'].'",
+ `address`="'.$server['address'].'",
+ `port`="'.$address[1].'",
+ `status`="install",
+ `name`="'.$tarif['hostname'].'",
+ `pack`="'.$tarif['pack'].'",
+ `map_start`="'.$tarif['map'].'",
+ `vac`="1",
+ `hdd`="'.$tarif['hdd'].'",
+ `time`="'.$tarif['time'].'",
+ `autostop`="'.$tarif['autostop'].'",
+ `core_fix`="'.$tarif['core_fix'].'",
+ `core_fix_one`="'.$fix_one.'",
+ `reinstall`="'.$start_point.'" WHERE `id`="'.$server['id'].'" LIMIT 1');
- // Запись установленных плагинов
- if($tarif['plugins'])
- {
- // Массив идентификаторов плагинов
- $aPlugins = sys::b64js($tarif['plugins_install']);
+ // Запись установленных плагинов
+ if($tarif['plugins'])
+ {
+ // Массив идентификаторов плагинов
+ $aPlugins = sys::b64js($tarif['plugins_install']);
- if(isset($aPlugins[$tarif['pack']]))
- {
- $plugins = explode(',', $aPlugins[$tarif['pack']]);
+ if(isset($aPlugins[$tarif['pack']]))
+ {
+ $plugins = explode(',', $aPlugins[$tarif['pack']]);
- foreach($plugins as $plugin)
- if($plugin)
- $sql->query('INSERT INTO `plugins_install` set `server`="'.$server['id'].'", `plugin`="'.$plugin.'", `time`="'.$start_point.'"');
- }
- }
+ foreach($plugins as $plugin)
+ if($plugin)
+ $sql->query('INSERT INTO `plugins_install` set `server`="'.$server['id'].'", `plugin`="'.$plugin.'", `time`="'.$start_point.'"');
+ }
+ }
- return NULL;
- }
+ return NULL;
+ }
}
?>
\ No newline at end of file
diff --git a/system/library/games/mta/action.php b/system/library/games/mta/action.php
index 6e2cc55..bb747d7 100644
--- a/system/library/games/mta/action.php
+++ b/system/library/games/mta/action.php
@@ -1,157 +1,157 @@
query('SELECT `uid`, `unit`, `tarif`, `game`, `address`, `slots_start`, `name`, `time_start`, `core_fix` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `uid`, `unit`, `tarif`, `game`, `address`, `slots_start`, `name`, `time_start`, `core_fix` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
+ $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
$tarif = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return array('e' => sys::text('error', 'ssh'));
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return array('e' => sys::text('error', 'ssh'));
- list($ip, $port) = explode(':', $server['address']);
+ list($ip, $port) = explode(':', $server['address']);
- // Убить процессы
- $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
- .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe;');
+ // Убить процессы
+ $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
+ .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe;');
- // Временный файл
- $temp = sys::temp(action::config($ip, $port, $server['slots_start'], $ssh->get('cat '.$tarif['install'].'/'.$server['uid'].'/mods/deathmatch/mtaserver.conf')));
+ // Временный файл
+ $temp = sys::temp(action::config($ip, $port, $server['slots_start'], $ssh->get('cat '.$tarif['install'].'/'.$server['uid'].'/mods/deathmatch/mtaserver.conf')));
- // Обновление файла server.cfg
- $ssh->setfile($temp, $tarif['install'].$server['uid'].'/mods/deathmatch/mtaserver.conf', 0644);
+ // Обновление файла server.cfg
+ $ssh->setfile($temp, $tarif['install'].$server['uid'].'/mods/deathmatch/mtaserver.conf', 0644);
- unlink($temp);
+ unlink($temp);
- $taskset = '';
+ $taskset = '';
- // Если включена система автораспределения и не установлен фиксированный поток
- if($cfg['cpu_route'] AND !$server['core_fix'])
- {
- $proc_stat = array();
+ // Если включена система автораспределения и не установлен фиксированный поток
+ if($cfg['cpu_route'] AND !$server['core_fix'])
+ {
+ $proc_stat = array();
- $proc_stat[0] = $ssh->get('cat /proc/stat');
- }
+ $proc_stat[0] = $ssh->get('cat /proc/stat');
+ }
- // Если система автораспределения продолжить парсинг загрузки процессора
- if(isset($proc_stat))
- {
- $proc_stat[1] = $ssh->get('cat /proc/stat');
+ // Если система автораспределения продолжить парсинг загрузки процессора
+ if(isset($proc_stat))
+ {
+ $proc_stat[1] = $ssh->get('cat /proc/stat');
- // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
- $core = sys::cpu_idle($proc_stat, $server['unit'], false); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
+ // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
+ $core = sys::cpu_idle($proc_stat, $server['unit'], false); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
- if(!is_numeric($core))
- return array('e' => sys::text('error', 'cpu'));
+ if(!is_numeric($core))
+ return array('e' => sys::text('error', 'cpu'));
- $taskset = 'taskset -c '.$core;
- }
+ $taskset = 'taskset -c '.$core;
+ }
- if($server['core_fix'])
- {
- $core = $server['core_fix']-1;
- $taskset = 'taskset -c '.$core;
- }
+ if($server['core_fix'])
+ {
+ $core = $server['core_fix']-1;
+ $taskset = 'taskset -c '.$core;
+ }
- // Параметры запуска
- $bash = './mta-server';
+ // Параметры запуска
+ $bash = './mta-server';
- // Временный файл
- $temp = sys::temp($bash);
+ // Временный файл
+ $temp = sys::temp($bash);
- // Обновление файла start.sh
- $ssh->setfile($temp, $tarif['install'].$server['uid'].'/start.sh', 0500);
+ // Обновление файла start.sh
+ $ssh->setfile($temp, $tarif['install'].$server['uid'].'/start.sh', 0500);
- // Строка запуска
- $ssh->set('cd '.$tarif['install'].$server['uid'].';' // переход в директорию игрового сервера
- .'rm *.pid;' // Удаление *.pid файлов
- .'sudo -u server'.$server['uid'].' mkdir -p mods/deathmatch/oldstart;' // Создание папки логов
- .'cat mods/deathmatch/logs/server.log >> mods/deathmatch/oldstart/'.date('d.m.Y_H:i:s', $server['time_start']).'.log; rm mods/deathmatch/logs/server.log; rm mods/deathmatch/logs/01.01.1970_03:00:00.log;' // Перемещение лога предыдущего запуска
- .'chown server'.$server['uid'].':1000 mods/deathmatch/mtaserver.conf start.sh;' // Обновление владельца файлов
- .'sudo -u server'.$server['uid'].' screen -dmS s_'.$server['uid'].' '.$taskset.' sh -c "./start.sh"'); // Запуск игровго сервера
+ // Строка запуска
+ $ssh->set('cd '.$tarif['install'].$server['uid'].';' // переход в директорию игрового сервера
+ .'rm *.pid;' // Удаление *.pid файлов
+ .'sudo -u server'.$server['uid'].' mkdir -p mods/deathmatch/oldstart;' // Создание папки логов
+ .'cat mods/deathmatch/logs/server.log >> mods/deathmatch/oldstart/'.date('d.m.Y_H:i:s', $server['time_start']).'.log; rm mods/deathmatch/logs/server.log; rm mods/deathmatch/logs/01.01.1970_03:00:00.log;' // Перемещение лога предыдущего запуска
+ .'chown server'.$server['uid'].':1000 mods/deathmatch/mtaserver.conf start.sh;' // Обновление владельца файлов
+ .'sudo -u server'.$server['uid'].' screen -dmS s_'.$server['uid'].' '.$taskset.' sh -c "./start.sh"'); // Запуск игровго сервера
- $core = !isset($core) ? 0 : $core+1;
+ $core = !isset($core) ? 0 : $core+1;
- // Обновление информации в базе
- $sql->query('UPDATE `servers` set `status`="'.$type.'", `online`="0", `players`="", `core_use`="'.$core.'", `time_start`="'.$start_point.'", `stop`="1" WHERE `id`="'.$id.'" LIMIT 1');
+ // Обновление информации в базе
+ $sql->query('UPDATE `servers` set `status`="'.$type.'", `online`="0", `players`="", `core_use`="'.$core.'", `time_start`="'.$start_point.'", `stop`="1" WHERE `id`="'.$id.'" LIMIT 1');
- unlink($temp);
+ unlink($temp);
- // Сброс кеша
- actions::clmcache($id);
+ // Сброс кеша
+ actions::clmcache($id);
- sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0, 'players' => ''));
- sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0));
+ sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0, 'players' => ''));
+ sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0));
- return array('s' => 'ok');
- }
+ return array('s' => 'ok');
+ }
- public static function config($ip, $port, $slots, $config)
- {
- $aRepl = array(
- '', ' ',
- '', ' ',
- '', ' ',
- '', ' ',
- '', ' ',
- '', ' ',
- '', ' '
- );
+ public static function config($ip, $port, $slots, $config)
+ {
+ $aRepl = array(
+ '', ' ',
+ '', ' ',
+ '', ' ',
+ '', ' ',
+ '', ' ',
+ '', ' ',
+ '', ' '
+ );
- $config = str_ireplace($aRepl, $aRepl, $config);
- $config = str_ireplace(array('', ' ', "\r", "\t"),'', $config);
- $config = preg_replace("#\<\!--(.+?)--\>#is", '', $config);
+ $config = str_ireplace($aRepl, $aRepl, $config);
+ $config = str_ireplace(array('', ' ', "\r", "\t"),'', $config);
+ $config = preg_replace("#\<\!--(.+?)--\>#is", '', $config);
- $aLine = explode("\n", $config);
+ $aLine = explode("\n", $config);
- $search = array(
- "#\(.+?)\<\/serverip\>#is",
- "#\(.+?)\<\/maxplayers\>#is",
- "#\(.+?)\<\/httpserver\>#is",
- "#\(.+?)\<\/serverport\>#is",
- "#\(.+?)\<\/httpport\>#is",
- "#\(.+?)\<\/logfile\>#is",
- "#\(.+?)\<\/ase\>#is"
- );
+ $search = array(
+ "#\(.+?)\<\/serverip\>#is",
+ "#\(.+?)\<\/maxplayers\>#is",
+ "#\(.+?)\<\/httpserver\>#is",
+ "#\(.+?)\<\/serverport\>#is",
+ "#\(.+?)\<\/httpport\>#is",
+ "#\(.+?)\<\/logfile\>#is",
+ "#\(.+?)\<\/ase\>#is"
+ );
- $config = ''.PHP_EOL;
+ $config = ''.PHP_EOL;
- foreach($aLine as $line)
- {
- if(str_replace(array(' ', "\t"), '', $line) != '')
- $edit = trim(preg_replace($search, array('','','','','',''), $line));
+ foreach($aLine as $line)
+ {
+ if(str_replace(array(' ', "\t"), '', $line) != '')
+ $edit = trim(preg_replace($search, array('','','','','',''), $line));
- if($edit != '')
- $config .= ' '.$edit.PHP_EOL;
+ if($edit != '')
+ $config .= ' '.$edit.PHP_EOL;
- $edit = '';
- }
+ $edit = '';
+ }
- $config .= ' '.$ip.' '.PHP_EOL
- .' '.$slots.' '.PHP_EOL
- .' 1 '.PHP_EOL
- .' '.$port.' '.PHP_EOL
- .' '.($port+10000).' '.PHP_EOL
- .' 1 '.PHP_EOL
- .' logs/server.log ';
+ $config .= ' '.$ip.' '.PHP_EOL
+ .' '.$slots.' '.PHP_EOL
+ .' 1 '.PHP_EOL
+ .' '.$port.' '.PHP_EOL
+ .' '.($port+10000).' '.PHP_EOL
+ .' 1 '.PHP_EOL
+ .' logs/server.log ';
- return $config."\n".' ';
- }
+ return $config."\n".' ';
+ }
}
?>
\ No newline at end of file
diff --git a/system/library/games/mta/scan.php b/system/library/games/mta/scan.php
index 7fe2d08..2f1b47e 100644
--- a/system/library/games/mta/scan.php
+++ b/system/library/games/mta/scan.php
@@ -1,114 +1,114 @@
query('SELECT `address`, `game`, `name`, `map`, `online`, `players`, `status`, `time`, `overdue` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `address`, `game`, `name`, `map`, `online`, `players`, `status`, `time`, `overdue` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- list($ip, $port) = explode(':', $server['address']);
+ list($ip, $port) = explode(':', $server['address']);
- include(LIB.'games/query/MtaQuery.php');
+ include(LIB.'games/query/MtaQuery.php');
- $sq = new MtaQuery($ip, $port);
+ $sq = new MtaQuery($ip, $port);
- if($players_get)
- $nmch = 'server_scan_mon_pl_'.$id;
- else
- $nmch = 'server_scan_mon_'.$id;
+ if($players_get)
+ $nmch = 'server_scan_mon_pl_'.$id;
+ else
+ $nmch = 'server_scan_mon_'.$id;
- if(is_array($mcache->get($nmch)))
- return $mcache->get($nmch);
+ if(is_array($mcache->get($nmch)))
+ return $mcache->get($nmch);
- $out = array();
+ $out = array();
- $out['time'] = 'Арендован до: '.date('d.m.Y - H:i', $server['time']);
+ $out['time'] = 'Арендован до: '.date('d.m.Y - H:i', $server['time']);
- if($server['status'] == 'overdue')
- $out['time_end'] = 'Удаление через: '.sys::date('min', $server['overdue']+$cfg['server_delete']*86400);
- else
- $out['time_end'] = 'Осталось: '.sys::date('min', $server['time']);
+ if($server['status'] == 'overdue')
+ $out['time_end'] = 'Удаление через: '.sys::date('min', $server['overdue']+$cfg['server_delete']*86400);
+ else
+ $out['time_end'] = 'Осталось: '.sys::date('min', $server['time']);
- $info = $sq->getInfo($players_get);
+ $info = $sq->getInfo($players_get);
- if(!is_array($info))
- {
- $out['name'] = $server['name'];
- $out['status'] = sys::status($server['status'], $server['game'], $server['map']);
- $out['online'] = $server['online'];
- $out['image'] = ' ';
- $out['buttons'] = sys::buttons($id, $server['status'], $server['game']);
+ if(!is_array($info))
+ {
+ $out['name'] = $server['name'];
+ $out['status'] = sys::status($server['status'], $server['game'], $server['map']);
+ $out['online'] = $server['online'];
+ $out['image'] = ' ';
+ $out['buttons'] = sys::buttons($id, $server['status'], $server['game']);
- if($players_get)
- $out['players'] = base64_decode($server['players']);
+ if($players_get)
+ $out['players'] = base64_decode($server['players']);
- $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
+ $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
- return $out;
- }
+ return $out;
+ }
- $players = scan::players($info['players_list']);
+ $players = scan::players($info['players_list']);
- $info['map'] = htmlspecialchars(mb_convert_encoding($info['map'], 'UTF-8', 'WINDOWS-1251'));
- $out['name'] = htmlspecialchars(mb_convert_encoding($info['hostname'], 'UTF-8', 'WINDOWS-1251'));
- $out['status'] = sys::status('working', $server['game'], $info['map']);
- $out['online'] = sys::int($info['players']);
- $out['image'] = ' ';
- $out['buttons'] = sys::buttons($id, 'working', $server['game']);
- $out['players'] = '';
+ $info['map'] = htmlspecialchars(mb_convert_encoding($info['map'], 'UTF-8', 'WINDOWS-1251'));
+ $out['name'] = htmlspecialchars(mb_convert_encoding($info['hostname'], 'UTF-8', 'WINDOWS-1251'));
+ $out['status'] = sys::status('working', $server['game'], $info['map']);
+ $out['online'] = sys::int($info['players']);
+ $out['image'] = ' ';
+ $out['buttons'] = sys::buttons($id, 'working', $server['game']);
+ $out['players'] = '';
- if($players_get)
- {
- foreach($players as $index => $player)
- {
- $html->get($server['game'], 'sections/servers/players');
+ if($players_get)
+ {
+ foreach($players as $index => $player)
+ {
+ $html->get($server['game'], 'sections/servers/players');
- $html->set('i', $player['i']);
- $html->set('name', $player['name']);
- $html->set('ping', $player['ping']);
+ $html->set('i', $player['i']);
+ $html->set('name', $player['name']);
+ $html->set('ping', $player['ping']);
- $html->pack('list');
- }
+ $html->pack('list');
+ }
- $out['players'] = isset($html->arr['list']) ? $html->arr['list'] : '';
- }
+ $out['players'] = isset($html->arr['list']) ? $html->arr['list'] : '';
+ }
- $sql->query('UPDATE `servers` set '
- .'`name`="'.$out['name'].'", '
- .'`online`="'.$out['online'].'", '
- .'`map`="'.$info['map'].'", '
- .'`status`="working" WHERE `id`="'.$id.'" LIMIT 1');
+ $sql->query('UPDATE `servers` set '
+ .'`name`="'.$out['name'].'", '
+ .'`online`="'.$out['online'].'", '
+ .'`map`="'.$info['map'].'", '
+ .'`status`="working" WHERE `id`="'.$id.'" LIMIT 1');
- if($players_get)
- $sql->query('UPDATE `servers` set `players`="'.base64_encode($out['players']).'" WHERE `id`="'.$id.'" LIMIT 1');
+ if($players_get)
+ $sql->query('UPDATE `servers` set `players`="'.base64_encode($out['players']).'" WHERE `id`="'.$id.'" LIMIT 1');
- $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
+ $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
- return $out;
- }
+ return $out;
+ }
- public static function players($aPlayrs)
- {
- $i = 1;
- $aData = array();
+ public static function players($aPlayrs)
+ {
+ $i = 1;
+ $aData = array();
- foreach($aPlayrs as $n => $player)
- {
- $aData[$i]['i'] = $i;
- $aData[$i]['name'] = $player['nickname'] == '' ? 'Подключается' : htmlspecialchars($player['nickname']);
- $aData[$i]['ping'] = sys::int($player['ping']);
+ foreach($aPlayrs as $n => $player)
+ {
+ $aData[$i]['i'] = $i;
+ $aData[$i]['name'] = $player['nickname'] == '' ? 'Подключается' : htmlspecialchars($player['nickname']);
+ $aData[$i]['ping'] = sys::int($player['ping']);
- $i+=1;
- }
+ $i+=1;
+ }
- return $aData;
- }
- }
+ return $aData;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/games/mta/service.php b/system/library/games/mta/service.php
index 74aa423..168b1ce 100644
--- a/system/library/games/mta/service.php
+++ b/system/library/games/mta/service.php
@@ -1,354 +1,354 @@
query('SELECT `address`, `test` FROM `units` WHERE `id`="'.$aData['unit'].'" AND `mta`="1" AND `show`="1" LIMIT 1');
- if(!$sql->num())
- sys::outjs(array('e' => 'Локация не найдена.'));
+ // Проверка локации
+ $sql->query('SELECT `address`, `test` FROM `units` WHERE `id`="'.$aData['unit'].'" AND `mta`="1" AND `show`="1" LIMIT 1');
+ if(!$sql->num())
+ sys::outjs(array('e' => 'Локация не найдена.'));
- $unit = $sql->get();
+ $unit = $sql->get();
- // Проверка тарифа
- $sql->query('SELECT `id` FROM `tarifs` WHERE `id`="'.$aData['tarif'].'" AND `unit`="'.$aData['unit'].'" AND `show`="1" LIMIT 1');
- if(!$sql->num())
- sys::outjs(array('e' => 'Тариф не найден.'));
+ // Проверка тарифа
+ $sql->query('SELECT `id` FROM `tarifs` WHERE `id`="'.$aData['tarif'].'" AND `unit`="'.$aData['unit'].'" AND `show`="1" LIMIT 1');
+ if(!$sql->num())
+ sys::outjs(array('e' => 'Тариф не найден.'));
- $sql->query('SELECT '
- .'`slots_min`,'
- .'`slots_max`,'
- .'`port_min`,'
- .'`port_max`,'
- .'`hostname`,'
- .'`packs`,'
- .'`time`,'
- .'`test`,'
- .'`tests`,'
- .'`discount`,'
- .'`ftp`,'
- .'`plugins`,'
- .'`console`,'
- .'`stats`,'
- .'`copy`,'
- .'`web`,'
- .'`plugins_install`,'
- .'`hdd`,'
- .'`autostop`,'
- .'`core_fix`,'
- .'`ip`,'
- .'`price`'
- .' FROM `tarifs` WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
+ $sql->query('SELECT '
+ .'`slots_min`,'
+ .'`slots_max`,'
+ .'`port_min`,'
+ .'`port_max`,'
+ .'`hostname`,'
+ .'`packs`,'
+ .'`time`,'
+ .'`test`,'
+ .'`tests`,'
+ .'`discount`,'
+ .'`ftp`,'
+ .'`plugins`,'
+ .'`console`,'
+ .'`stats`,'
+ .'`copy`,'
+ .'`web`,'
+ .'`plugins_install`,'
+ .'`hdd`,'
+ .'`autostop`,'
+ .'`core_fix`,'
+ .'`ip`,'
+ .'`price`'
+ .' FROM `tarifs` WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
- $tarif = $sql->get();
+ $tarif = $sql->get();
- // Проверка сборки
- if(!array_key_exists($aData['pack'], sys::b64djs($tarif['packs'], true)))
- sys::outjs(array('e' => 'Сборка не найдена.'));
+ // Проверка сборки
+ if(!array_key_exists($aData['pack'], sys::b64djs($tarif['packs'], true)))
+ sys::outjs(array('e' => 'Сборка не найдена.'));
- $test = 0;
+ $test = 0;
- // Проверка периода на тест
- if($aData['test'])
- {
- if(!$tarif['test'] || !$unit['test'])
- sys::outjs(array('e' => 'Тестовый период недоступен.'));
+ // Проверка периода на тест
+ if($aData['test'])
+ {
+ if(!$tarif['test'] || !$unit['test'])
+ sys::outjs(array('e' => 'Тестовый период недоступен.'));
- // Проверка на повторный запрос
- $sql->query('SELECT `id`, `game` FROM `tests` WHERE `user`="'.$user['id'].'" LIMIT 1');
- if($sql->num())
- {
- $test_info = $sql->get();
+ // Проверка на повторный запрос
+ $sql->query('SELECT `id`, `game` FROM `tests` WHERE `user`="'.$user['id'].'" LIMIT 1');
+ if($sql->num())
+ {
+ $test_info = $sql->get();
- if(!$cfg['tests']['game'] || $test_info['game'] == 'mta')
- sys::outjs(array('e' => 'Тестовый период предоставляется один раз.'));
+ if(!$cfg['tests']['game'] || $test_info['game'] == 'mta')
+ sys::outjs(array('e' => 'Тестовый период предоставляется один раз.'));
- $sql->query('SELECT `id` FROM `servers` WHERE `user`="'.$user['id'].'" AND `test`="1" LIMIT 1');
- if($sql->num() AND !$cfg['tests']['sametime'])
- sys::outjs(array('e' => 'Чтобы получить тестовый период другой игры, дождитесь окончания текущего.'));
- }
+ $sql->query('SELECT `id` FROM `servers` WHERE `user`="'.$user['id'].'" AND `test`="1" LIMIT 1');
+ if($sql->num() AND !$cfg['tests']['sametime'])
+ sys::outjs(array('e' => 'Чтобы получить тестовый период другой игры, дождитесь окончания текущего.'));
+ }
- // Проверка наличия мест на локации
- $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `test`="1" AND `time`>"'.$start_point.'" LIMIT '.$unit['test']);
- if($sql->num() == $unit['test'])
- sys::outjs(array('e' => 'Свободного места для тестового периода нет.'));
+ // Проверка наличия мест на локации
+ $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `test`="1" AND `time`>"'.$start_point.'" LIMIT '.$unit['test']);
+ if($sql->num() == $unit['test'])
+ sys::outjs(array('e' => 'Свободного места для тестового периода нет.'));
- // Проверка наличия мест для выбранного тарифа
- $sql->query('SELECT `id` FROM `servers` WHERE `tarif`="'.$aData['tarif'].'" AND `test`="1" AND `time`>"'.$start_point.'" LIMIT '.$tarif['tests']);
- if($sql->num() == $tarif['tests'])
- sys::outjs(array('e' => 'Свободного места для тестового периода выбранного тарифа нет.'));
+ // Проверка наличия мест для выбранного тарифа
+ $sql->query('SELECT `id` FROM `servers` WHERE `tarif`="'.$aData['tarif'].'" AND `test`="1" AND `time`>"'.$start_point.'" LIMIT '.$tarif['tests']);
+ if($sql->num() == $tarif['tests'])
+ sys::outjs(array('e' => 'Свободного места для тестового периода выбранного тарифа нет.'));
- $test = 1;
- }else
- // Проверка периода
- if(!$cfg['settlement_period'] AND !in_array($aData['time'], explode(':', $tarif['time'])))
- sys::outjs(array('e' => 'Переданные данные периода неверны.'));
+ $test = 1;
+ }else
+ // Проверка периода
+ if(!$cfg['settlement_period'] AND !in_array($aData['time'], explode(':', $tarif['time'])))
+ sys::outjs(array('e' => 'Переданные данные периода неверны.'));
- // Проверка слот
- if($aData['slots'] < $tarif['slots_min'] || $aData['slots'] > $tarif['slots_max'])
- sys::outjs(array('e' => 'Переданные данные слот неверны.'));
+ // Проверка слот
+ if($aData['slots'] < $tarif['slots_min'] || $aData['slots'] > $tarif['slots_max'])
+ sys::outjs(array('e' => 'Переданные данные слот неверны.'));
- // Определение суммы
- if($cfg['settlement_period'])
- {
- // Цена аренды за расчетный период
- $sum = games::define_sum($tarif['discount'], $tarif['price'], $aData['slots'], $start_point);
+ // Определение суммы
+ if($cfg['settlement_period'])
+ {
+ // Цена аренды за расчетный период
+ $sum = games::define_sum($tarif['discount'], $tarif['price'], $aData['slots'], $start_point);
- $aData['time'] = games::define_period('buy', params::$aDayMonth);
- }else
- $sum = games::define_sum($tarif['discount'], $tarif['price'], $aData['slots'], $aData['time']);
+ $aData['time'] = games::define_period('buy', params::$aDayMonth);
+ }else
+ $sum = games::define_sum($tarif['discount'], $tarif['price'], $aData['slots'], $aData['time']);
- // Проверка промо-кода
- $promo = games::define_promo(
- $aData['promo'],
- array(
- 'tarif' => $aData['tarif'],
- 'slots' => $aData['slots'],
- 'time' => $aData['time'],
- 'user' => $user['id']
- ),
- $tarif['discount'],
- $sum
- );
+ // Проверка промо-кода
+ $promo = games::define_promo(
+ $aData['promo'],
+ array(
+ 'tarif' => $aData['tarif'],
+ 'slots' => $aData['slots'],
+ 'time' => $aData['time'],
+ 'user' => $user['id']
+ ),
+ $tarif['discount'],
+ $sum
+ );
- $days = $aData['time']; // Кол-во дней аренды
+ $days = $aData['time']; // Кол-во дней аренды
- // Использование промо-кода
- if(is_array($promo))
- {
- if(array_key_exists('sum', $promo))
- $sum = $promo['sum'];
- else
- $days += $promo['days']; // Кол-во дней аренды с учетом подарочных (промо-код)
- }
+ // Использование промо-кода
+ if(is_array($promo))
+ {
+ if(array_key_exists('sum', $promo))
+ $sum = $promo['sum'];
+ else
+ $days += $promo['days']; // Кол-во дней аренды с учетом подарочных (промо-код)
+ }
- // Проверка баланса
- if($user['balance'] < $sum)
- sys::outjs(array('e' => 'У вас не хватает '.(round($sum-$user['balance'], 2)).' '.$cfg['currency']));
+ // Проверка баланса
+ if($user['balance'] < $sum)
+ sys::outjs(array('e' => 'У вас не хватает '.(round($sum-$user['balance'], 2)).' '.$cfg['currency']));
- // Выделенный адрес игрового сервера
- if(!empty($tarif['ip']))
- {
- $aIp = explode(':', $tarif['ip']);
+ // Выделенный адрес игрового сервера
+ if(!empty($tarif['ip']))
+ {
+ $aIp = explode(':', $tarif['ip']);
- $ip = false;
- $port = params::$aDefPort['mta'];
+ $ip = false;
+ $port = params::$aDefPort['mta'];
- // Проверка наличия свободного адреса
- foreach($aIp as $adr)
- {
- $adr = trim($adr);
+ // Проверка наличия свободного адреса
+ foreach($aIp as $adr)
+ {
+ $adr = trim($adr);
- $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `address` LIKE "'.$adr.':%" LIMIT 1');
- if(!$sql->num())
- {
- $ip = $adr;
+ $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `address` LIKE "'.$adr.':%" LIMIT 1');
+ if(!$sql->num())
+ {
+ $ip = $adr;
- break;
- }
- }
- }else{
- $ip = sys::first(explode(':', $unit['address']));
- $port = false;
+ break;
+ }
+ }
+ }else{
+ $ip = sys::first(explode(':', $unit['address']));
+ $port = false;
- // Проверка наличия свободного порта
- for($tarif['port_min']; $tarif['port_min'] <= $tarif['port_max']; $tarif['port_min']+=1)
- {
- $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND (`address`="'.$ip.':'.$tarif['port_min'].'" OR `port`="'.$tarif['port_min'].'") LIMIT 1');
- if(!$sql->num())
- {
- $port = $tarif['port_min'];
+ // Проверка наличия свободного порта
+ for($tarif['port_min']; $tarif['port_min'] <= $tarif['port_max']; $tarif['port_min']+=1)
+ {
+ $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND (`address`="'.$ip.':'.$tarif['port_min'].'" OR `port`="'.$tarif['port_min'].'") LIMIT 1');
+ if(!$sql->num())
+ {
+ $port = $tarif['port_min'];
- break;
- }
- }
- }
+ break;
+ }
+ }
+ }
- if(!$ip || !$port)
- {
- $sql->query('UPDATE `tarifs` set `show`="0" WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
+ if(!$ip || !$port)
+ {
+ $sql->query('UPDATE `tarifs` set `show`="0" WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
- sys::outjs(array('e' => 'К сожалению нет доступных мест, обратитесь в тех.поддержку.'));
- }
+ sys::outjs(array('e' => 'К сожалению нет доступных мест, обратитесь в тех.поддержку.'));
+ }
- if($test)
- $aData['time'] = games::time($start_point, $tarif['test']);
- else
- $aData['time'] = games::time($start_point, $days);
+ if($test)
+ $aData['time'] = games::time($start_point, $tarif['test']);
+ else
+ $aData['time'] = games::time($start_point, $days);
- $fix_one = 0;
- $core = 0;
+ $fix_one = 0;
+ $core = 0;
- if($tarif['core_fix'] != '')
- {
- $aCore = explode(',', $tarif['core_fix']);
+ if($tarif['core_fix'] != '')
+ {
+ $aCore = explode(',', $tarif['core_fix']);
- foreach($aCore as $cpu)
- {
- $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `tarif`="'.$aData['tarif'].'" AND `core_fix`="'.$cpu.'" AND `core_fix_one`="1" LIMIT 1');
+ foreach($aCore as $cpu)
+ {
+ $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `tarif`="'.$aData['tarif'].'" AND `core_fix`="'.$cpu.'" AND `core_fix_one`="1" LIMIT 1');
- if($sql->num())
- continue;
+ if($sql->num())
+ continue;
- $fix_one = 1;
- $core = $cpu;
+ $fix_one = 1;
+ $core = $cpu;
- break;
- }
+ break;
+ }
- if(!$core)
- {
- $sql->query('UPDATE `tarifs` set `show`="0" WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
+ if(!$core)
+ {
+ $sql->query('UPDATE `tarifs` set `show`="0" WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
- sys::outjs(array('e' => 'К сожалению нет доступных мест, обратитесь в тех.поддержку.'));
- }
- }
+ sys::outjs(array('e' => 'К сожалению нет доступных мест, обратитесь в тех.поддержку.'));
+ }
+ }
- $ram = $tarif['param_fix'] ? $aData['ram'] : $cfg['ram']['mta']*$aSDATA['slots'];
+ $ram = $tarif['param_fix'] ? $aData['ram'] : $cfg['ram']['mta']*$aSDATA['slots'];
- // Массив данных
- $aSDATA = array(
- 'unit' => $aData['unit'], // идентификатор локации
- 'tarif' => $aData['tarif'], // идентификатор тарифа
- 'ram' => $ram, // значение ram
- 'param_fix' => $tarif['param_fix'], // фиксированные параметры
- 'pack' => $aData['pack'], // Выбранная сборка для установки
- 'time' => $aData['time'], // Время аренды
- 'days' => $days, // Число дней
- 'sum' => $sum, // Сумма списания
- 'test' => $test, // тестовый период
- 'address' => $ip.':'.$port, // адрес игрового сервера
- 'port' => $port, // порт игрового сервера
- 'slots' => $aData['slots'], // Кол-во слот
- 'autostop' => $tarif['autostop'], // Выключение при 0 онлайне
- 'ftp' => $tarif['ftp'], // Использование ftp
- 'plugins' => $tarif['plugins'], // Использование плагинов
- 'console' => $tarif['console'], // Использование консоли
- 'stats' => $tarif['stats'], // Использование графиков (ведение статистики)
- 'copy' => $tarif['copy'], // Использование резервных копий
- 'web' => $tarif['web'], // Использование доп услуг
- 'plugins_install' => $tarif['plugins_install'], // Список установленных плагинов
- 'hdd' => $tarif['hdd'], // Дисковое пространство
- 'core_fix' => $core, // Выделенный поток
- 'core_fix_one' => $fix_one, // Выделенный поток
- 'promo' => $promo // Использование промо-кода
- );
+ // Массив данных
+ $aSDATA = array(
+ 'unit' => $aData['unit'], // идентификатор локации
+ 'tarif' => $aData['tarif'], // идентификатор тарифа
+ 'ram' => $ram, // значение ram
+ 'param_fix' => $tarif['param_fix'], // фиксированные параметры
+ 'pack' => $aData['pack'], // Выбранная сборка для установки
+ 'time' => $aData['time'], // Время аренды
+ 'days' => $days, // Число дней
+ 'sum' => $sum, // Сумма списания
+ 'test' => $test, // тестовый период
+ 'address' => $ip.':'.$port, // адрес игрового сервера
+ 'port' => $port, // порт игрового сервера
+ 'slots' => $aData['slots'], // Кол-во слот
+ 'autostop' => $tarif['autostop'], // Выключение при 0 онлайне
+ 'ftp' => $tarif['ftp'], // Использование ftp
+ 'plugins' => $tarif['plugins'], // Использование плагинов
+ 'console' => $tarif['console'], // Использование консоли
+ 'stats' => $tarif['stats'], // Использование графиков (ведение статистики)
+ 'copy' => $tarif['copy'], // Использование резервных копий
+ 'web' => $tarif['web'], // Использование доп услуг
+ 'plugins_install' => $tarif['plugins_install'], // Список установленных плагинов
+ 'hdd' => $tarif['hdd'], // Дисковое пространство
+ 'core_fix' => $core, // Выделенный поток
+ 'core_fix_one' => $fix_one, // Выделенный поток
+ 'promo' => $promo // Использование промо-кода
+ );
- return $aSDATA;
- }
+ return $aSDATA;
+ }
- public static function install($aSDATA = array())
- {
- global $cfg, $sql, $user, $start_point;
+ public static function install($aSDATA = array())
+ {
+ global $cfg, $sql, $user, $start_point;
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- // Массив данных локации (адрес,пароль)
- $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$aSDATA['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ // Массив данных локации (адрес,пароль)
+ $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$aSDATA['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- // Проверка ssh соединения с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- sys::outjs(array('e' => sys::text('error', 'ssh')));
+ // Проверка ssh соединения с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ sys::outjs(array('e' => sys::text('error', 'ssh')));
- // Массив данных тарифа (путь сборки,путь установки)
- $sql->query('SELECT `path`, `install`, `hostname` FROM `tarifs` WHERE `id`="'.$aSDATA['tarif'].'" LIMIT 1');
- $tarif = $sql->get();
+ // Массив данных тарифа (путь сборки,путь установки)
+ $sql->query('SELECT `path`, `install`, `hostname` FROM `tarifs` WHERE `id`="'.$aSDATA['tarif'].'" LIMIT 1');
+ $tarif = $sql->get();
- // Получение идентификаторов игрового сервера
- $sql->query('INSERT INTO `servers` set uid="1"');
- $id = $sql->id();
- $uid = $id+1000;
+ // Получение идентификаторов игрового сервера
+ $sql->query('INSERT INTO `servers` set uid="1"');
+ $id = $sql->id();
+ $uid = $id+1000;
- // Директория сборки
- $path = $tarif['path'].$aSDATA['pack'];
+ // Директория сборки
+ $path = $tarif['path'].$aSDATA['pack'];
- // Директория игрового сервера
- $install = $tarif['install'].$uid;
+ // Директория игрового сервера
+ $install = $tarif['install'].$uid;
- $ssh->set('mkdir '.$install.';' // Создание директории
- .'useradd -s /bin/false -d '.$install.' -g servers -u '.$uid.' server'.$uid.';' // Создание пользователя сервера на локации
- .'chown server'.$uid.':1000 '.$install.';' // Изменение владельца и группы директории
- .'cd '.$install.' && sudo -u server'.$uid.' screen -dmS i_'.$uid.' sh -c "cp -r '.$path.'/. .;' // Копирование файлов сборки для сервера
- .'find . -type d -exec chmod 700 {} \;;'
- .'find . -type f -exec chmod 777 {} \;;'
- .'chmod 500 '.params::$aFileGame[$server['mta']].'"');
+ $ssh->set('mkdir '.$install.';' // Создание директории
+ .'useradd -s /bin/false -d '.$install.' -g servers -u '.$uid.' server'.$uid.';' // Создание пользователя сервера на локации
+ .'chown server'.$uid.':1000 '.$install.';' // Изменение владельца и группы директории
+ .'cd '.$install.' && sudo -u server'.$uid.' screen -dmS i_'.$uid.' sh -c "cp -r '.$path.'/. .;' // Копирование файлов сборки для сервера
+ .'find . -type d -exec chmod 700 {} \;;'
+ .'find . -type f -exec chmod 777 {} \;;'
+ .'chmod 500 '.params::$aFileGame[$server['mta']].'"');
- // Запись данных нового сервера
- $sql->query('UPDATE `servers` set
- `uid`="'.$uid.'",
- `unit`="'.$aSDATA['unit'].'",
- `tarif`="'.$aSDATA['tarif'].'",
- `user`="'.$user['id'].'",
- `address`="'.$aSDATA['address'].'",
- `port`="'.$aSDATA['port'].'",
- `game`="mta",
- `slots`="'.$aSDATA['slots'].'",
- `slots_start`="'.$aSDATA['slots'].'",
- `status`="install",
- `name`="'.$tarif['hostname'].'",
- `pack`="'.$aSDATA['pack'].'",
- `plugins_use`="'.$aSDATA['plugins'].'",
- `ftp_use`="'.$aSDATA['ftp'].'",
- `console_use`="'.$aSDATA['console'].'",
- `stats_use`="'.$aSDATA['stats'].'",
- `copy_use`="'.$aSDATA['copy'].'",
- `web_use`="'.$aSDATA['web'].'",
- `vac`="1",
- `hdd`="'.$aSDATA['hdd'].'",
- `time`="'.$aSDATA['time'].'",
- `date`="'.$start_point.'",
- `test`="'.$aSDATA['test'].'",
- `ram`="'.$aSDATA['ram'].'",
- `core_fix`="'.$aSDATA['core_fix'].'",
- `core_fix_one`="'.$aSDATA['core_fix_one'].'",
- `autostop`="'.$aSDATA['autostop'].'" WHERE `id`="'.$id.'" LIMIT 1');
+ // Запись данных нового сервера
+ $sql->query('UPDATE `servers` set
+ `uid`="'.$uid.'",
+ `unit`="'.$aSDATA['unit'].'",
+ `tarif`="'.$aSDATA['tarif'].'",
+ `user`="'.$user['id'].'",
+ `address`="'.$aSDATA['address'].'",
+ `port`="'.$aSDATA['port'].'",
+ `game`="mta",
+ `slots`="'.$aSDATA['slots'].'",
+ `slots_start`="'.$aSDATA['slots'].'",
+ `status`="install",
+ `name`="'.$tarif['hostname'].'",
+ `pack`="'.$aSDATA['pack'].'",
+ `plugins_use`="'.$aSDATA['plugins'].'",
+ `ftp_use`="'.$aSDATA['ftp'].'",
+ `console_use`="'.$aSDATA['console'].'",
+ `stats_use`="'.$aSDATA['stats'].'",
+ `copy_use`="'.$aSDATA['copy'].'",
+ `web_use`="'.$aSDATA['web'].'",
+ `vac`="1",
+ `hdd`="'.$aSDATA['hdd'].'",
+ `time`="'.$aSDATA['time'].'",
+ `date`="'.$start_point.'",
+ `test`="'.$aSDATA['test'].'",
+ `ram`="'.$aSDATA['ram'].'",
+ `core_fix`="'.$aSDATA['core_fix'].'",
+ `core_fix_one`="'.$aSDATA['core_fix_one'].'",
+ `autostop`="'.$aSDATA['autostop'].'" WHERE `id`="'.$id.'" LIMIT 1');
- // Запись установленных плагинов
- if($aSDATA['plugins'])
- {
- // Массив идентификаторов плагинов
- $aPlugins = sys::b64djs($aSDATA['plugins_install']);
+ // Запись установленных плагинов
+ if($aSDATA['plugins'])
+ {
+ // Массив идентификаторов плагинов
+ $aPlugins = sys::b64djs($aSDATA['plugins_install']);
- if(isset($aPlugins[$aSDATA['pack']]))
- {
- $plugins = explode(',', $aPlugins[$aSDATA['pack']]);
+ if(isset($aPlugins[$aSDATA['pack']]))
+ {
+ $plugins = explode(',', $aPlugins[$aSDATA['pack']]);
- foreach($plugins as $plugin)
- if($plugin)
- $sql->query('INSERT INTO `plugins_install` set `server`="'.$id.'", `plugin`="'.$plugin.'", `time`="'.$start_point.'"');
- }
- }
+ foreach($plugins as $plugin)
+ if($plugin)
+ $sql->query('INSERT INTO `plugins_install` set `server`="'.$id.'", `plugin`="'.$plugin.'", `time`="'.$start_point.'"');
+ }
+ }
- // Списание средств с баланса пользователя
- $sql->query('UPDATE `users` set `balance`="'.($user['balance']-$aSDATA['sum']).'" WHERE `id`="'.$user['id'].'" LIMIT 1');
+ // Списание средств с баланса пользователя
+ $sql->query('UPDATE `users` set `balance`="'.($user['balance']-$aSDATA['sum']).'" WHERE `id`="'.$user['id'].'" LIMIT 1');
- // Запись получения тестового периода
- if($aSDATA['test'])
- {
- $sql->query('INSERT INTO `tests` set `server`="'.$id.'", `unit`="'.$aSDATA['unit'].'", `game`="mta", `user`="'.$user['id'].'", `time`="'.$start_point.'"');
- $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server_test'), array('id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="0"');
- }else{
- // Реф. система
- games::part($user['id'], $aSDATA['sum']);
+ // Запись получения тестового периода
+ if($aSDATA['test'])
+ {
+ $sql->query('INSERT INTO `tests` set `server`="'.$id.'", `unit`="'.$aSDATA['unit'].'", `game`="mta", `user`="'.$user['id'].'", `time`="'.$start_point.'"');
+ $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server_test'), array('id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="0"');
+ }else{
+ // Реф. система
+ games::part($user['id'], $aSDATA['sum']);
- // Запись логов
- if(!is_array($aSDATA['promo']))
- $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server'), array('days' => games::parse_day($aSDATA['days'], true), 'money' => $aSDATA['sum'], 'id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="'.$aSDATA['sum'].'"');
- else{
- $sql->query('UPDATE `servers` set `benefit`="'.$aSDATA['time'].'" WHERE `id`="'.$id.'" LIMIT 1');
- $sql->query('INSERT INTO `promo_use` set `promo`="'.$aSDATA['promo']['id'].'", `user`="'.$user['id'].'", `time`="'.$start_point.'"');
- $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server_promo'), array('days' => games::parse_day($aSDATA['days'], true), 'money' => $aSDATA['sum'], 'promo' => $aSDATA['promo']['cod'], 'id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="'.$aSDATA['sum'].'"');
- }
- }
+ // Запись логов
+ if(!is_array($aSDATA['promo']))
+ $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server'), array('days' => games::parse_day($aSDATA['days'], true), 'money' => $aSDATA['sum'], 'id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="'.$aSDATA['sum'].'"');
+ else{
+ $sql->query('UPDATE `servers` set `benefit`="'.$aSDATA['time'].'" WHERE `id`="'.$id.'" LIMIT 1');
+ $sql->query('INSERT INTO `promo_use` set `promo`="'.$aSDATA['promo']['id'].'", `user`="'.$user['id'].'", `time`="'.$start_point.'"');
+ $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server_promo'), array('days' => games::parse_day($aSDATA['days'], true), 'money' => $aSDATA['sum'], 'promo' => $aSDATA['promo']['cod'], 'id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="'.$aSDATA['sum'].'"');
+ }
+ }
- return $id;
- }
+ return $id;
+ }
}
?>
\ No newline at end of file
diff --git a/system/library/games/mta/tarif.php b/system/library/games/mta/tarif.php
index a65da45..b61e6a3 100644
--- a/system/library/games/mta/tarif.php
+++ b/system/library/games/mta/tarif.php
@@ -1,179 +1,179 @@
get('extend', 'sections/servers/games/tarif');
+ $html->get('extend', 'sections/servers/games/tarif');
- if(isset($html->arr['extend_address']))
- {
- $html->unit('extend_address', 1);
- $html->set('extend_address', $html->arr['extend_address']);
- }else
- $html->unit('extend_address');
+ if(isset($html->arr['extend_address']))
+ {
+ $html->unit('extend_address', 1);
+ $html->set('extend_address', $html->arr['extend_address']);
+ }else
+ $html->unit('extend_address');
- $html->set('id', $sid);
- $html->set('time', sys::date('min', $server['time']));
- $html->set('options', 'Выберете период продления '.$options);
- $html->set('slots', $server['slots']);
- $html->set('info', '');
- $html->set('tarif', $tarif_name);
- $html->set('cur', $cfg['currency']);
+ $html->set('id', $sid);
+ $html->set('time', sys::date('min', $server['time']));
+ $html->set('options', 'Выберете период продления '.$options);
+ $html->set('slots', $server['slots']);
+ $html->set('info', '');
+ $html->set('tarif', $tarif_name);
+ $html->set('cur', $cfg['currency']);
- $html->pack('main');
+ $html->pack('main');
- return NULL;
- }
+ return NULL;
+ }
public static function extend_sp($server, $tarif, $sid)
{
- global $cfg, $sql, $html, $start_point;
+ global $cfg, $sql, $html, $start_point;
- tarifs::extend_address($server['game'], $sid);
+ tarifs::extend_address($server['game'], $sid);
- $sum = $tarif['slots'] ? $tarif['price'] : $tarif['price']*$server['slots'];
+ $sum = $tarif['slots'] ? $tarif['price'] : $tarif['price']*$server['slots'];
- $html->get('extend_sp', 'sections/servers/games/tarif');
+ $html->get('extend_sp', 'sections/servers/games/tarif');
- if(isset($html->arr['extend_address']))
- {
- $html->unit('extend_address', 1);
- $html->set('extend_address', $html->arr['extend_address']);
- }else
- $html->unit('extend_address');
+ if(isset($html->arr['extend_address']))
+ {
+ $html->unit('extend_address', 1);
+ $html->set('extend_address', $html->arr['extend_address']);
+ }else
+ $html->unit('extend_address');
- $html->set('id', $sid);
- $html->set('time', sys::date('min', $server['time']));
- $html->set('date', $server['time'] > $start_point ? 'Сервер продлен до: '.date('d.m.Y', $server['time']) : 'Текущая дата: '.date('d.m.Y', $start_point));
- $html->set('options', 'Выберете период продления '.$options);
- $html->set('slots', $server['slots']);
- $html->set('info', '');
- $html->set('tarif', $tarif['name']);
- $html->set('sum', $sum);
- $html->set('cur', $cfg['currency']);
+ $html->set('id', $sid);
+ $html->set('time', sys::date('min', $server['time']));
+ $html->set('date', $server['time'] > $start_point ? 'Сервер продлен до: '.date('d.m.Y', $server['time']) : 'Текущая дата: '.date('d.m.Y', $start_point));
+ $html->set('options', 'Выберете период продления '.$options);
+ $html->set('slots', $server['slots']);
+ $html->set('info', '');
+ $html->set('tarif', $tarif['name']);
+ $html->set('sum', $sum);
+ $html->set('cur', $cfg['currency']);
- $html->pack('main');
+ $html->pack('main');
- return NULL;
- }
+ return NULL;
+ }
public static function plan()
{
- return NULL;
- }
+ return NULL;
+ }
- public static function unit($server, $unit_name, $tarif_name, $sid)
+ public static function unit($server, $unit_name, $tarif_name, $sid)
{
- global $cfg, $sql, $html;
+ global $cfg, $sql, $html;
- if(!$cfg['change_unit'][$server['game']])
- return NULL;
+ if(!$cfg['change_unit'][$server['game']])
+ return NULL;
- $tarifs = $sql->query('SELECT `unit` FROM `tarifs` WHERE `game`="'.$server['game'].'" AND `name`="'.$tarif_name.'" AND `id`!="'.$server['tarif'].'" AND `show`="1" ORDER BY `unit`');
- if(!$sql->num($tarifs))
- return NULL;
+ $tarifs = $sql->query('SELECT `unit` FROM `tarifs` WHERE `game`="'.$server['game'].'" AND `name`="'.$tarif_name.'" AND `id`!="'.$server['tarif'].'" AND `show`="1" ORDER BY `unit`');
+ if(!$sql->num($tarifs))
+ return NULL;
- $units = 0;
+ $units = 0;
- $options = 'Выберете новую локацию ';
+ $options = 'Выберете новую локацию ';
- while($tarif = $sql->get($tarifs))
- {
- $sql->query('SELECT `id`, `name` FROM `units` WHERE `id`="'.$tarif['unit'].'" AND `show`="1" LIMIT 1');
- if(!$sql->num())
- continue;
+ while($tarif = $sql->get($tarifs))
+ {
+ $sql->query('SELECT `id`, `name` FROM `units` WHERE `id`="'.$tarif['unit'].'" AND `show`="1" LIMIT 1');
+ if(!$sql->num())
+ continue;
- $unit = $sql->get();
+ $unit = $sql->get();
- $options .= ''.$unit['name'].' ';
+ $options .= ''.$unit['name'].' ';
- $units+=1;
- }
+ $units+=1;
+ }
- if(!$units)
- return NULL;
+ if(!$units)
+ return NULL;
- $html->get('unit', 'sections/servers/games/tarif');
+ $html->get('unit', 'sections/servers/games/tarif');
- $html->set('id', $sid);
- $html->set('options', $options);
- $html->set('slots', $server['slots']);
- $html->set('info', '');
- $html->set('unit', $unit_name);
- $html->set('tarif', $tarif_name);
+ $html->set('id', $sid);
+ $html->set('options', $options);
+ $html->set('slots', $server['slots']);
+ $html->set('info', '');
+ $html->set('unit', $unit_name);
+ $html->set('tarif', $tarif_name);
- $html->pack('main');
+ $html->pack('main');
- return NULL;
- }
+ return NULL;
+ }
- public static function unit_new($tarif, $unit, $server, $mcache)
- {
- global $ssh, $sql, $user, $start_point;
+ public static function unit_new($tarif, $unit, $server, $mcache)
+ {
+ global $ssh, $sql, $user, $start_point;
- // Проверка ssh соединения с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- sys::outjs(array('e' => sys::text('error', 'ssh')));
+ // Проверка ssh соединения с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ sys::outjs(array('e' => sys::text('error', 'ssh')));
- // Директория сборки
- $path = $tarif['path'].$tarif['pack'];
+ // Директория сборки
+ $path = $tarif['path'].$tarif['pack'];
- // Директория игрового сервера
- $install = $tarif['install'].$server['uid'];
+ // Директория игрового сервера
+ $install = $tarif['install'].$server['uid'];
- // Пользователь сервера
- $uS = 'server'.$server['uid'];
+ // Пользователь сервера
+ $uS = 'server'.$server['uid'];
- $ssh->set('mkdir '.$install.';' // Создание директории
- .'useradd -d '.$install.' -g servers -u '.$server['uid'].' '.$uS.';' // Создание пользователя сервера на локации
- .'chown '.$uS.':1000 '.$install.';' // Изменение владельца и группы директории
- .'cd '.$install.' && sudo -u '.$uS.' screen -dmS i_'.$server['uid'].' cp -r '.$path.'/. .'); // Копирование файлов сборки для сервера
+ $ssh->set('mkdir '.$install.';' // Создание директории
+ .'useradd -d '.$install.' -g servers -u '.$server['uid'].' '.$uS.';' // Создание пользователя сервера на локации
+ .'chown '.$uS.':1000 '.$install.';' // Изменение владельца и группы директории
+ .'cd '.$install.' && sudo -u '.$uS.' screen -dmS i_'.$server['uid'].' cp -r '.$path.'/. .'); // Копирование файлов сборки для сервера
- $address = explode(':', $server['address']);
+ $address = explode(':', $server['address']);
- $fix_one = $tarif['core_fix'] ? 1 : 0;
+ $fix_one = $tarif['core_fix'] ? 1 : 0;
- // Обновление данных нового сервера
- $sql->query('UPDATE `servers` set
- `unit`="'.$tarif['unit'].'",
- `tarif`="'.$tarif['id'].'",
- `address`="'.$server['address'].'",
- `port`="'.$address[1].'",
- `status`="install",
- `name`="'.$tarif['hostname'].'",
- `pack`="'.$tarif['pack'].'",
- `map_start`="'.$tarif['map'].'",
- `hdd`="'.$tarif['hdd'].'",
- `time`="'.$tarif['time'].'",
- `autostop`="'.$tarif['autostop'].'",
- `core_fix`="'.$tarif['core_fix'].'",
- `core_fix_one`="'.$fix_one.'",
- `reinstall`="'.$start_point.'" WHERE `id`="'.$server['id'].'" LIMIT 1');
+ // Обновление данных нового сервера
+ $sql->query('UPDATE `servers` set
+ `unit`="'.$tarif['unit'].'",
+ `tarif`="'.$tarif['id'].'",
+ `address`="'.$server['address'].'",
+ `port`="'.$address[1].'",
+ `status`="install",
+ `name`="'.$tarif['hostname'].'",
+ `pack`="'.$tarif['pack'].'",
+ `map_start`="'.$tarif['map'].'",
+ `hdd`="'.$tarif['hdd'].'",
+ `time`="'.$tarif['time'].'",
+ `autostop`="'.$tarif['autostop'].'",
+ `core_fix`="'.$tarif['core_fix'].'",
+ `core_fix_one`="'.$fix_one.'",
+ `reinstall`="'.$start_point.'" WHERE `id`="'.$server['id'].'" LIMIT 1');
- // Запись установленных плагинов
- if($tarif['plugins'])
- {
- // Массив идентификаторов плагинов
- $aPlugins = sys::b64js($tarif['plugins_install']);
+ // Запись установленных плагинов
+ if($tarif['plugins'])
+ {
+ // Массив идентификаторов плагинов
+ $aPlugins = sys::b64js($tarif['plugins_install']);
- if(isset($aPlugins[$tarif['pack']]))
- {
- $plugins = explode(',', $aPlugins[$tarif['pack']]);
+ if(isset($aPlugins[$tarif['pack']]))
+ {
+ $plugins = explode(',', $aPlugins[$tarif['pack']]);
- foreach($plugins as $plugin)
- if($plugin)
- $sql->query('INSERT INTO `plugins_install` set `server`="'.$server['id'].'", `plugin`="'.$plugin.'", `time`="'.$start_point.'"');
- }
- }
+ foreach($plugins as $plugin)
+ if($plugin)
+ $sql->query('INSERT INTO `plugins_install` set `server`="'.$server['id'].'", `plugin`="'.$plugin.'", `time`="'.$start_point.'"');
+ }
+ }
- return NULL;
- }
+ return NULL;
+ }
}
?>
\ No newline at end of file
diff --git a/system/library/games/plugins.php b/system/library/games/plugins.php
index cbfe1e5..414684f 100644
--- a/system/library/games/plugins.php
+++ b/system/library/games/plugins.php
@@ -1,181 +1,181 @@
arr['images']))
- unset($html->arr['images']);
+ if(isset($html->arr['images']))
+ unset($html->arr['images']);
- $aImg = explode("\n", $images);
+ $aImg = explode("\n", $images);
- foreach($aImg as $img)
- {
- $html->get('plugin_images', 'sections/servers/games/plugins');
+ foreach($aImg as $img)
+ {
+ $html->get('plugin_images', 'sections/servers/games/plugins');
- $html->set('id', $plugin);
- $html->set('img', $img);
+ $html->set('id', $plugin);
+ $html->set('img', $img);
- $html->pack('images');
- }
+ $html->pack('images');
+ }
- return isset($html->arr['images']) ? $html->arr['images'] : '';
- }
+ return isset($html->arr['images']) ? $html->arr['images'] : '';
+ }
- public static function status($status)
- {
- global $html;
+ public static function status($status)
+ {
+ global $html;
- if(!$status)
- {
- $html->unit('unstable');
- $html->unit('stable', 1);
- $html->unit('testing');
- }elseif($status == 2){
- $html->unit('unstable');
- $html->unit('stable');
- $html->unit('testing', 1);
- }else{
- $html->unit('unstable', 1);
- $html->unit('stable');
- $html->unit('testing');
- }
+ if(!$status)
+ {
+ $html->unit('unstable');
+ $html->unit('stable', 1);
+ $html->unit('testing');
+ }elseif($status == 2){
+ $html->unit('unstable');
+ $html->unit('stable');
+ $html->unit('testing', 1);
+ }else{
+ $html->unit('unstable', 1);
+ $html->unit('stable');
+ $html->unit('testing');
+ }
- return NULL;
- }
+ return NULL;
+ }
- public static function required($id, $required, $choice, $mcache)
- {
- global $sql;
+ public static function required($id, $required, $choice, $mcache)
+ {
+ global $sql;
- if($required == '')
- return NULL;
+ if($required == '')
+ return NULL;
- $aRequi = explode(':', $required);
+ $aRequi = explode(':', $required);
- foreach($aRequi as $pl)
- {
- $sql->query('SELECT `id` FROM `plugins_install` WHERE `server`="'.$id.'" AND `plugin`="'.$pl.'" LIMIT 1');
- if(!$sql->num())
- {
- $sql->query('SELECT `name` FROM `plugins` WHERE `id`="'.$pl.'" LIMIT 1');
- $plRequi = $sql->get();
+ foreach($aRequi as $pl)
+ {
+ $sql->query('SELECT `id` FROM `plugins_install` WHERE `server`="'.$id.'" AND `plugin`="'.$pl.'" LIMIT 1');
+ if(!$sql->num())
+ {
+ $sql->query('SELECT `name` FROM `plugins` WHERE `id`="'.$pl.'" LIMIT 1');
+ $plRequi = $sql->get();
- if($choice != '')
- {
- $aChoice = explode(' ', $choice);
+ if($choice != '')
+ {
+ $aChoice = explode(' ', $choice);
- foreach($aChoice as $plugins)
- {
- $aPlugins = explode(':', $plugins);
+ foreach($aChoice as $plugins)
+ {
+ $aPlugins = explode(':', $plugins);
- if(in_array($pl, $aPlugins))
- {
- $options = '';
- foreach($aPlugins as $plugin)
- {
- $sql->query('SELECT `name`, `upd` FROM `plugins` WHERE `id`="'.$plugin.'" LIMIT 1');
- $data = $sql->get();
+ if(in_array($pl, $aPlugins))
+ {
+ $options = '';
+ foreach($aPlugins as $plugin)
+ {
+ $sql->query('SELECT `name`, `upd` FROM `plugins` WHERE `id`="'.$plugin.'" LIMIT 1');
+ $data = $sql->get();
- if($data['upd'])
- {
- $sql->query('SELECT `name` FROM `plugins_update` WHERE `plugin`="'.$plugin.'" ORDER BY `id` DESC LIMIT 1');
- $data = $sql->get();
- }
+ if($data['upd'])
+ {
+ $sql->query('SELECT `name` FROM `plugins_update` WHERE `plugin`="'.$plugin.'" ORDER BY `id` DESC LIMIT 1');
+ $data = $sql->get();
+ }
- $options .= ''.strip_tags($data['name']).' ';
- }
+ $options .= ''.strip_tags($data['name']).' ';
+ }
- if($options != '')
- sys::outjs(array('e' => 'Для данного плагина требуется установка одного из родителя', 'required' => true, 'pid' => $pl, 'select' => $options), $mcache);
- }
- }
- }
+ if($options != '')
+ sys::outjs(array('e' => 'Для данного плагина требуется установка одного из родителя', 'required' => true, 'pid' => $pl, 'select' => $options), $mcache);
+ }
+ }
+ }
- sys::outjs(array('e' => 'Для данного плагина требуется установка родителя', 'required' => true, 'pid' => $pl, 'pname' => htmlspecialchars_decode($plRequi['name'])), $mcache);
- }
- }
+ sys::outjs(array('e' => 'Для данного плагина требуется установка родителя', 'required' => true, 'pid' => $pl, 'pname' => htmlspecialchars_decode($plRequi['name'])), $mcache);
+ }
+ }
- return NULL;
- }
+ return NULL;
+ }
- public static function incompatible($id, $incompatible, $mcache)
- {
- global $sql;
+ public static function incompatible($id, $incompatible, $mcache)
+ {
+ global $sql;
- if($incompatible == '')
- return NULL;
+ if($incompatible == '')
+ return NULL;
- $aIncomp = explode(':', $incompatible);
+ $aIncomp = explode(':', $incompatible);
- foreach($aIncomp as $pl)
- {
- $sql->query('SELECT `id` FROM `plugins_install` WHERE `server`="'.$id.'" AND `plugin`="'.$pl.'" LIMIT 1');
- if($sql->num())
- {
- $sql->query('SELECT `name` FROM `plugins` WHERE `id`="'.$pl.'" LIMIT 1');
- $plIncomp = $sql->get();
+ foreach($aIncomp as $pl)
+ {
+ $sql->query('SELECT `id` FROM `plugins_install` WHERE `server`="'.$id.'" AND `plugin`="'.$pl.'" LIMIT 1');
+ if($sql->num())
+ {
+ $sql->query('SELECT `name` FROM `plugins` WHERE `id`="'.$pl.'" LIMIT 1');
+ $plIncomp = $sql->get();
- sys::outjs(array('e' => 'Данный плагин несовместим с уже установленным плагином', 'pid' => $pl, 'pname' => htmlspecialchars_decode($plIncomp['name'])), $mcache);
- }
- }
+ sys::outjs(array('e' => 'Данный плагин несовместим с уже установленным плагином', 'pid' => $pl, 'pname' => htmlspecialchars_decode($plIncomp['name'])), $mcache);
+ }
+ }
- return NULL;
- }
+ return NULL;
+ }
- public static function clear($clear, $uid, $dir)
- {
- global $ssh;
+ public static function clear($clear, $uid, $dir)
+ {
+ global $ssh;
- // Если регулярное выражение
- if(isset($clear['regex']) AND $clear['regex'])
- {
- $file = preg_replace($clear['text'], '', $ssh->get('sudo -u server'.$uid.' cat '.$dir.$clear['file']));
+ // Если регулярное выражение
+ if(isset($clear['regex']) AND $clear['regex'])
+ {
+ $file = preg_replace($clear['text'], '', $ssh->get('sudo -u server'.$uid.' cat '.$dir.$clear['file']));
- // Временный файл
- $temp = sys::temp($file);
+ // Временный файл
+ $temp = sys::temp($file);
- $ssh->setfile($temp, $dir.$clear['file'], 0644);
+ $ssh->setfile($temp, $dir.$clear['file'], 0644);
- unlink($temp);
+ unlink($temp);
- $query = 'chown server'.$uid.':servers '.$dir.$clear['file'].';';
+ $query = 'chown server'.$uid.':servers '.$dir.$clear['file'].';';
- }else
- // Удаление текста из файла
- $query = 'sudo -u server'.$uid.' sed -i '."'s/".str_replace('/', '\/', htmlspecialchars_decode($clear['text']))."//g'".' '.$dir.$clear['file'].';';
+ }else
+ // Удаление текста из файла
+ $query = 'sudo -u server'.$uid.' sed -i '."'s/".str_replace('/', '\/', htmlspecialchars_decode($clear['text']))."//g'".' '.$dir.$clear['file'].';';
- $ssh->set($query.'sudo -u server'.$uid.' sed -i '."'/./!d'".' '.$dir.$clear['file']);
+ $ssh->set($query.'sudo -u server'.$uid.' sed -i '."'/./!d'".' '.$dir.$clear['file']);
- return NULL;
- }
+ return NULL;
+ }
- public static function write($write, $uid, $dir)
- {
- global $ssh;
+ public static function write($write, $uid, $dir)
+ {
+ global $ssh;
- // Костыль (добавить пустую строку на всякий случай)
- $query = 'sudo -u server'.$uid.' echo "" >> '.$dir.$write['file'].';';
+ // Костыль (добавить пустую строку на всякий случай)
+ $query = 'sudo -u server'.$uid.' echo "" >> '.$dir.$write['file'].';';
- // Исключить дублирование, путем удаления добавляемого текста
- $query .= 'sudo -u server'.$uid.' sed -i '."'s/".str_replace('/', '\/', htmlspecialchars_decode($write['text']))."//g'".' '.$dir.$write['file'].';';
+ // Исключить дублирование, путем удаления добавляемого текста
+ $query .= 'sudo -u server'.$uid.' sed -i '."'s/".str_replace('/', '\/', htmlspecialchars_decode($write['text']))."//g'".' '.$dir.$write['file'].';';
- // Добавление текста в начало файла
- if($write['top'])
- $query .= 'sudo -u server'.$uid.' touch '.$dir.$write['file'].'; sudo -u server'.$uid.' sed -i '."'1i ".str_replace(array('/', "'", '\"'), array('\/', "\'", '"'), htmlspecialchars_decode($write['text']))."'".' '.$dir.$write['file'].';';
- else
- // Добавление текста в конец файла
- $query .= 'sudo -u server'.$uid.' touch '.$dir.$write['file'].'; sudo -u server'.$uid.' echo "'.str_replace('"', '\"', htmlspecialchars_decode($write['text'])).'" >> '.$dir.$write['file'].';';
+ // Добавление текста в начало файла
+ if($write['top'])
+ $query .= 'sudo -u server'.$uid.' touch '.$dir.$write['file'].'; sudo -u server'.$uid.' sed -i '."'1i ".str_replace(array('/', "'", '\"'), array('\/', "\'", '"'), htmlspecialchars_decode($write['text']))."'".' '.$dir.$write['file'].';';
+ else
+ // Добавление текста в конец файла
+ $query .= 'sudo -u server'.$uid.' touch '.$dir.$write['file'].'; sudo -u server'.$uid.' echo "'.str_replace('"', '\"', htmlspecialchars_decode($write['text'])).'" >> '.$dir.$write['file'].';';
- $ssh->set($query.'sudo -u server'.$uid.' sed -i '."'/./!d'".' '.$dir.$clear['file']);
+ $ssh->set($query.'sudo -u server'.$uid.' sed -i '."'/./!d'".' '.$dir.$clear['file']);
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/games/query/BaseSocket.php b/system/library/games/query/BaseSocket.php
index 0e7cb0e..56e064c 100644
--- a/system/library/games/query/BaseSocket.php
+++ b/system/library/games/query/BaseSocket.php
@@ -1,98 +1,98 @@
Close();
- }
+ public function __destruct()
+ {
+ $this->Close();
+ }
- abstract public function Close();
- abstract public function Open($Address, $Port, $Timeout, $Engine);
- abstract public function Write($Header, $String = '');
- abstract public function Read($Length = 1400);
+ abstract public function Close();
+ abstract public function Open($Address, $Port, $Timeout, $Engine);
+ abstract public function Write($Header, $String = '');
+ abstract public function Read($Length = 1400);
- protected function ReadInternal($Buffer, $Length, $SherlockFunction)
- {
- if($Buffer->Remaining() === 0)
- return false;
+ protected function ReadInternal($Buffer, $Length, $SherlockFunction)
+ {
+ if($Buffer->Remaining() === 0)
+ return false;
- if($Buffer->Remaining() === 0)
- return false;
+ if($Buffer->Remaining() === 0)
+ return false;
- $Header = $Buffer->GetLong();
+ $Header = $Buffer->GetLong();
- if($Header === -2)
- {
- $Packets = [];
- $IsCompressed = false;
- $ReadMore = false;
+ if($Header === -2)
+ {
+ $Packets = [];
+ $IsCompressed = false;
+ $ReadMore = false;
- do
- {
- $RequestID = $Buffer->GetLong();
+ do
+ {
+ $RequestID = $Buffer->GetLong();
- switch($this->Engine)
- {
- case SourceQuery::GOLDSOURCE:
- {
- $PacketCountAndNumber = $Buffer->GetByte();
- $PacketCount = $PacketCountAndNumber & 0xF;
- $PacketNumber = $PacketCountAndNumber >> 4;
+ switch($this->Engine)
+ {
+ case SourceQuery::GOLDSOURCE:
+ {
+ $PacketCountAndNumber = $Buffer->GetByte();
+ $PacketCount = $PacketCountAndNumber & 0xF;
+ $PacketNumber = $PacketCountAndNumber >> 4;
- break;
- }
+ break;
+ }
- case SourceQuery::SOURCE:
- {
- $IsCompressed = ($RequestID & 0x80000000) !== 0;
- $PacketCount = $Buffer->GetByte();
- $PacketNumber = $Buffer->GetByte() + 1;
+ case SourceQuery::SOURCE:
+ {
+ $IsCompressed = ($RequestID & 0x80000000) !== 0;
+ $PacketCount = $Buffer->GetByte();
+ $PacketNumber = $Buffer->GetByte() + 1;
- if($IsCompressed)
- {
- $Buffer->GetLong();
-
- $PacketChecksum = $Buffer->GetUnsignedLong();
- }else
- $Buffer->GetShort();
+ if($IsCompressed)
+ {
+ $Buffer->GetLong();
+
+ $PacketChecksum = $Buffer->GetUnsignedLong();
+ }else
+ $Buffer->GetShort();
- break;
- }
- }
+ break;
+ }
+ }
- $Packets[$PacketNumber] = $Buffer->Get();
+ $Packets[$PacketNumber] = $Buffer->Get();
- $ReadMore = $PacketCount > sizeof($Packets);
- }
+ $ReadMore = $PacketCount > sizeof($Packets);
+ }
- while($ReadMore && $SherlockFunction($Buffer, $Length));
+ while($ReadMore && $SherlockFunction($Buffer, $Length));
- $Data = Implode($Packets);
+ $Data = Implode($Packets);
- if($IsCompressed)
- {
- if(!Function_Exists('bzdecompress'))
- return false;
+ if($IsCompressed)
+ {
+ if(!Function_Exists('bzdecompress'))
+ return false;
- $Data = bzdecompress($Data);
+ $Data = bzdecompress($Data);
- if(CRC32($Data) !== $PacketChecksum)
- return false;
- }
+ if(CRC32($Data) !== $PacketChecksum)
+ return false;
+ }
- $Buffer->Set(SubStr($Data, 4));
- }else
- return false;
+ $Buffer->Set(SubStr($Data, 4));
+ }else
+ return false;
- return $Buffer;
- }
- }
\ No newline at end of file
+ return $Buffer;
+ }
+ }
\ No newline at end of file
diff --git a/system/library/games/query/Buffer.php b/system/library/games/query/Buffer.php
index ae2e9d5..4145e1c 100644
--- a/system/library/games/query/Buffer.php
+++ b/system/library/games/query/Buffer.php
@@ -1,102 +1,102 @@
Buffer = $Buffer;
- $this->Length = StrLen($Buffer);
- $this->Position = 0;
- }
+ public function Set($Buffer)
+ {
+ $this->Buffer = $Buffer;
+ $this->Length = StrLen($Buffer);
+ $this->Position = 0;
+ }
- public function Remaining()
- {
- return $this->Length - $this->Position;
- }
+ public function Remaining()
+ {
+ return $this->Length - $this->Position;
+ }
- public function Get($Length = -1)
- {
- if($Length === 0)
- return '';
+ public function Get($Length = -1)
+ {
+ if($Length === 0)
+ return '';
- $Remaining = $this->Remaining();
+ $Remaining = $this->Remaining();
- if($Length === -1)
- $Length = $Remaining;
+ if($Length === -1)
+ $Length = $Remaining;
- else if($Length > $Remaining)
- return '';
+ else if($Length > $Remaining)
+ return '';
- $Data = SubStr($this->Buffer, $this->Position, $Length);
+ $Data = SubStr($this->Buffer, $this->Position, $Length);
- $this->Position += $Length;
+ $this->Position += $Length;
- return $Data;
- }
+ return $Data;
+ }
- public function GetByte()
- {
- return Ord($this->Get(1));
- }
+ public function GetByte()
+ {
+ return Ord($this->Get(1));
+ }
- public function GetShort()
- {
- if($this->Remaining() < 2)
- return false;
+ public function GetShort()
+ {
+ if($this->Remaining() < 2)
+ return false;
- $Data = UnPack('v', $this->Get(2));
+ $Data = UnPack('v', $this->Get(2));
- return $Data[ 1 ];
- }
+ return $Data[ 1 ];
+ }
- public function GetLong()
- {
- if($this->Remaining() < 4)
- return false;
+ public function GetLong()
+ {
+ if($this->Remaining() < 4)
+ return false;
- $Data = UnPack('l', $this->Get(4));
+ $Data = UnPack('l', $this->Get(4));
- return $Data[ 1 ];
- }
+ return $Data[ 1 ];
+ }
- public function GetFloat()
- {
- if($this->Remaining() < 4)
- return false;
+ public function GetFloat()
+ {
+ if($this->Remaining() < 4)
+ return false;
- $Data = UnPack('f', $this->Get(4));
+ $Data = UnPack('f', $this->Get(4));
- return $Data[ 1 ];
- }
+ return $Data[ 1 ];
+ }
- public function GetUnsignedLong()
- {
- if($this->Remaining() < 4)
- return false;
+ public function GetUnsignedLong()
+ {
+ if($this->Remaining() < 4)
+ return false;
- $Data = UnPack('V', $this->Get(4));
+ $Data = UnPack('V', $this->Get(4));
- return $Data[ 1 ];
- }
+ return $Data[ 1 ];
+ }
- public function GetString()
- {
- $ZeroBytePosition = StrPos($this->Buffer, "\0", $this->Position);
+ public function GetString()
+ {
+ $ZeroBytePosition = StrPos($this->Buffer, "\0", $this->Position);
- if($ZeroBytePosition === false)
- return '';
+ if($ZeroBytePosition === false)
+ return '';
- $String = $this->Get($ZeroBytePosition - $this->Position);
+ $String = $this->Get($ZeroBytePosition - $this->Position);
- $this->Position++;
+ $this->Position++;
- return $String;
- }
- }
\ No newline at end of file
+ return $String;
+ }
+ }
\ No newline at end of file
diff --git a/system/library/games/query/GoldSourceRcon.php b/system/library/games/query/GoldSourceRcon.php
index 3e2f466..5abcd4d 100644
--- a/system/library/games/query/GoldSourceRcon.php
+++ b/system/library/games/query/GoldSourceRcon.php
@@ -1,105 +1,105 @@
Socket = $Socket;
- }
+ public function __construct($Socket)
+ {
+ $this->Socket = $Socket;
+ }
- public function Close()
- {
- $this->RconChallenge = 0;
- $this->RconRequestId = 0;
- $this->RconPassword = 0;
- }
+ public function Close()
+ {
+ $this->RconChallenge = 0;
+ $this->RconRequestId = 0;
+ $this->RconPassword = 0;
+ }
- public function Open()
- {
- //
- }
+ public function Open()
+ {
+ //
+ }
- public function Write($Header, $String = '')
- {
- $Command = Pack('cccca*', 0xFF, 0xFF, 0xFF, 0xFF, $String);
- $Length = StrLen($Command);
+ public function Write($Header, $String = '')
+ {
+ $Command = Pack('cccca*', 0xFF, 0xFF, 0xFF, 0xFF, $String);
+ $Length = StrLen($Command);
- return $Length === FWrite($this->Socket->Socket, $Command, $Length);
- }
+ return $Length === FWrite($this->Socket->Socket, $Command, $Length);
+ }
- public function Read($Length = 1400)
- {
- $Buffer = $this->Socket->Read();
+ public function Read($Length = 1400)
+ {
+ $Buffer = $this->Socket->Read();
- $StringBuffer = '';
- $ReadMore = false;
+ $StringBuffer = '';
+ $ReadMore = false;
- do
- {
- $ReadMore = $Buffer->Remaining() > 0;
+ do
+ {
+ $ReadMore = $Buffer->Remaining() > 0;
- if($ReadMore)
- {
- if($Buffer->GetByte() !== SourceQuery::S2A_RCON)
- sys::outjs(array('e' => 'неправильный rcon запрос.'));
+ if($ReadMore)
+ {
+ if($Buffer->GetByte() !== SourceQuery::S2A_RCON)
+ sys::outjs(array('e' => 'неправильный rcon запрос.'));
- $Packet = $Buffer->Get();
- $StringBuffer .= $Packet;
+ $Packet = $Buffer->Get();
+ $StringBuffer .= $Packet;
- $ReadMore = StrLen($Packet) > 1000;
+ $ReadMore = StrLen($Packet) > 1000;
- if($ReadMore)
- $Buffer = $this->Socket->Read();
- }
- }
+ if($ReadMore)
+ $Buffer = $this->Socket->Read();
+ }
+ }
- while($ReadMore);
+ while($ReadMore);
- $Trimmed = trim($StringBuffer);
+ $Trimmed = trim($StringBuffer);
- if($Trimmed === 'Bad rcon_password.')
- sys::outjs(array('e' => 'rcon_password из server.cfg не подходит.'));
+ if($Trimmed === 'Bad rcon_password.')
+ sys::outjs(array('e' => 'rcon_password из server.cfg не подходит.'));
- else if($Trimmed === 'You have been banned from this server.')
- sys::outjs(array('e' => 'Игровой сервер заблокировал доступ.'));
+ else if($Trimmed === 'You have been banned from this server.')
+ sys::outjs(array('e' => 'Игровой сервер заблокировал доступ.'));
- $Buffer->Set($Trimmed);
+ $Buffer->Set($Trimmed);
- return $Buffer;
- }
+ return $Buffer;
+ }
- public function Command($Command)
- {
- if(!$this->RconChallenge)
- return false;
+ public function Command($Command)
+ {
+ if(!$this->RconChallenge)
+ return false;
- $this->Write(0, 'rcon ' . $this->RconChallenge . ' "' . $this->RconPassword . '" ' . $Command . "\0");
- $Buffer = $this->Read();
+ $this->Write(0, 'rcon ' . $this->RconChallenge . ' "' . $this->RconPassword . '" ' . $Command . "\0");
+ $Buffer = $this->Read();
- if($Buffer)
- return $Buffer->Get();
+ if($Buffer)
+ return $Buffer->Get();
- return $Buffer;
- }
+ return $Buffer;
+ }
- public function Authorize($Password)
- {
- $this->RconPassword = $Password;
+ public function Authorize($Password)
+ {
+ $this->RconPassword = $Password;
- $this->Write(0, 'challenge rcon');
- $Buffer = $this->Socket->Read();
+ $this->Write(0, 'challenge rcon');
+ $Buffer = $this->Socket->Read();
- if($Buffer->Get(14) !== 'challenge rcon')
- sys::outjs(array('e' => 'Не удалось выполнить rcon запрос.'));
+ if($Buffer->Get(14) !== 'challenge rcon')
+ sys::outjs(array('e' => 'Не удалось выполнить rcon запрос.'));
- $this->RconChallenge = Trim($Buffer->Get());
- }
- }
\ No newline at end of file
+ $this->RconChallenge = Trim($Buffer->Get());
+ }
+ }
\ No newline at end of file
diff --git a/system/library/games/query/McQuery.php b/system/library/games/query/McQuery.php
index 2615d2c..c98b365 100644
--- a/system/library/games/query/McQuery.php
+++ b/system/library/games/query/McQuery.php
@@ -1,96 +1,96 @@
stack = fsockopen('udp://'.$ip, $port, $errorNum, $errorString, 2);
+ public function __construct($ip, $port = 25565)
+ {
+ $this->stack = fsockopen('udp://'.$ip, $port, $errorNum, $errorString, 2);
- socket_set_timeout($this->stack, 2);
- }
+ socket_set_timeout($this->stack, 2);
+ }
- public function getInfo($pl = false)
- {
- $Data = $this->WriteData(0x00, $this->GetChallenge().Pack('c*', 0x00, 0x00, 0x00, 0x00));
+ public function getInfo($pl = false)
+ {
+ $Data = $this->WriteData(0x00, $this->GetChallenge().Pack('c*', 0x00, 0x00, 0x00, 0x00));
- $server_info = array();
-
- $Data = substr($Data, 11);
- $Data = explode("\x00\x00\x01player_\x00\x00", $Data);
- $aData = explode("\x00", $Data[0]);
+ $server_info = array();
+
+ $Data = substr($Data, 11);
+ $Data = explode("\x00\x00\x01player_\x00\x00", $Data);
+ $aData = explode("\x00", $Data[0]);
- $last = '';
+ $last = '';
- $keys = Array(
- 'hostname' => 'hostname',
- 'version' => 'version',
- 'plugins' => 'plugins',
- 'map' => 'map',
- 'numplayers' => 'online'
- );
+ $keys = Array(
+ 'hostname' => 'hostname',
+ 'version' => 'version',
+ 'plugins' => 'plugins',
+ 'map' => 'map',
+ 'numplayers' => 'online'
+ );
- foreach($aData as $index => $val)
- {
- if(~$index & 1)
- {
- if(!array_key_exists($val, $keys))
- {
- $last = false;
- continue;
- }
+ foreach($aData as $index => $val)
+ {
+ if(~$index & 1)
+ {
+ if(!array_key_exists($val, $keys))
+ {
+ $last = false;
+ continue;
+ }
- $last = $keys[$val];
- $server_info[$last] = '';
+ $last = $keys[$val];
+ $server_info[$last] = '';
- }elseif($last != false)
- $server_info[$last] = $val;
- }
+ }elseif($last != false)
+ $server_info[$last] = $val;
+ }
- if(!count($server_info))
- return NULL;
+ if(!count($server_info))
+ return NULL;
- if(!$pl)
- return $server_info;
+ if(!$pl)
+ return $server_info;
- $server_info['players_list'] = explode("\x00", substr($Data[1], 0, -2));
+ $server_info['players_list'] = explode("\x00", substr($Data[1], 0, -2));
- if(!isset($server_info['players_list'][1]))
- $server_info['players_list'] = array();
+ if(!isset($server_info['players_list'][1]))
+ $server_info['players_list'] = array();
- return $server_info;
- }
+ return $server_info;
+ }
- private function GetChallenge()
- {
- $Data = $this->WriteData(0x09);
-
- if($Data === false)
- return NULL;
+ private function GetChallenge()
+ {
+ $Data = $this->WriteData(0x09);
+
+ if($Data === false)
+ return NULL;
- return Pack('N', $Data);
- }
+ return Pack('N', $Data);
+ }
- private function WriteData($Command, $Append = '')
- {
- $Command = Pack('c*', 0xFE, 0xFD, $Command, 0x01, 0x02, 0x03, 0x04).$Append;
- $Length = StrLen($Command);
-
- if($Length !== fwrite($this->stack, $Command, $Length))
- return NULL;
-
- $Data = fread($this->stack, 2048);
-
- if($Data === false)
- return NULL;
-
- if(StrLen($Data) < 5 || $Data[0] != $Command[2])
- return false;
+ private function WriteData($Command, $Append = '')
+ {
+ $Command = Pack('c*', 0xFE, 0xFD, $Command, 0x01, 0x02, 0x03, 0x04).$Append;
+ $Length = StrLen($Command);
+
+ if($Length !== fwrite($this->stack, $Command, $Length))
+ return NULL;
+
+ $Data = fread($this->stack, 2048);
+
+ if($Data === false)
+ return NULL;
+
+ if(StrLen($Data) < 5 || $Data[0] != $Command[2])
+ return false;
- return SubStr($Data, 5);
- }
- }
+ return SubStr($Data, 5);
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/games/query/MtaQuery.php b/system/library/games/query/MtaQuery.php
index e86cdb0..e48e540 100644
--- a/system/library/games/query/MtaQuery.php
+++ b/system/library/games/query/MtaQuery.php
@@ -1,93 +1,93 @@
stack = fsockopen('udp://'.$ip, $port+123, $errorNum, $errorString, 2);
+ public function __construct($ip, $port = 22003)
+ {
+ $this->stack = fsockopen('udp://'.$ip, $port+123, $errorNum, $errorString, 2);
- socket_set_timeout($this->stack, 2);
- }
+ socket_set_timeout($this->stack, 2);
+ }
- public function getInfo($pl = false)
- {
- fwrite($this->stack, 's');
+ public function getInfo($pl = false)
+ {
+ fwrite($this->stack, 's');
- $buffer = fread($this->stack, 4096);
+ $buffer = fread($this->stack, 4096);
- if(!$buffer)
- return NULL;
+ if(!$buffer)
+ return NULL;
- $buffer = substr($buffer, 4);
+ $buffer = substr($buffer, 4);
- $server_info = array();
+ $server_info = array();
- $server_info['gamename'] = $this->cut_pascal($buffer, 1, -1);
- $server_info['hostport'] = $this->cut_pascal($buffer, 1, -1);
- $server_info['hostname'] = $this->cut_pascal($buffer, 1, -1);
- $server_info['gamemode'] = $this->cut_pascal($buffer, 1, -1);
- $server_info['map'] = $this->cut_pascal($buffer, 1, -1);
- $server_info['version'] = $this->cut_pascal($buffer, 1, -1);
- $server_info['password'] = $this->cut_pascal($buffer, 1, -1);
- $server_info['players'] = $this->cut_pascal($buffer, 1, -1);
- $server_info['playersmax'] = $this->cut_pascal($buffer, 1, -1);
+ $server_info['gamename'] = $this->cut_pascal($buffer, 1, -1);
+ $server_info['hostport'] = $this->cut_pascal($buffer, 1, -1);
+ $server_info['hostname'] = $this->cut_pascal($buffer, 1, -1);
+ $server_info['gamemode'] = $this->cut_pascal($buffer, 1, -1);
+ $server_info['map'] = $this->cut_pascal($buffer, 1, -1);
+ $server_info['version'] = $this->cut_pascal($buffer, 1, -1);
+ $server_info['password'] = $this->cut_pascal($buffer, 1, -1);
+ $server_info['players'] = $this->cut_pascal($buffer, 1, -1);
+ $server_info['playersmax'] = $this->cut_pascal($buffer, 1, -1);
- while($buffer && $buffer[0] != "\x01")
- {
- $item_key = strtolower($this->cut_pascal($buffer, 1, -1));
- $item_value = $this->cut_pascal($buffer, 1, -1);
+ while($buffer && $buffer[0] != "\x01")
+ {
+ $item_key = strtolower($this->cut_pascal($buffer, 1, -1));
+ $item_value = $this->cut_pascal($buffer, 1, -1);
- $server_info[$item_key] = $item_value;
- }
+ $server_info[$item_key] = $item_value;
+ }
- if(!$pl)
- return $server_info;
+ if(!$pl)
+ return $server_info;
- $buffer = substr($buffer, 1);
+ $buffer = substr($buffer, 1);
- $i = 1;
+ $i = 1;
- while($buffer)
- {
- $bit_flags = $this->cut_byte($buffer, 1);
+ while($buffer)
+ {
+ $bit_flags = $this->cut_byte($buffer, 1);
- $field_list = array('name', '', '', '', 'ping', '');
+ $field_list = array('name', '', '', '', 'ping', '');
- foreach($field_list as $item_key)
- {
- $item_value = $this->cut_pascal($buffer, 1, -1);
+ foreach($field_list as $item_key)
+ {
+ $item_value = $this->cut_pascal($buffer, 1, -1);
- if(!$item_key)
- continue;
+ if(!$item_key)
+ continue;
- $server_info['players_list'][$i][$item_key] = $item_value;
- }
+ $server_info['players_list'][$i][$item_key] = $item_value;
+ }
- $i+=1;
- }
+ $i+=1;
+ }
- return $server_info;
- }
+ return $server_info;
+ }
- private function cut_pascal(&$buffer, $start_byte = 1, $length_adjust = 0, $end_byte = 0)
- {
- $length = ord(substr($buffer, 0, $start_byte)) + $length_adjust;
- $string = substr($buffer, $start_byte, $length);
- $buffer = substr($buffer, $start_byte + $length + $end_byte);
+ private function cut_pascal(&$buffer, $start_byte = 1, $length_adjust = 0, $end_byte = 0)
+ {
+ $length = ord(substr($buffer, 0, $start_byte)) + $length_adjust;
+ $string = substr($buffer, $start_byte, $length);
+ $buffer = substr($buffer, $start_byte + $length + $end_byte);
- return $string;
- }
+ return $string;
+ }
- private function cut_byte(&$buffer, $length)
- {
- $string = substr($buffer, 0, $length);
- $buffer = substr($buffer, $length);
+ private function cut_byte(&$buffer, $length)
+ {
+ $string = substr($buffer, 0, $length);
+ $buffer = substr($buffer, $length);
- return $string;
- }
- }
+ return $string;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/games/query/SampQuery.php b/system/library/games/query/SampQuery.php
index 5b6a2ba..2b18ae2 100644
--- a/system/library/games/query/SampQuery.php
+++ b/system/library/games/query/SampQuery.php
@@ -1,122 +1,122 @@
stack = fsockopen('udp://'.$ip, $port, $errorNum, $errorString, 2);
+ public function __construct($ip, $port = 7777)
+ {
+ $this->stack = fsockopen('udp://'.$ip, $port, $errorNum, $errorString, 2);
- socket_set_timeout($this->stack, 2);
- }
+ socket_set_timeout($this->stack, 2);
+ }
- public function getInfo()
- {
- @fwrite($this->stack, $this->assemblePacket('i'));
+ public function getInfo()
+ {
+ @fwrite($this->stack, $this->assemblePacket('i'));
- fread($this->stack, 11);
+ fread($this->stack, 11);
- $serverInfo = array();
+ $serverInfo = array();
- $serverInfo['password'] = sys::int(ord(fread($this->stack, 1)));
+ $serverInfo['password'] = sys::int(ord(fread($this->stack, 1)));
- $serverInfo['players'] = sys::int($this->toInt(fread($this->stack, 2)));
+ $serverInfo['players'] = sys::int($this->toInt(fread($this->stack, 2)));
- $serverInfo['maxplayers'] = sys::int($this->toInt(fread($this->stack, 2)));
+ $serverInfo['maxplayers'] = sys::int($this->toInt(fread($this->stack, 2)));
- $strLen = ord(fread($this->stack, 4));
+ $strLen = ord(fread($this->stack, 4));
- if(!$strLen)
- return -1;
+ if(!$strLen)
+ return -1;
- $serverInfo['hostname'] = fread($this->stack, $strLen);
+ $serverInfo['hostname'] = fread($this->stack, $strLen);
- $strLen = ord(fread($this->stack, 4));
- $serverInfo['gamemode'] = fread($this->stack, $strLen);
+ $strLen = ord(fread($this->stack, 4));
+ $serverInfo['gamemode'] = fread($this->stack, $strLen);
- $strLen = ord(fread($this->stack, 4));
- $serverInfo['map'] = fread($this->stack, $strLen);
+ $strLen = ord(fread($this->stack, 4));
+ $serverInfo['map'] = fread($this->stack, $strLen);
- return $serverInfo;
- }
+ return $serverInfo;
+ }
- public function getDetailedPlayers()
- {
- @fwrite($this->stack, $this->assemblePacket('d'));
- fread($this->stack, 11);
+ public function getDetailedPlayers()
+ {
+ @fwrite($this->stack, $this->assemblePacket('d'));
+ fread($this->stack, 11);
- $playerCount = ord(fread($this->stack, 2));
- $players = array();
+ $playerCount = ord(fread($this->stack, 2));
+ $players = array();
- for($i = 0; $i < $playerCount; ++$i)
- {
- $player['playerid'] = ord(fread($this->stack, 1));
+ for($i = 0; $i < $playerCount; ++$i)
+ {
+ $player['playerid'] = ord(fread($this->stack, 1));
- $strLen = ord(fread($this->stack, 1));
- $player['nickname'] = fread($this->stack, $strLen);
+ $strLen = ord(fread($this->stack, 1));
+ $player['nickname'] = fread($this->stack, $strLen);
- $player['ping'] = $this->toInt(fread($this->stack, 4));
+ $player['ping'] = $this->toInt(fread($this->stack, 4));
- $players[$i] = $player;
+ $players[$i] = $player;
- unset($player);
- }
+ unset($player);
+ }
- return $players;
- }
+ return $players;
+ }
- private function toInt($string)
- {
- if($string === '')
- return null;
+ private function toInt($string)
+ {
+ if($string === '')
+ return null;
- $int = 0;
- $int += (ord($string[0]));
+ $int = 0;
+ $int += (ord($string[0]));
- if(isset($string[1]))
- $int += (ord($string[1]) << 8);
+ if(isset($string[1]))
+ $int += (ord($string[1]) << 8);
- if(isset($string[2]))
- $int += (ord($string[2]) << 16);
+ if(isset($string[2]))
+ $int += (ord($string[2]) << 16);
- if(isset($string[3]))
- $int += (ord($string[3]) << 24);
+ if(isset($string[3]))
+ $int += (ord($string[3]) << 24);
- if($int >= 4294967294)
- $int -= 4294967296;
+ if($int >= 4294967294)
+ $int -= 4294967296;
- return $int;
- }
+ return $int;
+ }
- private function assemblePacket($type)
- {
- $packet = 'SAMP';
- $packet .= chr(strtok($this->server, '.'));
- $packet .= chr(strtok('.'));
- $packet .= chr(strtok('.'));
- $packet .= chr(strtok('.'));
- $packet .= chr($this->port & 0xFF);
- $packet .= chr($this->port >> 8 & 0xFF);
- $packet .= $type;
+ private function assemblePacket($type)
+ {
+ $packet = 'SAMP';
+ $packet .= chr(strtok($this->server, '.'));
+ $packet .= chr(strtok('.'));
+ $packet .= chr(strtok('.'));
+ $packet .= chr(strtok('.'));
+ $packet .= chr($this->port & 0xFF);
+ $packet .= chr($this->port >> 8 & 0xFF);
+ $packet .= $type;
- return $packet;
- }
+ return $packet;
+ }
- public function connect()
- {
- $connected = false;
- fwrite($this->stack, $this->assemblePacket('p0101'));
+ public function connect()
+ {
+ $connected = false;
+ fwrite($this->stack, $this->assemblePacket('p0101'));
- if(fread($this->stack, 10))
- {
- if(fread($this->stack, 5) == 'p0101')
- $connected = true;
- }
+ if(fread($this->stack, 10))
+ {
+ if(fread($this->stack, 5) == 'p0101')
+ $connected = true;
+ }
- return $connected;
- }
- }
+ return $connected;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/games/query/Socket.php b/system/library/games/query/Socket.php
index ffe1444..7ebb8a9 100644
--- a/system/library/games/query/Socket.php
+++ b/system/library/games/query/Socket.php
@@ -1,62 +1,62 @@
Socket)
- {
- FClose($this->Socket);
+ class Socket extends BaseSocket
+ {
+ public function Close()
+ {
+ if($this->Socket)
+ {
+ FClose($this->Socket);
- $this->Socket = null;
- }
- }
+ $this->Socket = null;
+ }
+ }
- public function Open($Address, $Port, $Timeout, $Engine)
- {
- $this->Timeout = $Timeout;
- $this->Engine = $Engine;
- $this->Port = $Port;
- $this->Address = $Address;
+ public function Open($Address, $Port, $Timeout, $Engine)
+ {
+ $this->Timeout = $Timeout;
+ $this->Engine = $Engine;
+ $this->Port = $Port;
+ $this->Address = $Address;
- $this->Socket = @FSockOpen('udp://' . $Address, $Port, $ErrNo, $ErrStr, $Timeout);
+ $this->Socket = @FSockOpen('udp://' . $Address, $Port, $ErrNo, $ErrStr, $Timeout);
- if($ErrNo || $this->Socket === false)
- return false;
+ if($ErrNo || $this->Socket === false)
+ return false;
- Stream_Set_Timeout($this->Socket, $Timeout);
- Stream_Set_Blocking($this->Socket, true);
- }
+ Stream_Set_Timeout($this->Socket, $Timeout);
+ Stream_Set_Blocking($this->Socket, true);
+ }
- public function Write($Header, $String = '')
- {
- $Command = Pack('ccccca*', 0xFF, 0xFF, 0xFF, 0xFF, $Header, $String);
- $Length = StrLen($Command);
+ public function Write($Header, $String = '')
+ {
+ $Command = Pack('ccccca*', 0xFF, 0xFF, 0xFF, 0xFF, $Header, $String);
+ $Length = StrLen($Command);
- return $Length === FWrite($this->Socket, $Command, $Length);
- }
+ return $Length === FWrite($this->Socket, $Command, $Length);
+ }
- public function Read($Length = 1400)
- {
- $Buffer = new Buffer();
- $Buffer->Set(FRead($this->Socket, $Length));
+ public function Read($Length = 1400)
+ {
+ $Buffer = new Buffer();
+ $Buffer->Set(FRead($this->Socket, $Length));
- $this->ReadInternal($Buffer, $Length, [$this, 'Sherlock']);
+ $this->ReadInternal($Buffer, $Length, [$this, 'Sherlock']);
- return $Buffer;
- }
+ return $Buffer;
+ }
- public function Sherlock($Buffer, $Length)
- {
- $Data = FRead($this->Socket, $Length);
+ public function Sherlock($Buffer, $Length)
+ {
+ $Data = FRead($this->Socket, $Length);
- if(StrLen($Data) < 4)
- return false;
+ if(StrLen($Data) < 4)
+ return false;
- $Buffer->Set($Data);
+ $Buffer->Set($Data);
- return $Buffer->GetLong() === -2;
- }
- }
\ No newline at end of file
+ return $Buffer->GetLong() === -2;
+ }
+ }
\ No newline at end of file
diff --git a/system/library/games/query/SourceQuery.php b/system/library/games/query/SourceQuery.php
index 69f5685..bef4292 100644
--- a/system/library/games/query/SourceQuery.php
+++ b/system/library/games/query/SourceQuery.php
@@ -1,347 +1,347 @@
Socket = $Socket ?: new Socket();
- }
-
- public function __destruct()
- {
- $this->Disconnect();
- }
-
- public function Connect($Address, $Port, $Timeout = 3, $Engine = self::SOURCE)
- {
- $this->Disconnect();
-
- if(!is_int($Timeout) || $Timeout < 0)
- return false;
-
- $this->Socket->Open($Address, (int)$Port, $Timeout, (int)$Engine);
-
- $this->Connected = true;
- }
-
- public function SetUseOldGetChallengeMethod($Value)
- {
- $Previous = $this->UseOldGetChallengeMethod;
-
- $this->UseOldGetChallengeMethod = $Value === true;
-
- return $Previous;
- }
-
- public function Disconnect()
- {
- $this->Connected = false;
- $this->Challenge = 0;
-
- $this->Socket->Close();
-
- if($this->Rcon)
- {
- $this->Rcon->Close();
-
- $this->Rcon = null;
- }
- }
-
- public function Ping()
- {
- if(!$this->Connected)
- return false;
-
- $this->Socket->Write(self::A2S_PING);
- $Buffer = $this->Socket->Read();
-
- return $Buffer->GetByte() === self::S2A_PING;
- }
-
- public function GetInfo()
- {
- if(!$this->Connected)
- return false;
-
- $this->Socket->Write(self::A2S_INFO, "Source Engine Query\0");
- $Buffer = $this->Socket->Read();
-
- $Type = $Buffer->GetByte();
-
- if($Type === self::S2A_INFO_OLD && $this->Socket->Engine === self::GOLDSOURCE)
- {
- $Server['Address'] = $Buffer->GetString();
- $Server['HostName'] = $Buffer->GetString();
- $Server['Map'] = $Buffer->GetString();
- $Server['ModDir'] = $Buffer->GetString();
- $Server['ModDesc'] = $Buffer->GetString();
- $Server['Players'] = $Buffer->GetByte();
- $Server['MaxPlayers'] = $Buffer->GetByte();
- $Server['Protocol'] = $Buffer->GetByte();
- $Server['Dedicated'] = Chr($Buffer->GetByte());
- $Server['Os'] = Chr($Buffer->GetByte());
- $Server['Password'] = $Buffer->GetByte() === 1;
- $Server['IsMod'] = $Buffer->GetByte() === 1;
-
- if($Server['IsMod'])
- {
- $Mod['Url'] = $Buffer->GetString();
- $Mod['Download'] = $Buffer->GetString();
- $Buffer->Get(1);
- $Mod['Version'] = $Buffer->GetLong();
- $Mod['Size'] = $Buffer->GetLong();
- $Mod['ServerSide'] = $Buffer->GetByte() === 1;
- $Mod['CustomDLL'] = $Buffer->GetByte() === 1;
- }
-
- $Server['Secure'] = $Buffer->GetByte() === 1;
- $Server['Bots'] = $Buffer->GetByte();
-
- if(isset($Mod))
- $Server['Mod'] = $Mod;
-
- return $Server;
- }
-
- if($Type !== self::S2A_INFO)
- return false;
-
- if($Type !== self::S2A_INFO)
- return false;
-
- $Server['Protocol'] = $Buffer->GetByte();
- $Server['HostName'] = $Buffer->GetString();
- $Server['Map'] = $Buffer->GetString();
- $Server['ModDir'] = $Buffer->GetString();
- $Server['ModDesc'] = $Buffer->GetString();
- $Server['AppID'] = $Buffer->GetShort();
- $Server['Players'] = $Buffer->GetByte();
- $Server['MaxPlayers'] = $Buffer->GetByte();
- $Server['Bots'] = $Buffer->GetByte();
- $Server['Dedicated'] = Chr($Buffer->GetByte());
- $Server['Os'] = Chr($Buffer->GetByte());
- $Server['Password'] = $Buffer->GetByte() === 1;
- $Server['Secure'] = $Buffer->GetByte() === 1;
-
- if($Server['AppID'] === 2400)
- {
- $Server['GameMode'] = $Buffer->GetByte();
- $Server['WitnessCount'] = $Buffer->GetByte();
- $Server['WitnessTime'] = $Buffer->GetByte();
- }
-
- $Server['Version'] = $Buffer->GetString();
-
- if($Buffer->Remaining() > 0)
- {
- $Server['ExtraDataFlags'] = $Flags = $Buffer->GetByte();
-
- if($Flags & 0x80)
- $Server['GamePort'] = $Buffer->GetShort();
-
- if($Flags & 0x10)
- {
- $SteamIDLower = $Buffer->GetUnsignedLong();
- $SteamIDInstance = $Buffer->GetUnsignedLong();
- $SteamID = 0;
-
- if(PHP_INT_SIZE === 4)
- {
- if(extension_loaded('gmp'))
- {
- $SteamIDLower = gmp_abs($SteamIDLower);
- $SteamIDInstance = gmp_abs($SteamIDInstance);
- $SteamID = gmp_strval(gmp_or($SteamIDLower, gmp_mul($SteamIDInstance, gmp_pow(2, 32))));
- }else
- return false;
- }else
- $SteamID = $SteamIDLower | ($SteamIDInstance << 32);
-
- $Server['SteamID'] = $SteamID;
-
- unset($SteamIDLower, $SteamIDInstance, $SteamID);
- }
-
- if($Flags & 0x40)
- {
- $Server['SpecPort'] = $Buffer->GetShort();
- $Server['SpecName'] = $Buffer->GetString();
- }
-
- if($Flags & 0x20)
- $Server['GameTags'] = $Buffer->GetString();
-
- if($Flags & 0x01)
- $Server['GameID'] = $Buffer->GetUnsignedLong() | ($Buffer->GetUnsignedLong() << 32);
-
- if($Buffer->Remaining() > 0)
- return false;
- }
-
- return $Server;
- }
-
- public function GetPlayers()
- {
- if(!$this->Connected)
- return false;
-
- $this->GetChallenge(self::A2S_PLAYER, self::S2A_PLAYER);
-
- $this->Socket->Write(self::A2S_PLAYER, $this->Challenge);
- $Buffer = $this->Socket->Read(14000);
- $Type = $Buffer->GetByte();
-
- if($Type !== self::S2A_PLAYER)
- return false;
-
- $Players = [];
- $Count = $Buffer->GetByte();
-
- while($Count-- > 0 && $Buffer->Remaining() > 0)
- {
- $Player['Id'] = $Buffer->GetByte();
- $Player['Name'] = $Buffer->GetString();
- $Player['Frags'] = $Buffer->GetLong();
- $Player['Time'] = (int)$Buffer->GetFloat();
- $Player['TimeF'] = GMDate(($Player['Time'] > 3600 ? "H:i:s" : "i:s"), $Player['Time']);
-
- $Players[] = $Player;
- }
-
- return $Players;
- }
-
- public function GetRules()
- {
- if(!$this->Connected)
- return false;
-
- $this->GetChallenge(self::A2S_RULES, self::S2A_RULES);
- $this->Socket->Write(self::A2S_RULES, $this->Challenge);
- $Buffer = $this->Socket->Read();
- $Type = $Buffer->GetByte();
-
- if($Type !== self::S2A_RULES)
- return false;
-
- $Rules = [];
- $Count = $Buffer->GetShort();
-
- while($Count-- > 0 && $Buffer->Remaining() > 0)
- {
- $Rule = $Buffer->GetString();
- $Value = $Buffer->GetString();
-
- if(!empty($Rule))
- $Rules[$Rule] = $Value;
- }
-
- return $Rules;
- }
-
- private function GetChallenge($Header, $ExpectedResult)
- {
- if($this->Challenge)
- return;
-
- if($this->UseOldGetChallengeMethod)
- $Header = self::A2S_SERVERQUERY_GETCHALLENGE;
-
- $this->Socket->Write($Header, "\xFF\xFF\xFF\xFF");
- $Buffer = $this->Socket->Read();
- $Type = $Buffer->GetByte();
-
- switch($Type)
- {
- case self::S2A_CHALLENGE:
- {
- $this->Challenge = $Buffer->Get(4);
-
- return;
- }
- case $ExpectedResult:
- {
- return;
- }
- case 0:
- {
- return;
- }
- default:
- {
- return;
- }
- }
- }
-
- public function SetRconPassword($Password)
- {
- if(!$this->Connected)
- {
- return false;
- }
-
- switch($this->Socket->Engine)
- {
- case SourceQuery::GOLDSOURCE:
- {
- $this->Rcon = new GoldSourceRcon($this->Socket);
-
- break;
- }
- case SourceQuery::SOURCE:
- {
- $this->Rcon = new SourceRcon($this->Socket);
-
- break;
- }
- }
-
- $this->Rcon->Open();
- $this->Rcon->Authorize($Password);
- }
-
- public function Rcon($Command)
- {
- if(!$this->Connected)
- {
- return false;
- }
-
- if($this->Rcon === null)
- {
- return false;
- }
-
- return $this->Rcon->Command($Command);
- }
- }
\ No newline at end of file
+ if(!DEFINED('EGP'))
+ exit(header('Refresh: 0; URL=http://'.$_SERVER['SERVER_NAME'].'/404'));
+
+ class SourceQuery
+ {
+ const GOLDSOURCE = 0;
+ const SOURCE = 1;
+ const A2S_PING = 0x69;
+ const A2S_INFO = 0x54;
+ const A2S_PLAYER = 0x55;
+ const A2S_RULES = 0x56;
+ const A2S_SERVERQUERY_GETCHALLENGE = 0x57;
+ const S2A_PING = 0x6A;
+ const S2A_CHALLENGE = 0x41;
+ const S2A_INFO = 0x49;
+ const S2A_INFO_OLD = 0x6D;
+ const S2A_PLAYER = 0x44;
+ const S2A_RULES = 0x45;
+ const S2A_RCON = 0x6C;
+ const SERVERDATA_EXECCOMMAND = 2;
+ const SERVERDATA_AUTH = 3;
+ const SERVERDATA_RESPONSE_VALUE = 0;
+ const SERVERDATA_AUTH_RESPONSE = 2;
+
+ private $Rcon;
+ private $Socket;
+ private $Connected;
+ private $Challenge;
+ private $UseOldGetChallengeMethod;
+
+ public function __construct(BaseSocket $Socket = null)
+ {
+ $this->Socket = $Socket ?: new Socket();
+ }
+
+ public function __destruct()
+ {
+ $this->Disconnect();
+ }
+
+ public function Connect($Address, $Port, $Timeout = 3, $Engine = self::SOURCE)
+ {
+ $this->Disconnect();
+
+ if(!is_int($Timeout) || $Timeout < 0)
+ return false;
+
+ $this->Socket->Open($Address, (int)$Port, $Timeout, (int)$Engine);
+
+ $this->Connected = true;
+ }
+
+ public function SetUseOldGetChallengeMethod($Value)
+ {
+ $Previous = $this->UseOldGetChallengeMethod;
+
+ $this->UseOldGetChallengeMethod = $Value === true;
+
+ return $Previous;
+ }
+
+ public function Disconnect()
+ {
+ $this->Connected = false;
+ $this->Challenge = 0;
+
+ $this->Socket->Close();
+
+ if($this->Rcon)
+ {
+ $this->Rcon->Close();
+
+ $this->Rcon = null;
+ }
+ }
+
+ public function Ping()
+ {
+ if(!$this->Connected)
+ return false;
+
+ $this->Socket->Write(self::A2S_PING);
+ $Buffer = $this->Socket->Read();
+
+ return $Buffer->GetByte() === self::S2A_PING;
+ }
+
+ public function GetInfo()
+ {
+ if(!$this->Connected)
+ return false;
+
+ $this->Socket->Write(self::A2S_INFO, "Source Engine Query\0");
+ $Buffer = $this->Socket->Read();
+
+ $Type = $Buffer->GetByte();
+
+ if($Type === self::S2A_INFO_OLD && $this->Socket->Engine === self::GOLDSOURCE)
+ {
+ $Server['Address'] = $Buffer->GetString();
+ $Server['HostName'] = $Buffer->GetString();
+ $Server['Map'] = $Buffer->GetString();
+ $Server['ModDir'] = $Buffer->GetString();
+ $Server['ModDesc'] = $Buffer->GetString();
+ $Server['Players'] = $Buffer->GetByte();
+ $Server['MaxPlayers'] = $Buffer->GetByte();
+ $Server['Protocol'] = $Buffer->GetByte();
+ $Server['Dedicated'] = Chr($Buffer->GetByte());
+ $Server['Os'] = Chr($Buffer->GetByte());
+ $Server['Password'] = $Buffer->GetByte() === 1;
+ $Server['IsMod'] = $Buffer->GetByte() === 1;
+
+ if($Server['IsMod'])
+ {
+ $Mod['Url'] = $Buffer->GetString();
+ $Mod['Download'] = $Buffer->GetString();
+ $Buffer->Get(1);
+ $Mod['Version'] = $Buffer->GetLong();
+ $Mod['Size'] = $Buffer->GetLong();
+ $Mod['ServerSide'] = $Buffer->GetByte() === 1;
+ $Mod['CustomDLL'] = $Buffer->GetByte() === 1;
+ }
+
+ $Server['Secure'] = $Buffer->GetByte() === 1;
+ $Server['Bots'] = $Buffer->GetByte();
+
+ if(isset($Mod))
+ $Server['Mod'] = $Mod;
+
+ return $Server;
+ }
+
+ if($Type !== self::S2A_INFO)
+ return false;
+
+ if($Type !== self::S2A_INFO)
+ return false;
+
+ $Server['Protocol'] = $Buffer->GetByte();
+ $Server['HostName'] = $Buffer->GetString();
+ $Server['Map'] = $Buffer->GetString();
+ $Server['ModDir'] = $Buffer->GetString();
+ $Server['ModDesc'] = $Buffer->GetString();
+ $Server['AppID'] = $Buffer->GetShort();
+ $Server['Players'] = $Buffer->GetByte();
+ $Server['MaxPlayers'] = $Buffer->GetByte();
+ $Server['Bots'] = $Buffer->GetByte();
+ $Server['Dedicated'] = Chr($Buffer->GetByte());
+ $Server['Os'] = Chr($Buffer->GetByte());
+ $Server['Password'] = $Buffer->GetByte() === 1;
+ $Server['Secure'] = $Buffer->GetByte() === 1;
+
+ if($Server['AppID'] === 2400)
+ {
+ $Server['GameMode'] = $Buffer->GetByte();
+ $Server['WitnessCount'] = $Buffer->GetByte();
+ $Server['WitnessTime'] = $Buffer->GetByte();
+ }
+
+ $Server['Version'] = $Buffer->GetString();
+
+ if($Buffer->Remaining() > 0)
+ {
+ $Server['ExtraDataFlags'] = $Flags = $Buffer->GetByte();
+
+ if($Flags & 0x80)
+ $Server['GamePort'] = $Buffer->GetShort();
+
+ if($Flags & 0x10)
+ {
+ $SteamIDLower = $Buffer->GetUnsignedLong();
+ $SteamIDInstance = $Buffer->GetUnsignedLong();
+ $SteamID = 0;
+
+ if(PHP_INT_SIZE === 4)
+ {
+ if(extension_loaded('gmp'))
+ {
+ $SteamIDLower = gmp_abs($SteamIDLower);
+ $SteamIDInstance = gmp_abs($SteamIDInstance);
+ $SteamID = gmp_strval(gmp_or($SteamIDLower, gmp_mul($SteamIDInstance, gmp_pow(2, 32))));
+ }else
+ return false;
+ }else
+ $SteamID = $SteamIDLower | ($SteamIDInstance << 32);
+
+ $Server['SteamID'] = $SteamID;
+
+ unset($SteamIDLower, $SteamIDInstance, $SteamID);
+ }
+
+ if($Flags & 0x40)
+ {
+ $Server['SpecPort'] = $Buffer->GetShort();
+ $Server['SpecName'] = $Buffer->GetString();
+ }
+
+ if($Flags & 0x20)
+ $Server['GameTags'] = $Buffer->GetString();
+
+ if($Flags & 0x01)
+ $Server['GameID'] = $Buffer->GetUnsignedLong() | ($Buffer->GetUnsignedLong() << 32);
+
+ if($Buffer->Remaining() > 0)
+ return false;
+ }
+
+ return $Server;
+ }
+
+ public function GetPlayers()
+ {
+ if(!$this->Connected)
+ return false;
+
+ $this->GetChallenge(self::A2S_PLAYER, self::S2A_PLAYER);
+
+ $this->Socket->Write(self::A2S_PLAYER, $this->Challenge);
+ $Buffer = $this->Socket->Read(14000);
+ $Type = $Buffer->GetByte();
+
+ if($Type !== self::S2A_PLAYER)
+ return false;
+
+ $Players = [];
+ $Count = $Buffer->GetByte();
+
+ while($Count-- > 0 && $Buffer->Remaining() > 0)
+ {
+ $Player['Id'] = $Buffer->GetByte();
+ $Player['Name'] = $Buffer->GetString();
+ $Player['Frags'] = $Buffer->GetLong();
+ $Player['Time'] = (int)$Buffer->GetFloat();
+ $Player['TimeF'] = GMDate(($Player['Time'] > 3600 ? "H:i:s" : "i:s"), $Player['Time']);
+
+ $Players[] = $Player;
+ }
+
+ return $Players;
+ }
+
+ public function GetRules()
+ {
+ if(!$this->Connected)
+ return false;
+
+ $this->GetChallenge(self::A2S_RULES, self::S2A_RULES);
+ $this->Socket->Write(self::A2S_RULES, $this->Challenge);
+ $Buffer = $this->Socket->Read();
+ $Type = $Buffer->GetByte();
+
+ if($Type !== self::S2A_RULES)
+ return false;
+
+ $Rules = [];
+ $Count = $Buffer->GetShort();
+
+ while($Count-- > 0 && $Buffer->Remaining() > 0)
+ {
+ $Rule = $Buffer->GetString();
+ $Value = $Buffer->GetString();
+
+ if(!empty($Rule))
+ $Rules[$Rule] = $Value;
+ }
+
+ return $Rules;
+ }
+
+ private function GetChallenge($Header, $ExpectedResult)
+ {
+ if($this->Challenge)
+ return;
+
+ if($this->UseOldGetChallengeMethod)
+ $Header = self::A2S_SERVERQUERY_GETCHALLENGE;
+
+ $this->Socket->Write($Header, "\xFF\xFF\xFF\xFF");
+ $Buffer = $this->Socket->Read();
+ $Type = $Buffer->GetByte();
+
+ switch($Type)
+ {
+ case self::S2A_CHALLENGE:
+ {
+ $this->Challenge = $Buffer->Get(4);
+
+ return;
+ }
+ case $ExpectedResult:
+ {
+ return;
+ }
+ case 0:
+ {
+ return;
+ }
+ default:
+ {
+ return;
+ }
+ }
+ }
+
+ public function SetRconPassword($Password)
+ {
+ if(!$this->Connected)
+ {
+ return false;
+ }
+
+ switch($this->Socket->Engine)
+ {
+ case SourceQuery::GOLDSOURCE:
+ {
+ $this->Rcon = new GoldSourceRcon($this->Socket);
+
+ break;
+ }
+ case SourceQuery::SOURCE:
+ {
+ $this->Rcon = new SourceRcon($this->Socket);
+
+ break;
+ }
+ }
+
+ $this->Rcon->Open();
+ $this->Rcon->Authorize($Password);
+ }
+
+ public function Rcon($Command)
+ {
+ if(!$this->Connected)
+ {
+ return false;
+ }
+
+ if($this->Rcon === null)
+ {
+ return false;
+ }
+
+ return $this->Rcon->Command($Command);
+ }
+ }
\ No newline at end of file
diff --git a/system/library/games/query/SourceRcon.php b/system/library/games/query/SourceRcon.php
index 76ac507..378aaeb 100644
--- a/system/library/games/query/SourceRcon.php
+++ b/system/library/games/query/SourceRcon.php
@@ -1,148 +1,148 @@
Socket = $Socket;
- }
+ public function __construct($Socket)
+ {
+ $this->Socket = $Socket;
+ }
- public function Close()
- {
- if($this->RconSocket)
- {
- FClose($this->RconSocket);
+ public function Close()
+ {
+ if($this->RconSocket)
+ {
+ FClose($this->RconSocket);
- $this->RconSocket = null;
- }
+ $this->RconSocket = null;
+ }
- $this->RconRequestId = 0;
- }
+ $this->RconRequestId = 0;
+ }
- public function Open()
- {
- if(!$this->RconSocket)
- {
- $this->RconSocket = @FSockOpen($this->Socket->Address, $this->Socket->Port, $ErrNo, $ErrStr, $this->Socket->Timeout);
+ public function Open()
+ {
+ if(!$this->RconSocket)
+ {
+ $this->RconSocket = @FSockOpen($this->Socket->Address, $this->Socket->Port, $ErrNo, $ErrStr, $this->Socket->Timeout);
- if($ErrNo || !$this->RconSocket)
- return false;
+ if($ErrNo || !$this->RconSocket)
+ return false;
- Stream_Set_Timeout($this->RconSocket, $this->Socket->Timeout);
- Stream_Set_Blocking($this->RconSocket, true);
- }
- }
+ Stream_Set_Timeout($this->RconSocket, $this->Socket->Timeout);
+ Stream_Set_Blocking($this->RconSocket, true);
+ }
+ }
- public function Write($Header, $String = '')
- {
- $Command = Pack('VV', ++$this->RconRequestId, $Header) . $String . "\x00\x00";
- $Command = Pack('V', StrLen($Command)) . $Command;
- $Length = StrLen($Command);
+ public function Write($Header, $String = '')
+ {
+ $Command = Pack('VV', ++$this->RconRequestId, $Header) . $String . "\x00\x00";
+ $Command = Pack('V', StrLen($Command)) . $Command;
+ $Length = StrLen($Command);
- return $Length === FWrite($this->RconSocket, $Command, $Length);
- }
+ return $Length === FWrite($this->RconSocket, $Command, $Length);
+ }
- public function Read()
- {
- $Buffer = new Buffer();
- $Buffer->Set(FRead($this->RconSocket, 4));
+ public function Read()
+ {
+ $Buffer = new Buffer();
+ $Buffer->Set(FRead($this->RconSocket, 4));
- if($Buffer->Remaining() < 4)
- return false;
+ if($Buffer->Remaining() < 4)
+ return false;
- $PacketSize = $Buffer->GetLong();
+ $PacketSize = $Buffer->GetLong();
- $Buffer->Set(FRead($this->RconSocket, $PacketSize));
+ $Buffer->Set(FRead($this->RconSocket, $PacketSize));
- $Data = $Buffer->Get();
+ $Data = $Buffer->Get();
- $Remaining = $PacketSize - StrLen($Data);
+ $Remaining = $PacketSize - StrLen($Data);
- while($Remaining > 0)
- {
- $Data2 = FRead($this->RconSocket, $Remaining);
+ while($Remaining > 0)
+ {
+ $Data2 = FRead($this->RconSocket, $Remaining);
- $PacketSize = StrLen($Data2);
+ $PacketSize = StrLen($Data2);
- if($PacketSize === 0)
- return false;
+ if($PacketSize === 0)
+ return false;
- $Data .= $Data2;
- $Remaining -= $PacketSize;
- }
+ $Data .= $Data2;
+ $Remaining -= $PacketSize;
+ }
- $Buffer->Set($Data);
+ $Buffer->Set($Data);
- return $Buffer;
- }
+ return $Buffer;
+ }
- public function Command($Command)
- {
- $this->Write(SourceQuery::SERVERDATA_EXECCOMMAND, $Command);
- $Buffer = $this->Read();
+ public function Command($Command)
+ {
+ $this->Write(SourceQuery::SERVERDATA_EXECCOMMAND, $Command);
+ $Buffer = $this->Read();
- $Buffer->GetLong();
+ $Buffer->GetLong();
- $Type = $Buffer->GetLong();
+ $Type = $Buffer->GetLong();
- if($Type === SourceQuery::SERVERDATA_AUTH_RESPONSE)
- return false;
+ if($Type === SourceQuery::SERVERDATA_AUTH_RESPONSE)
+ return false;
- if($Type !== SourceQuery::SERVERDATA_RESPONSE_VALUE)
- return false;
+ if($Type !== SourceQuery::SERVERDATA_RESPONSE_VALUE)
+ return false;
- $Data = $Buffer->Get();
+ $Data = $Buffer->Get();
- if(StrLen($Data) >= 4000)
- {
- do
- {
- $this->Write(SourceQuery::SERVERDATA_RESPONSE_VALUE);
+ if(StrLen($Data) >= 4000)
+ {
+ do
+ {
+ $this->Write(SourceQuery::SERVERDATA_RESPONSE_VALUE);
- $Buffer = $this->Read();
+ $Buffer = $this->Read();
- $Buffer->GetLong();
+ $Buffer->GetLong();
- if($Buffer->GetLong() !== SourceQuery::SERVERDATA_RESPONSE_VALUE)
- break;
+ if($Buffer->GetLong() !== SourceQuery::SERVERDATA_RESPONSE_VALUE)
+ break;
- $Data2 = $Buffer->Get();
+ $Data2 = $Buffer->Get();
- if($Data2 === "\x00\x01\x00\x00\x00\x00")
- break;
+ if($Data2 === "\x00\x01\x00\x00\x00\x00")
+ break;
- $Data .= $Data2;
- }
+ $Data .= $Data2;
+ }
- while(true);
- }
+ while(true);
+ }
- return rtrim($Data, "\0");
- }
+ return rtrim($Data, "\0");
+ }
- public function Authorize($Password)
- {
- $this->Write(SourceQuery::SERVERDATA_AUTH, $Password);
- $Buffer = $this->Read();
+ public function Authorize($Password)
+ {
+ $this->Write(SourceQuery::SERVERDATA_AUTH, $Password);
+ $Buffer = $this->Read();
- $RequestID = $Buffer->GetLong();
- $Type = $Buffer->GetLong();
+ $RequestID = $Buffer->GetLong();
+ $Type = $Buffer->GetLong();
- if($Type === SourceQuery::SERVERDATA_RESPONSE_VALUE)
- {
- $Buffer = $this->Read();
+ if($Type === SourceQuery::SERVERDATA_RESPONSE_VALUE)
+ {
+ $Buffer = $this->Read();
- $RequestID = $Buffer->GetLong();
- $Type = $Buffer->GetLong();
- }
+ $RequestID = $Buffer->GetLong();
+ $Type = $Buffer->GetLong();
+ }
- if($RequestID === -1 || $Type !== SourceQuery::SERVERDATA_AUTH_RESPONSE)
- return false;
- }
- }
\ No newline at end of file
+ if($RequestID === -1 || $Type !== SourceQuery::SERVERDATA_AUTH_RESPONSE)
+ return false;
+ }
+ }
\ No newline at end of file
diff --git a/system/library/games/samp/action.php b/system/library/games/samp/action.php
index 6d96f64..6a327b4 100644
--- a/system/library/games/samp/action.php
+++ b/system/library/games/samp/action.php
@@ -1,129 +1,129 @@
query('SELECT `uid`, `unit`, `tarif`, `game`, `address`, `slots_start`, `name`, `map_start`, `time_start`, `core_fix` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `uid`, `unit`, `tarif`, `game`, `address`, `slots_start`, `name`, `map_start`, `time_start`, `core_fix` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
+ $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
$tarif = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- // Проверка ssh соедниения пу с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return array('e' => sys::text('error', 'ssh'));
+ // Проверка ssh соедниения пу с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return array('e' => sys::text('error', 'ssh'));
- list($ip, $port) = explode(':', $server['address']);
+ list($ip, $port) = explode(':', $server['address']);
- // Убить процессы
- $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
- .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe;');
+ // Убить процессы
+ $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
+ .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe;');
- // Временный файл
- $temp = sys::temp(action::config($ip, $port, $server['slots_start'], $ssh->get('cat '.$tarif['install'].'/'.$server['uid'].'/server.cfg')));
+ // Временный файл
+ $temp = sys::temp(action::config($ip, $port, $server['slots_start'], $ssh->get('cat '.$tarif['install'].'/'.$server['uid'].'/server.cfg')));
- // Обновление файла server.cfg
- $ssh->setfile($temp, $tarif['install'].$server['uid'].'/server.cfg', 0644);
+ // Обновление файла server.cfg
+ $ssh->setfile($temp, $tarif['install'].$server['uid'].'/server.cfg', 0644);
- unlink($temp);
+ unlink($temp);
- $taskset = '';
+ $taskset = '';
- // Если включена система автораспределения и не установлен фиксированный поток
- if($cfg['cpu_route'] AND !$server['core_fix'])
- {
- $proc_stat = array();
+ // Если включена система автораспределения и не установлен фиксированный поток
+ if($cfg['cpu_route'] AND !$server['core_fix'])
+ {
+ $proc_stat = array();
- $proc_stat[0] = $ssh->get('cat /proc/stat');
- }
+ $proc_stat[0] = $ssh->get('cat /proc/stat');
+ }
- // Если система автораспределения продолжить парсинг загрузки процессора
- if(isset($proc_stat))
- {
- $proc_stat[1] = $ssh->get('cat /proc/stat');
+ // Если система автораспределения продолжить парсинг загрузки процессора
+ if(isset($proc_stat))
+ {
+ $proc_stat[1] = $ssh->get('cat /proc/stat');
- // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
- $core = sys::cpu_idle($proc_stat, $server['unit'], false); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
+ // Ядро/поток, на котором будет запущен игровой сервер (поток выбран с рассчетом наименьшей загруженности в момент запуска игрового сервера)
+ $core = sys::cpu_idle($proc_stat, $server['unit'], false); // число от 1 до n (где n число ядер/потоков в процессоре (без нулевого)
- if(!is_numeric($core))
- return array('e' => sys::text('error', 'cpu'));
+ if(!is_numeric($core))
+ return array('e' => sys::text('error', 'cpu'));
- $taskset = 'taskset -c '.$core;
- }
+ $taskset = 'taskset -c '.$core;
+ }
- if($server['core_fix'])
- {
- $core = $server['core_fix']-1;
- $taskset = 'taskset -c '.$core;
- }
+ if($server['core_fix'])
+ {
+ $core = $server['core_fix']-1;
+ $taskset = 'taskset -c '.$core;
+ }
- // Параметры запуска
- $bash = './samp03svr';
+ // Параметры запуска
+ $bash = './samp03svr';
- // Временный файл
- $temp = sys::temp($bash);
+ // Временный файл
+ $temp = sys::temp($bash);
- // Обновление файла start.sh
- $ssh->setfile($temp, $tarif['install'].$server['uid'].'/start.sh', 0500);
+ // Обновление файла start.sh
+ $ssh->setfile($temp, $tarif['install'].$server['uid'].'/start.sh', 0500);
- // Строка запуска
- $ssh->set('cd '.$tarif['install'].$server['uid'].';' // переход в директорию игрового сервера
- .'rm *.pid;' // Удаление *.pid файлов
- .'sudo -u server'.$server['uid'].' mkdir -p oldstart;' // Создание папки логов
- .'cat server_log.txt >> oldstart/'.date('d.m.Y_H:i:s', $server['time_start']).'.log; rm server_log.txt; rm oldstart/01.01.1970_03:00:00.log;' // Перемещение лога предыдущего запуска
- .'chown server'.$server['uid'].':1000 server.cfg start.sh;' // Обновление владельца файлов
- .'sudo -u server'.$server['uid'].' screen -dmS s_'.$server['uid'].' '.$taskset.' sh -c "./start.sh"'); // Запуск игровго сервера
+ // Строка запуска
+ $ssh->set('cd '.$tarif['install'].$server['uid'].';' // переход в директорию игрового сервера
+ .'rm *.pid;' // Удаление *.pid файлов
+ .'sudo -u server'.$server['uid'].' mkdir -p oldstart;' // Создание папки логов
+ .'cat server_log.txt >> oldstart/'.date('d.m.Y_H:i:s', $server['time_start']).'.log; rm server_log.txt; rm oldstart/01.01.1970_03:00:00.log;' // Перемещение лога предыдущего запуска
+ .'chown server'.$server['uid'].':1000 server.cfg start.sh;' // Обновление владельца файлов
+ .'sudo -u server'.$server['uid'].' screen -dmS s_'.$server['uid'].' '.$taskset.' sh -c "./start.sh"'); // Запуск игровго сервера
- $core = !isset($core) ? 0 : $core+1;
+ $core = !isset($core) ? 0 : $core+1;
- // Обновление информации в базе
- $sql->query('UPDATE `servers` set `status`="'.$type.'", `online`="0", `players`="", `core_use`="'.$core.'", `time_start`="'.$start_point.'", `stop`="1" WHERE `id`="'.$id.'" LIMIT 1');
+ // Обновление информации в базе
+ $sql->query('UPDATE `servers` set `status`="'.$type.'", `online`="0", `players`="", `core_use`="'.$core.'", `time_start`="'.$start_point.'", `stop`="1" WHERE `id`="'.$id.'" LIMIT 1');
- unlink($temp);
+ unlink($temp);
- // Сброс кеша
- actions::clmcache($id);
+ // Сброс кеша
+ actions::clmcache($id);
- sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0, 'players' => ''));
- sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0));
+ sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0, 'players' => ''));
+ sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => $type, 'online' => 0));
- return array('s' => 'ok');
- }
+ return array('s' => 'ok');
+ }
- public static function config($ip, $port, $slots, $config)
- {
- $aLine = explode("\n", $config);
+ public static function config($ip, $port, $slots, $config)
+ {
+ $aLine = explode("\n", $config);
- $eConfig = '';
+ $eConfig = '';
- foreach($aLine as $line)
- {
- $param = explode(' ', trim($line));
+ foreach($aLine as $line)
+ {
+ $param = explode(' ', trim($line));
- if(in_array(trim($param[0]), array('bind', 'port', 'maxplayers', 'query')))
- continue;
+ if(in_array(trim($param[0]), array('bind', 'port', 'maxplayers', 'query')))
+ continue;
- $eConfig .= $line.PHP_EOL;
- }
+ $eConfig .= $line.PHP_EOL;
+ }
- $eConfig .= 'bind '.$ip.PHP_EOL
- .'port '.$port.PHP_EOL
- .'maxplayers '.$slots.PHP_EOL
- .'query 1';
+ $eConfig .= 'bind '.$ip.PHP_EOL
+ .'port '.$port.PHP_EOL
+ .'maxplayers '.$slots.PHP_EOL
+ .'query 1';
- return $eConfig;
- }
+ return $eConfig;
+ }
}
?>
\ No newline at end of file
diff --git a/system/library/games/samp/scan.php b/system/library/games/samp/scan.php
index 36cac68..1f15542 100644
--- a/system/library/games/samp/scan.php
+++ b/system/library/games/samp/scan.php
@@ -1,114 +1,114 @@
query('SELECT `address`, `game`, `name`, `map`, `online`, `players`, `status`, `time`, `overdue` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `address`, `game`, `name`, `map`, `online`, `players`, `status`, `time`, `overdue` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- list($ip, $port) = explode(':', $server['address']);
+ list($ip, $port) = explode(':', $server['address']);
- include(LIB.'games/query/SampQuery.php');
+ include(LIB.'games/query/SampQuery.php');
- $sq = new SampQuery($ip, $port);
+ $sq = new SampQuery($ip, $port);
- if($players_get)
- $nmch = 'server_scan_mon_pl_'.$id;
- else
- $nmch = 'server_scan_mon_'.$id;
+ if($players_get)
+ $nmch = 'server_scan_mon_pl_'.$id;
+ else
+ $nmch = 'server_scan_mon_'.$id;
- if(is_array($mcache->get($nmch)))
- return $mcache->get($nmch);
+ if(is_array($mcache->get($nmch)))
+ return $mcache->get($nmch);
- $out = array();
+ $out = array();
- $out['time'] = 'Арендован до: '.date('d.m.Y - H:i', $server['time']);
+ $out['time'] = 'Арендован до: '.date('d.m.Y - H:i', $server['time']);
- if($server['status'] == 'overdue')
- $out['time_end'] = 'Удаление через: '.sys::date('min', $server['overdue']+$cfg['server_delete']*86400);
- else
- $out['time_end'] = 'Осталось: '.sys::date('min', $server['time']);
+ if($server['status'] == 'overdue')
+ $out['time_end'] = 'Удаление через: '.sys::date('min', $server['overdue']+$cfg['server_delete']*86400);
+ else
+ $out['time_end'] = 'Осталось: '.sys::date('min', $server['time']);
- if(!$sq->connect())
- {
- $out['name'] = $server['name'];
- $out['status'] = sys::status($server['status'], $server['game'], $server['map']);
- $out['online'] = $server['online'];
- $out['image'] = ' ';
- $out['buttons'] = sys::buttons($id, $server['status'], $server['game']);
+ if(!$sq->connect())
+ {
+ $out['name'] = $server['name'];
+ $out['status'] = sys::status($server['status'], $server['game'], $server['map']);
+ $out['online'] = $server['online'];
+ $out['image'] = ' ';
+ $out['buttons'] = sys::buttons($id, $server['status'], $server['game']);
- if($players_get)
- $out['players'] = base64_decode($server['players']);
+ if($players_get)
+ $out['players'] = base64_decode($server['players']);
- $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
+ $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
- return $out;
- }
+ return $out;
+ }
- $info = $sq->getInfo();
+ $info = $sq->getInfo();
- if($players_get)
- $players = scan::players($sq->getDetailedPlayers());
+ if($players_get)
+ $players = scan::players($sq->getDetailedPlayers());
- $info['map'] = htmlspecialchars(mb_convert_encoding($info['map'], 'UTF-8', 'WINDOWS-1251'));
- $out['name'] = htmlspecialchars(mb_convert_encoding($info['hostname'], 'UTF-8', 'WINDOWS-1251'));
- $out['status'] = sys::status('working', $server['game'], $info['map']);
- $out['online'] = sys::int($info['players']);
- $out['image'] = ' ';
- $out['buttons'] = sys::buttons($id, 'working', $server['game']);
- $out['players'] = '';
+ $info['map'] = htmlspecialchars(mb_convert_encoding($info['map'], 'UTF-8', 'WINDOWS-1251'));
+ $out['name'] = htmlspecialchars(mb_convert_encoding($info['hostname'], 'UTF-8', 'WINDOWS-1251'));
+ $out['status'] = sys::status('working', $server['game'], $info['map']);
+ $out['online'] = sys::int($info['players']);
+ $out['image'] = ' ';
+ $out['buttons'] = sys::buttons($id, 'working', $server['game']);
+ $out['players'] = '';
- if($players_get)
- {
- foreach($players as $index => $player)
- {
- $html->get($server['game'], 'sections/servers/players');
+ if($players_get)
+ {
+ foreach($players as $index => $player)
+ {
+ $html->get($server['game'], 'sections/servers/players');
- $html->set('i', $player['i']);
- $html->set('name', htmlspecialchars($player['name']));
+ $html->set('i', $player['i']);
+ $html->set('name', htmlspecialchars($player['name']));
- $html->pack('list');
- }
+ $html->pack('list');
+ }
- $out['players'] = isset($html->arr['list']) ? $html->arr['list'] : '';
- }
+ $out['players'] = isset($html->arr['list']) ? $html->arr['list'] : '';
+ }
- $sql->query('UPDATE `servers` set '
- .'`name`="'.$out['name'].'", '
- .'`online`="'.$out['online'].'", '
- .'`map`="'.$info['map'].'", '
- .'`status`="working" WHERE `id`="'.$id.'" LIMIT 1');
+ $sql->query('UPDATE `servers` set '
+ .'`name`="'.$out['name'].'", '
+ .'`online`="'.$out['online'].'", '
+ .'`map`="'.$info['map'].'", '
+ .'`status`="working" WHERE `id`="'.$id.'" LIMIT 1');
- if($players_get)
- $sql->query('UPDATE `servers` set `players`="'.base64_encode($out['players']).'" WHERE `id`="'.$id.'" LIMIT 1');
+ if($players_get)
+ $sql->query('UPDATE `servers` set `players`="'.base64_encode($out['players']).'" WHERE `id`="'.$id.'" LIMIT 1');
- $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
+ $mcache->set($nmch, $out, false, $cfg['mcache_server_mon']);
- return $out;
- }
+ return $out;
+ }
- public static function players($aPlayrs)
- {
- $i = 1;
- $aData = array();
+ public static function players($aPlayrs)
+ {
+ $i = 1;
+ $aData = array();
- foreach($aPlayrs as $n => $player)
- {
- $aData[$i]['i'] = $i;
- $aData[$i]['name'] = $player['nickname'] == '' ? 'Подключается' : htmlspecialchars($player['nickname']);
- $aData[$i]['ping'] = sys::int($player['ping']);
+ foreach($aPlayrs as $n => $player)
+ {
+ $aData[$i]['i'] = $i;
+ $aData[$i]['name'] = $player['nickname'] == '' ? 'Подключается' : htmlspecialchars($player['nickname']);
+ $aData[$i]['ping'] = sys::int($player['ping']);
- $i+=1;
- }
+ $i+=1;
+ }
- return $aData;
- }
- }
+ return $aData;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/games/samp/service.php b/system/library/games/samp/service.php
index 0d45d60..5bcb0d9 100644
--- a/system/library/games/samp/service.php
+++ b/system/library/games/samp/service.php
@@ -1,355 +1,355 @@
query('SELECT `address`, `test` FROM `units` WHERE `id`="'.$aData['unit'].'" AND `samp`="1" AND `show`="1" LIMIT 1');
- if(!$sql->num())
- sys::outjs(array('e' => 'Локация не найдена.'));
+ // Проверка локации
+ $sql->query('SELECT `address`, `test` FROM `units` WHERE `id`="'.$aData['unit'].'" AND `samp`="1" AND `show`="1" LIMIT 1');
+ if(!$sql->num())
+ sys::outjs(array('e' => 'Локация не найдена.'));
- $unit = $sql->get();
+ $unit = $sql->get();
- // Проверка тарифа
- $sql->query('SELECT `id` FROM `tarifs` WHERE `id`="'.$aData['tarif'].'" AND `unit`="'.$aData['unit'].'" AND `show`="1" LIMIT 1');
- if(!$sql->num())
- sys::outjs(array('e' => 'Тариф не найден.'));
+ // Проверка тарифа
+ $sql->query('SELECT `id` FROM `tarifs` WHERE `id`="'.$aData['tarif'].'" AND `unit`="'.$aData['unit'].'" AND `show`="1" LIMIT 1');
+ if(!$sql->num())
+ sys::outjs(array('e' => 'Тариф не найден.'));
- $sql->query('SELECT '
- .'`slots_min`,'
- .'`slots_max`,'
- .'`port_min`,'
- .'`port_max`,'
- .'`hostname`,'
- .'`packs`,'
- .'`time`,'
- .'`test`,'
- .'`tests`,'
- .'`discount`,'
- .'`ftp`,'
- .'`plugins`,'
- .'`console`,'
- .'`stats`,'
- .'`copy`,'
- .'`web`,'
- .'`plugins_install`,'
- .'`hdd`,'
- .'`autostop`,'
- .'`core_fix`,'
- .'`ip`,'
- .'`price`'
- .' FROM `tarifs` WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
+ $sql->query('SELECT '
+ .'`slots_min`,'
+ .'`slots_max`,'
+ .'`port_min`,'
+ .'`port_max`,'
+ .'`hostname`,'
+ .'`packs`,'
+ .'`time`,'
+ .'`test`,'
+ .'`tests`,'
+ .'`discount`,'
+ .'`ftp`,'
+ .'`plugins`,'
+ .'`console`,'
+ .'`stats`,'
+ .'`copy`,'
+ .'`web`,'
+ .'`plugins_install`,'
+ .'`hdd`,'
+ .'`autostop`,'
+ .'`core_fix`,'
+ .'`ip`,'
+ .'`price`'
+ .' FROM `tarifs` WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
- $tarif = $sql->get();
+ $tarif = $sql->get();
- // Проверка сборки
- if(!array_key_exists($aData['pack'], sys::b64djs($tarif['packs'], true)))
- sys::outjs(array('e' => 'Сборка не найдена.'));
+ // Проверка сборки
+ if(!array_key_exists($aData['pack'], sys::b64djs($tarif['packs'], true)))
+ sys::outjs(array('e' => 'Сборка не найдена.'));
- $test = 0;
+ $test = 0;
- // Проверка периода на тест
- if($aData['test'])
- {
- if(!$tarif['test'] || !$unit['test'])
- sys::outjs(array('e' => 'Тестовый период недоступен.'));
-
+ // Проверка периода на тест
+ if($aData['test'])
+ {
+ if(!$tarif['test'] || !$unit['test'])
+ sys::outjs(array('e' => 'Тестовый период недоступен.'));
+
- // Проверка на повторный запрос
- $sql->query('SELECT `id`, `game` FROM `tests` WHERE `user`="'.$user['id'].'" LIMIT 1');
- if($sql->num())
- {
- $test_info = $sql->get();
+ // Проверка на повторный запрос
+ $sql->query('SELECT `id`, `game` FROM `tests` WHERE `user`="'.$user['id'].'" LIMIT 1');
+ if($sql->num())
+ {
+ $test_info = $sql->get();
- if(!$cfg['tests']['game'] || $test_info['game'] == 'samp')
- sys::outjs(array('e' => 'Тестовый период предоставляется один раз.'));
+ if(!$cfg['tests']['game'] || $test_info['game'] == 'samp')
+ sys::outjs(array('e' => 'Тестовый период предоставляется один раз.'));
- $sql->query('SELECT `id` FROM `servers` WHERE `user`="'.$user['id'].'" AND `test`="1" LIMIT 1');
- if($sql->num() AND !$cfg['tests']['sametime'])
- sys::outjs(array('e' => 'Чтобы получить тестовый период другой игры, дождитесь окончания текущего.'));
- }
+ $sql->query('SELECT `id` FROM `servers` WHERE `user`="'.$user['id'].'" AND `test`="1" LIMIT 1');
+ if($sql->num() AND !$cfg['tests']['sametime'])
+ sys::outjs(array('e' => 'Чтобы получить тестовый период другой игры, дождитесь окончания текущего.'));
+ }
- // Проверка наличия мест на локации
- $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `test`="1" AND `time`>"'.$start_point.'" LIMIT '.$unit['test']);
- if($sql->num() == $unit['test'])
- sys::outjs(array('e' => 'Свободного места для тестового периода нет.'));
+ // Проверка наличия мест на локации
+ $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `test`="1" AND `time`>"'.$start_point.'" LIMIT '.$unit['test']);
+ if($sql->num() == $unit['test'])
+ sys::outjs(array('e' => 'Свободного места для тестового периода нет.'));
- // Проверка наличия мест для выбранного тарифа
- $sql->query('SELECT `id` FROM `servers` WHERE `tarif`="'.$aData['tarif'].'" AND `test`="1" AND `time`>"'.$start_point.'" LIMIT '.$tarif['tests']);
- if($sql->num() == $tarif['tests'])
- sys::outjs(array('e' => 'Свободного места для тестового периода выбранного тарифа нет.'));
+ // Проверка наличия мест для выбранного тарифа
+ $sql->query('SELECT `id` FROM `servers` WHERE `tarif`="'.$aData['tarif'].'" AND `test`="1" AND `time`>"'.$start_point.'" LIMIT '.$tarif['tests']);
+ if($sql->num() == $tarif['tests'])
+ sys::outjs(array('e' => 'Свободного места для тестового периода выбранного тарифа нет.'));
- $test = 1;
- }else
- // Проверка периода
- if(!$cfg['settlement_period'] AND !in_array($aData['time'], explode(':', $tarif['time'])))
- sys::outjs(array('e' => 'Переданные данные периода неверны.'));
+ $test = 1;
+ }else
+ // Проверка периода
+ if(!$cfg['settlement_period'] AND !in_array($aData['time'], explode(':', $tarif['time'])))
+ sys::outjs(array('e' => 'Переданные данные периода неверны.'));
- // Проверка слот
- if($aData['slots'] < $tarif['slots_min'] || $aData['slots'] > $tarif['slots_max'])
- sys::outjs(array('e' => 'Переданные данные слот неверны.'));
+ // Проверка слот
+ if($aData['slots'] < $tarif['slots_min'] || $aData['slots'] > $tarif['slots_max'])
+ sys::outjs(array('e' => 'Переданные данные слот неверны.'));
- // Определение суммы
- if($cfg['settlement_period'])
- {
- // Цена аренды за расчетный период
- $sum = games::define_sum($tarif['discount'], $tarif['price'], $aData['slots'], $start_point);
+ // Определение суммы
+ if($cfg['settlement_period'])
+ {
+ // Цена аренды за расчетный период
+ $sum = games::define_sum($tarif['discount'], $tarif['price'], $aData['slots'], $start_point);
- $aData['time'] = games::define_period('buy', params::$aDayMonth);
- }else
- $sum = games::define_sum($tarif['discount'], $tarif['price'], $aData['slots'], $aData['time']);
+ $aData['time'] = games::define_period('buy', params::$aDayMonth);
+ }else
+ $sum = games::define_sum($tarif['discount'], $tarif['price'], $aData['slots'], $aData['time']);
- // Проверка промо-кода
- $promo = games::define_promo(
- $aData['promo'],
- array(
- 'tarif' => $aData['tarif'],
- 'slots' => $aData['slots'],
- 'time' => $aData['time'],
- 'user' => $user['id']
- ),
- $tarif['discount'],
- $sum
- );
+ // Проверка промо-кода
+ $promo = games::define_promo(
+ $aData['promo'],
+ array(
+ 'tarif' => $aData['tarif'],
+ 'slots' => $aData['slots'],
+ 'time' => $aData['time'],
+ 'user' => $user['id']
+ ),
+ $tarif['discount'],
+ $sum
+ );
- $days = $aData['time']; // Кол-во дней аренды
+ $days = $aData['time']; // Кол-во дней аренды
- // Использование промо-кода
- if(is_array($promo))
- {
- if(array_key_exists('sum', $promo))
- $sum = $promo['sum'];
- else
- $days += $promo['days']; // Кол-во дней аренды с учетом подарочных (промо-код)
- }
+ // Использование промо-кода
+ if(is_array($promo))
+ {
+ if(array_key_exists('sum', $promo))
+ $sum = $promo['sum'];
+ else
+ $days += $promo['days']; // Кол-во дней аренды с учетом подарочных (промо-код)
+ }
- // Проверка баланса
- if($user['balance'] < $sum)
- sys::outjs(array('e' => 'У вас не хватает '.(round($sum-$user['balance'], 2)).' '.$cfg['currency']));
+ // Проверка баланса
+ if($user['balance'] < $sum)
+ sys::outjs(array('e' => 'У вас не хватает '.(round($sum-$user['balance'], 2)).' '.$cfg['currency']));
- // Выделенный адрес игрового сервера
- if(!empty($tarif['ip']))
- {
- $aIp = explode(':', $tarif['ip']);
+ // Выделенный адрес игрового сервера
+ if(!empty($tarif['ip']))
+ {
+ $aIp = explode(':', $tarif['ip']);
- $ip = false;
- $port = params::$aDefPort['samp'];
+ $ip = false;
+ $port = params::$aDefPort['samp'];
- // Проверка наличия свободного адреса
- foreach($aIp as $adr)
- {
- $adr = trim($adr);
+ // Проверка наличия свободного адреса
+ foreach($aIp as $adr)
+ {
+ $adr = trim($adr);
- $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `address` LIKE "'.$adr.':%" LIMIT 1');
- if(!$sql->num())
- {
- $ip = $adr;
+ $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `address` LIKE "'.$adr.':%" LIMIT 1');
+ if(!$sql->num())
+ {
+ $ip = $adr;
- break;
- }
- }
- }else{
- $ip = sys::first(explode(':', $unit['address']));
- $port = false;
+ break;
+ }
+ }
+ }else{
+ $ip = sys::first(explode(':', $unit['address']));
+ $port = false;
- // Проверка наличия свободного порта
- for($tarif['port_min']; $tarif['port_min'] <= $tarif['port_max']; $tarif['port_min']+=1)
- {
- $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND (`address`="'.$ip.':'.$tarif['port_min'].'" OR `port`="'.$tarif['port_min'].'") LIMIT 1');
- if(!$sql->num())
- {
- $port = $tarif['port_min'];
+ // Проверка наличия свободного порта
+ for($tarif['port_min']; $tarif['port_min'] <= $tarif['port_max']; $tarif['port_min']+=1)
+ {
+ $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND (`address`="'.$ip.':'.$tarif['port_min'].'" OR `port`="'.$tarif['port_min'].'") LIMIT 1');
+ if(!$sql->num())
+ {
+ $port = $tarif['port_min'];
- break;
- }
- }
- }
+ break;
+ }
+ }
+ }
- if(!$ip || !$port)
- {
- $sql->query('UPDATE `tarifs` set `show`="0" WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
+ if(!$ip || !$port)
+ {
+ $sql->query('UPDATE `tarifs` set `show`="0" WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
- sys::outjs(array('e' => 'К сожалению нет доступных мест, обратитесь в тех.поддержку.'));
- }
+ sys::outjs(array('e' => 'К сожалению нет доступных мест, обратитесь в тех.поддержку.'));
+ }
- if($test)
- $aData['time'] = games::time($start_point, $tarif['test']);
- else
- $aData['time'] = games::time($start_point, $days);
+ if($test)
+ $aData['time'] = games::time($start_point, $tarif['test']);
+ else
+ $aData['time'] = games::time($start_point, $days);
- $fix_one = 0;
- $core = 0;
+ $fix_one = 0;
+ $core = 0;
- if($tarif['core_fix'] != '')
- {
- $aCore = explode(',', $tarif['core_fix']);
+ if($tarif['core_fix'] != '')
+ {
+ $aCore = explode(',', $tarif['core_fix']);
- foreach($aCore as $cpu)
- {
- $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `tarif`="'.$aData['tarif'].'" AND `core_fix`="'.$cpu.'" AND `core_fix_one`="1" LIMIT 1');
+ foreach($aCore as $cpu)
+ {
+ $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$aData['unit'].'" AND `tarif`="'.$aData['tarif'].'" AND `core_fix`="'.$cpu.'" AND `core_fix_one`="1" LIMIT 1');
- if($sql->num())
- continue;
+ if($sql->num())
+ continue;
- $fix_one = 1;
- $core = $cpu;
+ $fix_one = 1;
+ $core = $cpu;
- break;
- }
+ break;
+ }
- if(!$core)
- {
- $sql->query('UPDATE `tarifs` set `show`="0" WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
+ if(!$core)
+ {
+ $sql->query('UPDATE `tarifs` set `show`="0" WHERE `id`="'.$aData['tarif'].'" LIMIT 1');
- sys::outjs(array('e' => 'К сожалению нет доступных мест, обратитесь в тех.поддержку.'));
- }
- }
+ sys::outjs(array('e' => 'К сожалению нет доступных мест, обратитесь в тех.поддержку.'));
+ }
+ }
- $ram = $tarif['param_fix'] ? $aData['ram'] : $cfg['ram']['samp']*$aSDATA['slots'];
+ $ram = $tarif['param_fix'] ? $aData['ram'] : $cfg['ram']['samp']*$aSDATA['slots'];
- // Массив данных
- $aSDATA = array(
- 'unit' => $aData['unit'], // идентификатор локации
- 'tarif' => $aData['tarif'], // идентификатор тарифа
- 'ram' => $ram, // значение ram
- 'param_fix' => $tarif['param_fix'], // фиксированные параметры
- 'pack' => $aData['pack'], // Выбранная сборка для установки
- 'time' => $aData['time'], // Время аренды
- 'days' => $days, // Число дней
- 'sum' => $sum, // Сумма списания
- 'test' => $test, // тестовый период
- 'address' => $ip.':'.$port, // адрес игрового сервера
- 'port' => $port, // порт игрового сервера
- 'slots' => $aData['slots'], // Кол-во слот
- 'autostop' => $tarif['autostop'], // Выключение при 0 онлайне
- 'ftp' => $tarif['ftp'], // Использование ftp
- 'plugins' => $tarif['plugins'], // Использование плагинов
- 'console' => $tarif['console'], // Использование консоли
- 'stats' => $tarif['stats'], // Использование графиков (ведение статистики)
- 'copy' => $tarif['copy'], // Использование резервных копий
- 'web' => $tarif['web'], // Использование доп услуг
- 'plugins_install' => $tarif['plugins_install'], // Список установленных плагинов
- 'hdd' => $tarif['hdd'], // Дисковое пространство
- 'core_fix' => $core, // Выделенный поток
- 'core_fix_one' => $fix_one, // Выделенный поток
- 'promo' => $promo // Использование промо-кода
- );
+ // Массив данных
+ $aSDATA = array(
+ 'unit' => $aData['unit'], // идентификатор локации
+ 'tarif' => $aData['tarif'], // идентификатор тарифа
+ 'ram' => $ram, // значение ram
+ 'param_fix' => $tarif['param_fix'], // фиксированные параметры
+ 'pack' => $aData['pack'], // Выбранная сборка для установки
+ 'time' => $aData['time'], // Время аренды
+ 'days' => $days, // Число дней
+ 'sum' => $sum, // Сумма списания
+ 'test' => $test, // тестовый период
+ 'address' => $ip.':'.$port, // адрес игрового сервера
+ 'port' => $port, // порт игрового сервера
+ 'slots' => $aData['slots'], // Кол-во слот
+ 'autostop' => $tarif['autostop'], // Выключение при 0 онлайне
+ 'ftp' => $tarif['ftp'], // Использование ftp
+ 'plugins' => $tarif['plugins'], // Использование плагинов
+ 'console' => $tarif['console'], // Использование консоли
+ 'stats' => $tarif['stats'], // Использование графиков (ведение статистики)
+ 'copy' => $tarif['copy'], // Использование резервных копий
+ 'web' => $tarif['web'], // Использование доп услуг
+ 'plugins_install' => $tarif['plugins_install'], // Список установленных плагинов
+ 'hdd' => $tarif['hdd'], // Дисковое пространство
+ 'core_fix' => $core, // Выделенный поток
+ 'core_fix_one' => $fix_one, // Выделенный поток
+ 'promo' => $promo // Использование промо-кода
+ );
- return $aSDATA;
- }
+ return $aSDATA;
+ }
- public static function install($aSDATA = array())
- {
- global $cfg, $sql, $user, $start_point;
+ public static function install($aSDATA = array())
+ {
+ global $cfg, $sql, $user, $start_point;
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- // Массив данных локации (адрес,пароль)
- $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$aSDATA['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ // Массив данных локации (адрес,пароль)
+ $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$aSDATA['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- // Проверка ssh соединения с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- sys::outjs(array('e' => sys::text('error', 'ssh')));
+ // Проверка ssh соединения с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ sys::outjs(array('e' => sys::text('error', 'ssh')));
- // Массив данных тарифа (путь сборки,путь установки)
- $sql->query('SELECT `path`, `install`, `hostname` FROM `tarifs` WHERE `id`="'.$aSDATA['tarif'].'" LIMIT 1');
- $tarif = $sql->get();
+ // Массив данных тарифа (путь сборки,путь установки)
+ $sql->query('SELECT `path`, `install`, `hostname` FROM `tarifs` WHERE `id`="'.$aSDATA['tarif'].'" LIMIT 1');
+ $tarif = $sql->get();
- // Получение идентификаторов игрового сервера
- $sql->query('INSERT INTO `servers` set uid="1"');
- $id = $sql->id();
- $uid = $id+1000;
+ // Получение идентификаторов игрового сервера
+ $sql->query('INSERT INTO `servers` set uid="1"');
+ $id = $sql->id();
+ $uid = $id+1000;
- // Директория сборки
- $path = $tarif['path'].$aSDATA['pack'];
+ // Директория сборки
+ $path = $tarif['path'].$aSDATA['pack'];
- // Директория игрового сервера
- $install = $tarif['install'].$uid;
+ // Директория игрового сервера
+ $install = $tarif['install'].$uid;
- $ssh->set('mkdir '.$install.';' // Создание директории
- .'useradd -s /bin/false -d '.$install.' -g servers -u '.$uid.' server'.$uid.';' // Создание пользователя сервера на локации
- .'chown server'.$uid.':1000 '.$install.';' // Изменение владельца и группы директории
- .'cd '.$install.' && sudo -u server'.$uid.' screen -dmS i_'.$uid.' sh -c "cp -r '.$path.'/. .;' // Копирование файлов сборки для сервера
- .'find . -type d -exec chmod 700 {} \;;'
- .'find . -type f -exec chmod 777 {} \;;'
- .'chmod 500 '.params::$aFileGame[$server['samp']].'"');
+ $ssh->set('mkdir '.$install.';' // Создание директории
+ .'useradd -s /bin/false -d '.$install.' -g servers -u '.$uid.' server'.$uid.';' // Создание пользователя сервера на локации
+ .'chown server'.$uid.':1000 '.$install.';' // Изменение владельца и группы директории
+ .'cd '.$install.' && sudo -u server'.$uid.' screen -dmS i_'.$uid.' sh -c "cp -r '.$path.'/. .;' // Копирование файлов сборки для сервера
+ .'find . -type d -exec chmod 700 {} \;;'
+ .'find . -type f -exec chmod 777 {} \;;'
+ .'chmod 500 '.params::$aFileGame[$server['samp']].'"');
- // Запись данных нового сервера
- $sql->query('UPDATE `servers` set
- `uid`="'.$uid.'",
- `unit`="'.$aSDATA['unit'].'",
- `tarif`="'.$aSDATA['tarif'].'",
- `user`="'.$user['id'].'",
- `address`="'.$aSDATA['address'].'",
- `port`="'.$aSDATA['port'].'",
- `game`="samp",
- `slots`="'.$aSDATA['slots'].'",
- `slots_start`="'.$aSDATA['slots'].'",
- `status`="install",
- `name`="'.$tarif['hostname'].'",
- `pack`="'.$aSDATA['pack'].'",
- `plugins_use`="'.$aSDATA['plugins'].'",
- `ftp_use`="'.$aSDATA['ftp'].'",
- `console_use`="'.$aSDATA['console'].'",
- `stats_use`="'.$aSDATA['stats'].'",
- `copy_use`="'.$aSDATA['copy'].'",
- `web_use`="'.$aSDATA['web'].'",
- `vac`="1",
- `hdd`="'.$aSDATA['hdd'].'",
- `time`="'.$aSDATA['time'].'",
- `date`="'.$start_point.'",
- `test`="'.$aSDATA['test'].'",
- `ram`="'.$aSDATA['ram'].'",
- `map_start`="'.sys::passwd(8).'",
- `core_fix`="'.$aSDATA['core_fix'].'",
- `core_fix_one`="'.$aSDATA['core_fix_one'].'",
- `autostop`="'.$aSDATA['autostop'].'" WHERE `id`="'.$id.'" LIMIT 1');
+ // Запись данных нового сервера
+ $sql->query('UPDATE `servers` set
+ `uid`="'.$uid.'",
+ `unit`="'.$aSDATA['unit'].'",
+ `tarif`="'.$aSDATA['tarif'].'",
+ `user`="'.$user['id'].'",
+ `address`="'.$aSDATA['address'].'",
+ `port`="'.$aSDATA['port'].'",
+ `game`="samp",
+ `slots`="'.$aSDATA['slots'].'",
+ `slots_start`="'.$aSDATA['slots'].'",
+ `status`="install",
+ `name`="'.$tarif['hostname'].'",
+ `pack`="'.$aSDATA['pack'].'",
+ `plugins_use`="'.$aSDATA['plugins'].'",
+ `ftp_use`="'.$aSDATA['ftp'].'",
+ `console_use`="'.$aSDATA['console'].'",
+ `stats_use`="'.$aSDATA['stats'].'",
+ `copy_use`="'.$aSDATA['copy'].'",
+ `web_use`="'.$aSDATA['web'].'",
+ `vac`="1",
+ `hdd`="'.$aSDATA['hdd'].'",
+ `time`="'.$aSDATA['time'].'",
+ `date`="'.$start_point.'",
+ `test`="'.$aSDATA['test'].'",
+ `ram`="'.$aSDATA['ram'].'",
+ `map_start`="'.sys::passwd(8).'",
+ `core_fix`="'.$aSDATA['core_fix'].'",
+ `core_fix_one`="'.$aSDATA['core_fix_one'].'",
+ `autostop`="'.$aSDATA['autostop'].'" WHERE `id`="'.$id.'" LIMIT 1');
- // Запись установленных плагинов
- if($aSDATA['plugins'])
- {
- // Массив идентификаторов плагинов
- $aPlugins = sys::b64djs($aSDATA['plugins_install']);
+ // Запись установленных плагинов
+ if($aSDATA['plugins'])
+ {
+ // Массив идентификаторов плагинов
+ $aPlugins = sys::b64djs($aSDATA['plugins_install']);
- if(isset($aPlugins[$aSDATA['pack']]))
- {
- $plugins = explode(',', $aPlugins[$aSDATA['pack']]);
+ if(isset($aPlugins[$aSDATA['pack']]))
+ {
+ $plugins = explode(',', $aPlugins[$aSDATA['pack']]);
- foreach($plugins as $plugin)
- if($plugin)
- $sql->query('INSERT INTO `plugins_install` set `server`="'.$id.'", `plugin`="'.$plugin.'", `time`="'.$start_point.'"');
- }
- }
+ foreach($plugins as $plugin)
+ if($plugin)
+ $sql->query('INSERT INTO `plugins_install` set `server`="'.$id.'", `plugin`="'.$plugin.'", `time`="'.$start_point.'"');
+ }
+ }
- // Списание средств с баланса пользователя
- $sql->query('UPDATE `users` set `balance`="'.($user['balance']-$aSDATA['sum']).'" WHERE `id`="'.$user['id'].'" LIMIT 1');
+ // Списание средств с баланса пользователя
+ $sql->query('UPDATE `users` set `balance`="'.($user['balance']-$aSDATA['sum']).'" WHERE `id`="'.$user['id'].'" LIMIT 1');
- // Запись получения тестового периода
- if($aSDATA['test'])
- {
- $sql->query('INSERT INTO `tests` set `server`="'.$id.'", `unit`="'.$aSDATA['unit'].'", `game`="samp", `user`="'.$user['id'].'", `time`="'.$start_point.'"');
- $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server_test'), array('id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="0"');
- }else{
- // Реф. система
- games::part($user['id'], $aSDATA['sum']);
+ // Запись получения тестового периода
+ if($aSDATA['test'])
+ {
+ $sql->query('INSERT INTO `tests` set `server`="'.$id.'", `unit`="'.$aSDATA['unit'].'", `game`="samp", `user`="'.$user['id'].'", `time`="'.$start_point.'"');
+ $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server_test'), array('id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="0"');
+ }else{
+ // Реф. система
+ games::part($user['id'], $aSDATA['sum']);
- // Запись логов
- if(!is_array($aSDATA['promo']))
- $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server'), array('days' => games::parse_day($aSDATA['days'], true), 'money' => $aSDATA['sum'], 'id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="'.$aSDATA['sum'].'"');
- else{
- $sql->query('UPDATE `servers` set `benefit`="'.$aSDATA['time'].'" WHERE `id`="'.$id.'" LIMIT 1');
- $sql->query('INSERT INTO `promo_use` set `promo`="'.$aSDATA['promo']['id'].'", `user`="'.$user['id'].'", `time`="'.$start_point.'"');
- $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server_promo'), array('days' => games::parse_day($aSDATA['days'], true), 'money' => $aSDATA['sum'], 'promo' => $aSDATA['promo']['cod'], 'id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="'.$aSDATA['sum'].'"');
- }
- }
+ // Запись логов
+ if(!is_array($aSDATA['promo']))
+ $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server'), array('days' => games::parse_day($aSDATA['days'], true), 'money' => $aSDATA['sum'], 'id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="'.$aSDATA['sum'].'"');
+ else{
+ $sql->query('UPDATE `servers` set `benefit`="'.$aSDATA['time'].'" WHERE `id`="'.$id.'" LIMIT 1');
+ $sql->query('INSERT INTO `promo_use` set `promo`="'.$aSDATA['promo']['id'].'", `user`="'.$user['id'].'", `time`="'.$start_point.'"');
+ $sql->query('INSERT INTO `logs` set `user`="'.$user['id'].'", `text`="'.sys::updtext(sys::text('logs', 'buy_server_promo'), array('days' => games::parse_day($aSDATA['days'], true), 'money' => $aSDATA['sum'], 'promo' => $aSDATA['promo']['cod'], 'id' => $id)).'", `date`="'.$start_point.'", `type`="buy", `money`="'.$aSDATA['sum'].'"');
+ }
+ }
- return $id;
- }
+ return $id;
+ }
}
?>
\ No newline at end of file
diff --git a/system/library/games/samp/tarif.php b/system/library/games/samp/tarif.php
index a65da45..b61e6a3 100644
--- a/system/library/games/samp/tarif.php
+++ b/system/library/games/samp/tarif.php
@@ -1,179 +1,179 @@
get('extend', 'sections/servers/games/tarif');
+ $html->get('extend', 'sections/servers/games/tarif');
- if(isset($html->arr['extend_address']))
- {
- $html->unit('extend_address', 1);
- $html->set('extend_address', $html->arr['extend_address']);
- }else
- $html->unit('extend_address');
+ if(isset($html->arr['extend_address']))
+ {
+ $html->unit('extend_address', 1);
+ $html->set('extend_address', $html->arr['extend_address']);
+ }else
+ $html->unit('extend_address');
- $html->set('id', $sid);
- $html->set('time', sys::date('min', $server['time']));
- $html->set('options', 'Выберете период продления '.$options);
- $html->set('slots', $server['slots']);
- $html->set('info', '');
- $html->set('tarif', $tarif_name);
- $html->set('cur', $cfg['currency']);
+ $html->set('id', $sid);
+ $html->set('time', sys::date('min', $server['time']));
+ $html->set('options', 'Выберете период продления '.$options);
+ $html->set('slots', $server['slots']);
+ $html->set('info', '');
+ $html->set('tarif', $tarif_name);
+ $html->set('cur', $cfg['currency']);
- $html->pack('main');
+ $html->pack('main');
- return NULL;
- }
+ return NULL;
+ }
public static function extend_sp($server, $tarif, $sid)
{
- global $cfg, $sql, $html, $start_point;
+ global $cfg, $sql, $html, $start_point;
- tarifs::extend_address($server['game'], $sid);
+ tarifs::extend_address($server['game'], $sid);
- $sum = $tarif['slots'] ? $tarif['price'] : $tarif['price']*$server['slots'];
+ $sum = $tarif['slots'] ? $tarif['price'] : $tarif['price']*$server['slots'];
- $html->get('extend_sp', 'sections/servers/games/tarif');
+ $html->get('extend_sp', 'sections/servers/games/tarif');
- if(isset($html->arr['extend_address']))
- {
- $html->unit('extend_address', 1);
- $html->set('extend_address', $html->arr['extend_address']);
- }else
- $html->unit('extend_address');
+ if(isset($html->arr['extend_address']))
+ {
+ $html->unit('extend_address', 1);
+ $html->set('extend_address', $html->arr['extend_address']);
+ }else
+ $html->unit('extend_address');
- $html->set('id', $sid);
- $html->set('time', sys::date('min', $server['time']));
- $html->set('date', $server['time'] > $start_point ? 'Сервер продлен до: '.date('d.m.Y', $server['time']) : 'Текущая дата: '.date('d.m.Y', $start_point));
- $html->set('options', 'Выберете период продления '.$options);
- $html->set('slots', $server['slots']);
- $html->set('info', '');
- $html->set('tarif', $tarif['name']);
- $html->set('sum', $sum);
- $html->set('cur', $cfg['currency']);
+ $html->set('id', $sid);
+ $html->set('time', sys::date('min', $server['time']));
+ $html->set('date', $server['time'] > $start_point ? 'Сервер продлен до: '.date('d.m.Y', $server['time']) : 'Текущая дата: '.date('d.m.Y', $start_point));
+ $html->set('options', 'Выберете период продления '.$options);
+ $html->set('slots', $server['slots']);
+ $html->set('info', '');
+ $html->set('tarif', $tarif['name']);
+ $html->set('sum', $sum);
+ $html->set('cur', $cfg['currency']);
- $html->pack('main');
+ $html->pack('main');
- return NULL;
- }
+ return NULL;
+ }
public static function plan()
{
- return NULL;
- }
+ return NULL;
+ }
- public static function unit($server, $unit_name, $tarif_name, $sid)
+ public static function unit($server, $unit_name, $tarif_name, $sid)
{
- global $cfg, $sql, $html;
+ global $cfg, $sql, $html;
- if(!$cfg['change_unit'][$server['game']])
- return NULL;
+ if(!$cfg['change_unit'][$server['game']])
+ return NULL;
- $tarifs = $sql->query('SELECT `unit` FROM `tarifs` WHERE `game`="'.$server['game'].'" AND `name`="'.$tarif_name.'" AND `id`!="'.$server['tarif'].'" AND `show`="1" ORDER BY `unit`');
- if(!$sql->num($tarifs))
- return NULL;
+ $tarifs = $sql->query('SELECT `unit` FROM `tarifs` WHERE `game`="'.$server['game'].'" AND `name`="'.$tarif_name.'" AND `id`!="'.$server['tarif'].'" AND `show`="1" ORDER BY `unit`');
+ if(!$sql->num($tarifs))
+ return NULL;
- $units = 0;
+ $units = 0;
- $options = 'Выберете новую локацию ';
+ $options = 'Выберете новую локацию ';
- while($tarif = $sql->get($tarifs))
- {
- $sql->query('SELECT `id`, `name` FROM `units` WHERE `id`="'.$tarif['unit'].'" AND `show`="1" LIMIT 1');
- if(!$sql->num())
- continue;
+ while($tarif = $sql->get($tarifs))
+ {
+ $sql->query('SELECT `id`, `name` FROM `units` WHERE `id`="'.$tarif['unit'].'" AND `show`="1" LIMIT 1');
+ if(!$sql->num())
+ continue;
- $unit = $sql->get();
+ $unit = $sql->get();
- $options .= ''.$unit['name'].' ';
+ $options .= ''.$unit['name'].' ';
- $units+=1;
- }
+ $units+=1;
+ }
- if(!$units)
- return NULL;
+ if(!$units)
+ return NULL;
- $html->get('unit', 'sections/servers/games/tarif');
+ $html->get('unit', 'sections/servers/games/tarif');
- $html->set('id', $sid);
- $html->set('options', $options);
- $html->set('slots', $server['slots']);
- $html->set('info', '');
- $html->set('unit', $unit_name);
- $html->set('tarif', $tarif_name);
+ $html->set('id', $sid);
+ $html->set('options', $options);
+ $html->set('slots', $server['slots']);
+ $html->set('info', '');
+ $html->set('unit', $unit_name);
+ $html->set('tarif', $tarif_name);
- $html->pack('main');
+ $html->pack('main');
- return NULL;
- }
+ return NULL;
+ }
- public static function unit_new($tarif, $unit, $server, $mcache)
- {
- global $ssh, $sql, $user, $start_point;
+ public static function unit_new($tarif, $unit, $server, $mcache)
+ {
+ global $ssh, $sql, $user, $start_point;
- // Проверка ssh соединения с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- sys::outjs(array('e' => sys::text('error', 'ssh')));
+ // Проверка ssh соединения с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ sys::outjs(array('e' => sys::text('error', 'ssh')));
- // Директория сборки
- $path = $tarif['path'].$tarif['pack'];
+ // Директория сборки
+ $path = $tarif['path'].$tarif['pack'];
- // Директория игрового сервера
- $install = $tarif['install'].$server['uid'];
+ // Директория игрового сервера
+ $install = $tarif['install'].$server['uid'];
- // Пользователь сервера
- $uS = 'server'.$server['uid'];
+ // Пользователь сервера
+ $uS = 'server'.$server['uid'];
- $ssh->set('mkdir '.$install.';' // Создание директории
- .'useradd -d '.$install.' -g servers -u '.$server['uid'].' '.$uS.';' // Создание пользователя сервера на локации
- .'chown '.$uS.':1000 '.$install.';' // Изменение владельца и группы директории
- .'cd '.$install.' && sudo -u '.$uS.' screen -dmS i_'.$server['uid'].' cp -r '.$path.'/. .'); // Копирование файлов сборки для сервера
+ $ssh->set('mkdir '.$install.';' // Создание директории
+ .'useradd -d '.$install.' -g servers -u '.$server['uid'].' '.$uS.';' // Создание пользователя сервера на локации
+ .'chown '.$uS.':1000 '.$install.';' // Изменение владельца и группы директории
+ .'cd '.$install.' && sudo -u '.$uS.' screen -dmS i_'.$server['uid'].' cp -r '.$path.'/. .'); // Копирование файлов сборки для сервера
- $address = explode(':', $server['address']);
+ $address = explode(':', $server['address']);
- $fix_one = $tarif['core_fix'] ? 1 : 0;
+ $fix_one = $tarif['core_fix'] ? 1 : 0;
- // Обновление данных нового сервера
- $sql->query('UPDATE `servers` set
- `unit`="'.$tarif['unit'].'",
- `tarif`="'.$tarif['id'].'",
- `address`="'.$server['address'].'",
- `port`="'.$address[1].'",
- `status`="install",
- `name`="'.$tarif['hostname'].'",
- `pack`="'.$tarif['pack'].'",
- `map_start`="'.$tarif['map'].'",
- `hdd`="'.$tarif['hdd'].'",
- `time`="'.$tarif['time'].'",
- `autostop`="'.$tarif['autostop'].'",
- `core_fix`="'.$tarif['core_fix'].'",
- `core_fix_one`="'.$fix_one.'",
- `reinstall`="'.$start_point.'" WHERE `id`="'.$server['id'].'" LIMIT 1');
+ // Обновление данных нового сервера
+ $sql->query('UPDATE `servers` set
+ `unit`="'.$tarif['unit'].'",
+ `tarif`="'.$tarif['id'].'",
+ `address`="'.$server['address'].'",
+ `port`="'.$address[1].'",
+ `status`="install",
+ `name`="'.$tarif['hostname'].'",
+ `pack`="'.$tarif['pack'].'",
+ `map_start`="'.$tarif['map'].'",
+ `hdd`="'.$tarif['hdd'].'",
+ `time`="'.$tarif['time'].'",
+ `autostop`="'.$tarif['autostop'].'",
+ `core_fix`="'.$tarif['core_fix'].'",
+ `core_fix_one`="'.$fix_one.'",
+ `reinstall`="'.$start_point.'" WHERE `id`="'.$server['id'].'" LIMIT 1');
- // Запись установленных плагинов
- if($tarif['plugins'])
- {
- // Массив идентификаторов плагинов
- $aPlugins = sys::b64js($tarif['plugins_install']);
+ // Запись установленных плагинов
+ if($tarif['plugins'])
+ {
+ // Массив идентификаторов плагинов
+ $aPlugins = sys::b64js($tarif['plugins_install']);
- if(isset($aPlugins[$tarif['pack']]))
- {
- $plugins = explode(',', $aPlugins[$tarif['pack']]);
+ if(isset($aPlugins[$tarif['pack']]))
+ {
+ $plugins = explode(',', $aPlugins[$tarif['pack']]);
- foreach($plugins as $plugin)
- if($plugin)
- $sql->query('INSERT INTO `plugins_install` set `server`="'.$server['id'].'", `plugin`="'.$plugin.'", `time`="'.$start_point.'"');
- }
- }
+ foreach($plugins as $plugin)
+ if($plugin)
+ $sql->query('INSERT INTO `plugins_install` set `server`="'.$server['id'].'", `plugin`="'.$plugin.'", `time`="'.$start_point.'"');
+ }
+ }
- return NULL;
- }
+ return NULL;
+ }
}
?>
\ No newline at end of file
diff --git a/system/library/games/scans.php b/system/library/games/scans.php
index 5a94ea6..a8ce22b 100644
--- a/system/library/games/scans.php
+++ b/system/library/games/scans.php
@@ -1,237 +1,237 @@
'hlds_',
- 'cssold' => 'srcds_i686',
- 'css' => 'srcds_',
- 'csgo' => 'srcds_',
- 'samp' => 'samp',
- 'crmp' => 'samp',
- 'mta' => 'mta',
- 'mc' => 'java'
- );
+ class scans
+ {
+ private static $process = array(
+ 'cs' => 'hlds_',
+ 'cssold' => 'srcds_i686',
+ 'css' => 'srcds_',
+ 'csgo' => 'srcds_',
+ 'samp' => 'samp',
+ 'crmp' => 'samp',
+ 'mta' => 'mta',
+ 'mc' => 'java'
+ );
- public static function resources($id)
- {
- global $cfg, $sql, $mcache;
+ public static function resources($id)
+ {
+ global $cfg, $sql, $mcache;
- $nmch = 'server_resources_'.$id;
+ $nmch = 'server_resources_'.$id;
- if(is_array($mcache->get($nmch)))
- return $mcache->get($nmch);
+ if(is_array($mcache->get($nmch)))
+ return $mcache->get($nmch);
- $sql->query('SELECT `uid`, `unit`, `tarif`, `game`, `slots`, `slots_start`, `status`, `online`, `ram`, `hdd`, `hdd_use` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $sql->query('SELECT `uid`, `unit`, `tarif`, `game`, `slots`, `slots_start`, `status`, `online`, `ram`, `hdd`, `hdd_use` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- if(!$sql->num())
- return NULL;
+ if(!$sql->num())
+ return NULL;
- $server = $sql->get();
+ $server = $sql->get();
- $resources = array(
- 'usr' => 0,
- 'cpu' => 0,
- 'ram' => 0,
- 'hdd' => $server['hdd_use']
- );
+ $resources = array(
+ 'usr' => 0,
+ 'cpu' => 0,
+ 'ram' => 0,
+ 'hdd' => $server['hdd_use']
+ );
- $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
- $tarif = $sql->get();
+ $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
+ $tarif = $sql->get();
- $sql->query('SELECT `address`, `passwd`, `ram` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd`, `ram` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return $resources;
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return $resources;
- if(!in_array($server['status'], array('working', 'start', 'restart', 'change')))
- return $resources;
+ if(!in_array($server['status'], array('working', 'start', 'restart', 'change')))
+ return $resources;
- $resources['usr'] = ceil(100/$server['slots_start']*$server['online']);
- $resources['usr'] = $resources['usr'] > 100 ? 100 : $resources['usr'];
+ $resources['usr'] = ceil(100/$server['slots_start']*$server['online']);
+ $resources['usr'] = $resources['usr'] > 100 ? 100 : $resources['usr'];
- $cr = explode('|', $ssh->get('top -u '.$server['uid'].' -b -n 1 | grep '.(scans::$process[$server['game']]).' | sort | tail -1 | awk \'{print $9"|"$10}\''));
+ $cr = explode('|', $ssh->get('top -u '.$server['uid'].' -b -n 1 | grep '.(scans::$process[$server['game']]).' | sort | tail -1 | awk \'{print $9"|"$10}\''));
- if(isset($cr[0]))
- $resources['cpu'] = str_replace(',', '.', $cr[0]);
+ if(isset($cr[0]))
+ $resources['cpu'] = str_replace(',', '.', $cr[0]);
- $resources['cpu'] = $resources['cpu'] > 100 ? 100 : round($resources['cpu']);
+ $resources['cpu'] = $resources['cpu'] > 100 ? 100 : round($resources['cpu']);
- if(isset($cr[1]))
- $resources['ram'] = str_replace(',', '.', $cr[1]);
+ if(isset($cr[1]))
+ $resources['ram'] = str_replace(',', '.', $cr[1]);
- // ram на сервер
- $ram = $server['ram'] ? $server['ram'] : $server['slots']*$cfg['ram'][$server['game']];
+ // ram на сервер
+ $ram = $server['ram'] ? $server['ram'] : $server['slots']*$cfg['ram'][$server['game']];
- $resources['ram'] = $unit['ram']/100*$resources['ram']/($ram/100);
-
- $resources['ram'] = $resources['ram'] > 100 ? 100 : round($resources['ram']);
+ $resources['ram'] = $unit['ram']/100*$resources['ram']/($ram/100);
+
+ $resources['ram'] = $resources['ram'] > 100 ? 100 : round($resources['ram']);
- $resources['hdd'] = ceil(sys::int($ssh->get('cd '.$tarif['install'].$server['uid'].' && du -ms'))/($server['hdd']/100));
- $resources['hdd'] = $resources['hdd'] > 100 ? 100 : $resources['hdd'];
+ $resources['hdd'] = ceil(sys::int($ssh->get('cd '.$tarif['install'].$server['uid'].' && du -ms'))/($server['hdd']/100));
+ $resources['hdd'] = $resources['hdd'] > 100 ? 100 : $resources['hdd'];
- $sql->query('UPDATE `servers` set `ram_use`="'.$resources['ram'].'", `cpu_use`="'.$resources['cpu'].'", `hdd_use`="'.$resources['hdd'].'" WHERE `id`="'.$id.'" LIMIT 1');
+ $sql->query('UPDATE `servers` set `ram_use`="'.$resources['ram'].'", `cpu_use`="'.$resources['cpu'].'", `hdd_use`="'.$resources['hdd'].'" WHERE `id`="'.$id.'" LIMIT 1');
- $mcache->set($nmch, $resources, false, $cfg['mcache_server_resources']);
+ $mcache->set($nmch, $resources, false, $cfg['mcache_server_resources']);
- return $resources;
- }
+ return $resources;
+ }
- public static function status($id)
- {
- global $start_point, $cfg, $sql, $mcache;
+ public static function status($id)
+ {
+ global $start_point, $cfg, $sql, $mcache;
- $nmch = 'server_status_'.$id;
+ $nmch = 'server_status_'.$id;
- if($mcache->get($nmch))
- return 'mcache -> system_block_operation';
+ if($mcache->get($nmch))
+ return 'mcache -> system_block_operation';
- $mcache->set($nmch, true, false, $cfg['mcache_server_status']);
+ $mcache->set($nmch, true, false, $cfg['mcache_server_status']);
- $sql->query('SELECT `uid`, `unit`, `game`, `address`, `status`, `name`, `online`, `players`, `time`, `overdue`, `ftp`, `block` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $server = $sql->get();
+ $sql->query('SELECT `uid`, `unit`, `game`, `address`, `status`, `name`, `online`, `players`, `time`, `overdue`, `ftp`, `block` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $server = $sql->get();
- // Если аренда не закончилась, а сервер просрочен
- if($server['time'] > $start_point && $server['status'] == 'overdue')
- {
- $sql->query('UPDATE `servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
+ // Если аренда не закончилась, а сервер просрочен
+ if($server['time'] > $start_point && $server['status'] == 'overdue')
+ {
+ $sql->query('UPDATE `servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
- sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0, 'players' => ''));
- sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0));
+ sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0, 'players' => ''));
+ sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0));
- return 'server -> extend -> off';
- }
+ return 'server -> extend -> off';
+ }
- // Если аренда закончилась и сервер просрочен длительное время
- if($server['time'] < $start_point && $server['status'] == 'overdue' && ($server['overdue']+$cfg['server_delete']*86400) < $start_point)
- {
- $sql->query('UPDATE `servers` set `user`="-1" WHERE `id`="'.$id.'" LIMIT 1');
+ // Если аренда закончилась и сервер просрочен длительное время
+ if($server['time'] < $start_point && $server['status'] == 'overdue' && ($server['overdue']+$cfg['server_delete']*86400) < $start_point)
+ {
+ $sql->query('UPDATE `servers` set `user`="-1" WHERE `id`="'.$id.'" LIMIT 1');
- return 'server -> overdue -> delete';
- }
+ return 'server -> overdue -> delete';
+ }
- $sql->query('SELECT `address`, `passwd`, `sql_login`, `sql_passwd`, `sql_port`, `sql_ftp` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $sql->query('SELECT `address`, `passwd`, `sql_login`, `sql_passwd`, `sql_port`, `sql_ftp` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- return 'unit error connect';
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ return 'unit error connect';
- // Если аренда закончилась, а сервер не просрочен
- if($server['time'] < $start_point && !in_array($server['status'], array('overdue', 'blocked')))
- {
- // Убить процессы
- $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
- .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
+ // Если аренда закончилась, а сервер не просрочен
+ if($server['time'] < $start_point && !in_array($server['status'], array('overdue', 'blocked')))
+ {
+ // Убить процессы
+ $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
+ .'lsof -i@'.$server['address'].' | awk '."'{print $2}'".' | grep -v PID | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
- if($server['ftp'])
- $ssh->set("mysql -P ".$unit['sql_port']." -u".$unit['sql_login']." -p".$unit['sql_passwd']." --database ".$unit['sql_ftp']." -e \"DELETE FROM ftp WHERE user='".$server['uid']."'\"");
+ if($server['ftp'])
+ $ssh->set("mysql -P ".$unit['sql_port']." -u".$unit['sql_login']." -p".$unit['sql_passwd']." --database ".$unit['sql_ftp']." -e \"DELETE FROM ftp WHERE user='".$server['uid']."'\"");
- $sql->query('UPDATE `servers` set `status`="overdue", `online`="0", `players`="", `ftp`="0", `overdue`="'.$start_point.'", `mail`="1" WHERE `id`="'.$id.'" LIMIT 1');
+ $sql->query('UPDATE `servers` set `status`="overdue", `online`="0", `players`="", `ftp`="0", `overdue`="'.$start_point.'", `mail`="1" WHERE `id`="'.$id.'" LIMIT 1');
- sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'overdue', 'online' => 0, 'players' => ''));
- sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'overdue', 'online' => 0));
+ sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'overdue', 'online' => 0, 'players' => ''));
+ sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'overdue', 'online' => 0));
- return 'server -> overdue -> stoping';
- }
+ return 'server -> overdue -> stoping';
+ }
- switch($server['status'])
- {
- case 'working': case 'change': case 'start': case 'restart':
- if(!sys::int($ssh->get('ps aux | grep s_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
- {
- $sql->query('UPDATE `servers` set `status`="off", `online`="0", `players`="0" WHERE `id`="'.$id.'" LIMIT 1');
+ switch($server['status'])
+ {
+ case 'working': case 'change': case 'start': case 'restart':
+ if(!sys::int($ssh->get('ps aux | grep s_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
+ {
+ $sql->query('UPDATE `servers` set `status`="off", `online`="0", `players`="0" WHERE `id`="'.$id.'" LIMIT 1');
- sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0, 'players' => ''));
- sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0));
+ sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0, 'players' => ''));
+ sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0));
- return 'server -> working -> off';
- }
+ return 'server -> working -> off';
+ }
- break;
+ break;
- case 'off':
- if(sys::int($ssh->get('ps aux | grep s_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
- {
- $sql->query('UPDATE `servers` set `status`="working" WHERE `id`="'.$id.'" LIMIT 1');
+ case 'off':
+ if(sys::int($ssh->get('ps aux | grep s_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
+ {
+ $sql->query('UPDATE `servers` set `status`="working" WHERE `id`="'.$id.'" LIMIT 1');
- sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'working', 'online' => $server['online'], 'players' => $server['players']));
- sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'working', 'online' => $server['online']));
+ sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'working', 'online' => $server['online'], 'players' => $server['players']));
+ sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'working', 'online' => $server['online']));
- return 'server -> off -> working';
- }
+ return 'server -> off -> working';
+ }
- break;
+ break;
- case 'reinstall':
- if(!sys::int($ssh->get('ps aux | grep r_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
- {
- $sql->query('UPDATE `servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
+ case 'reinstall':
+ if(!sys::int($ssh->get('ps aux | grep r_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
+ {
+ $sql->query('UPDATE `servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
- sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0, 'players' => ''));
- sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0));
+ sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0, 'players' => ''));
+ sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0));
- return 'server -> reinstall -> end';
- }
+ return 'server -> reinstall -> end';
+ }
- break;
+ break;
- case 'update':
- if(!sys::int($ssh->get('ps aux | grep u_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
- {
- $sql->query('UPDATE `servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
+ case 'update':
+ if(!sys::int($ssh->get('ps aux | grep u_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
+ {
+ $sql->query('UPDATE `servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
- sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0, 'players' => ''));
- sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0));
+ sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0, 'players' => ''));
+ sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0));
- return 'server -> update -> end';
- }
+ return 'server -> update -> end';
+ }
- break;
+ break;
- case 'install':
- if(!sys::int($ssh->get('ps aux | grep i_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
- {
- $sql->query('UPDATE `servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
+ case 'install':
+ if(!sys::int($ssh->get('ps aux | grep i_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
+ {
+ $sql->query('UPDATE `servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
- sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0, 'players' => ''));
- sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0));
+ sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0, 'players' => ''));
+ sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0));
- return 'server -> install -> end';
- }
+ return 'server -> install -> end';
+ }
- break;
+ break;
- case 'recovery':
- if(!sys::int($ssh->get('ps aux | grep rec_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
- {
- $sql->query('UPDATE `servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
+ case 'recovery':
+ if(!sys::int($ssh->get('ps aux | grep rec_'.$server['uid'].' | grep -v grep | awk \'{print $2}\'')))
+ {
+ $sql->query('UPDATE `servers` set `status`="off" WHERE `id`="'.$id.'" LIMIT 1');
- sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0, 'players' => ''));
- sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0));
+ sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0, 'players' => ''));
+ sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0));
- return 'server -> recovery -> end';
- }
+ return 'server -> recovery -> end';
+ }
- break;
+ break;
- case 'blocked':
- if($server['block'] > $start_point)
- break;
+ case 'blocked':
+ if($server['block'] > $start_point)
+ break;
- $sql->query('UPDATE `servers` set `status`="off", `block`="0" WHERE `id`="'.$id.'" LIMIT 1');
+ $sql->query('UPDATE `servers` set `status`="off", `block`="0" WHERE `id`="'.$id.'" LIMIT 1');
- sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0, 'players' => ''));
- sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0));
- }
+ sys::reset_mcache('server_scan_mon_pl_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0, 'players' => ''));
+ sys::reset_mcache('server_scan_mon_'.$id, $id, array('name' => $server['name'], 'game' => $server['game'], 'status' => 'off', 'online' => 0));
+ }
- return 'server -> no change -> end scan';
- }
- }
+ return 'server -> no change -> end scan';
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/games/services.php b/system/library/games/services.php
index 4ab56b6..48d32b6 100644
--- a/system/library/games/services.php
+++ b/system/library/games/services.php
@@ -1,58 +1,58 @@
query('SELECT `id` FROM `units` WHERE `'.$game.'`="1" AND `show`="1" ORDER BY `sort` ASC');
- while($unit = $sql->get($units))
- {
- $sql->query('SELECT `id` FROM `tarifs` WHERE `unit`="'.$unit['id'].'" AND `game`="'.$game.'" AND `show`="1" LIMIT 1');
- if(!$sql->num())
- continue;
- else{
- $sel = $unit['id'];
- break;
- }
- }
+ $units = $sql->query('SELECT `id` FROM `units` WHERE `'.$game.'`="1" AND `show`="1" ORDER BY `sort` ASC');
+ while($unit = $sql->get($units))
+ {
+ $sql->query('SELECT `id` FROM `tarifs` WHERE `unit`="'.$unit['id'].'" AND `game`="'.$game.'" AND `show`="1" LIMIT 1');
+ if(!$sql->num())
+ continue;
+ else{
+ $sel = $unit['id'];
+ break;
+ }
+ }
- return 'SELECT `id`, `test` FROM `units` WHERE `id`="'.$sel.'" LIMIT 1';
- }
+ return 'SELECT `id`, `test` FROM `units` WHERE `id`="'.$sel.'" LIMIT 1';
+ }
- public static function units($game)
- {
- global $sql;
+ public static function units($game)
+ {
+ global $sql;
- $list = '';
+ $list = '';
- $units = $sql->query('SELECT `id`, `name` FROM `units` WHERE `'.$game.'`="1" AND `show`="1" ORDER BY `sort` ASC');
- while($unit = $sql->get($units))
- {
- $sql->query('SELECT `id` FROM `tarifs` WHERE `unit`="'.$unit['id'].'" AND `game`="'.$game.'" AND `show`="1" LIMIT 1');
- if($sql->num())
- $list .= '#'.$unit['id'].' '.$unit['name'].' ';
- }
+ $units = $sql->query('SELECT `id`, `name` FROM `units` WHERE `'.$game.'`="1" AND `show`="1" ORDER BY `sort` ASC');
+ while($unit = $sql->get($units))
+ {
+ $sql->query('SELECT `id` FROM `tarifs` WHERE `unit`="'.$unit['id'].'" AND `game`="'.$game.'" AND `show`="1" LIMIT 1');
+ if($sql->num())
+ $list .= '#'.$unit['id'].' '.$unit['name'].' ';
+ }
- return $list;
- }
+ return $list;
+ }
- public static function tarifs($game, $unit)
- {
- global $sql;
+ public static function tarifs($game, $unit)
+ {
+ global $sql;
- $list = '';
+ $list = '';
- $sql->query('SELECT `id`, `name` FROM `tarifs` WHERE `game`="'.$game.'" AND `unit`="'.$unit.'" AND `show`="1" ORDER BY `sort` ASC');
- while($tarif = $sql->get())
- $list .= ''.$tarif['name'].' ';
+ $sql->query('SELECT `id`, `name` FROM `tarifs` WHERE `game`="'.$game.'" AND `unit`="'.$unit.'" AND `show`="1" ORDER BY `sort` ASC');
+ while($tarif = $sql->get())
+ $list .= ''.$tarif['name'].' ';
- return $list;
- }
- }
+ return $list;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/games/tarifs.php b/system/library/games/tarifs.php
index bda7f67..5c18f2f 100644
--- a/system/library/games/tarifs.php
+++ b/system/library/games/tarifs.php
@@ -1,218 +1,218 @@
query('SELECT `aid`, `time` FROM `address_buy` WHERE `server`="'.$sid.'" LIMIT 1');
- if(!$sql->num())
- return NULL;
-
- $ip_buy = $sql->get();
-
- $sql->query('SELECT `ip`, `price` FROM `address` WHERE `id`="'.$ip_buy['aid'].'" LIMIT 1');
-
- $ip_buy = array_merge($ip_buy, $sql->get());
-
- $html->get('extend_address', 'sections/servers/games/tarif');
- $html->set('address', $ip_buy['ip'].':'.params::$aDefPort[$game]);
- $html->set('iptime', sys::date('max', $ip_buy['time']));
- $html->set('ipprice', $ip_buy['price']);
- $html->set('cur', $cfg['currency']);
- $html->pack('extend_address');
-
- return NULL;
- }
-
- public static function address($server, $sid)
- {
- global $cfg, $sql, $html;
-
- $sql->query('SELECT `address` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $sUnit = $sql->get();
-
- if(sys::first(explode(':', $sUnit['address'])) != sys::first(explode(':', $server['address'])))
- {
- if($cfg['buy_address'][$server['game']])
- tarif::address_extend($server['address'], $sid);
-
- return NULL;
- }
-
- $options = 'Выберете выделенный адрес ';
-
- $sql->query('SELECT `id`, `ip`, `price` FROM `address` WHERE `unit`="'.$server['unit'].'" AND `buy`="0"');
- if(!$sql->num())
- return NULL;
-
- while($ip = $sql->get())
- $options .= ''.$ip['ip'].':'.params::$aDefPort[$server['game']].' ';
-
- $html->get('address', 'sections/servers/games/tarif');
- if($cfg['buy_address'][$server['game']]){
- $html->unit('!mounth');
- $html->unit('mounth', 1);
- }else{
- $html->unit('!mounth', 1);
- $html->unit('mounth');
- }
-
- $html->set('id', $sid);
- $html->set('options', $options);
- $html->set('address', $server['address']);
- $html->set('cur', $cfg['currency']);
- $html->pack('main');
-
- return NULL;
- }
-
- public static function address_extend($address, $sid)
- {
- global $cfg, $sql, $html;
-
- $sql->query('SELECT `aid`, `time` FROM `address_buy` WHERE `server`="'.$sid.'" LIMIT 1');
-
- if(!$sql->num())
- return NULL;
-
- $add = $sql->get();
-
- $sql->query('SELECT `price` FROM `address` WHERE `id`="'.$add['aid'].'" LIMIT 1');
-
- if(!$sql->num())
- return NULL;
-
- $add = array_merge($add, $sql->get());
-
- $html->get('address_extend', 'sections/servers/games/tarif');
- $html->set('address', $address);
- $html->set('time', sys::date('max', $add['time']));
- $html->set('price', $add['price']);
- $html->set('cur', $cfg['currency']);
- $html->pack('main');
-
- return NULL;
- }
-
- public static function address_add_sum($address, $server)
- {
- global $sql;
-
- if(!$address)
- return 0;
-
- $ip = sys::first(explode(':', $server['address']));
-
- $sql->query('SELECT `address` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
-
- if($address AND sys::first(explode(':', $unit['address'])) != $ip)
- {
- $sql->query('SELECT `price` FROM `address` WHERE `ip`="'.$ip.'" LIMIT 1');
-
- if($sql->num())
- {
- $add = $sql->get();
-
- return $add['price'];
- }
- }
-
- return 0;
- }
-
- public static function slots($server, $aSlots, $sid)
+ class tarifs
+ {
+ public static function extend_address($game, $sid)
{
- global $cfg, $html, $start_point;
+ global $cfg, $sql, $html, $start_point;
- $options = 'Выберете количество слот ';
+ $sql->query('SELECT `aid`, `time` FROM `address_buy` WHERE `server`="'.$sid.'" LIMIT 1');
+ if(!$sql->num())
+ return NULL;
- // С уменьшением (min ==> max) || закончился срок аренды
- if(($cfg['change_slots'][$server['game']]['days'] AND $cfg['change_slots'][$server['game']]['down']) || $server['time'] < $start_point)
- {
- for($i = $aSlots['min']; $i <= $aSlots['max']; $i+=1)
- $options .= ''.$i.' шт. ';
+ $ip_buy = $sql->get();
- $html->get('slots', 'sections/servers/games/tarif');
- }else{
- if($server['slots'] == $aSlots['max'])
- return NULL;
+ $sql->query('SELECT `ip`, `price` FROM `address` WHERE `id`="'.$ip_buy['aid'].'" LIMIT 1');
- $max = $aSlots['max']-$server['slots'];
+ $ip_buy = array_merge($ip_buy, $sql->get());
- if($max < 1)
- return NULL;
+ $html->get('extend_address', 'sections/servers/games/tarif');
+ $html->set('address', $ip_buy['ip'].':'.params::$aDefPort[$game]);
+ $html->set('iptime', sys::date('max', $ip_buy['time']));
+ $html->set('ipprice', $ip_buy['price']);
+ $html->set('cur', $cfg['currency']);
+ $html->pack('extend_address');
- for($i = 1; $i <= $max; $i+=1)
- $options .= ''.$i.' шт. ';
+ return NULL;
+ }
- $html->get('slots_buy', 'sections/servers/games/tarif');
- }
+ public static function address($server, $sid)
+ {
+ global $cfg, $sql, $html;
- $html->set('id', $sid);
- $html->set('options', $options);
- $html->set('slots', $server['slots']);
- $html->set('cur', $cfg['currency']);
- $html->pack('main');
+ $sql->query('SELECT `address` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $sUnit = $sql->get();
- return NULL;
- }
+ if(sys::first(explode(':', $sUnit['address'])) != sys::first(explode(':', $server['address'])))
+ {
+ if($cfg['buy_address'][$server['game']])
+ tarif::address_extend($server['address'], $sid);
- public static function price($plan)
- {
- $aPrice = explode(':', $plan);
+ return NULL;
+ }
- $check = $aPrice[0];
+ $options = 'Выберете выделенный адрес ';
- unset($aPrice[0]);
+ $sql->query('SELECT `id`, `ip`, `price` FROM `address` WHERE `unit`="'.$server['unit'].'" AND `buy`="0"');
+ if(!$sql->num())
+ return NULL;
- if(!count($aPrice))
- return false;
+ while($ip = $sql->get())
+ $options .= ''.$ip['ip'].':'.params::$aDefPort[$server['game']].' ';
- foreach($aPrice as $price)
- if($check != $price)
- return true;
+ $html->get('address', 'sections/servers/games/tarif');
+ if($cfg['buy_address'][$server['game']]){
+ $html->unit('!mounth');
+ $html->unit('mounth', 1);
+ }else{
+ $html->unit('!mounth', 1);
+ $html->unit('mounth');
+ }
- return false;
- }
+ $html->set('id', $sid);
+ $html->set('options', $options);
+ $html->set('address', $server['address']);
+ $html->set('cur', $cfg['currency']);
+ $html->pack('main');
- public static function unit_old($tarif, $unit, $server, $mcache)
- {
- global $ssh, $sql, $user, $start_point;
+ return NULL;
+ }
- // Проверка ssh соединения с локацией
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- sys::outjs(array('e' => sys::text('error', 'ssh')), $mcache);
+ public static function address_extend($address, $sid)
+ {
+ global $cfg, $sql, $html;
- // Убить процессы
- $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
- .'lsof -i@:'.$server['address'].' | awk '."'{print $2}'".' | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
+ $sql->query('SELECT `aid`, `time` FROM `address_buy` WHERE `server`="'.$sid.'" LIMIT 1');
- // Директория игрового сервера
- $install = $tarif['install'].$server['uid'];
+ if(!$sql->num())
+ return NULL;
- $copys = 'screen -dmS r_copy_'.$server['uid'].' sh -c "';
+ $add = $sql->get();
- $scopy = $sql->query('SELECT `id`, `name` FROM `copy` WHERE `server`="'.$server['id'].'"');
- while($copy = $sql->get($scopy))
- {
- $copys .= 'rm /copy/'.$copy['name'].'.tar;';
+ $sql->query('SELECT `price` FROM `address` WHERE `id`="'.$add['aid'].'" LIMIT 1');
- $sql->query('DELETE FROM `copy` WHERE `id`="'.$copy['id'].'" LIMIT 1');
- }
+ if(!$sql->num())
+ return NULL;
- $copys .= '";';
+ $add = array_merge($add, $sql->get());
- $ssh->set($copys // Удаление резервных копий
- .'screen -dmS r_'.$server['uid'].' rm -r '.$install.';' // Удаление директории сервера
- .'userdel server'.$server['uid']); // Удаление пользователя сервера c локации
+ $html->get('address_extend', 'sections/servers/games/tarif');
+ $html->set('address', $address);
+ $html->set('time', sys::date('max', $add['time']));
+ $html->set('price', $add['price']);
+ $html->set('cur', $cfg['currency']);
+ $html->pack('main');
- // Удаление ftp доступа
- $qSql = 'DELETE FROM users WHERE username=\''.$server['uid'].'\';'
+ return NULL;
+ }
+
+ public static function address_add_sum($address, $server)
+ {
+ global $sql;
+
+ if(!$address)
+ return 0;
+
+ $ip = sys::first(explode(':', $server['address']));
+
+ $sql->query('SELECT `address` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
+
+ if($address AND sys::first(explode(':', $unit['address'])) != $ip)
+ {
+ $sql->query('SELECT `price` FROM `address` WHERE `ip`="'.$ip.'" LIMIT 1');
+
+ if($sql->num())
+ {
+ $add = $sql->get();
+
+ return $add['price'];
+ }
+ }
+
+ return 0;
+ }
+
+ public static function slots($server, $aSlots, $sid)
+ {
+ global $cfg, $html, $start_point;
+
+ $options = 'Выберете количество слот ';
+
+ // С уменьшением (min ==> max) || закончился срок аренды
+ if(($cfg['change_slots'][$server['game']]['days'] AND $cfg['change_slots'][$server['game']]['down']) || $server['time'] < $start_point)
+ {
+ for($i = $aSlots['min']; $i <= $aSlots['max']; $i+=1)
+ $options .= ''.$i.' шт. ';
+
+ $html->get('slots', 'sections/servers/games/tarif');
+ }else{
+ if($server['slots'] == $aSlots['max'])
+ return NULL;
+
+ $max = $aSlots['max']-$server['slots'];
+
+ if($max < 1)
+ return NULL;
+
+ for($i = 1; $i <= $max; $i+=1)
+ $options .= ''.$i.' шт. ';
+
+ $html->get('slots_buy', 'sections/servers/games/tarif');
+ }
+
+ $html->set('id', $sid);
+ $html->set('options', $options);
+ $html->set('slots', $server['slots']);
+ $html->set('cur', $cfg['currency']);
+ $html->pack('main');
+
+ return NULL;
+ }
+
+ public static function price($plan)
+ {
+ $aPrice = explode(':', $plan);
+
+ $check = $aPrice[0];
+
+ unset($aPrice[0]);
+
+ if(!count($aPrice))
+ return false;
+
+ foreach($aPrice as $price)
+ if($check != $price)
+ return true;
+
+ return false;
+ }
+
+ public static function unit_old($tarif, $unit, $server, $mcache)
+ {
+ global $ssh, $sql, $user, $start_point;
+
+ // Проверка ssh соединения с локацией
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ sys::outjs(array('e' => sys::text('error', 'ssh')), $mcache);
+
+ // Убить процессы
+ $ssh->set('kill -9 `ps aux | grep s_'.$server['uid'].' | grep -v grep | awk '."'{print $2}'".' | xargs;'
+ .'lsof -i@:'.$server['address'].' | awk '."'{print $2}'".' | xargs`; sudo -u server'.$server['uid'].' screen -wipe');
+
+ // Директория игрового сервера
+ $install = $tarif['install'].$server['uid'];
+
+ $copys = 'screen -dmS r_copy_'.$server['uid'].' sh -c "';
+
+ $scopy = $sql->query('SELECT `id`, `name` FROM `copy` WHERE `server`="'.$server['id'].'"');
+ while($copy = $sql->get($scopy))
+ {
+ $copys .= 'rm /copy/'.$copy['name'].'.tar;';
+
+ $sql->query('DELETE FROM `copy` WHERE `id`="'.$copy['id'].'" LIMIT 1');
+ }
+
+ $copys .= '";';
+
+ $ssh->set($copys // Удаление резервных копий
+ .'screen -dmS r_'.$server['uid'].' rm -r '.$install.';' // Удаление директории сервера
+ .'userdel server'.$server['uid']); // Удаление пользователя сервера c локации
+
+ // Удаление ftp доступа
+ $qSql = 'DELETE FROM users WHERE username=\''.$server['uid'].'\';'
.'DELETE FROM quotalimits WHERE name=\''.$server['uid'].'\';'
.'DELETE FROM quotatallies WHERE name=\''.$server['uid'].'\'';
@@ -220,50 +220,50 @@
$sql->query('UPDATE `servers` SET `ftp`="0" WHERE `id`="'.$server['id'].'" LIMIT 1');
- // Очистка правил FireWall
- games::iptables($server['id'], 'remove', NULL, NULL, NULL, false, $ssh);
+ // Очистка правил FireWall
+ games::iptables($server['id'], 'remove', NULL, NULL, NULL, false, $ssh);
- // Удаление заданий из crontab
- $sql->query('SELECT `address`, `passwd` FROM `panel` LIMIT 1');
- $panel = $sql->get();
+ // Удаление заданий из crontab
+ $sql->query('SELECT `address`, `passwd` FROM `panel` LIMIT 1');
+ $panel = $sql->get();
- if(!$ssh->auth($panel['passwd'], $panel['address']))
- sys::outjs(array('e' => sys::text('error', 'ssh')), $mcache);
+ if(!$ssh->auth($panel['passwd'], $panel['address']))
+ sys::outjs(array('e' => sys::text('error', 'ssh')), $mcache);
- $crons = $sql->query('SELECT `id`, `cron` FROM `crontab` WHERE `server`="'.$server['id'].'"');
- while($cron = $sql->get($crons))
- {
- $ssh->set('echo "" >> /etc/crontab && cat /etc/crontab');
- $crontab = str_replace($cron['cron'], '', $ssh->get());
+ $crons = $sql->query('SELECT `id`, `cron` FROM `crontab` WHERE `server`="'.$server['id'].'"');
+ while($cron = $sql->get($crons))
+ {
+ $ssh->set('echo "" >> /etc/crontab && cat /etc/crontab');
+ $crontab = str_replace($cron['cron'], '', $ssh->get());
- // Временный файл
- $temp = sys::temp($crontab);
+ // Временный файл
+ $temp = sys::temp($crontab);
- $ssh->setfile($temp, '/etc/crontab', 0644);
+ $ssh->setfile($temp, '/etc/crontab', 0644);
- $ssh->set("sed -i '/^$/d' /etc/crontab");
- $ssh->set('crontab -u root /etc/crontab');
+ $ssh->set("sed -i '/^$/d' /etc/crontab");
+ $ssh->set('crontab -u root /etc/crontab');
- unlink($temp);
+ unlink($temp);
- $sql->query('DELETE FROM `crontab` WHERE `id`="'.$cron['id'].'" LIMIT 1');
- }
+ $sql->query('DELETE FROM `crontab` WHERE `id`="'.$cron['id'].'" LIMIT 1');
+ }
- // Удаление установок игрового сервера
- $sql->query('DELETE FROM `admins_'.$server['game'].'` WHERE `server`="'.$server['id'].'" LIMIT 1');
- $sql->query('DELETE FROM `plugins_install` WHERE `server`="'.$server['id'].'" LIMIT 1');
+ // Удаление установок игрового сервера
+ $sql->query('DELETE FROM `admins_'.$server['game'].'` WHERE `server`="'.$server['id'].'" LIMIT 1');
+ $sql->query('DELETE FROM `plugins_install` WHERE `server`="'.$server['id'].'" LIMIT 1');
- // Обновление данных выделенного адреса
- $sql->query('SELECT `id`, `aid` FROM `address_buy` WHERE `server`="'.$server['id'].'" LIMIT 1');
- if($sql->num())
- {
- $add = $sql->get();
+ // Обновление данных выделенного адреса
+ $sql->query('SELECT `id`, `aid` FROM `address_buy` WHERE `server`="'.$server['id'].'" LIMIT 1');
+ if($sql->num())
+ {
+ $add = $sql->get();
- $sql->query('UPDATE `address` set `buy`="0" WHERE `id`="'.$add['aid'].'" LIMIT 1');
- $sql->query('DELETE FROM `address_buy` WHERE `id`="'.$add['id'].'" LIMIT 1');
- }
+ $sql->query('UPDATE `address` set `buy`="0" WHERE `id`="'.$add['aid'].'" LIMIT 1');
+ $sql->query('DELETE FROM `address_buy` WHERE `id`="'.$add['id'].'" LIMIT 1');
+ }
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/geo.php b/system/library/geo.php
index 0188dc3..7364474 100644
--- a/system/library/geo.php
+++ b/system/library/geo.php
@@ -1,393 +1,393 @@
fh = fopen($db_file, 'rb');
-
- $header = fread($this->fh, 40);
- if(substr($header, 0, 3) != 'SxG')
- die("Can't open {$db_file}\n");
-
- $info = unpack('Cver/Ntime/Ctype/Ccharset/Cb_idx_len/nm_idx_len/nrange/Ndb_items/Cid_len/nmax_region/nmax_city/Nregion_size/Ncity_size/nmax_country/Ncountry_size/npack_size', substr($header, 3));
-
- if($info['b_idx_len'] * $info['m_idx_len'] * $info['range'] * $info['db_items'] * $info['time'] * $info['id_len'] == 0)
- die("Wrong file format {$db_file}\n");
-
- $this->range = $info['range'];
- $this->b_idx_len = $info['b_idx_len'];
- $this->m_idx_len = $info['m_idx_len'];
- $this->db_items = $info['db_items'];
- $this->id_len = $info['id_len'];
- $this->block_len = 3 + $this->id_len;
- $this->max_region = $info['max_region'];
- $this->max_city = $info['max_city'];
- $this->max_country = $info['max_country'];
- $this->country_size = $info['country_size'];
- $this->batch_mode = $type & SXGEO_BATCH;
- $this->memory_mode = $type & SXGEO_MEMORY;
- $this->pack = $info['pack_size'] ? explode("\0", fread($this->fh, $info['pack_size'])) : '';
- $this->b_idx_str = fread($this->fh, $info['b_idx_len'] * 4);
- $this->m_idx_str = fread($this->fh, $info['m_idx_len'] * 4);
- $this->db_begin = ftell($this->fh);
-
- if($this->batch_mode)
- {
- $this->b_idx_arr = array_values(unpack("N*", $this->b_idx_str));
-
- unset($this->b_idx_str);
-
- $this->m_idx_arr = str_split($this->m_idx_str, 4);
-
- unset($this->m_idx_str);
- }
-
- if($this->memory_mode)
- {
- $this->db = fread($this->fh, $this->db_items * $this->block_len);
- $this->regions_db = $info['region_size'] > 0 ? fread($this->fh, $info['region_size']) : '';
- $this->cities_db = $info['city_size'] > 0 ? fread($this->fh, $info['city_size']) : '';
- }
-
- $this->info = $info;
-
- $this->info['regions_begin'] = $this->db_begin + $this->db_items * $this->block_len;
- $this->info['cities_begin'] = $this->info['regions_begin'] + $info['region_size'];
- }
-
- protected function search_idx($ipn, $min, $max)
- {
- if($this->batch_mode)
- {
- while($max - $min > 8)
- {
- $offset = ($min + $max) >> 1;
-
- if($ipn > $this->m_idx_arr[$offset])
- $min = $offset;
- else
- $max = $offset;
- }
-
- while ($ipn > $this->m_idx_arr[$min] && $min++ < $max){};
- }else{
- while($max - $min > 8)
- {
- $offset = ($min + $max) >> 1;
-
- if($ipn > substr($this->m_idx_str, $offset*4, 4))
- $min = $offset;
- else
- $max = $offset;
- }
-
- while($ipn > substr($this->m_idx_str, $min*4, 4) && $min++ < $max){};
- }
-
- return $min;
- }
-
- protected function search_db($str, $ipn, $min, $max)
- {
- if($max - $min > 1)
- {
- $ipn = substr($ipn, 1);
-
- while($max - $min > 8)
- {
- $offset = ($min + $max) >> 1;
- if($ipn > substr($str, $offset * $this->block_len, 3))
- $min = $offset;
- else
- $max = $offset;
- }
-
- while($ipn >= substr($str, $min * $this->block_len, 3) && ++$min < $max){};
- }else
- $min++;
-
- return hexdec(bin2hex(substr($str, $min * $this->block_len - $this->id_len, $this->id_len)));
- }
-
- public function get_num($ip)
- {
- $ip1n = (int)$ip;
-
- if($ip1n == 0 || $ip1n == 10 || $ip1n == 127 || $ip1n >= $this->b_idx_len || false === ($ipn = ip2long($ip)))
- return false;
-
- $ipn = pack('N', $ipn);
- $this->ip1c = chr($ip1n);
-
- if($this->batch_mode)
- $blocks = array('min' => $this->b_idx_arr[$ip1n-1], 'max' => $this->b_idx_arr[$ip1n]);
- else
- $blocks = unpack("Nmin/Nmax", substr($this->b_idx_str, ($ip1n - 1) * 4, 8));
-
- if($blocks['max'] - $blocks['min'] > $this->range)
- {
- $part = $this->search_idx($ipn, floor($blocks['min'] / $this->range), floor($blocks['max'] / $this->range)-1);
-
- $min = $part > 0 ? $part * $this->range : 0;
- $max = $part > $this->m_idx_len ? $this->db_items : ($part+1) * $this->range;
-
- if($min < $blocks['min'])
- $min = $blocks['min'];
-
- if($max > $blocks['max'])
- $max = $blocks['max'];
- }else{
- $min = $blocks['min'];
- $max = $blocks['max'];
- }
-
- $len = $max - $min;
-
- if($this->memory_mode)
- return $this->search_db($this->db, $ipn, $min, $max);
-
- else{
- fseek($this->fh, $this->db_begin + $min * $this->block_len);
-
- return $this->search_db(fread($this->fh, $len * $this->block_len), $ipn, 0, $len);
- }
- }
-
- protected function readData($seek, $max, $type)
- {
- $raw = '';
- if($seek && $max)
- {
- if ($this->memory_mode)
- $raw = substr($type == 1 ? $this->regions_db : $this->cities_db, $seek, $max);
- else{
- fseek($this->fh, $this->info[$type == 1 ? 'regions_begin' : 'cities_begin'] + $seek);
-
- $raw = fread($this->fh, $max);
- }
- }
-
- return $this->unpack($this->pack[$type], $raw);
- }
-
- protected function parseCity($seek, $full = false)
- {
- if(!$this->pack)
- return false;
-
- $only_country = false;
-
- if($seek < $this->country_size)
- {
- $country = $this->readData($seek, $this->max_country, 0);
- $city = $this->unpack($this->pack[2]);
- $city['lat'] = $country['lat'];
- $city['lon'] = $country['lon'];
- $only_country = true;
- }else{
- $city = $this->readData($seek, $this->max_city, 2);
- $country = array('id' => $city['country_id'], 'iso' => $this->id2iso[$city['country_id']]);
- unset($city['country_id']);
- }
-
- if($full){
- $region = $this->readData($city['region_seek'], $this->max_region, 1);
-
- if(!$only_country)
- $country = $this->readData($region['country_seek'], $this->max_country, 0);
-
- unset($city['region_seek']);
- unset($region['country_seek']);
-
- return array('city' => $city, 'region' => $region, 'country' => $country);
- }else{
- unset($city['region_seek']);
-
- return array('city' => $city, 'country' => array('id' => $country['id'], 'iso' => $country['iso']));
- }
- }
-
- protected function unpack($pack, $item = '')
- {
- $unpacked = array();
- $empty = empty($item);
- $pack = explode('/', $pack);
- $pos = 0;
-
- foreach($pack AS $p)
- {
- list($type, $name) = explode(':', $p);
-
- $type0 = $type[0];
-
- if($empty)
- {
- $unpacked[$name] = $type0 == 'b' || $type0 == 'c' ? '' : 0;
-
- continue;
- }
-
- switch($type0)
- {
- case 't':
- case 'T': $l = 1; break;
- case 's':
- case 'n':
- case 'S': $l = 2; break;
- case 'm':
- case 'M': $l = 3; break;
- case 'd': $l = 8; break;
- case 'c': $l = (int)substr($type, 1); break;
- case 'b': $l = strpos($item, "\0", $pos)-$pos; break;
- default: $l = 4;
- }
-
- $val = substr($item, $pos, $l);
-
- switch($type0)
- {
- case 't': $v = unpack('c', $val); break;
- case 'T': $v = unpack('C', $val); break;
- case 's': $v = unpack('s', $val); break;
- case 'S': $v = unpack('S', $val); break;
- case 'm': $v = unpack('l', $val . (ord($val[2]) >> 7 ? "\xff" : "\0")); break;
- case 'M': $v = unpack('L', $val . "\0"); break;
- case 'i': $v = unpack('l', $val); break;
- case 'I': $v = unpack('L', $val); break;
- case 'f': $v = unpack('f', $val); break;
- case 'd': $v = unpack('d', $val); break;
-
- case 'n': $v = current(unpack('s', $val)) / pow(10, $type[1]); break;
- case 'N': $v = current(unpack('l', $val)) / pow(10, $type[1]); break;
-
- case 'c': $v = rtrim($val, ' '); break;
- case 'b': $v = $val; $l++; break;
- }
-
- $pos += $l;
- $unpacked[$name] = is_array($v) ? current($v) : $v;
- }
-
- return $unpacked;
- }
-
- public function get($ip)
- {
- return $this->max_city ? $this->getCity($ip) : $this->getCountry($ip);
- }
-
- public function getCountry($ip)
- {
- if($this->max_city)
- {
- $tmp = $this->parseCity($this->get_num($ip));
-
- return $tmp['country']['iso'];
- }else
- return $this->id2iso[$this->get_num($ip)];
- }
-
- public function getCountryId($ip)
- {
- if($this->max_city)
- {
- $tmp = $this->parseCity($this->get_num($ip));
-
- return $tmp['country']['id'];
- }else
- return $this->get_num($ip);
- }
-
- public function getCity($ip)
- {
- $seek = $this->get_num($ip);
-
- return $seek ? $this->parseCity($seek) : false;
- }
-
- public function getCityFull($ip)
- {
- $seek = $this->get_num($ip);
-
- return $seek ? $this->parseCity($seek, 1) : false;
- }
-
- public function about()
- {
- $charset = array('utf-8', 'latin1', 'cp1251');
- $types = array('n/a', 'SxGeo Country', 'SxGeo City RU', 'SxGeo City EN', 'SxGeo City', 'SxGeo City Max RU', 'SxGeo City Max EN', 'SxGeo City Max');
-
- return array(
- 'Created' => date('Y.m.d', $this->info['time']),
- 'Timestamp' => $this->info['time'],
- 'Charset' => $charset[$this->info['charset']],
- 'Type' => $types[$this->info['type']],
- 'Byte Index' => $this->b_idx_len,
- 'Main Index' => $this->m_idx_len,
- 'Blocks In Index Item' => $this->range,
- 'IP Blocks' => $this->db_items,
- 'Block Size' => $this->block_len,
-
- 'City' => array(
- 'Max Length' => $this->max_city,
- 'Total Size' => $this->info['city_size'],
- ),
-
- 'Region' => array(
- 'Max Length' => $this->max_region,
- 'Total Size' => $this->info['region_size'],
- ),
-
- 'Country' => array(
- 'Max Length' => $this->max_country,
- 'Total Size' => $this->info['country_size'],
- ),
- );
- }
- }
+ exit(header('Refresh: 0; URL=http://'.$_SERVER['SERVER_NAME'].'/404'));
+
+ define('SXGEO_FILE', 0);
+ define('SXGEO_MEMORY', 1);
+ define('SXGEO_BATCH', 2);
+
+ class SxGeo
+ {
+ protected $fh;
+ protected $ip1c;
+ protected $info;
+ protected $range;
+ protected $db_begin;
+ protected $b_idx_str;
+ protected $m_idx_str;
+ protected $b_idx_arr;
+ protected $m_idx_arr;
+ protected $m_idx_len;
+ protected $db_items;
+ protected $country_size;
+ protected $db;
+ protected $regions_db;
+ protected $cities_db;
+
+ public $id2iso = array(
+ '', 'AP', 'EU', 'AD', 'AE', 'AF', 'AG', 'AI', 'AL', 'AM', 'CW', 'AO', 'AQ', 'AR', 'AS', 'AT', 'AU',
+ 'AW', 'AZ', 'BA', 'BB', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BM', 'BN', 'BO', 'BR', 'BS',
+ 'BT', 'BV', 'BW', 'BY', 'BZ', 'CA', 'CC', 'CD', 'CF', 'CG', 'CH', 'CI', 'CK', 'CL', 'CM', 'CN',
+ 'CO', 'CR', 'CU', 'CV', 'CX', 'CY', 'CZ', 'DE', 'DJ', 'DK', 'DM', 'DO', 'DZ', 'EC', 'EE', 'EG',
+ 'EH', 'ER', 'ES', 'ET', 'FI', 'FJ', 'FK', 'FM', 'FO', 'FR', 'SX', 'GA', 'GB', 'GD', 'GE', 'GF',
+ 'GH', 'GI', 'GL', 'GM', 'GN', 'GP', 'GQ', 'GR', 'GS', 'GT', 'GU', 'GW', 'GY', 'HK', 'HM', 'HN',
+ 'HR', 'HT', 'HU', 'ID', 'IE', 'IL', 'IN', 'IO', 'IQ', 'IR', 'IS', 'IT', 'JM', 'JO', 'JP', 'KE',
+ 'KG', 'KH', 'KI', 'KM', 'KN', 'KP', 'KR', 'KW', 'KY', 'KZ', 'LA', 'LB', 'LC', 'LI', 'LK', 'LR',
+ 'LS', 'LT', 'LU', 'LV', 'LY', 'MA', 'MC', 'MD', 'MG', 'MH', 'MK', 'ML', 'MM', 'MN', 'MO', 'MP',
+ 'MQ', 'MR', 'MS', 'MT', 'MU', 'MV', 'MW', 'MX', 'MY', 'MZ', 'NA', 'NC', 'NE', 'NF', 'NG', 'NI',
+ 'NL', 'NO', 'NP', 'NR', 'NU', 'NZ', 'OM', 'PA', 'PE', 'PF', 'PG', 'PH', 'PK', 'PL', 'PM', 'PN',
+ 'PR', 'PS', 'PT', 'PW', 'PY', 'QA', 'RE', 'RO', 'RU', 'RW', 'SA', 'SB', 'SC', 'SD', 'SE', 'SG',
+ 'SH', 'SI', 'SJ', 'SK', 'SL', 'SM', 'SN', 'SO', 'SR', 'ST', 'SV', 'SY', 'SZ', 'TC', 'TD', 'TF',
+ 'TG', 'TH', 'TJ', 'TK', 'TM', 'TN', 'TO', 'TL', 'TR', 'TT', 'TV', 'TW', 'TZ', 'UA', 'UG', 'UM',
+ 'US', 'UY', 'UZ', 'VA', 'VC', 'VE', 'VG', 'VI', 'VN', 'VU', 'WF', 'WS', 'YE', 'YT', 'RS', 'ZA',
+ 'ZM', 'ME', 'ZW', 'A1', 'XK', 'O1', 'AX', 'GG', 'IM', 'JE', 'BL', 'MF', 'BQ', 'SS'
+ );
+
+ public $batch_mode = false;
+ public $memory_mode = false;
+
+ public function __construct($db_file = 'SxGeo.dat', $type = SXGEO_FILE)
+ {
+ $this->fh = fopen($db_file, 'rb');
+
+ $header = fread($this->fh, 40);
+ if(substr($header, 0, 3) != 'SxG')
+ die("Can't open {$db_file}\n");
+
+ $info = unpack('Cver/Ntime/Ctype/Ccharset/Cb_idx_len/nm_idx_len/nrange/Ndb_items/Cid_len/nmax_region/nmax_city/Nregion_size/Ncity_size/nmax_country/Ncountry_size/npack_size', substr($header, 3));
+
+ if($info['b_idx_len'] * $info['m_idx_len'] * $info['range'] * $info['db_items'] * $info['time'] * $info['id_len'] == 0)
+ die("Wrong file format {$db_file}\n");
+
+ $this->range = $info['range'];
+ $this->b_idx_len = $info['b_idx_len'];
+ $this->m_idx_len = $info['m_idx_len'];
+ $this->db_items = $info['db_items'];
+ $this->id_len = $info['id_len'];
+ $this->block_len = 3 + $this->id_len;
+ $this->max_region = $info['max_region'];
+ $this->max_city = $info['max_city'];
+ $this->max_country = $info['max_country'];
+ $this->country_size = $info['country_size'];
+ $this->batch_mode = $type & SXGEO_BATCH;
+ $this->memory_mode = $type & SXGEO_MEMORY;
+ $this->pack = $info['pack_size'] ? explode("\0", fread($this->fh, $info['pack_size'])) : '';
+ $this->b_idx_str = fread($this->fh, $info['b_idx_len'] * 4);
+ $this->m_idx_str = fread($this->fh, $info['m_idx_len'] * 4);
+ $this->db_begin = ftell($this->fh);
+
+ if($this->batch_mode)
+ {
+ $this->b_idx_arr = array_values(unpack("N*", $this->b_idx_str));
+
+ unset($this->b_idx_str);
+
+ $this->m_idx_arr = str_split($this->m_idx_str, 4);
+
+ unset($this->m_idx_str);
+ }
+
+ if($this->memory_mode)
+ {
+ $this->db = fread($this->fh, $this->db_items * $this->block_len);
+ $this->regions_db = $info['region_size'] > 0 ? fread($this->fh, $info['region_size']) : '';
+ $this->cities_db = $info['city_size'] > 0 ? fread($this->fh, $info['city_size']) : '';
+ }
+
+ $this->info = $info;
+
+ $this->info['regions_begin'] = $this->db_begin + $this->db_items * $this->block_len;
+ $this->info['cities_begin'] = $this->info['regions_begin'] + $info['region_size'];
+ }
+
+ protected function search_idx($ipn, $min, $max)
+ {
+ if($this->batch_mode)
+ {
+ while($max - $min > 8)
+ {
+ $offset = ($min + $max) >> 1;
+
+ if($ipn > $this->m_idx_arr[$offset])
+ $min = $offset;
+ else
+ $max = $offset;
+ }
+
+ while ($ipn > $this->m_idx_arr[$min] && $min++ < $max){};
+ }else{
+ while($max - $min > 8)
+ {
+ $offset = ($min + $max) >> 1;
+
+ if($ipn > substr($this->m_idx_str, $offset*4, 4))
+ $min = $offset;
+ else
+ $max = $offset;
+ }
+
+ while($ipn > substr($this->m_idx_str, $min*4, 4) && $min++ < $max){};
+ }
+
+ return $min;
+ }
+
+ protected function search_db($str, $ipn, $min, $max)
+ {
+ if($max - $min > 1)
+ {
+ $ipn = substr($ipn, 1);
+
+ while($max - $min > 8)
+ {
+ $offset = ($min + $max) >> 1;
+ if($ipn > substr($str, $offset * $this->block_len, 3))
+ $min = $offset;
+ else
+ $max = $offset;
+ }
+
+ while($ipn >= substr($str, $min * $this->block_len, 3) && ++$min < $max){};
+ }else
+ $min++;
+
+ return hexdec(bin2hex(substr($str, $min * $this->block_len - $this->id_len, $this->id_len)));
+ }
+
+ public function get_num($ip)
+ {
+ $ip1n = (int)$ip;
+
+ if($ip1n == 0 || $ip1n == 10 || $ip1n == 127 || $ip1n >= $this->b_idx_len || false === ($ipn = ip2long($ip)))
+ return false;
+
+ $ipn = pack('N', $ipn);
+ $this->ip1c = chr($ip1n);
+
+ if($this->batch_mode)
+ $blocks = array('min' => $this->b_idx_arr[$ip1n-1], 'max' => $this->b_idx_arr[$ip1n]);
+ else
+ $blocks = unpack("Nmin/Nmax", substr($this->b_idx_str, ($ip1n - 1) * 4, 8));
+
+ if($blocks['max'] - $blocks['min'] > $this->range)
+ {
+ $part = $this->search_idx($ipn, floor($blocks['min'] / $this->range), floor($blocks['max'] / $this->range)-1);
+
+ $min = $part > 0 ? $part * $this->range : 0;
+ $max = $part > $this->m_idx_len ? $this->db_items : ($part+1) * $this->range;
+
+ if($min < $blocks['min'])
+ $min = $blocks['min'];
+
+ if($max > $blocks['max'])
+ $max = $blocks['max'];
+ }else{
+ $min = $blocks['min'];
+ $max = $blocks['max'];
+ }
+
+ $len = $max - $min;
+
+ if($this->memory_mode)
+ return $this->search_db($this->db, $ipn, $min, $max);
+
+ else{
+ fseek($this->fh, $this->db_begin + $min * $this->block_len);
+
+ return $this->search_db(fread($this->fh, $len * $this->block_len), $ipn, 0, $len);
+ }
+ }
+
+ protected function readData($seek, $max, $type)
+ {
+ $raw = '';
+ if($seek && $max)
+ {
+ if ($this->memory_mode)
+ $raw = substr($type == 1 ? $this->regions_db : $this->cities_db, $seek, $max);
+ else{
+ fseek($this->fh, $this->info[$type == 1 ? 'regions_begin' : 'cities_begin'] + $seek);
+
+ $raw = fread($this->fh, $max);
+ }
+ }
+
+ return $this->unpack($this->pack[$type], $raw);
+ }
+
+ protected function parseCity($seek, $full = false)
+ {
+ if(!$this->pack)
+ return false;
+
+ $only_country = false;
+
+ if($seek < $this->country_size)
+ {
+ $country = $this->readData($seek, $this->max_country, 0);
+ $city = $this->unpack($this->pack[2]);
+ $city['lat'] = $country['lat'];
+ $city['lon'] = $country['lon'];
+ $only_country = true;
+ }else{
+ $city = $this->readData($seek, $this->max_city, 2);
+ $country = array('id' => $city['country_id'], 'iso' => $this->id2iso[$city['country_id']]);
+ unset($city['country_id']);
+ }
+
+ if($full){
+ $region = $this->readData($city['region_seek'], $this->max_region, 1);
+
+ if(!$only_country)
+ $country = $this->readData($region['country_seek'], $this->max_country, 0);
+
+ unset($city['region_seek']);
+ unset($region['country_seek']);
+
+ return array('city' => $city, 'region' => $region, 'country' => $country);
+ }else{
+ unset($city['region_seek']);
+
+ return array('city' => $city, 'country' => array('id' => $country['id'], 'iso' => $country['iso']));
+ }
+ }
+
+ protected function unpack($pack, $item = '')
+ {
+ $unpacked = array();
+ $empty = empty($item);
+ $pack = explode('/', $pack);
+ $pos = 0;
+
+ foreach($pack AS $p)
+ {
+ list($type, $name) = explode(':', $p);
+
+ $type0 = $type[0];
+
+ if($empty)
+ {
+ $unpacked[$name] = $type0 == 'b' || $type0 == 'c' ? '' : 0;
+
+ continue;
+ }
+
+ switch($type0)
+ {
+ case 't':
+ case 'T': $l = 1; break;
+ case 's':
+ case 'n':
+ case 'S': $l = 2; break;
+ case 'm':
+ case 'M': $l = 3; break;
+ case 'd': $l = 8; break;
+ case 'c': $l = (int)substr($type, 1); break;
+ case 'b': $l = strpos($item, "\0", $pos)-$pos; break;
+ default: $l = 4;
+ }
+
+ $val = substr($item, $pos, $l);
+
+ switch($type0)
+ {
+ case 't': $v = unpack('c', $val); break;
+ case 'T': $v = unpack('C', $val); break;
+ case 's': $v = unpack('s', $val); break;
+ case 'S': $v = unpack('S', $val); break;
+ case 'm': $v = unpack('l', $val . (ord($val[2]) >> 7 ? "\xff" : "\0")); break;
+ case 'M': $v = unpack('L', $val . "\0"); break;
+ case 'i': $v = unpack('l', $val); break;
+ case 'I': $v = unpack('L', $val); break;
+ case 'f': $v = unpack('f', $val); break;
+ case 'd': $v = unpack('d', $val); break;
+
+ case 'n': $v = current(unpack('s', $val)) / pow(10, $type[1]); break;
+ case 'N': $v = current(unpack('l', $val)) / pow(10, $type[1]); break;
+
+ case 'c': $v = rtrim($val, ' '); break;
+ case 'b': $v = $val; $l++; break;
+ }
+
+ $pos += $l;
+ $unpacked[$name] = is_array($v) ? current($v) : $v;
+ }
+
+ return $unpacked;
+ }
+
+ public function get($ip)
+ {
+ return $this->max_city ? $this->getCity($ip) : $this->getCountry($ip);
+ }
+
+ public function getCountry($ip)
+ {
+ if($this->max_city)
+ {
+ $tmp = $this->parseCity($this->get_num($ip));
+
+ return $tmp['country']['iso'];
+ }else
+ return $this->id2iso[$this->get_num($ip)];
+ }
+
+ public function getCountryId($ip)
+ {
+ if($this->max_city)
+ {
+ $tmp = $this->parseCity($this->get_num($ip));
+
+ return $tmp['country']['id'];
+ }else
+ return $this->get_num($ip);
+ }
+
+ public function getCity($ip)
+ {
+ $seek = $this->get_num($ip);
+
+ return $seek ? $this->parseCity($seek) : false;
+ }
+
+ public function getCityFull($ip)
+ {
+ $seek = $this->get_num($ip);
+
+ return $seek ? $this->parseCity($seek, 1) : false;
+ }
+
+ public function about()
+ {
+ $charset = array('utf-8', 'latin1', 'cp1251');
+ $types = array('n/a', 'SxGeo Country', 'SxGeo City RU', 'SxGeo City EN', 'SxGeo City', 'SxGeo City Max RU', 'SxGeo City Max EN', 'SxGeo City Max');
+
+ return array(
+ 'Created' => date('Y.m.d', $this->info['time']),
+ 'Timestamp' => $this->info['time'],
+ 'Charset' => $charset[$this->info['charset']],
+ 'Type' => $types[$this->info['type']],
+ 'Byte Index' => $this->b_idx_len,
+ 'Main Index' => $this->m_idx_len,
+ 'Blocks In Index Item' => $this->range,
+ 'IP Blocks' => $this->db_items,
+ 'Block Size' => $this->block_len,
+
+ 'City' => array(
+ 'Max Length' => $this->max_city,
+ 'Total Size' => $this->info['city_size'],
+ ),
+
+ 'Region' => array(
+ 'Max Length' => $this->max_region,
+ 'Total Size' => $this->info['region_size'],
+ ),
+
+ 'Country' => array(
+ 'Max Length' => $this->max_country,
+ 'Total Size' => $this->info['country_size'],
+ ),
+ );
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/help.php b/system/library/help.php
index d94f78d..03140cd 100644
--- a/system/library/help.php
+++ b/system/library/help.php
@@ -1,100 +1,100 @@
$str)
- {
- $check = str_replace(' ', '', $str);
+ foreach($aStr as $line => $str)
+ {
+ $check = str_replace(' ', '', $str);
- if(isset($aStr[$line+1]) AND ($check == '' AND str_replace(' ', '', $aStr[$line+1]) == ''))
- continue;
- else{
- $etext .= rtrim(str_replace("\t", ' ', $str))."\n";
+ if(isset($aStr[$line+1]) AND ($check == '' AND str_replace(' ', '', $aStr[$line+1]) == ''))
+ continue;
+ else{
+ $etext .= rtrim(str_replace("\t", ' ', $str))."\n";
- continue;
- }
+ continue;
+ }
- if($check != '')
- $etext .= rtrim(str_replace("\t", ' ', $str))."\n";
- }
+ if($check != '')
+ $etext .= rtrim(str_replace("\t", ' ', $str))."\n";
+ }
- $str_search = array(
- "#\\\n#is",
- "#\[spoiler\](.+?)\[\/spoiler\]#is",
- "#\[sp\](.+?)\[\/sp\]#is",
- "#\[b\](.+?)\[\/b\]#is",
- "#\[u\](.+?)\[\/u\]#is",
- "#\[code\](.+?)\[\/code\]#is",
- "#\[quote\](.+?)\[\/quote\]#is",
- "#\[url=(.+?)\](.+?)\[\/url\]#is",
- "#(^|[\n ])([\w]+?://[\w\#$%&~/.\-;:=,?@\[\]+]*)#is"
- );
+ $str_search = array(
+ "#\\\n#is",
+ "#\[spoiler\](.+?)\[\/spoiler\]#is",
+ "#\[sp\](.+?)\[\/sp\]#is",
+ "#\[b\](.+?)\[\/b\]#is",
+ "#\[u\](.+?)\[\/u\]#is",
+ "#\[code\](.+?)\[\/code\]#is",
+ "#\[quote\](.+?)\[\/quote\]#is",
+ "#\[url=(.+?)\](.+?)\[\/url\]#is",
+ "#(^|[\n ])([\w]+?://[\w\#$%&~/.\-;:=,?@\[\]+]*)#is"
+ );
- $str_replace = array(
- " ",
- "",
- "",
- "\\1 ",
- "\\1 ",
- "",
- "\\1
",
- "\\2 ",
- " \\2 "
- );
+ $str_replace = array(
+ " ",
+ "",
+ "",
+ "\\1 ",
+ "\\1 ",
+ "",
+ "\\1
",
+ "\\2 ",
+ " \\2 "
+ );
- return preg_replace($str_search, $str_replace, $etext);
- }
+ return preg_replace($str_search, $str_replace, $etext);
+ }
- public static function ago($time, $brackets = false)
- {
- global $start_point;
+ public static function ago($time, $brackets = false)
+ {
+ global $start_point;
- $diff = $start_point-$time;
+ $diff = $start_point-$time;
- if($diff < 0)
- return '';
+ if($diff < 0)
+ return '';
- if(!$diff)
- $diff = 1;
+ if(!$diff)
+ $diff = 1;
- $seconds = array('секунду', 'секунды', 'секунд');
- $minutes = array('минуту', 'минуты', 'минут');
- $hours = array('час', 'часа', 'часов');
- $days = array('день', 'дня', 'дней');
- $weeks = array('неделю', 'недели', 'недель');
- $months = array('месяц', 'месяца', 'месяцев');
- $years = array('год', 'года', 'лет');
+ $seconds = array('секунду', 'секунды', 'секунд');
+ $minutes = array('минуту', 'минуты', 'минут');
+ $hours = array('час', 'часа', 'часов');
+ $days = array('день', 'дня', 'дней');
+ $weeks = array('неделю', 'недели', 'недель');
+ $months = array('месяц', 'месяца', 'месяцев');
+ $years = array('год', 'года', 'лет');
- $phrase = array($seconds, $minutes, $hours, $days, $weeks, $months, $years);
- $length = array(1, 60, 3600, 86400, 604800, 2630880, 31570560);
+ $phrase = array($seconds, $minutes, $hours, $days, $weeks, $months, $years);
+ $length = array(1, 60, 3600, 86400, 604800, 2630880, 31570560);
- for($i = 6; ($i >= 0) AND (($no = $diff/$length[$i]) <= 1); $i-=1);
+ for($i = 6; ($i >= 0) AND (($no = $diff/$length[$i]) <= 1); $i-=1);
- if($i < 0)
- $i = 0;
+ if($i < 0)
+ $i = 0;
- $_time = $start_point-($diff % $length[$i]);
- $no = ceil($no);
+ $_time = $start_point-($diff % $length[$i]);
+ $no = ceil($no);
- if($brackets)
- return '('.$no.' '.help::parse_ago($no, $phrase[$i]).' назад)';
+ if($brackets)
+ return '('.$no.' '.help::parse_ago($no, $phrase[$i]).' назад)';
- return $no.' '.help::parse_ago($no, $phrase[$i]).' назад';
- }
+ return $no.' '.help::parse_ago($no, $phrase[$i]).' назад';
+ }
- private static function parse_ago($number, $titles)
- {
- $cases = array(2, 0, 1, 1, 1, 2);
+ private static function parse_ago($number, $titles)
+ {
+ $cases = array(2, 0, 1, 1, 1, 2);
- return $titles[($number % 100 > 4 AND $number % 100 < 20 ) ? 2 : $cases[min($number % 10, 5)]];
- }
- }
+ return $titles[($number % 100 > 4 AND $number % 100 < 20 ) ? 2 : $cases[min($number % 10, 5)]];
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/html.php b/system/library/html.php
index 58d6016..da88687 100644
--- a/system/library/html.php
+++ b/system/library/html.php
@@ -1,173 +1,173 @@
data['['.$name.']'] = $var;
+ public function set($name, $var, $unset = false)
+ {
+ $this->data['['.$name.']'] = $var;
- if($unset)
- unset($this->arr[$name]);
+ if($unset)
+ unset($this->arr[$name]);
- return NULL;
- }
+ return NULL;
+ }
- public function unit($name, $var = false, $mirror = false)
- {
- $block = str_replace($name, "'\\|".$name."\\|(.*?)\\|_".$name."\\|'si", $name);
+ public function unit($name, $var = false, $mirror = false)
+ {
+ $block = str_replace($name, "'\\|".$name."\\|(.*?)\\|_".$name."\\|'si", $name);
- $var = $var ? '\\1' : '';
+ $var = $var ? '\\1' : '';
- $this->unitblock[$block] = $var;
+ $this->unitblock[$block] = $var;
- if($mirror)
- {
- $block = str_replace($name, "'\\|!".$name."\\|(.*?)\\|_!".$name."\\|'si", $name);
+ if($mirror)
+ {
+ $block = str_replace($name, "'\\|!".$name."\\|(.*?)\\|_!".$name."\\|'si", $name);
- $var = !$var ? '\\1' : '';
+ $var = !$var ? '\\1' : '';
- $this->unitblock[$block] = $var;
- }
+ $this->unitblock[$block] = $var;
+ }
- return NULL;
- }
+ return NULL;
+ }
- public function nav($name, $link = false)
- {
- $this->get('nav');
- if($link)
- {
- $this->set('link', $link);
- $this->unit('link', 1, 1);
- }else
- $this->unit('link', 0, 1);
- $this->set('name', $name);
- $this->pack('nav');
+ public function nav($name, $link = false)
+ {
+ $this->get('nav');
+ if($link)
+ {
+ $this->set('link', $link);
+ $this->unit('link', 1, 1);
+ }else
+ $this->unit('link', 0, 1);
+ $this->set('name', $name);
+ $this->pack('nav');
- return NULL;
- }
+ return NULL;
+ }
- public function get($name, $path = '')
- {
- global $device, $cfg;
+ public function get($name, $path = '')
+ {
+ global $device, $cfg;
- $path_root = $device == '!mobile' ? '' : 'megp/';
+ $path_root = $device == '!mobile' ? '' : 'megp/';
- $path = $path_root.$path;
+ $path = $path_root.$path;
- if($path != '')
- $name = str_replace('//', '/', $path.'/'.$name);
+ if($path != '')
+ $name = str_replace('//', '/', $path.'/'.$name);
- if(!file_exists($this->dir.'/'.$name.'.html'))
- {
- $route = explode('/', $name);
- $namefile = end($route);
- $dir = $this->dir.str_replace($namefile, '', $name);
+ if(!file_exists($this->dir.'/'.$name.'.html'))
+ {
+ $route = explode('/', $name);
+ $namefile = end($route);
+ $dir = $this->dir.str_replace($namefile, '', $name);
- die('Error: html file '.$namefile.'.html not found in: '.$dir.' ');
- }
+ die('Error: html file '.$namefile.'.html not found in: '.$dir.' ');
+ }
- $this->template = file_get_contents($this->dir.'/'.$name.'.html');
- $this->select_template = $this->template;
+ $this->template = file_get_contents($this->dir.'/'.$name.'.html');
+ $this->select_template = $this->template;
- return NULL;
- }
+ return NULL;
+ }
- private function delete()
- {
- unset($this->data);
- unset($this->unitblock);
+ private function delete()
+ {
+ unset($this->data);
+ unset($this->unitblock);
- $this->select_template = $this->template;
+ $this->select_template = $this->template;
- return NULL;
- }
+ return NULL;
+ }
- public function pack($compile)
- {
- if(isset($this->unitblock))
- {
- $find_preg = array();
- $replace_preg = array();
+ public function pack($compile)
+ {
+ if(isset($this->unitblock))
+ {
+ $find_preg = array();
+ $replace_preg = array();
- foreach($this->unitblock as $key_find => $key_replace)
- {
- $find_preg[] = $key_find;
- $replace_preg[] = $key_replace;
- }
+ foreach($this->unitblock as $key_find => $key_replace)
+ {
+ $find_preg[] = $key_find;
+ $replace_preg[] = $key_replace;
+ }
- $this->select_template = preg_replace($find_preg, $replace_preg, $this->select_template);
- }
+ $this->select_template = preg_replace($find_preg, $replace_preg, $this->select_template);
+ }
- $find = array();
- $replace = array();
+ $find = array();
+ $replace = array();
- if(isset($this->data))
- {
- foreach($this->data as $key_find => $key_replace)
- {
- $find[] = $key_find;
- $replace[] = $key_replace;
- }
- }
+ if(isset($this->data))
+ {
+ foreach($this->data as $key_find => $key_replace)
+ {
+ $find[] = $key_find;
+ $replace[] = $key_replace;
+ }
+ }
- $this->select_template = str_replace($find, $replace, $this->select_template);
+ $this->select_template = str_replace($find, $replace, $this->select_template);
- if(isset($this->arr[$compile]))
- $this->arr[$compile] .= $this->select_template;
- else
- $this->arr[$compile] = $this->select_template;
+ if(isset($this->arr[$compile]))
+ $this->arr[$compile] .= $this->select_template;
+ else
+ $this->arr[$compile] = $this->select_template;
- $this->delete();
+ $this->delete();
- return NULL;
- }
+ return NULL;
+ }
- public function upd($name, $old = array(), $new = array())
- {
- $this->arr[$name] = str_replace($old, $new, $this->arr[$name]);
+ public function upd($name, $old = array(), $new = array())
+ {
+ $this->arr[$name] = str_replace($old, $new, $this->arr[$name]);
- return NULL;
- }
+ return NULL;
+ }
- public function unitall($name, $arr = array(), $var = false, $mirror = false)
- {
- $block = str_replace($name, "'\\|".$name."\\|(.*?)\\|_".$name."\\|'si", $name);
+ public function unitall($name, $arr = array(), $var = false, $mirror = false)
+ {
+ $block = str_replace($name, "'\\|".$name."\\|(.*?)\\|_".$name."\\|'si", $name);
- $var = $var ? '\\1' : '';
+ $var = $var ? '\\1' : '';
- $this->unitblock[$block] = $var;
+ $this->unitblock[$block] = $var;
- if($mirror)
- {
- $block = str_replace($name, "'\\|!".$name."\\|(.*?)\\|_!".$name."\\|'si", $name);
+ if($mirror)
+ {
+ $block = str_replace($name, "'\\|!".$name."\\|(.*?)\\|_!".$name."\\|'si", $name);
- $var = !$var ? '\\1' : '';
+ $var = !$var ? '\\1' : '';
- $this->unitblock[$block] = $var;
- }
+ $this->unitblock[$block] = $var;
+ }
- if(count($this->unitblock))
- {
- foreach($this->unitblock as $key_find => $key_replace)
- {
- $find_preg[] = $key_find;
- $replace_preg[] = $key_replace;
- }
+ if(count($this->unitblock))
+ {
+ foreach($this->unitblock as $key_find => $key_replace)
+ {
+ $find_preg[] = $key_find;
+ $replace_preg[] = $key_replace;
+ }
- $this->arr[$arr] = preg_replace($find_preg, $replace_preg, $this->arr[$arr]);
- }
+ $this->arr[$arr] = preg_replace($find_preg, $replace_preg, $this->arr[$arr]);
+ }
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
- $html = new html;
+ $html = new html;
?>
\ No newline at end of file
diff --git a/system/library/smtp.php b/system/library/smtp.php
index d2a3361..5e4f451 100644
--- a/system/library/smtp.php
+++ b/system/library/smtp.php
@@ -1,6 +1,6 @@
smtp_host, $this->smtp_port, $errorNumber, $errorDescription, 30))
throw new Exception($errorNumber.'.'.$errorDescription);
diff --git a/system/library/sql.php b/system/library/sql.php
index 477a78b..899a3c3 100644
--- a/system/library/sql.php
+++ b/system/library/sql.php
@@ -1,6 +1,6 @@
query_id;
- $get = mysqli_fetch_assoc($query_id);
+ $get = mysqli_fetch_assoc($query_id);
return $get;
}
@@ -69,10 +69,10 @@
private function out_error($error, $query = '')
{
- global $go;
+ global $go;
- if($go)
- sys::outjs(array('e' => 'Query: '.$query.' Error: '.$error));
+ if($go)
+ sys::outjs(array('e' => 'Query: '.$query.' Error: '.$error));
if($query != '')
echo 'Query: '.$query.' ';
diff --git a/system/library/ssh.php b/system/library/ssh.php
index 4385ea1..4ea6c45 100644
--- a/system/library/ssh.php
+++ b/system/library/ssh.php
@@ -1,99 +1,99 @@
connect($address) AND $this->auth_pwd('root', $passwd))
- return true;
+ public function auth($passwd, $address)
+ {
+ if($this->connect($address) AND $this->auth_pwd('root', $passwd))
+ return true;
- return false;
- }
+ return false;
+ }
- public function connect($address)
- {
- list($host, $port) = explode(':', $address);
+ public function connect($address)
+ {
+ list($host, $port) = explode(':', $address);
- if($port == '')
- $port = 22;
+ if($port == '')
+ $port = 22;
- ini_set('default_socket_timeout', '3');
+ ini_set('default_socket_timeout', '3');
- if($this->conn = ssh2_connect($host, $port))
- {
- ini_set('default_socket_timeout', '180');
+ if($this->conn = ssh2_connect($host, $port))
+ {
+ ini_set('default_socket_timeout', '180');
- return true;
- }
+ return true;
+ }
- return false;
- }
+ return false;
+ }
- public function setfile($localFile, $remoteFile, $permision)
- {
- if(@ssh2_scp_send($this->conn, $localFile, $remoteFile, $permision))
- return true;
+ public function setfile($localFile, $remoteFile, $permision)
+ {
+ if(@ssh2_scp_send($this->conn, $localFile, $remoteFile, $permision))
+ return true;
- return false;
- }
+ return false;
+ }
- public function getfile($remoteFile, $localFile)
- {
- if(@ssh2_scp_recv($this->conn, $remoteFile, $localFile))
- return true;
+ public function getfile($remoteFile, $localFile)
+ {
+ if(@ssh2_scp_recv($this->conn, $remoteFile, $localFile))
+ return true;
- return false;
- }
+ return false;
+ }
- public function set($cmd)
- {
- $this->stream = ssh2_exec($this->conn, $cmd);
+ public function set($cmd)
+ {
+ $this->stream = ssh2_exec($this->conn, $cmd);
- stream_set_blocking($this->stream, true);
- }
+ stream_set_blocking($this->stream, true);
+ }
- public function auth_pwd($u, $p)
- {
- if(@ssh2_auth_password($this->conn, $u, $p))
- return true;
+ public function auth_pwd($u, $p)
+ {
+ if(@ssh2_auth_password($this->conn, $u, $p))
+ return true;
- return false;
- }
+ return false;
+ }
- public function get($cmd = false)
- {
- if($cmd)
- {
- $this->stream = ssh2_exec($this->conn, $cmd);
+ public function get($cmd = false)
+ {
+ if($cmd)
+ {
+ $this->stream = ssh2_exec($this->conn, $cmd);
- stream_set_blocking($this->stream, true);
- }
+ stream_set_blocking($this->stream, true);
+ }
- $line = '';
+ $line = '';
- while($get = fgets($this->stream))
- $line.= $get;
+ while($get = fgets($this->stream))
+ $line.= $get;
- return $line;
- }
+ return $line;
+ }
- public function esc()
- {
- if(function_exists('ssh2_disconnect'))
- ssh2_disconnect($this->conn);
- else{
- @fclose($this->conn);
- unset($this->conn);
- }
+ public function esc()
+ {
+ if(function_exists('ssh2_disconnect'))
+ ssh2_disconnect($this->conn);
+ else{
+ @fclose($this->conn);
+ unset($this->conn);
+ }
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
- $ssh = new ssh;
+ $ssh = new ssh;
?>
\ No newline at end of file
diff --git a/system/library/system.php b/system/library/system.php
index ce51319..aa81e59 100644
--- a/system/library/system.php
+++ b/system/library/system.php
@@ -1,9 +1,9 @@
query('UPDATE `users` set `time`="'.$start_point.'" WHERE `id`="'.$user['id'].'" LIMIT 1');
+ if($user['time']+10 < $start_point)
+ $sql->query('UPDATE `users` set `time`="'.$start_point.'" WHERE `id`="'.$user['id'].'" LIMIT 1');
- return NULL;
- }
+ return NULL;
+ }
- public static function users($users, $user, $authkey, $del = false)
- {
- global $mcache;
+ public static function users($users, $user, $authkey, $del = false)
+ {
+ global $mcache;
- if($del)
- unset($users[md5($user['login'].$user['authkey'].$user['passwd'])]);
- else
- $users[md5($user['login'].$user['authkey'].$user['passwd'])] = $user;
+ if($del)
+ unset($users[md5($user['login'].$user['authkey'].$user['passwd'])]);
+ else
+ $users[md5($user['login'].$user['authkey'].$user['passwd'])] = $user;
- $mcache->set('users_auth', $users, false, 1000);
+ $mcache->set('users_auth', $users, false, 1000);
- return NULL;
- }
+ return NULL;
+ }
- public static function nav($server, $sid, $active)
- {
- global $cfg, $html, $sql, $mcache, $start_point;
+ public static function nav($server, $sid, $active)
+ {
+ global $cfg, $html, $sql, $mcache, $start_point;
- $notice_sid = $mcache->get('notice_'.$sid);
+ $notice_sid = $mcache->get('notice_'.$sid);
- $notice = is_array($notice_sid) ? $notice_sid : $mcache->get('notice_'.$server['unit']);
+ $notice = is_array($notice_sid) ? $notice_sid : $mcache->get('notice_'.$server['unit']);
- if(!is_array($notice))
- {
- $sql->query('SELECT `server`, `text`, `color` FROM `notice` WHERE `server`="'.$sid.'" AND `time`>"'.$start_point.'" ORDER BY `id` DESC LIMIT 1');
+ if(!is_array($notice))
+ {
+ $sql->query('SELECT `server`, `text`, `color` FROM `notice` WHERE `server`="'.$sid.'" AND `time`>"'.$start_point.'" ORDER BY `id` DESC LIMIT 1');
- if(!$sql->num())
- $sql->query('SELECT `unit`, `text`, `color` FROM `notice` WHERE `unit`="'.$server['unit'].'" AND `time`>"'.$start_point.'" ORDER BY `id` DESC LIMIT 1');
+ if(!$sql->num())
+ $sql->query('SELECT `unit`, `text`, `color` FROM `notice` WHERE `unit`="'.$server['unit'].'" AND `time`>"'.$start_point.'" ORDER BY `id` DESC LIMIT 1');
- if($sql->num())
- {
- $notice = $sql->get();
+ if($sql->num())
+ {
+ $notice = $sql->get();
- $nmc = $notice['server'] ? 'notice_'.$sid : 'notice_'.$server['unit'];
+ $nmc = $notice['server'] ? 'notice_'.$sid : 'notice_'.$server['unit'];
- $mcache->set('notice_'.$nmc, $notice, false, 10);
- }else
- $mcache->set('notice_'.$server['unit'], NULL, false, 10);
- }
+ $mcache->set('notice_'.$nmc, $notice, false, 10);
+ }else
+ $mcache->set('notice_'.$server['unit'], NULL, false, 10);
+ }
- $aUnit = array('index', 'console', 'settings', 'plugins', 'maps', 'owners', 'filetp', 'tarif', 'copy', 'graph', 'web', 'boost');
+ $aUnit = array('index', 'console', 'settings', 'plugins', 'maps', 'owners', 'filetp', 'tarif', 'copy', 'graph', 'web', 'boost');
- $html->get('gmenu', 'sections/servers/'.$server['game']);
+ $html->get('gmenu', 'sections/servers/'.$server['game']);
- $html->set('id', $sid);
- $html->set('home', $cfg['http']);
+ $html->set('id', $sid);
+ $html->set('home', $cfg['http']);
- if(is_array($notice))
- {
- global $device;
+ if(is_array($notice))
+ {
+ global $device;
- if($device == '!mobile')
- $html->set('notice', ''.$notice['text'].'
');
- else
- $html->set('notice', '');
- }else
- $html->set('notice', '');
+ if($device == '!mobile')
+ $html->set('notice', ''.$notice['text'].'
');
+ else
+ $html->set('notice', '');
+ }else
+ $html->set('notice', '');
- if($server['console_use']) $html->unit('console_use', 1); else $html->unit('console_use');
- if($server['plugins_use']) $html->unit('plugins_use', 1); else $html->unit('plugins_use');
- if($server['ftp_use']) $html->unit('ftp_use', 1); else $html->unit('ftp_use');
- if($server['stats_use']) $html->unit('graph_use', 1); else $html->unit('graph_use');
- if($server['web_use']) $html->unit('web_use', 1); else $html->unit('web_use');
- if($server['copy_use']) $html->unit('copy_use', 1); else $html->unit('copy_use');
+ if($server['console_use']) $html->unit('console_use', 1); else $html->unit('console_use');
+ if($server['plugins_use']) $html->unit('plugins_use', 1); else $html->unit('plugins_use');
+ if($server['ftp_use']) $html->unit('ftp_use', 1); else $html->unit('ftp_use');
+ if($server['stats_use']) $html->unit('graph_use', 1); else $html->unit('graph_use');
+ if($server['web_use']) $html->unit('web_use', 1); else $html->unit('web_use');
+ if($server['copy_use']) $html->unit('copy_use', 1); else $html->unit('copy_use');
- foreach($aUnit as $unit)
- if($unit == $active) $html->unit($unit, 1); else $html->unit($unit);
+ foreach($aUnit as $unit)
+ if($unit == $active) $html->unit($unit, 1); else $html->unit($unit);
- $html->pack('main');
+ $html->pack('main');
- $html->get('vmenu', 'sections/servers/'.$server['game']);
+ $html->get('vmenu', 'sections/servers/'.$server['game']);
- $html->set('id', $sid);
- $html->set('home', $cfg['http']);
+ $html->set('id', $sid);
+ $html->set('home', $cfg['http']);
- if($server['console_use']) $html->unit('console_use', 1); else $html->unit('console_use');
- if($server['plugins_use']) $html->unit('plugins_use', 1); else $html->unit('plugins_use');
- if($server['ftp_use']) $html->unit('ftp_use', 1); else $html->unit('ftp_use');
- if($server['stats_use']) $html->unit('graph_use', 1); else $html->unit('graph_use');
- if($server['web_use']) $html->unit('web_use', 1); else $html->unit('web_use');
- if($server['copy_use']) $html->unit('copy_use', 1); else $html->unit('copy_use');
+ if($server['console_use']) $html->unit('console_use', 1); else $html->unit('console_use');
+ if($server['plugins_use']) $html->unit('plugins_use', 1); else $html->unit('plugins_use');
+ if($server['ftp_use']) $html->unit('ftp_use', 1); else $html->unit('ftp_use');
+ if($server['stats_use']) $html->unit('graph_use', 1); else $html->unit('graph_use');
+ if($server['web_use']) $html->unit('web_use', 1); else $html->unit('web_use');
+ if($server['copy_use']) $html->unit('copy_use', 1); else $html->unit('copy_use');
- foreach($aUnit as $unit)
- if($unit == $active) $html->unit($unit, 1); else $html->unit($unit);
+ foreach($aUnit as $unit)
+ if($unit == $active) $html->unit($unit, 1); else $html->unit($unit);
- $html->pack('vmenu');
+ $html->pack('vmenu');
- return NULL;
- }
+ return NULL;
+ }
- public static function route($server, $inc, $go, $all = false)
- {
- global $device, $start_point;
+ public static function route($server, $inc, $go, $all = false)
+ {
+ global $device, $start_point;
- $dir = $device == '!mobile' ? '' : 'megp/';
- $use = true;
+ $dir = $device == '!mobile' ? '' : 'megp/';
+ $use = true;
- if(in_array($inc, array('plugins', 'ftp', 'console', 'graph', 'copy', 'web')))
- {
- $server['graph_use'] = $server['stats_use'];
+ if(in_array($inc, array('plugins', 'ftp', 'console', 'graph', 'copy', 'web')))
+ {
+ $server['graph_use'] = $server['stats_use'];
- if(!$server[$inc.'_use'])
- $use = false;
- }
+ if(!$server[$inc.'_use'])
+ $use = false;
+ }
- if(!$use || $server['time'] < $start_point || in_array($server['status'], array('install', 'reinstall', 'update', 'recovery', 'blocked')))
- {
- if($go)
- sys::out('Раздел недоступен');
+ if(!$use || $server['time'] < $start_point || in_array($server['status'], array('install', 'reinstall', 'update', 'recovery', 'blocked')))
+ {
+ if($go)
+ sys::out('Раздел недоступен');
- if(!$use)
- return SEC.$dir.'servers/'.$server['game'].'/index.php';
+ if(!$use)
+ return SEC.$dir.'servers/'.$server['game'].'/index.php';
- return SEC.$dir.'servers/noaccess.php';
- }
+ return SEC.$dir.'servers/noaccess.php';
+ }
- if($all)
- return SEC.'servers/games/'.$inc.'.php';
+ if($all)
+ return SEC.'servers/games/'.$inc.'.php';
- if(!file_exists(SEC.$dir.'servers/'.$server['game'].'/'.$inc.'.php'))
- return SEC.$dir.'servers/'.$server['game'].'/index.php';
+ if(!file_exists(SEC.$dir.'servers/'.$server['game'].'/'.$inc.'.php'))
+ return SEC.$dir.'servers/'.$server['game'].'/index.php';
- return SEC.$dir.'servers/'.$server['game'].'/'.$inc.'.php';
- }
+ return SEC.$dir.'servers/'.$server['game'].'/'.$inc.'.php';
+ }
- public static function int($data, $width = false)
- {
- if($width)
- return preg_replace("([^0-9]{0, ".$width."})", '', $data);
+ public static function int($data, $width = false)
+ {
+ if($width)
+ return preg_replace("([^0-9]{0, ".$width."})", '', $data);
- return preg_replace("([^0-9])", '', $data);
- }
+ return preg_replace("([^0-9])", '', $data);
+ }
- public static function b64js($data)
- {
- return base64_encode(json_encode($data));
- }
+ public static function b64js($data)
+ {
+ return base64_encode(json_encode($data));
+ }
- public static function b64djs($data)
- {
- return json_decode(base64_decode($data), true);
- }
+ public static function b64djs($data)
+ {
+ return json_decode(base64_decode($data), true);
+ }
- public static function hb64($data)
- {
- return base64_encode(htmlspecialchars($data));
- }
+ public static function hb64($data)
+ {
+ return base64_encode(htmlspecialchars($data));
+ }
- public static function hb64d($data)
- {
- return htmlspecialchars_decode(base64_decode($data));
- }
+ public static function hb64d($data)
+ {
+ return htmlspecialchars_decode(base64_decode($data));
+ }
- public static function outjs($val, $cache = false)
- {
- global $mcache;
+ public static function outjs($val, $cache = false)
+ {
+ global $mcache;
- if($cache)
- $mcache->delete($cache);
+ if($cache)
+ $mcache->delete($cache);
- die(json_encode($val));
- }
+ die(json_encode($val));
+ }
- public static function out($val = '', $cache = false)
- {
- global $mcache;
+ public static function out($val = '', $cache = false)
+ {
+ global $mcache;
- if($cache)
- $mcache->delete($cache);
+ if($cache)
+ $mcache->delete($cache);
- die(''.$val.'');
- }
+ die(''.$val.'');
+ }
- public static function outhtml($text, $time = 3, $url = false, $cache = false)
- {
- global $device, $mcache, $html, $cfg;
+ public static function outhtml($text, $time = 3, $url = false, $cache = false)
+ {
+ global $device, $mcache, $html, $cfg;
- if($cache)
- $mcache->delete($cache);
+ if($cache)
+ $mcache->delete($cache);
- $tpl = $device == '!mobile' ? '' : '/megp';
+ $tpl = $device == '!mobile' ? '' : '/megp';
- $html->get('out');
+ $html->get('out');
- $html->set('title', $cfg['name']);
- $html->set('home', $cfg['http']);
- $html->set('css', $cfg['http'].'template'.$tpl.'/css/');
- $html->set('js', $cfg['http'].'template'.$tpl.'/js/');
- $html->set('img', $cfg['http'].'template'.$tpl.'/images/');
- $html->set('text', $text);
+ $html->set('title', $cfg['name']);
+ $html->set('home', $cfg['http']);
+ $html->set('css', $cfg['http'].'template'.$tpl.'/css/');
+ $html->set('js', $cfg['http'].'template'.$tpl.'/js/');
+ $html->set('img', $cfg['http'].'template'.$tpl.'/images/');
+ $html->set('text', $text);
- $html->pack('out');
+ $html->pack('out');
- if(!$url)
- $url = $cfg['http'];
+ if(!$url)
+ $url = $cfg['http'];
- header('Refresh: '.$time.'; URL='.$url);
+ header('Refresh: '.$time.'; URL='.$url);
- die($html->arr['out']);
- }
+ die($html->arr['out']);
+ }
- public static function valid($val, $type, $preg = '')
- {
+ public static function valid($val, $type, $preg = '')
+ {
$val = (isset($val) ? $val : '');
- switch($type)
- {
- case 'promo':
- if(!preg_match("/^[A-Za-z0-9]{2,20}$/", $val))
- return true;
+ switch($type)
+ {
+ case 'promo':
+ if(!preg_match("/^[A-Za-z0-9]{2,20}$/", $val))
+ return true;
- return false;
+ return false;
- case 'en':
- if(!preg_match("/^[A-Za-z0-9]$/", $val))
- return true;
+ case 'en':
+ if(!preg_match("/^[A-Za-z0-9]$/", $val))
+ return true;
- return false;
+ return false;
- case 'ru':
- if(!preg_match("/^[А-Яа-я]$/u", $val))
- return true;
+ case 'ru':
+ if(!preg_match("/^[А-Яа-я]$/u", $val))
+ return true;
- return false;
+ return false;
- case 'wm':
- if(!preg_match('/^R[0-9]{12,12}$|^Z[0-9]{12,12}$|^U[0-9]{12,12}$/m', $val))
- return true;
+ case 'wm':
+ if(!preg_match('/^R[0-9]{12,12}$|^Z[0-9]{12,12}$|^U[0-9]{12,12}$/m', $val))
+ return true;
- return false;
+ return false;
- case 'ip':
- if(!preg_match('/^(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[0-9]{2}|[0-9])(\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[0-9]{2}|[0-9])){3}$/', $val))
- return true;
+ case 'ip':
+ if(!preg_match('/^(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[0-9]{2}|[0-9])(\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[0-9]{2}|[0-9])){3}$/', $val))
+ return true;
- return false;
+ return false;
- case 'steamid':
- if(!preg_match("/^STEAM_[0-9]:[0-9]:[0-9]{6,12}$|^HLTV$|^STEAM_ID_LAN$|^STEAM_ID_PENDING$|^VALVE_ID_LAN$|^VALVE_ID_PENDING$|^STEAM_666:88:666$/", $val))
- return true;
+ case 'steamid':
+ if(!preg_match("/^STEAM_[0-9]:[0-9]:[0-9]{6,12}$|^HLTV$|^STEAM_ID_LAN$|^STEAM_ID_PENDING$|^VALVE_ID_LAN$|^VALVE_ID_PENDING$|^STEAM_666:88:666$/", $val))
+ return true;
- return false;
+ return false;
- case 'steamid3':
- if(!preg_match("/^\[U:[01]:[0-9]{3,12}\]$/i", $val))
- return true;
+ case 'steamid3':
+ if(!preg_match("/^\[U:[01]:[0-9]{3,12}\]$/i", $val))
+ return true;
- return false;
+ return false;
- case 'num':
- if(!preg_match('/[^0-9]/', $val))
- return true;
+ case 'num':
+ if(!preg_match('/[^0-9]/', $val))
+ return true;
- return false;
+ return false;
- case 'md5':
- if(!preg_match("/^[a-z0-9]{32,32}$/", $val))
- return true;
+ case 'md5':
+ if(!preg_match("/^[a-z0-9]{32,32}$/", $val))
+ return true;
- return false;
+ return false;
- case 'other':
- if(!preg_match($preg, $val))
- return true;
+ case 'other':
+ if(!preg_match($preg, $val))
+ return true;
- return false;
- }
+ return false;
+ }
- return true;
- }
+ return true;
+ }
- public static function mail($name, $text, $mail)
- {
- global $cfg;
+ public static function mail($name, $text, $mail)
+ {
+ global $cfg;
- require_once(LIB.'smtp.php');
+ require_once(LIB.'smtp.php');
- $tpl = file_get_contents(DATA.'mail.ini', "r");
+ $tpl = file_get_contents(DATA.'mail.ini', "r");
- $text = str_replace(
- array('[name]', '[text]', '[http]', '[img]', '[css]'),
- array($cfg['name'], $text, $cfg['http'], $cfg['http'].'template/images/', $cfg['http'].'template/css/'),
- $tpl
- );
+ $text = str_replace(
+ array('[name]', '[text]', '[http]', '[img]', '[css]'),
+ array($cfg['name'], $text, $cfg['http'], $cfg['http'].'template/images/', $cfg['http'].'template/css/'),
+ $tpl
+ );
- $smtp = new smtp($cfg['smtp_login'], $cfg['smtp_passwd'], $cfg['smtp_url'], $cfg['smtp_mail'], 465);
+ $smtp = new smtp($cfg['smtp_login'], $cfg['smtp_passwd'], $cfg['smtp_url'], $cfg['smtp_mail'], 465);
- $headers = "MIME-Version: 1.0\r\n";
- $headers .= "Content-type: text/html; charset=utf-8\r\n";
- $headers .= "From: ".$cfg['smtp_name']." <".$cfg['smtp_mail'].">\r\n";
+ $headers = "MIME-Version: 1.0\r\n";
+ $headers .= "Content-type: text/html; charset=utf-8\r\n";
+ $headers .= "From: ".$cfg['smtp_name']." <".$cfg['smtp_mail'].">\r\n";
- if($smtp->send($mail, $name, $text, $headers))
- return true;
+ if($smtp->send($mail, $name, $text, $headers))
+ return true;
- return false;
- }
+ return false;
+ }
- public static function mail_domain($mail)
- {
- $domain = explode('@', $mail);
+ public static function mail_domain($mail)
+ {
+ $domain = explode('@', $mail);
- $domain = end($domain);
+ $domain = end($domain);
- if(in_array($domain, array('list.ru', 'bk.ru', 'inbox.ru')))
- $domain = 'mail.ru';
+ if(in_array($domain, array('list.ru', 'bk.ru', 'inbox.ru')))
+ $domain = 'mail.ru';
- switch($domain)
- {
- case 'mail.ru':
- return $domain;
+ switch($domain)
+ {
+ case 'mail.ru':
+ return $domain;
- case 'yandex.ru':
- return 'mail.yandex.ru';
+ case 'yandex.ru':
+ return 'mail.yandex.ru';
- case 'google.com':
- return 'mail.google.com';
+ case 'google.com':
+ return 'mail.google.com';
- default:
- return '';
- }
- }
+ default:
+ return '';
+ }
+ }
- public static function domain($domain)
- {
- $domain = explode('.', $domain);
+ public static function domain($domain)
+ {
+ $domain = explode('.', $domain);
- unset($domain[0]);
+ unset($domain[0]);
- return implode('.', $domain);
- }
+ return implode('.', $domain);
+ }
- public static function updtext($text, $data)
- {
- foreach($data as $name => $val)
- $text = str_replace('['.$name.']', $val, $text);
+ public static function updtext($text, $data)
+ {
+ foreach($data as $name => $val)
+ $text = str_replace('['.$name.']', $val, $text);
- return $text;
- }
+ return $text;
+ }
- public static function login($mail, $lchar)
- {
- if(!$lchar)
- return str_replace(array('.', '_', '+', '-'), '', sys::first(explode('@', $mail)));
+ public static function login($mail, $lchar)
+ {
+ if(!$lchar)
+ return str_replace(array('.', '_', '+', '-'), '', sys::first(explode('@', $mail)));
- $list = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuWwXxYyZz0123456789';
- $a = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuWwXxYyZz';
- $selections = strlen($list)-1;
- $start = strlen($a)-1;
- $b = rand(0, $start);
- $start = $a[$b];
- $login = array();
+ $list = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuWwXxYyZz0123456789';
+ $a = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuWwXxYyZz';
+ $selections = strlen($list)-1;
+ $start = strlen($a)-1;
+ $b = rand(0, $start);
+ $start = $a[$b];
+ $login = array();
- $i = 0;
+ $i = 0;
- for($i; $i <= 10; $i+=1)
- {
- $n = rand(0, $selections);
- $login[] = $list[$n];
- }
+ for($i; $i <= 10; $i+=1)
+ {
+ $n = rand(0, $selections);
+ $login[] = $list[$n];
+ }
- return $start.implode('', $login);
- }
+ return $start.implode('', $login);
+ }
- public static function passwd($length = 8)
- {
- $list = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuWwXxYyZz0123456789';
- $a = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuWwXxYyZz';
- $selections = strlen($list)-1;
- $start = strlen($a)-1;
- $b = rand(0, $start);
- $start = $a[$b];
- $passwd = array();
+ public static function passwd($length = 8)
+ {
+ $list = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuWwXxYyZz0123456789';
+ $a = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuWwXxYyZz';
+ $selections = strlen($list)-1;
+ $start = strlen($a)-1;
+ $b = rand(0, $start);
+ $start = $a[$b];
+ $passwd = array();
- $i = 0;
+ $i = 0;
- for($i; $i <= $length-2; $i+=1)
- {
- $n = rand(0, $selections);
- $passwd[] = $list[$n];
- }
+ for($i; $i <= $length-2; $i+=1)
+ {
+ $n = rand(0, $selections);
+ $passwd[] = $list[$n];
+ }
- return $start.implode('', $passwd);
- }
+ return $start.implode('', $passwd);
+ }
- public static function passwdkey($passwd)
- {
- return md5($passwd);
- }
+ public static function passwdkey($passwd)
+ {
+ return md5($passwd);
+ }
public static function cookie($name, $value, $expires)
{
@@ -447,1033 +447,1033 @@
\Delight\Cookie\Cookie::setcookie($name, $value, $expires, '/', $cfg['url'], self::isSecure(), true, $cfg['cookie_same_site']);
}
- public static function auth()
- {
- global $auth, $go, $text, $cfg;
+ public static function auth()
+ {
+ global $auth, $go, $text, $cfg;
- if($auth)
- {
- if($go)
- sys::outjs(array('e' => sys::text('output', 'auth')));
+ if($auth)
+ {
+ if($go)
+ sys::outjs(array('e' => sys::text('output', 'auth')));
- global $device;
+ global $device;
- $link = $device == '!mobile' ? 'user/section/lk' : '';
+ $link = $device == '!mobile' ? 'user/section/lk' : '';
- exit(header('Refresh: 0; URL='.$cfg['http'].$link));
- }
+ exit(header('Refresh: 0; URL='.$cfg['http'].$link));
+ }
- return NULL;
- }
+ return NULL;
+ }
- public static function noauth()
- {
- global $auth, $go, $text, $cfg;
+ public static function noauth()
+ {
+ global $auth, $go, $text, $cfg;
- if(!$auth)
- {
- if($go)
- sys::outjs(array('e' => sys::text('output', 'noauth')));
+ if(!$auth)
+ {
+ if($go)
+ sys::outjs(array('e' => sys::text('output', 'noauth')));
- global $device;
+ global $device;
- $link = $device == '!mobile' ? 'user/section/auth' : 'auth';
+ $link = $device == '!mobile' ? 'user/section/auth' : 'auth';
- exit(header('Refresh: 0; URL='.$cfg['http'].$link));
- }
+ exit(header('Refresh: 0; URL='.$cfg['http'].$link));
+ }
- return NULL;
- }
+ return NULL;
+ }
- public static function browser($agent)
- {
- if(strpos($agent, 'Firefox') !== false)
- return 'Mozilla Firefox';
+ public static function browser($agent)
+ {
+ if(strpos($agent, 'Firefox') !== false)
+ return 'Mozilla Firefox';
- if(strpos($agent, 'Opera') !== false)
- return 'Opera';
+ if(strpos($agent, 'Opera') !== false)
+ return 'Opera';
- if(strpos($agent, 'Chrome') !== false)
- return 'Google Chrome';
+ if(strpos($agent, 'Chrome') !== false)
+ return 'Google Chrome';
- if(strpos($agent, 'MSIE') !== false)
- return 'Internet Explorer';
+ if(strpos($agent, 'MSIE') !== false)
+ return 'Internet Explorer';
- if(strpos($agent, 'Safari') !== false)
- return 'Safari';
+ if(strpos($agent, 'Safari') !== false)
+ return 'Safari';
- return 'Неизвестный';
- }
+ return 'Неизвестный';
+ }
- public static function date($lenght, $date)
- {
- global $start_point;
+ public static function date($lenght, $date)
+ {
+ global $start_point;
- $check_time = $date-$start_point;
+ $check_time = $date-$start_point;
- if($check_time < 1)
- return 'время истекло.';
+ if($check_time < 1)
+ return 'время истекло.';
- $days = floor($check_time/86400);
- $hours = floor(($check_time%86400)/3600);
- $minutes = floor(($check_time%3600)/60);
- $seconds = $check_time%60;
+ $days = floor($check_time/86400);
+ $hours = floor(($check_time%86400)/3600);
+ $minutes = floor(($check_time%3600)/60);
+ $seconds = $check_time%60;
- $adata = array(
- 'min' => array(
- 'days' => array('день', 'дня', 'дней'),
- 'hours' => array('ч.', 'ч.', 'ч.'),
- 'minutes' => array('мин.', 'мин.', 'мин.'),
- 'seconds' => array('сек.', 'сек.', 'сек.')
- ),
- 'max' => array(
- 'days' => array('день', 'дня', 'дней'),
- 'hours' => array('час', 'часа', 'часов'),
- 'minutes' => array('минуту','минуты','минут'),
- 'seconds' => array('секунду','секунды','секунд')
- )
- );
+ $adata = array(
+ 'min' => array(
+ 'days' => array('день', 'дня', 'дней'),
+ 'hours' => array('ч.', 'ч.', 'ч.'),
+ 'minutes' => array('мин.', 'мин.', 'мин.'),
+ 'seconds' => array('сек.', 'сек.', 'сек.')
+ ),
+ 'max' => array(
+ 'days' => array('день', 'дня', 'дней'),
+ 'hours' => array('час', 'часа', 'часов'),
+ 'minutes' => array('минуту','минуты','минут'),
+ 'seconds' => array('секунду','секунды','секунд')
+ )
+ );
- $text = '';
+ $text = '';
- if($days > 0)
- $text .= sys::date_decl($days, $adata[$lenght]['days']);
+ if($days > 0)
+ $text .= sys::date_decl($days, $adata[$lenght]['days']);
- if($days < 1 AND $hours > 0)
- $text .= ' '.sys::date_decl($hours, $adata[$lenght]['hours']);
+ if($days < 1 AND $hours > 0)
+ $text .= ' '.sys::date_decl($hours, $adata[$lenght]['hours']);
- if($days < 1 AND $minutes > 0)
- $text .= ' '.sys::date_decl($minutes, $adata[$lenght]['minutes']);
+ if($days < 1 AND $minutes > 0)
+ $text .= ' '.sys::date_decl($minutes, $adata[$lenght]['minutes']);
- if($days < 1 AND $seconds > 0)
- $text .= ' '.sys::date_decl($seconds, $adata[$lenght]['seconds']);
+ if($days < 1 AND $seconds > 0)
+ $text .= ' '.sys::date_decl($seconds, $adata[$lenght]['seconds']);
- return $text;
- }
+ return $text;
+ }
- public static function date_decl($digit, $expr, $onlyword = false)
- {
- if(!is_array($expr))
- $expr = array_filter(explode(' ', $expr));
+ public static function date_decl($digit, $expr, $onlyword = false)
+ {
+ if(!is_array($expr))
+ $expr = array_filter(explode(' ', $expr));
- if(empty($expr[2]))
- $expr[2] = $expr[1];
+ if(empty($expr[2]))
+ $expr[2] = $expr[1];
- $i = sys::int($digit)%100;
+ $i = sys::int($digit)%100;
- if($onlyword)
- $digit = '';
+ if($onlyword)
+ $digit = '';
- if($i > 4 AND $i < 21)
- $res = $digit.' '.$expr[2];
- else
- $i%=10;
+ if($i > 4 AND $i < 21)
+ $res = $digit.' '.$expr[2];
+ else
+ $i%=10;
- if($i == 1)
- $res = $digit.' '.$expr[0];
- elseif($i > 1 AND $i < 5)
- $res = $digit.' '.$expr[1];
- else
- $res = $digit.' '.$expr[2];
+ if($i == 1)
+ $res = $digit.' '.$expr[0];
+ elseif($i > 1 AND $i < 5)
+ $res = $digit.' '.$expr[1];
+ else
+ $res = $digit.' '.$expr[2];
- return trim($res);
- }
+ return trim($res);
+ }
- public static function today($time, $cp = false)
- {
- global $start_point;
+ public static function today($time, $cp = false)
+ {
+ global $start_point;
- $today = date('d.m.Y', $start_point);
- $day = date('d.m.Y', $time);
+ $today = date('d.m.Y', $start_point);
+ $day = date('d.m.Y', $time);
- if($day == $today)
- {
- if($cp)
- return 'Сегодня '.date('H:i', $time);
+ if($day == $today)
+ {
+ if($cp)
+ return 'Сегодня '.date('H:i', $time);
- return 'Сегодня '.date('- H:i', $time);
- }
+ return 'Сегодня '.date('- H:i', $time);
+ }
- $yesterday_first = sys::int(sys::first(explode('.', $today)))-1;
- $yesterday_full = date('m.Y', $time);
+ $yesterday_first = sys::int(sys::first(explode('.', $today)))-1;
+ $yesterday_full = date('m.Y', $time);
- if($day == $yesterday_first.'.'.$yesterday_full AND !$yesterday_first)
- {
- if($cp)
- return 'Вчера '.date('H:i', $time);
+ if($day == $yesterday_first.'.'.$yesterday_full AND !$yesterday_first)
+ {
+ if($cp)
+ return 'Вчера '.date('H:i', $time);
- return 'Вчера '.date('- H:i', $time);
- }
+ return 'Вчера '.date('- H:i', $time);
+ }
- if($cp)
- return date('d.m.Y H:i', $time);
+ if($cp)
+ return date('d.m.Y H:i', $time);
- return date('d.m.Y - H:i', $time);
- }
+ return date('d.m.Y - H:i', $time);
+ }
- public static function day($time)
- {
- $days = array('день', 'дня', 'дней');
-
- $time = $time % 100;
-
- if($n > 10 AND $n < 20)
- return $days[2];
-
- $time = $time % 10;
-
- if($time > 1 AND $time < 5)
- return $days[1];
+ public static function day($time)
+ {
+ $days = array('день', 'дня', 'дней');
+
+ $time = $time % 100;
+
+ if($n > 10 AND $n < 20)
+ return $days[2];
+
+ $time = $time % 10;
+
+ if($time > 1 AND $time < 5)
+ return $days[1];
- if($time == 1)
- return $days[0];
+ if($time == 1)
+ return $days[0];
- return $days[2];
- }
+ return $days[2];
+ }
- public static function bbc($text)
- {
- global $cfg;
+ public static function bbc($text)
+ {
+ global $cfg;
- $lines = explode("\n", $text);
+ $lines = explode("\n", $text);
- $str_search = array(
- "#\\\n#is",
- "#\[spoiler\](.+?)\[\/spoiler\]#is",
- "#\[sp\](.+?)\[\/sp\]#is",
- "#\[b\](.+?)\[\/b\]#is",
- "#\[u\](.+?)\[\/u\]#is",
- "#\[code\](.+?)\[\/code\]#is",
- "#\[quote\](.+?)\[\/quote\]#is",
- "#\[url=(.+?)\](.+?)\[\/url\]#is",
- "#\[img=(.+?)\] \[\/img\]#is",
- "#(^|[\n ])([\w]+?://[\w\#$%&~/.\-;:=,?@\[\]+]*)#is"
- );
+ $str_search = array(
+ "#\\\n#is",
+ "#\[spoiler\](.+?)\[\/spoiler\]#is",
+ "#\[sp\](.+?)\[\/sp\]#is",
+ "#\[b\](.+?)\[\/b\]#is",
+ "#\[u\](.+?)\[\/u\]#is",
+ "#\[code\](.+?)\[\/code\]#is",
+ "#\[quote\](.+?)\[\/quote\]#is",
+ "#\[url=(.+?)\](.+?)\[\/url\]#is",
+ "#\[img=(.+?)\] \[\/img\]#is",
+ "#(^|[\n ])([\w]+?://[\w\#$%&~/.\-;:=,?@\[\]+]*)#is"
+ );
- $str_replace = array(
- " ",
- "",
- "",
- "\\1 ",
- "\\1 ",
- "",
- "\\1
",
- "\\2 ",
- " ",
- " \\2 "
- );
+ $str_replace = array(
+ " ",
+ "",
+ "",
+ "\\1 ",
+ "\\1 ",
+ "",
+ "\\1
",
+ "\\2 ",
+ " ",
+ " \\2 "
+ );
- $uptext = '';
-
- foreach($lines as $line)
- $uptext .= preg_replace($str_search, $str_replace, $line)." ";
+ $uptext = '';
+
+ foreach($lines as $line)
+ $uptext .= preg_replace($str_search, $str_replace, $line)." ";
- return $uptext;
- }
+ return $uptext;
+ }
- public static function first($array = array())
- {
- return $array[0];
- }
+ public static function first($array = array())
+ {
+ return $array[0];
+ }
- public static function back($url)
- {
- exit(header('Refresh: 0; URL='.$url));
- }
+ public static function back($url)
+ {
+ exit(header('Refresh: 0; URL='.$url));
+ }
- public static function strlen($str)
- {
- return iconv_strlen($str, 'UTF-8');
- }
+ public static function strlen($str)
+ {
+ return iconv_strlen($str, 'UTF-8');
+ }
- public static function text($section, $name)
- {
- global $cfg, $user;
+ public static function text($section, $name)
+ {
+ global $cfg, $user;
- $group = isset($user['group']) ? $user['group'] : 'user';
+ $group = isset($user['group']) ? $user['group'] : 'user';
- if($section != 'error' || !$cfg['text_group'])
- $group = 'all';
+ if($section != 'error' || !$cfg['text_group'])
+ $group = 'all';
- include(DATA.'text/'.$section.'.php');
+ include(DATA.'text/'.$section.'.php');
- return isset($text[$name][$group]) ? $text[$name][$group] : $text[$name];
- }
-
- public static function key($param = 'defegp')
- {
- return md5(sha1(rand(1, 15).$param.rand(16, 30).rand(200, 1000).rand(1, 100)));
- }
+ return isset($text[$name][$group]) ? $text[$name][$group] : $text[$name];
+ }
+
+ public static function key($param = 'defegp')
+ {
+ return md5(sha1(rand(1, 15).$param.rand(16, 30).rand(200, 1000).rand(1, 100)));
+ }
- public static function captcha($type, $ip)
- {
- global $mcache;
-
- $cod = '';
- $width = 100;
- $height = 45;
- $font_size = 16;
- $symbols = 3;
- $symbols_fon = 20;
- $font = LIB.'captcha/text.ttf';
-
- $chars = array('a','b','c','d','e','f','g','h','j','k','m','n','p','q','r','s','t','u','v','w','x','y','z','2','3','4','5','6','7','9');
- $colors = array('20','50','80','100');
+ public static function captcha($type, $ip)
+ {
+ global $mcache;
+
+ $cod = '';
+ $width = 100;
+ $height = 45;
+ $font_size = 16;
+ $symbols = 3;
+ $symbols_fon = 20;
+ $font = LIB.'captcha/text.ttf';
+
+ $chars = array('a','b','c','d','e','f','g','h','j','k','m','n','p','q','r','s','t','u','v','w','x','y','z','2','3','4','5','6','7','9');
+ $colors = array('20','50','80','100');
- $src = imagecreatetruecolor($width, $height);
- $fon = imagecolorallocate($src, 255, 255, 255);
-
- imagefill($src, 0, 0, $fon);
-
- $i = 0;
- for($i; $i < $symbols_fon; $i+=1)
- {
- $color = imagecolorallocatealpha($src, rand(0,255), rand(0,255), rand(0,255), 100);
- $char = $chars[rand(0, sizeof($chars)-1)];
- $size = rand($font_size-2, $font_size+2);
-
- imagettftext($src, $size, rand(0,45), rand($width*0.1,$width-$width*0.1), rand($height*0.2,$height), $color, $font, $char);
- }
-
- $i = 0;
- for($i; $i < $symbols; $i+=1)
- {
- $color = imagecolorallocatealpha($src, $colors[rand(0,sizeof($colors)-1)], $colors[rand(0,sizeof($colors)-1)], $colors[rand(0,sizeof($colors)-1)], rand(20,40));
- $char = $chars[rand(0, sizeof($chars)-1)];
- $size = rand($font_size*2.1-2, $font_size*2.1+2);
-
- $x = ($i+1)*$font_size + rand(6,8);
- $y = (($height*2)/3) + rand(3,7);
-
- $cod .= $char;
-
- imagettftext($src, $size, rand(0,15), $x, $y, $color, $font, $char);
- }
+ $src = imagecreatetruecolor($width, $height);
+ $fon = imagecolorallocate($src, 255, 255, 255);
+
+ imagefill($src, 0, 0, $fon);
+
+ $i = 0;
+ for($i; $i < $symbols_fon; $i+=1)
+ {
+ $color = imagecolorallocatealpha($src, rand(0,255), rand(0,255), rand(0,255), 100);
+ $char = $chars[rand(0, sizeof($chars)-1)];
+ $size = rand($font_size-2, $font_size+2);
+
+ imagettftext($src, $size, rand(0,45), rand($width*0.1,$width-$width*0.1), rand($height*0.2,$height), $color, $font, $char);
+ }
+
+ $i = 0;
+ for($i; $i < $symbols; $i+=1)
+ {
+ $color = imagecolorallocatealpha($src, $colors[rand(0,sizeof($colors)-1)], $colors[rand(0,sizeof($colors)-1)], $colors[rand(0,sizeof($colors)-1)], rand(20,40));
+ $char = $chars[rand(0, sizeof($chars)-1)];
+ $size = rand($font_size*2.1-2, $font_size*2.1+2);
+
+ $x = ($i+1)*$font_size + rand(6,8);
+ $y = (($height*2)/3) + rand(3,7);
+
+ $cod .= $char;
+
+ imagettftext($src, $size, rand(0,15), $x, $y, $color, $font, $char);
+ }
- $mcache->set($type.'_captcha_'.$ip, $cod, false, 120);
+ $mcache->set($type.'_captcha_'.$ip, $cod, false, 120);
- header("Content-type: image/gif");
- imagegif($src);
- imagedestroy($src);
- exit;
- }
+ header("Content-type: image/gif");
+ imagegif($src);
+ imagedestroy($src);
+ exit;
+ }
- public static function captcha_check($type, $ip, $cod = '')
- {
- global $cfg, $mcache;
+ public static function captcha_check($type, $ip, $cod = '')
+ {
+ global $cfg, $mcache;
- // Если повтор ввода капчи выключен и в кеше есть подтвержденный сеанс
- if(!$cfg['recaptcha'] AND $mcache->get($type.'_captcha_valid_'.$ip))
- return false;
+ // Если повтор ввода капчи выключен и в кеше есть подтвержденный сеанс
+ if(!$cfg['recaptcha'] AND $mcache->get($type.'_captcha_valid_'.$ip))
+ return false;
- if($mcache->get($type.'_captcha_'.$ip) != strtolower($cod))
- {
- $mcache->set($type.'_captcha_valid_'.$ip, true, false, 60);
+ if($mcache->get($type.'_captcha_'.$ip) != strtolower($cod))
+ {
+ $mcache->set($type.'_captcha_valid_'.$ip, true, false, 60);
- return true;
- }
+ return true;
+ }
- return false;
- }
+ return false;
+ }
- public static function ismail($data)
- {
- $aData = explode('@', $data);
+ public static function ismail($data)
+ {
+ $aData = explode('@', $data);
- if(count($aData) > 1)
- return true;
+ if(count($aData) > 1)
+ return true;
- return false;
- }
+ return false;
+ }
- public static function smscode()
- {
- return rand(1,9).rand(100,500).rand(10,99);
- }
+ public static function smscode()
+ {
+ return rand(1,9).rand(100,500).rand(10,99);
+ }
- public static function code($length = 8)
- {
- $list = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuWwXxYyZz0123456789';
- $a = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuWwXxYyZz';
- $selections = strlen($list)-1;
- $start = strlen($a)-1;
- $b = rand(0, $start);
- $start = $a[$b];
- $code = array();
+ public static function code($length = 8)
+ {
+ $list = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuWwXxYyZz0123456789';
+ $a = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuWwXxYyZz';
+ $selections = strlen($list)-1;
+ $start = strlen($a)-1;
+ $b = rand(0, $start);
+ $start = $a[$b];
+ $code = array();
- $i = 0;
+ $i = 0;
- for($i; $i <= $length-2; $i+=1)
- {
- $n = rand(0, $selections);
- $code[] = $list[$n];
- }
+ for($i; $i <= $length-2; $i+=1)
+ {
+ $n = rand(0, $selections);
+ $code[] = $list[$n];
+ }
- return $start.implode('', $code);
- }
+ return $start.implode('', $code);
+ }
- public static function sms($text, $phone)
- {
- global $cfg;
+ public static function sms($text, $phone)
+ {
+ global $cfg;
- $out = file_get_contents($cfg['sms_gateway'].'&'.$cfg['sms_to'].'='.$phone.'&'.$cfg['sms_text'].'='.urlencode($text));
+ $out = file_get_contents($cfg['sms_gateway'].'&'.$cfg['sms_to'].'='.$phone.'&'.$cfg['sms_text'].'='.urlencode($text));
- $aOut = explode("\n", $out);
+ $aOut = explode("\n", $out);
- if(trim($aOut[0]) == $cfg['sms_ok'])
- return true;
+ if(trim($aOut[0]) == $cfg['sms_ok'])
+ return true;
- return false;
- }
+ return false;
+ }
- public static function find($text, $find)
- {
- $words = explode(' ', $find);
+ public static function find($text, $find)
+ {
+ $words = explode(' ', $find);
- foreach($words as $word)
- if(strlen($word) >= 2)
- $text = preg_replace('#'.quotemeta($word).'#iu', '$0 ', $text);
+ foreach($words as $word)
+ if(strlen($word) >= 2)
+ $text = preg_replace('#'.quotemeta($word).'#iu', '$0 ', $text);
- return $text;
- }
+ return $text;
+ }
- public static function str_first_replace($search, $replace, $text)
- {
- $pos = strpos($text, $search);
-
- return $pos!==false ? substr_replace($text, $replace, $pos, strlen($search)) : $text;
- }
+ public static function str_first_replace($search, $replace, $text)
+ {
+ $pos = strpos($text, $search);
+
+ return $pos!==false ? substr_replace($text, $replace, $pos, strlen($search)) : $text;
+ }
- public static function cmd($command)
- {
- $text = preg_replace('/\\$/', '$ы', trim($command));
+ public static function cmd($command)
+ {
+ $text = preg_replace('/\\$/', '$ы', trim($command));
- mb_internal_encoding('UTF-8');
+ mb_internal_encoding('UTF-8');
- if(mb_substr($text, -1) == 'ы')
- $text = quotemeta(substr($text, 0, -2));
+ if(mb_substr($text, -1) == 'ы')
+ $text = quotemeta(substr($text, 0, -2));
- return $text;
- }
+ return $text;
+ }
- public static function map($map)
- {
- $name = quotemeta(trim($map));
+ public static function map($map)
+ {
+ $name = quotemeta(trim($map));
- if(substr($name, -1) == '$')
- $name = substr($name, 0, -2).'$';
+ if(substr($name, -1) == '$')
+ $name = substr($name, 0, -2).'$';
- return str_replace(array('\.', '\*'), array('.', '*'), $name);
- }
+ return str_replace(array('\.', '\*'), array('.', '*'), $name);
+ }
- public static function temp($text)
- {
- $temp = TEMP.md5(time().rand(5, 100).rand(10, 20).rand(1, 20).rand(40, 80));
+ public static function temp($text)
+ {
+ $temp = TEMP.md5(time().rand(5, 100).rand(10, 20).rand(1, 20).rand(40, 80));
- $file = fopen($temp, "w");
+ $file = fopen($temp, "w");
- fputs($file, $text);
+ fputs($file, $text);
- fclose($file);
+ fclose($file);
- return $temp;
- }
+ return $temp;
+ }
- public static function size($val)
- {
- $aSize = array(' Байт', ' Кб', ' Мб', ' Гб', ' Тб', ' Пб');
+ public static function size($val)
+ {
+ $aSize = array(' Байт', ' Кб', ' Мб', ' Гб', ' Тб', ' Пб');
- return $val ? round($val/pow(1024, ($i = floor(log($val, 1024)))), 2) . $aSize[$i] : '0 Байт';
- }
+ return $val ? round($val/pow(1024, ($i = floor(log($val, 1024)))), 2) . $aSize[$i] : '0 Байт';
+ }
- public static function unidate($date)
- {
- $aDate = explode('-', $date);
-
- $aFirst = explode(' ', $aDate[2]);
-
- return $aFirst[1].' - '.$aFirst[0].'.'.$aDate[1].'.'.$aDate[0];
- }
-
- public static function page($page, $nums, $num)
- {
- $ceil = ceil($nums/$num);
-
- if($page > $ceil)
- $page = $ceil;
-
- $next = $page*$num;
-
- if($next <= $nums)
- $next = $next-$num;
+ public static function unidate($date)
+ {
+ $aDate = explode('-', $date);
+
+ $aFirst = explode(' ', $aDate[2]);
+
+ return $aFirst[1].' - '.$aFirst[0].'.'.$aDate[1].'.'.$aDate[0];
+ }
+
+ public static function page($page, $nums, $num)
+ {
+ $ceil = ceil($nums/$num);
+
+ if($page > $ceil)
+ $page = $ceil;
+
+ $next = $page*$num;
+
+ if($next <= $nums)
+ $next = $next-$num;
- if($next > $nums)
- $next = $next-$num;
+ if($next > $nums)
+ $next = $next-$num;
- if($next < 1)
- $next = 0;
+ if($next < 1)
+ $next = 0;
- $num_go = $next;
- if($page == '')
- $page = 1;
+ $num_go = $next;
+ if($page == '')
+ $page = 1;
- $aPage = array(
- 'page' => $page,
- 'num' => $num_go,
- 'ceil' => $ceil
- );
+ $aPage = array(
+ 'page' => $page,
+ 'num' => $num_go,
+ 'ceil' => $ceil
+ );
- return $aPage;
- }
+ return $aPage;
+ }
- public static function page_list($countnum, $actnum)
- {
- if($countnum == 0 || $countnum == 1)
- return array();
+ public static function page_list($countnum, $actnum)
+ {
+ if($countnum == 0 || $countnum == 1)
+ return array();
- if($countnum > 10)
- {
- if($actnum <= 4 || $actnum + 3 >= $countnum)
- {
- for($i = 0; $i <= 4; $i++)
- $numlist[$i] = $i + 1;
+ if($countnum > 10)
+ {
+ if($actnum <= 4 || $actnum + 3 >= $countnum)
+ {
+ for($i = 0; $i <= 4; $i++)
+ $numlist[$i] = $i + 1;
- $numlist[5] = '...';
- for($j = 6, $k = 4; $j <= 10; $j+=1, $k-=1)
- $numlist[$j] = $countnum - $k;
- }else{
- $numlist[0] = 1;
- $numlist[1] = 2;
- $numlist[2] = '...';
- $numlist[3] = $actnum - 2;
- $numlist[4] = $actnum - 1;
- $numlist[5] = $actnum;
- $numlist[6] = $actnum + 1;
- $numlist[7] = $actnum + 2;
- $numlist[8] = '...';
- $numlist[9] = $countnum - 1;
- $numlist[10] = $countnum;
- }
- }else
- for($n = 0; $n < $countnum; $n+=1)
- $numlist[$n] = $n + 1;
+ $numlist[5] = '...';
+ for($j = 6, $k = 4; $j <= 10; $j+=1, $k-=1)
+ $numlist[$j] = $countnum - $k;
+ }else{
+ $numlist[0] = 1;
+ $numlist[1] = 2;
+ $numlist[2] = '...';
+ $numlist[3] = $actnum - 2;
+ $numlist[4] = $actnum - 1;
+ $numlist[5] = $actnum;
+ $numlist[6] = $actnum + 1;
+ $numlist[7] = $actnum + 2;
+ $numlist[8] = '...';
+ $numlist[9] = $countnum - 1;
+ $numlist[10] = $countnum;
+ }
+ }else
+ for($n = 0; $n < $countnum; $n+=1)
+ $numlist[$n] = $n + 1;
- return $numlist;
- }
+ return $numlist;
+ }
- public static function page_gen($ceil, $page, $actnum, $section)
- {
- global $cfg, $html;
+ public static function page_gen($ceil, $page, $actnum, $section)
+ {
+ global $cfg, $html;
- $aNum = sys::page_list($ceil, $actnum);
+ $aNum = sys::page_list($ceil, $actnum);
- $pages = '';
+ $pages = '';
- $html->get('pages');
+ $html->get('pages');
- if($ceil)
- {
- if($page != 1)
- {
- $next = $page-1;
- $pages .= 'Предыдущая ';
- }
+ if($ceil)
+ {
+ if($page != 1)
+ {
+ $next = $page-1;
+ $pages .= 'Предыдущая ';
+ }
- foreach($aNum as $v)
- {
- if($v != $page && $v != '...')
- $pages .= ''.$v.' ';
-
- if($v == $page)
- $pages .= ''.$v.' ';
-
- if($v == '...')
- $pages .= '... ';
- }
+ foreach($aNum as $v)
+ {
+ if($v != $page && $v != '...')
+ $pages .= ''.$v.' ';
+
+ if($v == $page)
+ $pages .= ''.$v.' ';
+
+ if($v == '...')
+ $pages .= '... ';
+ }
- if($ceil > $page)
- {
- if($page < $ceil)
- {
- $next = $page+1;
- $pages .= 'Следующая ';
- }else
- $pages .= 'Следующая ';
- }
- }
+ if($ceil > $page)
+ {
+ if($page < $ceil)
+ {
+ $next = $page+1;
+ $pages .= 'Следующая ';
+ }else
+ $pages .= 'Следующая ';
+ }
+ }
- $html->set('pages', $pages);
+ $html->set('pages', $pages);
- $html->pack('pages');
+ $html->pack('pages');
- return NULL;
- }
+ return NULL;
+ }
- public static function country($name)
- {
- global $cfg;
-
- $fileimg = file_exists(TPL.'/images/country/'.$name.'.png');
-
- if($fileimg)
- return $cfg['http'].'template/images/country/'.$name.'.png';
-
- return $cfg['http'].'template/images/country/none.png';
- }
-
- public static function ipproxy()
- {
- global $_SERVER;
-
- if(isset($_SERVER['HTTP_CF_CONNECTING_IP']) && !empty($_SERVER['HTTP_CF_CONNECTING_IP']))
- return $_SERVER['HTTP_CF_CONNECTING_IP'];
-
- return NULL;
- }
+ public static function country($name)
+ {
+ global $cfg;
+
+ $fileimg = file_exists(TPL.'/images/country/'.$name.'.png');
+
+ if($fileimg)
+ return $cfg['http'].'template/images/country/'.$name.'.png';
+
+ return $cfg['http'].'template/images/country/none.png';
+ }
+
+ public static function ipproxy()
+ {
+ global $_SERVER;
+
+ if(isset($_SERVER['HTTP_CF_CONNECTING_IP']) && !empty($_SERVER['HTTP_CF_CONNECTING_IP']))
+ return $_SERVER['HTTP_CF_CONNECTING_IP'];
+
+ return NULL;
+ }
- public static function ip()
- {
- $ip = sys::ipproxy();
+ public static function ip()
+ {
+ $ip = sys::ipproxy();
- if(sys::valid($ip, 'ip'))
- return $_SERVER['REMOTE_ADDR'];
+ if(sys::valid($ip, 'ip'))
+ return $_SERVER['REMOTE_ADDR'];
- return $ip;
- }
+ return $ip;
+ }
- public static function whois($ip)
- {
- $stack = fsockopen('whois.ripe.net', 43, $errno, $errstr);
+ public static function whois($ip)
+ {
+ $stack = fsockopen('whois.ripe.net', 43, $errno, $errstr);
- if(!$stack)
- return 'не определена';
+ if(!$stack)
+ return 'не определена';
- fputs($stack, $ip."\r\n");
+ fputs($stack, $ip."\r\n");
- $subnetwork = '';
+ $subnetwork = '';
- while(!feof($stack))
- {
- $str = fgets($stack, 128);
+ while(!feof($stack))
+ {
+ $str = fgets($stack, 128);
- if(strpos($str, 'route:') !== FALSE)
- {
- $subnetwork = trim(str_replace('route:', '', $str));
+ if(strpos($str, 'route:') !== FALSE)
+ {
+ $subnetwork = trim(str_replace('route:', '', $str));
- break;
- }
- }
+ break;
+ }
+ }
- fclose($stack);
+ fclose($stack);
- return isset($subnetwork[0]) ? $subnetwork : 'не определена';
- }
+ return isset($subnetwork[0]) ? $subnetwork : 'не определена';
+ }
- public static function rep_act($name, $time = 20)
- {
- global $go, $mcache;
+ public static function rep_act($name, $time = 20)
+ {
+ global $go, $mcache;
- if(!$go)
- return NULL;
+ if(!$go)
+ return NULL;
- if($mcache->get($name))
- sys::outjs(array('e' => sys::text('other', 'mcache')));
+ if($mcache->get($name))
+ sys::outjs(array('e' => sys::text('other', 'mcache')));
- $mcache->set($name, true, false, $time);
+ $mcache->set($name, true, false, $time);
- return $name;
- }
+ return $name;
+ }
- public static function check_php_config($file, &$error)
- {
- exec('php -l '.$file, $error, $code);
+ public static function check_php_config($file, &$error)
+ {
+ exec('php -l '.$file, $error, $code);
- if(!$code)
- return true;
+ if(!$code)
+ return true;
- return false;
- }
+ return false;
+ }
- public static function cpu_idle($pros_stat = array(), $unit = false, $fcpu = false, $ctrl = false)
- {
- return sys::cpu_get_idle(sys::parse_cpu($pros_stat[0]), sys::parse_cpu($pros_stat[1]), $unit, $fcpu, $ctrl);
- }
+ public static function cpu_idle($pros_stat = array(), $unit = false, $fcpu = false, $ctrl = false)
+ {
+ return sys::cpu_get_idle(sys::parse_cpu($pros_stat[0]), sys::parse_cpu($pros_stat[1]), $unit, $fcpu, $ctrl);
+ }
- public static function cpu_get_idle($first, $second, $unit, $fcpu, $ctrl)
- {
- global $sql;
+ public static function cpu_get_idle($first, $second, $unit, $fcpu, $ctrl)
+ {
+ global $sql;
- if(count($first) !== count($second))
- return;
+ if(count($first) !== count($second))
+ return;
- $cpus = array();
+ $cpus = array();
- for($i = 0, $l = count($first); $i < $l; $i+=1)
- {
- $dif = array();
- $dif['use'] = $second[$i]['use']-$first[$i]['use'];
- $dif['nice'] = $second[$i]['nice']-$first[$i]['nice'];
- $dif['sys'] = $second[$i]['sys']-$first[$i]['sys'];
- $dif['idle'] = $second[$i]['idle']-$first[$i]['idle'];
- $total = array_sum($dif);
- $cpu = array();
+ for($i = 0, $l = count($first); $i < $l; $i+=1)
+ {
+ $dif = array();
+ $dif['use'] = $second[$i]['use']-$first[$i]['use'];
+ $dif['nice'] = $second[$i]['nice']-$first[$i]['nice'];
+ $dif['sys'] = $second[$i]['sys']-$first[$i]['sys'];
+ $dif['idle'] = $second[$i]['idle']-$first[$i]['idle'];
+ $total = array_sum($dif);
+ $cpu = array();
- foreach($dif as $x => $y)
- $cpu[$x] = $y ? round($y/$total*100, 1) : 0;
+ foreach($dif as $x => $y)
+ $cpu[$x] = $y ? round($y/$total*100, 1) : 0;
- $cpus['cpu'.$i] = $cpu;
- }
+ $cpus['cpu'.$i] = $cpu;
+ }
- if($fcpu)
- return $cpus;
+ if($fcpu)
+ return $cpus;
- $threads = array();
+ $threads = array();
- $l = count($first);
+ $l = count($first);
- for($i = 0; $i < $l; $i+=1)
- $threads[$i] = $cpus['cpu'.$i]['idle'];
+ for($i = 0; $i < $l; $i+=1)
+ $threads[$i] = $cpus['cpu'.$i]['idle'];
- if(count($first) > 1)
- unset($threads[0]);
+ if(count($first) > 1)
+ unset($threads[0]);
- $max = max($threads);
+ $max = max($threads);
- foreach($threads as $idle)
- {
- $core = array_search($max, $threads);
+ foreach($threads as $idle)
+ {
+ $core = array_search($max, $threads);
- if($ctrl)
- $sql->query('SELECT `id` FROM `control_servers` WHERE `unit`="'.$unit.'" AND `core_fix`="'.($core+1).'" LIMIT 1');
- else
- $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$unit.'" AND `core_fix`="'.($core+1).'" AND `core_fix_one`="1" LIMIT 1');
- if($sql->num())
- {
- unset($threads[$core]);
+ if($ctrl)
+ $sql->query('SELECT `id` FROM `control_servers` WHERE `unit`="'.$unit.'" AND `core_fix`="'.($core+1).'" LIMIT 1');
+ else
+ $sql->query('SELECT `id` FROM `servers` WHERE `unit`="'.$unit.'" AND `core_fix`="'.($core+1).'" AND `core_fix_one`="1" LIMIT 1');
+ if($sql->num())
+ {
+ unset($threads[$core]);
- if(!count($threads))
- return NULL;
+ if(!count($threads))
+ return NULL;
- $max = max($threads);
- }
- }
+ $max = max($threads);
+ }
+ }
- return array_search($max, $threads);
- }
+ return array_search($max, $threads);
+ }
- public static function parse_cpu($data)
- {
- $data = explode("\n", $data);
+ public static function parse_cpu($data)
+ {
+ $data = explode("\n", $data);
- $cpu = array();
+ $cpu = array();
- foreach($data as $line)
- {
- if(preg_match('/^cpu[0-9]/', $line))
- {
- $info = explode(' ', $line);
+ foreach($data as $line)
+ {
+ if(preg_match('/^cpu[0-9]/', $line))
+ {
+ $info = explode(' ', $line);
- $cpu[] = array(
- 'use' => $info[1],
- 'nice' => $info[2],
- 'sys' => $info[3],
- 'idle' => $info[4]
- );
- }
- }
+ $cpu[] = array(
+ 'use' => $info[1],
+ 'nice' => $info[2],
+ 'sys' => $info[3],
+ 'idle' => $info[4]
+ );
+ }
+ }
- return $cpu;
- }
+ return $cpu;
+ }
- public static function reset_mcache($nmch, $id, $data = array(), $ctrl = false)
- {
- global $mcache;
+ public static function reset_mcache($nmch, $id, $data = array(), $ctrl = false)
+ {
+ global $mcache;
- $cache = array(
- 'name' => $data['name'],
- 'status' => sys::status($data['status'], $data['game']),
- 'online' => $data['online'],
- 'image' => ' ',
- );
+ $cache = array(
+ 'name' => $data['name'],
+ 'status' => sys::status($data['status'], $data['game']),
+ 'online' => $data['online'],
+ 'image' => ' ',
+ );
- $cache = $ctrl ? sys::buttons($id, $data['status'], $data['game'], $ctrl) : sys::buttons($id, $data['status'], $data['game']);
+ $cache = $ctrl ? sys::buttons($id, $data['status'], $data['game'], $ctrl) : sys::buttons($id, $data['status'], $data['game']);
- if(isset($data['players']))
- $cache['players'] = $data['players'];
+ if(isset($data['players']))
+ $cache['players'] = $data['players'];
- $mcache->set($nmch, $cache, false, 5);
+ $mcache->set($nmch, $cache, false, 5);
- return NULL;
- }
+ return NULL;
+ }
- public static function status($status, $game, $map = '', $get = 'text')
- {
- global $cfg;
+ public static function status($status, $game, $map = '', $get = 'text')
+ {
+ global $cfg;
- switch($status)
- {
- case 'working':
- if($get == 'img')
- {
- if(in_array($game, array('samp', 'crmp', 'mta', 'mc')))
- $map = $game;
+ switch($status)
+ {
+ case 'working':
+ if($get == 'img')
+ {
+ if(in_array($game, array('samp', 'crmp', 'mta', 'mc')))
+ $map = $game;
- return sys::img($map, $game);
- }
+ return sys::img($map, $game);
+ }
- return 'Карта: '.($map == '' ? '-' : $map);
+ return 'Карта: '.($map == '' ? '-' : $map);
- case 'off':
- if($get == 'img')
- return $cfg['http'].'template/images/status/off.jpg';
+ case 'off':
+ if($get == 'img')
+ return $cfg['http'].'template/images/status/off.jpg';
- return 'Статус: выключен ';
+ return 'Статус: выключен ';
- case 'start':
- if($get == 'img')
- return $cfg['http'].'template/images/status/start.gif';
+ case 'start':
+ if($get == 'img')
+ return $cfg['http'].'template/images/status/start.gif';
- return 'Статус: запускается ';
+ return 'Статус: запускается ';
- case 'restart':
- if($get == 'img')
- return $cfg['http'].'template/images/status/restart.gif';
+ case 'restart':
+ if($get == 'img')
+ return $cfg['http'].'template/images/status/restart.gif';
- return 'Статус: перезапускается ';
+ return 'Статус: перезапускается ';
- case 'change':
- if($get == 'img')
- return $cfg['http'].'template/images/status/change.gif';
+ case 'change':
+ if($get == 'img')
+ return $cfg['http'].'template/images/status/change.gif';
- return 'Статус: меняется карта ';
+ return 'Статус: меняется карта ';
- case 'install':
- if($get == 'img')
- return $cfg['http'].'template/images/status/install.gif';
+ case 'install':
+ if($get == 'img')
+ return $cfg['http'].'template/images/status/install.gif';
- return 'Статус: устанавливается ';
+ return 'Статус: устанавливается ';
- case 'reinstall':
- if($get == 'img')
- return $cfg['http'].'template/images/status/reinstall.gif';
+ case 'reinstall':
+ if($get == 'img')
+ return $cfg['http'].'template/images/status/reinstall.gif';
- return 'Статус: переустанавливается ';
+ return 'Статус: переустанавливается ';
- case 'update':
- if($get == 'img')
- return $cfg['http'].'template/images/status/update.gif';
+ case 'update':
+ if($get == 'img')
+ return $cfg['http'].'template/images/status/update.gif';
- return 'Статус: обновляется ';
+ return 'Статус: обновляется ';
- case 'recovery':
- if($get == 'img')
- return $cfg['http'].'template/images/status/recovery.gif';
+ case 'recovery':
+ if($get == 'img')
+ return $cfg['http'].'template/images/status/recovery.gif';
- return 'Статус: восстанавливается ';
+ return 'Статус: восстанавливается ';
- case 'overdue':
- if($get == 'img')
- return $cfg['http'].'template/images/status/overdue.jpg';
+ case 'overdue':
+ if($get == 'img')
+ return $cfg['http'].'template/images/status/overdue.jpg';
- return 'Статус: просрочен';
+ return 'Статус: просрочен';
- case 'blocked':
- if($get == 'img')
- return $cfg['http'].'template/images/status/blocked.jpg';
+ case 'blocked':
+ if($get == 'img')
+ return $cfg['http'].'template/images/status/blocked.jpg';
- return 'Статус: заблокирован';
- }
- }
+ return 'Статус: заблокирован';
+ }
+ }
- public static function img($name, $game)
- {
- global $cfg;
-
- $filename = 'http://cdn.enginegp.ru/maps/'.$game.'/'.$name.'.jpg';
- $file_headers = @get_headers($filename) ;
- $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://";
- if(!$file_headers || $file_headers[0] == 'HTTP/1.1 404 Not Found' ||trim($file_headers[0]) == 'HTTP/1.1 403 Forbidden') {
- return $cfg['http'].'template/images/status/none.jpg';
- }
- else {
- return '' . $protocol .'cdn.enginegp.ru/maps/'.$game.'/'.$name.'.jpg';
- }
- }
+ public static function img($name, $game)
+ {
+ global $cfg;
+
+ $filename = 'http://cdn.enginegp.ru/maps/'.$game.'/'.$name.'.jpg';
+ $file_headers = @get_headers($filename) ;
+ $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://";
+ if(!$file_headers || $file_headers[0] == 'HTTP/1.1 404 Not Found' ||trim($file_headers[0]) == 'HTTP/1.1 403 Forbidden') {
+ return $cfg['http'].'template/images/status/none.jpg';
+ }
+ else {
+ return '' . $protocol .'cdn.enginegp.ru/maps/'.$game.'/'.$name.'.jpg';
+ }
+ }
- public static function buttons($id, $status, $game = false, $ctrl = false)
- {
- global $html;
+ public static function buttons($id, $status, $game = false, $ctrl = false)
+ {
+ global $html;
- if(isset($html->arr['buttons']))
- unset($html->arr['buttons']);
+ if(isset($html->arr['buttons']))
+ unset($html->arr['buttons']);
- $other = in_array($game, array('samp', 'crmp', 'mta', 'mc'));
+ $other = in_array($game, array('samp', 'crmp', 'mta', 'mc'));
- $dir = $ctrl ? 'control/servers' : 'servers';
+ $dir = $ctrl ? 'control/servers' : 'servers';
- if(in_array($status, array('working', 'change', 'start', 'restart')))
- {
- $html->get('stop', 'sections/'.$dir.'/buttons');
+ if(in_array($status, array('working', 'change', 'start', 'restart')))
+ {
+ $html->get('stop', 'sections/'.$dir.'/buttons');
- $html->set('id', $id);
- if($ctrl)
- $html->set('ctrl', $ctrl);
+ $html->set('id', $id);
+ if($ctrl)
+ $html->set('ctrl', $ctrl);
- $html->pack('buttons');
+ $html->pack('buttons');
- $html->get('restart', 'sections/'.$dir.'/buttons');
+ $html->get('restart', 'sections/'.$dir.'/buttons');
- $html->set('id', $id);
- if($ctrl)
- $html->set('ctrl', $ctrl);
+ $html->set('id', $id);
+ if($ctrl)
+ $html->set('ctrl', $ctrl);
- $html->pack('buttons');
+ $html->pack('buttons');
- if(!$other)
- {
- $html->get('change', 'sections/'.$dir.'/buttons');
+ if(!$other)
+ {
+ $html->get('change', 'sections/'.$dir.'/buttons');
- $html->set('id', $id);
- if($ctrl)
- $html->set('ctrl', $ctrl);
+ $html->set('id', $id);
+ if($ctrl)
+ $html->set('ctrl', $ctrl);
- $html->pack('buttons');
- }
+ $html->pack('buttons');
+ }
- return $html->arr['buttons'];
- }
+ return $html->arr['buttons'];
+ }
- if($status == 'off')
- {
- $html->get('start', 'sections/'.$dir.'/buttons');
+ if($status == 'off')
+ {
+ $html->get('start', 'sections/'.$dir.'/buttons');
- $html->set('id', $id);
- if($ctrl)
- $html->set('ctrl', $ctrl);
+ $html->set('id', $id);
+ if($ctrl)
+ $html->set('ctrl', $ctrl);
- $html->pack('buttons');
+ $html->pack('buttons');
- $html->get('reinstall', 'sections/'.$dir.'/buttons');
+ $html->get('reinstall', 'sections/'.$dir.'/buttons');
- $html->set('id', $id);
- if($ctrl)
- $html->set('ctrl', $ctrl);
+ $html->set('id', $id);
+ if($ctrl)
+ $html->set('ctrl', $ctrl);
- $html->pack('buttons');
+ $html->pack('buttons');
- if(!$other)
- {
- $html->get('update', 'sections/'.$dir.'/buttons');
+ if(!$other)
+ {
+ $html->get('update', 'sections/'.$dir.'/buttons');
- $html->set('id', $id);
- if($ctrl)
- $html->set('ctrl', $ctrl);
+ $html->set('id', $id);
+ if($ctrl)
+ $html->set('ctrl', $ctrl);
- $html->pack('buttons');
- }
+ $html->pack('buttons');
+ }
- return $html->arr['buttons'];
- }
+ return $html->arr['buttons'];
+ }
- $html->get('other', 'sections/'.$dir.'/buttons');
- $html->pack('buttons');
+ $html->get('other', 'sections/'.$dir.'/buttons');
+ $html->pack('buttons');
- return $html->arr['buttons'];
- }
+ return $html->arr['buttons'];
+ }
- public static function entoru($month)
- {
- $ru = array(
- 1 => 'Янв', 2 => 'Фев', 3 => 'Мар', 4 => 'Апр',
- 5 => 'Май', 6 => 'Июн', 7 => 'Июл', 8 => 'Авг',
- 9 => 'Сен', 10 => 'Окт', 11 => 'Ноя', 12 => 'Дек'
- );
+ public static function entoru($month)
+ {
+ $ru = array(
+ 1 => 'Янв', 2 => 'Фев', 3 => 'Мар', 4 => 'Апр',
+ 5 => 'Май', 6 => 'Июн', 7 => 'Июл', 8 => 'Авг',
+ 9 => 'Сен', 10 => 'Окт', 11 => 'Ноя', 12 => 'Дек'
+ );
- return $ru[$month];
- }
+ return $ru[$month];
+ }
- public static function head($head)
- {
- global $route, $header;
+ public static function head($head)
+ {
+ global $route, $header;
- if($head == 'description')
- {
- global $description;
+ if($head == 'description')
+ {
+ global $description;
- if(isset($description))
- {
- $text = str_replace(array('"', '-'), array('', '—'), strip_tags($description));
+ if(isset($description))
+ {
+ $text = str_replace(array('"', '-'), array('', '—'), strip_tags($description));
- if(strlen($text) > 160)
- {
- mb_internal_encoding('UTF-8');
+ if(strlen($text) > 160)
+ {
+ mb_internal_encoding('UTF-8');
- $text = mb_substr($text, 0, 157).'...';
- }
+ $text = mb_substr($text, 0, 157).'...';
+ }
- return $text;
- }
- }else{
- global $keywords;
+ return $text;
+ }
+ }else{
+ global $keywords;
- if(isset($keywords))
- return str_replace(array('"', '-'), array('', '—'), strip_tags($keywords));
- }
+ if(isset($keywords))
+ return str_replace(array('"', '-'), array('', '—'), strip_tags($keywords));
+ }
- return array_key_exists($route, $header) ? $header[$route][$head] : $header['index'][$head];
- }
+ return array_key_exists($route, $header) ? $header[$route][$head] : $header['index'][$head];
+ }
- public static function tags($tags)
- {
- $aTags = explode(',', $tags);
+ public static function tags($tags)
+ {
+ $aTags = explode(',', $tags);
- $text = '';
+ $text = '';
- foreach($aTags as $tag)
- $text .= ''.trim($tag).' , ';
+ foreach($aTags as $tag)
+ $text .= ''.trim($tag).' , ';
- return isset($text[0]) ? substr($text, 0, -2) : 'отсутствуют';
- }
+ return isset($text[0]) ? substr($text, 0, -2) : 'отсутствуют';
+ }
- public static function benefitblock($id, $nmch = false)
- {
- global $cfg, $sql, $start_point;
+ public static function benefitblock($id, $nmch = false)
+ {
+ global $cfg, $sql, $start_point;
- if($cfg['benefitblock'])
- {
- $sql->query('SELECT `benefit` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
- $info = $sql->get();
+ if($cfg['benefitblock'])
+ {
+ $sql->query('SELECT `benefit` FROM `servers` WHERE `id`="'.$id.'" LIMIT 1');
+ $info = $sql->get();
- if($info['benefit'] > $start_point)
- sys::outjs(array('e' => 'Операция недоступна до '.date('d.m.Y - H:i:s', $info['benefit'])), $nmch);
- }
+ if($info['benefit'] > $start_point)
+ sys::outjs(array('e' => 'Операция недоступна до '.date('d.m.Y - H:i:s', $info['benefit'])), $nmch);
+ }
- return NULL;
- }
+ return NULL;
+ }
- function outfile($file, $name, $del = false)
- {
- if(file_exists($file))
- {
- if(ob_get_level())
- ob_end_clean();
+ function outfile($file, $name, $del = false)
+ {
+ if(file_exists($file))
+ {
+ if(ob_get_level())
+ ob_end_clean();
- header('Content-Description: File Transfer');
- header('Content-Type: application/octet-stream');
- header('Content-Disposition: attachment; filename='.$name);
- header('Content-Transfer-Encoding: binary');
- header('Expires: 0');
- header('Cache-Control: must-revalidate');
- header('Pragma: public');
- header('Content-Length: '.filesize($file));
+ header('Content-Description: File Transfer');
+ header('Content-Type: application/octet-stream');
+ header('Content-Disposition: attachment; filename='.$name);
+ header('Content-Transfer-Encoding: binary');
+ header('Expires: 0');
+ header('Cache-Control: must-revalidate');
+ header('Pragma: public');
+ header('Content-Length: '.filesize($file));
- readfile($file);
+ readfile($file);
- if($del)
- unlink($file);
+ if($del)
+ unlink($file);
- exit;
- }
- }
- }
+ exit;
+ }
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/users.php b/system/library/users.php
index 732d68a..fb87b91 100644
--- a/system/library/users.php
+++ b/system/library/users.php
@@ -1,53 +1,53 @@
get('gmenu', 'sections/user');
+ $html->get('gmenu', 'sections/user');
- $html->set('home', $cfg['http']);
+ $html->set('home', $cfg['http']);
- foreach($aUnit as $unit)
- if($unit == $active) $html->unit($unit, 1); else $html->unit($unit);
+ foreach($aUnit as $unit)
+ if($unit == $active) $html->unit($unit, 1); else $html->unit($unit);
- $html->pack('main');
+ $html->pack('main');
- $html->get('vmenu', 'sections/user');
+ $html->get('vmenu', 'sections/user');
- $html->set('home', $cfg['http']);
+ $html->set('home', $cfg['http']);
- foreach($aUnit as $unit)
- if($unit == $active) $html->unit($unit, 1); else $html->unit($unit);
+ foreach($aUnit as $unit)
+ if($unit == $active) $html->unit($unit, 1); else $html->unit($unit);
- $html->pack('vmenu');
+ $html->pack('vmenu');
- return NULL;
- }
- }
+ return NULL;
+ }
+ }
?>
\ No newline at end of file
diff --git a/system/library/web/free.php b/system/library/web/free.php
index fef8c55..2302c94 100644
--- a/system/library/web/free.php
+++ b/system/library/web/free.php
@@ -1,496 +1,496 @@
'Дополнительная услуга недоступна для установки.'), $mcache);
+ if(!$aWeb[$aData['server']['game']][$aData['type']])
+ sys::outjs(array('e' => 'Дополнительная услуга недоступна для установки.'), $mcache);
- // Проверка на наличие уже установленной выбранной услуги
- if($sql->num(web::stack($aData, '`id`')))
- sys::outjs(array('i' => 'Дополнительная услуга уже установлена.'), $mcache);
+ // Проверка на наличие уже установленной выбранной услуги
+ if($sql->num(web::stack($aData, '`id`')))
+ sys::outjs(array('i' => 'Дополнительная услуга уже установлена.'), $mcache);
- // Проверка на наличие уже установленной подобной услуги
- switch($aWebInstall[$aData['server']['game']][$aData['type']])
- {
- case 'server':
- foreach($aWebOne[$aData['server']['game']][$aData['type']] as $type)
- {
- $sql->query('SELECT `id` FROM `web` WHERE `type`="'.$type.'" AND `server`="'.$aData['server']['id'].'" LIMIT 1');
- if($sql->num())
- sys::outjs(array('i' => 'Подобная услуга уже установлена.', 'type' => $type), $mcache);
- }
+ // Проверка на наличие уже установленной подобной услуги
+ switch($aWebInstall[$aData['server']['game']][$aData['type']])
+ {
+ case 'server':
+ foreach($aWebOne[$aData['server']['game']][$aData['type']] as $type)
+ {
+ $sql->query('SELECT `id` FROM `web` WHERE `type`="'.$type.'" AND `server`="'.$aData['server']['id'].'" LIMIT 1');
+ if($sql->num())
+ sys::outjs(array('i' => 'Подобная услуга уже установлена.', 'type' => $type), $mcache);
+ }
- break;
+ break;
- case 'user':
- foreach($aWebOne[$aData['server']['game']][$aData['type']] as $type)
- {
- $sql->query('SELECT `id` FROM `web` WHERE `type`="'.$type.'" AND `user`="'.$aData['server']['user'].'" LIMIT 1');
- if($sql->num())
- sys::outjs(array('i' => 'Подобная услуга уже установлена.', 'type' => $type), $mcache);
- }
+ case 'user':
+ foreach($aWebOne[$aData['server']['game']][$aData['type']] as $type)
+ {
+ $sql->query('SELECT `id` FROM `web` WHERE `type`="'.$type.'" AND `user`="'.$aData['server']['user'].'" LIMIT 1');
+ if($sql->num())
+ sys::outjs(array('i' => 'Подобная услуга уже установлена.', 'type' => $type), $mcache);
+ }
- break;
+ break;
- case 'unit':
- foreach($aWebOne[$aData['server']['game']][$aData['type']] as $type)
- {
- $sql->query('SELECT `id` FROM `web` WHERE `type`="'.$type.'" AND `user`="'.$aData['server']['user'].'" AND `unit`="'.$aData['server']['unit'].'" LIMIT 1');
- if($sql->num())
- sys::outjs(array('i' => 'Подобная услуга уже установлена.', 'type' => $type), $mcache);
- }
- }
+ case 'unit':
+ foreach($aWebOne[$aData['server']['game']][$aData['type']] as $type)
+ {
+ $sql->query('SELECT `id` FROM `web` WHERE `type`="'.$type.'" AND `user`="'.$aData['server']['user'].'" AND `unit`="'.$aData['server']['unit'].'" LIMIT 1');
+ if($sql->num())
+ sys::outjs(array('i' => 'Подобная услуга уже установлена.', 'type' => $type), $mcache);
+ }
+ }
- // Проверка валидности поддомена
- if(sys::valid($aData['subdomain'], 'other', "/^[a-z0-9]+$/"))
- sys::outjs(array('e' => 'Адрес должен состоять из букв a-z и цифр.'), $mcache);
+ // Проверка валидности поддомена
+ if(sys::valid($aData['subdomain'], 'other', "/^[a-z0-9]+$/"))
+ sys::outjs(array('e' => 'Адрес должен состоять из букв a-z и цифр.'), $mcache);
- // Проверка длины поддомена
- if(!isset($aData['subdomain']{3}) || isset($aData['subdomain']{15}))
- sys::outjs(array('e' => 'Длина адреса не должна превышать 16-и символов и быть не менее 4-х символов.'), $mcache);
+ // Проверка длины поддомена
+ if(!isset($aData['subdomain']{3}) || isset($aData['subdomain']{15}))
+ sys::outjs(array('e' => 'Длина адреса не должна превышать 16-и символов и быть не менее 4-х символов.'), $mcache);
- // Проверка запрещенного поддомена
- if(in_array($aData['subdomain'], $aWebUnit['subdomains']))
- sys::outjs(array('e' => 'Нельзя создать данный адрес, придумайте другой.'), $mcache);
+ // Проверка запрещенного поддомена
+ if(in_array($aData['subdomain'], $aWebUnit['subdomains']))
+ sys::outjs(array('e' => 'Нельзя создать данный адрес, придумайте другой.'), $mcache);
- // Проверка наличия домена
- if(!in_array($aData['domain'], $aWebUnit['domains']))
- sys::outjs(array('e' => 'Выбранный домен не найден.'), $mcache);
+ // Проверка наличия домена
+ if(!in_array($aData['domain'], $aWebUnit['domains']))
+ sys::outjs(array('e' => 'Выбранный домен не найден.'), $mcache);
- // Проверка поддомена на занятость
- $sql->query('SELECT `id` FROM `web` WHERE `domain`="'.$aData['subdomain'].'.'.$aData['domain'].'" LIMIT 1');
- if($sql->num())
- sys::outjs(array('e' => 'Данный адрес уже занят.'), $mcache);
+ // Проверка поддомена на занятость
+ $sql->query('SELECT `id` FROM `web` WHERE `domain`="'.$aData['subdomain'].'.'.$aData['domain'].'" LIMIT 1');
+ if($sql->num())
+ sys::outjs(array('e' => 'Данный адрес уже занят.'), $mcache);
- // Проверка наличия шаблона
- if(!array_key_exists($aData['desing'], $aWebParam[$aData['type']]['desing']))
- sys::outjs(array('e' => 'Выбранный шаблон не найден.'), $mcache);
+ // Проверка наличия шаблона
+ if(!array_key_exists($aData['desing'], $aWebParam[$aData['type']]['desing']))
+ sys::outjs(array('e' => 'Выбранный шаблон не найден.'), $mcache);
- if(isset($aData['passwd']))
- {
- // Если не указан пароль сгенерировать
- if($aData['passwd'] == '')
- $aData['passwd'] = sys::passwd($aWebParam[$aData['type']]['passwd']);
+ if(isset($aData['passwd']))
+ {
+ // Если не указан пароль сгенерировать
+ if($aData['passwd'] == '')
+ $aData['passwd'] = sys::passwd($aWebParam[$aData['type']]['passwd']);
- // Проверка длинны пароля
- if(!isset($aData['passwd']{5}) || isset($aData['passwd']{15}))
- sys::outjs(array('e' => 'Необходимо указать пароль длинной не менее 6-и символов и не более 16-и.'), $mcache);
+ // Проверка длинны пароля
+ if(!isset($aData['passwd']{5}) || isset($aData['passwd']{15}))
+ sys::outjs(array('e' => 'Необходимо указать пароль длинной не менее 6-и символов и не более 16-и.'), $mcache);
- // Проверка валидности пароля
- if(sys::valid($aData['passwd'], 'other', "/^[A-Za-z0-9]{6,16}$/"))
- sys::outjs(array('e' => 'Пароль должен состоять из букв a-z и цифр.'), $mcache);
- }
+ // Проверка валидности пароля
+ if(sys::valid($aData['passwd'], 'other', "/^[A-Za-z0-9]{6,16}$/"))
+ sys::outjs(array('e' => 'Пароль должен состоять из букв a-z и цифр.'), $mcache);
+ }
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- $unit = web::unit($aWebUnit, $aData['type'], $aData['server']['unit']);
+ $unit = web::unit($aWebUnit, $aData['type'], $aData['server']['unit']);
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- sys::outjs(array('e' => sys::text('error', 'ssh')), $mcache);
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ sys::outjs(array('e' => sys::text('error', 'ssh')), $mcache);
- // Директория файлов услуги
- $path = $aWebUnit['path'][$aWebUnit['unit'][$aData['type']]][$aData['type']].$aData['desing'];
+ // Директория файлов услуги
+ $path = $aWebUnit['path'][$aWebUnit['unit'][$aData['type']]][$aData['type']].$aData['desing'];
- // Директория дополнительной услуги
- $install = $aWebUnit['install'][$aWebUnit['unit'][$aData['type']]][$aData['type']].$aData['subdomain'].'.'.$aData['domain'];
+ // Директория дополнительной услуги
+ $install = $aWebUnit['install'][$aWebUnit['unit'][$aData['type']]][$aData['type']].$aData['subdomain'].'.'.$aData['domain'];
- $sql->query('INSERT INTO `web` set `type`="'.$aData['type'].'", `server`="'.$aData['server']['id'].'", `user`="'.$aData['server']['user'].'", `unit`="'.$aData['server']['unit'].'", `config`=""');
- $wid = $sql->id();
- $uid = $wid+10000;
+ $sql->query('INSERT INTO `web` set `type`="'.$aData['type'].'", `server`="'.$aData['server']['id'].'", `user`="'.$aData['server']['user'].'", `unit`="'.$aData['server']['unit'].'", `config`=""');
+ $wid = $sql->id();
+ $uid = $wid+10000;
- $sql->query('SELECT `mail` FROM `users` WHERE `id`="'.$aData['server']['user'].'" LIMIT 1');
- if(!$sql->num())
- {
- $sql->query('DELETE FROM `web` WHERE `id`="'.$wid.'" LIMIT 1');
+ $sql->query('SELECT `mail` FROM `users` WHERE `id`="'.$aData['server']['user'].'" LIMIT 1');
+ if(!$sql->num())
+ {
+ $sql->query('DELETE FROM `web` WHERE `id`="'.$wid.'" LIMIT 1');
- sys::outjs(array('e' => 'Необходимо указать пользователя сервера.'), $mcache);
- }
+ sys::outjs(array('e' => 'Необходимо указать пользователя сервера.'), $mcache);
+ }
- $u = $sql->get();
+ $u = $sql->get();
- // Данные
- $login = 'w'.$uid;
- $passwd = sys::passwd(10);
- $ip = sys::first(explode(':', $unit['address']));
- $host = $aWebUnit['unit'][$aData['type']] == 'local' ? '127.0.0.1' : $ip;
+ // Данные
+ $login = 'w'.$uid;
+ $passwd = sys::passwd(10);
+ $ip = sys::first(explode(':', $unit['address']));
+ $host = $aWebUnit['unit'][$aData['type']] == 'local' ? '127.0.0.1' : $ip;
- $conf = array(
- 'address' => $aData['server']['address'],
- 'install' => $install,
- 'login' => $login,
- 'passwd' => $passwd,
- 'host' => $host,
- 'url' => $cfg['http'],
- 'domain' => $aData['subdomain'].'.'.$aData['domain']
- );
+ $conf = array(
+ 'address' => $aData['server']['address'],
+ 'install' => $install,
+ 'login' => $login,
+ 'passwd' => $passwd,
+ 'host' => $host,
+ 'url' => $cfg['http'],
+ 'domain' => $aData['subdomain'].'.'.$aData['domain']
+ );
- $aData['config_sql'] = sys::updtext($aData['config_sql'], $conf);
+ $aData['config_sql'] = sys::updtext($aData['config_sql'], $conf);
- if(isset($aWebdbConf[$aData['type']]))
- {
- $aData['config_php'] = sys::updtext($aData['config_php'], $conf);
+ if(isset($aWebdbConf[$aData['type']]))
+ {
+ $aData['config_php'] = sys::updtext($aData['config_php'], $conf);
- $temp = sys::temp($aData['config_php']);
- $ssh->setfile($temp, $path.$aWebdbConf[$aData['type']]['file'], $aWebdbConf[$aData['type']]['chmod']);
+ $temp = sys::temp($aData['config_php']);
+ $ssh->setfile($temp, $path.$aWebdbConf[$aData['type']]['file'], $aWebdbConf[$aData['type']]['chmod']);
- unlink($temp);
- }
+ unlink($temp);
+ }
- if(isset($aWebothPath[$aData['type']]))
- {
- $aData['config_oth'] = sys::updtext($aData['config_oth'], $conf);
+ if(isset($aWebothPath[$aData['type']]))
+ {
+ $aData['config_oth'] = sys::updtext($aData['config_oth'], $conf);
- $temp = sys::temp($aData['config_oth']);
- $ssh->setfile($temp, $path.$aWebothPath[$aData['type']]['file'], $aWebothPath[$aData['type']]['chmod']);
+ $temp = sys::temp($aData['config_oth']);
+ $ssh->setfile($temp, $path.$aWebothPath[$aData['type']]['file'], $aWebothPath[$aData['type']]['chmod']);
- unlink($temp);
- }
+ unlink($temp);
+ }
- // Создание поддомена
- $result = json_decode(file_get_contents(sys::updtext($aWebUnit['isp']['domain']['create'], array('subdomain' => $aData['subdomain'], 'ip' => $ip, 'domain' => $aData['domain']))), true);
- if(!isset($result['result']) || strtolower($result['result']) != 'ok')
- {
- $sql->query('DELETE FROM `web` WHERE `id`="'.$wid.'" LIMIT 1');
+ // Создание поддомена
+ $result = json_decode(file_get_contents(sys::updtext($aWebUnit['isp']['domain']['create'], array('subdomain' => $aData['subdomain'], 'ip' => $ip, 'domain' => $aData['domain']))), true);
+ if(!isset($result['result']) || strtolower($result['result']) != 'ok')
+ {
+ $sql->query('DELETE FROM `web` WHERE `id`="'.$wid.'" LIMIT 1');
- sys::outjs(array('e' => 'Не удалось создать поддомен, обратитесь в тех.поддержку.'), $mcache);
- }
+ sys::outjs(array('e' => 'Не удалось создать поддомен, обратитесь в тех.поддержку.'), $mcache);
+ }
- // Создание задания crontab
- if(isset($aWebUnit['isp']['crontab'][$aData['type']]['install']))
- {
- $result = json_decode(file_get_contents(sys::updtext($aWebUnit['isp']['crontab'][$aData['type']]['install'], array('subdomain' => $aData['subdomain'], 'domain' => $aData['domain']))), true);
- if(!isset($result['result']) || strtolower($result['result']) != 'ok')
- {
- $sql->query('DELETE FROM `web` WHERE `id`="'.$wid.'" LIMIT 1');
+ // Создание задания crontab
+ if(isset($aWebUnit['isp']['crontab'][$aData['type']]['install']))
+ {
+ $result = json_decode(file_get_contents(sys::updtext($aWebUnit['isp']['crontab'][$aData['type']]['install'], array('subdomain' => $aData['subdomain'], 'domain' => $aData['domain']))), true);
+ if(!isset($result['result']) || strtolower($result['result']) != 'ok')
+ {
+ $sql->query('DELETE FROM `web` WHERE `id`="'.$wid.'" LIMIT 1');
- sys::outjs(array('e' => 'Не удалось создать задание, обратитесь в тех.поддержку.'), $mcache);
- }
- }
+ sys::outjs(array('e' => 'Не удалось создать задание, обратитесь в тех.поддержку.'), $mcache);
+ }
+ }
- $a2 = ''.PHP_EOL
- .' ServerName '.$aData['subdomain'].'.'.$aData['domain'].PHP_EOL
- .' DocumentRoot '.$install.PHP_EOL
- .' AddType application/x-httpd-php .php .php3 .php4 .php5 .phtml'.PHP_EOL
- .' AddType application/x-httpd-php-source .phps'.PHP_EOL
- .' ';
+ $a2 = ''.PHP_EOL
+ .' ServerName '.$aData['subdomain'].'.'.$aData['domain'].PHP_EOL
+ .' DocumentRoot '.$install.PHP_EOL
+ .' AddType application/x-httpd-php .php .php3 .php4 .php5 .phtml'.PHP_EOL
+ .' AddType application/x-httpd-php-source .phps'.PHP_EOL
+ .' ';
- // Смена прав на файлы/папки
- $chmod = isset($aWebChmod[$aData['type']]) ? $aWebChmod[$aData['type']] : '';
+ // Смена прав на файлы/папки
+ $chmod = isset($aWebChmod[$aData['type']]) ? $aWebChmod[$aData['type']] : '';
- $sql_q = '';
+ $sql_q = '';
- if(isset($aWebSQL[$aData['type']]))
- {
- $sql_q .= 'mysql --login-path=local -e "CREATE DATABASE '.$login.';'
- ."CREATE USER '".$login."'@'%' IDENTIFIED BY '".$passwd."';"
- .'GRANT ALL PRIVILEGES ON '.$login.' . * TO \''.$login.'\'@\'%\';";'
- .'mysql --login-path=local '.$login.' < '.$aWebUnit['path'][$aWebUnit['unit'][$aData['type']]][$aData['type']].'dump.sql;';
+ if(isset($aWebSQL[$aData['type']]))
+ {
+ $sql_q .= 'mysql --login-path=local -e "CREATE DATABASE '.$login.';'
+ ."CREATE USER '".$login."'@'%' IDENTIFIED BY '".$passwd."';"
+ .'GRANT ALL PRIVILEGES ON '.$login.' . * TO \''.$login.'\'@\'%\';";'
+ .'mysql --login-path=local '.$login.' < '.$aWebUnit['path'][$aWebUnit['unit'][$aData['type']]][$aData['type']].'dump.sql;';
- if(isset($aWebSQL[$aData['type']]['install']))
- foreach($aWebSQL[$aData['type']]['install'] as $query)
- $sql_q .= "mysql --login-path=local ".$login." -e \"".sys::updtext($query,
- array(
- 'url' => $cfg['http'],
- 'passwd' => $aData['passwd'],
- 'mail' => $u['mail'],
- 'folder' => $install)
- )."\";";
- }
+ if(isset($aWebSQL[$aData['type']]['install']))
+ foreach($aWebSQL[$aData['type']]['install'] as $query)
+ $sql_q .= "mysql --login-path=local ".$login." -e \"".sys::updtext($query,
+ array(
+ 'url' => $cfg['http'],
+ 'passwd' => $aData['passwd'],
+ 'mail' => $u['mail'],
+ 'folder' => $install)
+ )."\";";
+ }
- // Установка
- $ssh->set('echo "'.$a2.'" > /etc/apache2/sites-enabled/'.$aData['subdomain'].'.'.$aData['domain'].';' // Настроки апач
- .'mkdir -p '.$install.';' // Создание директории
- .'useradd -d '.$install.' -g web -u '.$uid.' web'.$uid.';' // Создание пользователя услуги на локации
- .'chown -R web'.$uid.':999 '.$install.';' // Изменение владельца и группы директории
- .'cd '.$install.' && sudo -u web'.$uid.' screen -dmS i_w_'.$uid.' sh -c "cp -r '.$path.'/. .; '.$chmod.'";' // Копирование файлов услуги
- .'screen -dmS apache_reload_'.$uid.' service apache2 reload;' // Перезагрузить конфигурации апач
- .$sql_q); // sql запросы
+ // Установка
+ $ssh->set('echo "'.$a2.'" > /etc/apache2/sites-enabled/'.$aData['subdomain'].'.'.$aData['domain'].';' // Настроки апач
+ .'mkdir -p '.$install.';' // Создание директории
+ .'useradd -d '.$install.' -g web -u '.$uid.' web'.$uid.';' // Создание пользователя услуги на локации
+ .'chown -R web'.$uid.':999 '.$install.';' // Изменение владельца и группы директории
+ .'cd '.$install.' && sudo -u web'.$uid.' screen -dmS i_w_'.$uid.' sh -c "cp -r '.$path.'/. .; '.$chmod.'";' // Копирование файлов услуги
+ .'screen -dmS apache_reload_'.$uid.' service apache2 reload;' // Перезагрузить конфигурации апач
+ .$sql_q); // sql запросы
- $aData['passwd'] = isset($aData['passwd']) ? $aData['passwd'] : '';
+ $aData['passwd'] = isset($aData['passwd']) ? $aData['passwd'] : '';
- // Обновление данных
- $sql->query('UPDATE `web` set `uid`="'.$uid.'", `desing`="'.$aData['desing'].'", '
- .'`domain`="'.$aData['subdomain'].'.'.$aData['domain'].'", '
- .'`passwd`="'.$aData['passwd'].'", `config`="'.base64_encode($aData['config_sql']).'", '
- .'`login`="'.$login.'", `date`="'.$start_point.'" '
- .'WHERE `id`="'.$wid.'" LIMIT 1');
+ // Обновление данных
+ $sql->query('UPDATE `web` set `uid`="'.$uid.'", `desing`="'.$aData['desing'].'", '
+ .'`domain`="'.$aData['subdomain'].'.'.$aData['domain'].'", '
+ .'`passwd`="'.$aData['passwd'].'", `config`="'.base64_encode($aData['config_sql']).'", '
+ .'`login`="'.$login.'", `date`="'.$start_point.'" '
+ .'WHERE `id`="'.$wid.'" LIMIT 1');
- sys::outjs(array('s' => 'ok'), $mcache);
+ sys::outjs(array('s' => 'ok'), $mcache);
}
- public static function update($aData = array(), $mcache)
- {
- global $sql, $start_point;
-
- include(DATA.'web.php');
-
- $stack = web::stack($aData, '`id`, `uid`, `unit`, `login`, `desing`, `domain`, `update`');
-
- if(!$sql->num($stack))
- sys::outjs(array('e' => 'Дополнительная услуга не установлена.'), $mcache);
-
- $web = $sql->get($stack);
-
- // Проверка времени последнего обновления
- include(LIB.'games/games.php');
-
- $upd = $web['update']+86400;
-
- if($upd > $start_point)
- sys::outjs(array('e' => 'Для повторного обновления должно пройти: '.games::date('max', $upd)));
-
- include(LIB.'ssh.php');
-
- $unit = web::unit($aWebUnit, $aData['type'], $web['unit']);
-
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- sys::outjs(array('e' => sys::text('error', 'ssh')), $mcache);
-
- $install = $aWebUnit['install'][$aWebUnit['unit'][$aData['type']]][$aData['type']].$web['domain'];
-
- $path = $aWebUnit['path'][$aWebUnit['unit'][$aData['type']]][$aData['type']].$web['desing'];
-
- $sql->query('SELECT `mail` FROM `users` WHERE `id`="'.$aData['server']['user'].'" LIMIT 1');
- if(!$sql->num())
- sys::outjs(array('e' => 'Необходимо указать пользователя сервера.'), $mcache);
-
- $u = $sql->get();
-
- // sql запросы
- $sql_q = '';
-
- if(isset($aWebSQL[$aData['type']]['update']))
- foreach($aWebSQL[$aData['type']]['update'] as $query)
- $sql_q .= "mysql --login-path=local ".$web['login']." -e \"".sys::updtext($query, array('passwd' => $aData['passwd'], 'mail' => $u['mail']))."\";";
-
- $cat = isset($aWebdbConf[$aData['type']]) ? 'cat '.$install.$aWebdbConf[$aData['type']]['file'].' > '.$path.$aWebdbConf[$aData['type']]['file'].';' : '';
- $chmod = isset($aWebChmod[$aData['type']]) ? $aWebChmod[$aData['type']] : '';
-
- $ssh->set($cat
- .'cd '.$install.' && sudo -u web'.$web['uid'].' screen -dmS u_w_'.$web['uid'].' sh -c "YES | cp -rf '.$path.'/. .; '.$chmod.'";'
- .$sql_q); // sql запрос
-
- $sql->query('UPDATE `web` set `update`="'.$start_point.'" WHERE `id`="'.$web['id'].'" LIMIT 1');
-
- sys::outjs(array('s' => 'ok'), $mcache);
- }
-
- public static function delete($aData = array(), $mcache)
+ public static function update($aData = array(), $mcache)
{
- global $sql;
+ global $sql, $start_point;
- include(DATA.'web.php');
+ include(DATA.'web.php');
- $stack = web::stack($aData, '`id`, `uid`, `unit`, `domain`, `login`');
+ $stack = web::stack($aData, '`id`, `uid`, `unit`, `login`, `desing`, `domain`, `update`');
- if(!$sql->num($stack))
- sys::outjs(array('e' => 'Дополнительная услуга не установлена.'), $mcache);
+ if(!$sql->num($stack))
+ sys::outjs(array('e' => 'Дополнительная услуга не установлена.'), $mcache);
- $web = $sql->get($stack);
+ $web = $sql->get($stack);
- include(LIB.'ssh.php');
+ // Проверка времени последнего обновления
+ include(LIB.'games/games.php');
- $unit = web::unit($aWebUnit, $aData['type'], $web['unit']);
+ $upd = $web['update']+86400;
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- sys::outjs(array('e' => sys::text('error', 'ssh')), $mcache);
+ if($upd > $start_point)
+ sys::outjs(array('e' => 'Для повторного обновления должно пройти: '.games::date('max', $upd)));
- // Директория дополнительной услуги
- $delete = '';
+ include(LIB.'ssh.php');
- if($web['domain'] != '')
- $delete = 'screen -dmS r_w_'.$web['uid'].' rm -r '.$aWebUnit['install'][$aWebUnit['unit'][$aData['type']]][$aData['type']].$web['domain'].';';
+ $unit = web::unit($aWebUnit, $aData['type'], $web['unit']);
- $ip = sys::first(explode(':', $unit['address']));
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ sys::outjs(array('e' => sys::text('error', 'ssh')), $mcache);
- $aDomain = explode('.', $web['domain']);
- $zone = array_pop($aDomain);
+ $install = $aWebUnit['install'][$aWebUnit['unit'][$aData['type']]][$aData['type']].$web['domain'];
- // Удаление поддомена
- if($aData['type'] != 'mysql')
- {
- $result = json_decode(file_get_contents(sys::updtext($aWebUnit['isp']['domain']['delete'], array('subdomain' => $web['domain'], 'domain' => end($aDomain).'.'.$zone, 'ip' => $ip))), true);
+ $path = $aWebUnit['path'][$aWebUnit['unit'][$aData['type']]][$aData['type']].$web['desing'];
- if(!isset($result['result']) || strtolower($result['result']) != 'ok')
- sys::outjs(array('e' => 'Не удалось удалить поддомен, обратитесь в тех.поддержку.'), $mcache);
- }
+ $sql->query('SELECT `mail` FROM `users` WHERE `id`="'.$aData['server']['user'].'" LIMIT 1');
+ if(!$sql->num())
+ sys::outjs(array('e' => 'Необходимо указать пользователя сервера.'), $mcache);
- // Удаление задания crontab
- if(isset($aWebUnit['isp']['crontab'][$aData['type']]['delete']) && isset($aData['cron']))
- {
- $result = json_decode(file_get_contents(sys::updtext($aWebUnit['isp']['crontab'][$aData['type']]['delete'], array('data' => $aData['cron']))), true);
- if(!isset($result['result']) || strtolower($result['result']) != 'ok')
- sys::outjs(array('e' => 'Не удалось удалить задание, обратитесь в тех.поддержку.'), $mcache);
- }
+ $u = $sql->get();
- $sql_q = isset($aWebSQL[$aData['type']]) ? "mysql --login-path=local -e \"DROP DATABASE IF EXISTS ".$web['login']."; DROP USER ".$web['login']."\"" : '';
+ // sql запросы
+ $sql_q = '';
- $ssh->set('rm /etc/apache2/sites-enabled/'.$web['domain'].';' // Удаление настроек апач
- .$delete // Удаление файлов
- .'userdel web'.$web['uid'].';' // Удаление пользователя
- .'screen -dmS apache_reload_'.$web['uid'].' service apache2 reload;' // Перезагрузить конфигурации апач
- .$sql_q); // sql запрос
+ if(isset($aWebSQL[$aData['type']]['update']))
+ foreach($aWebSQL[$aData['type']]['update'] as $query)
+ $sql_q .= "mysql --login-path=local ".$web['login']." -e \"".sys::updtext($query, array('passwd' => $aData['passwd'], 'mail' => $u['mail']))."\";";
- $sql->query('DELETE FROM `web` WHERE `id`="'.$web['id'].'" LIMIT 1');
+ $cat = isset($aWebdbConf[$aData['type']]) ? 'cat '.$install.$aWebdbConf[$aData['type']]['file'].' > '.$path.$aWebdbConf[$aData['type']]['file'].';' : '';
+ $chmod = isset($aWebChmod[$aData['type']]) ? $aWebChmod[$aData['type']] : '';
- sys::outjs(array('s' => 'ok'), $mcache);
- }
+ $ssh->set($cat
+ .'cd '.$install.' && sudo -u web'.$web['uid'].' screen -dmS u_w_'.$web['uid'].' sh -c "YES | cp -rf '.$path.'/. .; '.$chmod.'";'
+ .$sql_q); // sql запрос
- public static function connect($aData = array(), $mcache)
+ $sql->query('UPDATE `web` set `update`="'.$start_point.'" WHERE `id`="'.$web['id'].'" LIMIT 1');
+
+ sys::outjs(array('s' => 'ok'), $mcache);
+ }
+
+ public static function delete($aData = array(), $mcache)
{
- global $cfg, $sql, $start_point;
+ global $sql;
- include(DATA.'web.php');
+ include(DATA.'web.php');
- $sql->query('SELECT `id`, `uid`, `unit`, `game`, `user`, `tarif`, `address`, `status`, `name` FROM `servers` WHERE `id`="'.$aData['server'].'" AND `user`="'.$aData['user'].'" LIMIT 1');
- if(!$sql->num())
- sys::outjs(array('e' => 'Игровой сервер не найден.'), $mcache);
+ $stack = web::stack($aData, '`id`, `uid`, `unit`, `domain`, `login`');
- $server = $sql->get();
+ if(!$sql->num($stack))
+ sys::outjs(array('e' => 'Дополнительная услуга не установлена.'), $mcache);
- // Проверка статуса игрового сервера
- if(!in_array($server['status'], array('working', 'off', 'start', 'restart', 'change')))
- sys::outjs(array('e' => 'Игровой сервер недоступен для подключения.'), $mcache);
+ $web = $sql->get($stack);
- // Проверка установки плагина
- $sql->query('SELECT `id` FROM `plugins_install` WHERE `server`="'.$server['id'].'" AND `plugin`="'.$aWebConnect[$aData['type']][$server['game']].'" LIMIT 1');
- if(!$sql->num())
- sys::outjs(array('i' => 'Для подключения, необходимо установить плагин.', 'pid' => $aWebConnect[$aData['type']][$server['game']]), $mcache);
+ include(LIB.'ssh.php');
- $aData['server'] = array_merge($server, array('id' => $aData['server']));
+ $unit = web::unit($aWebUnit, $aData['type'], $web['unit']);
- $stack = web::stack($aData, '`config`, `unit`, `login`');
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ sys::outjs(array('e' => sys::text('error', 'ssh')), $mcache);
- if(!$sql->num($stack))
- sys::outjs(array('e' => 'Дополнительная услуга не установлена.'), $mcache);
+ // Директория дополнительной услуги
+ $delete = '';
- $web = $sql->get($stack);
+ if($web['domain'] != '')
+ $delete = 'screen -dmS r_w_'.$web['uid'].' rm -r '.$aWebUnit['install'][$aWebUnit['unit'][$aData['type']]][$aData['type']].$web['domain'].';';
- include(LIB.'ssh.php');
+ $ip = sys::first(explode(':', $unit['address']));
- $sql->query('SELECT `passwd`, `address` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ $aDomain = explode('.', $web['domain']);
+ $zone = array_pop($aDomain);
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- sys::outjs(array('e' => sys::text('error', 'ssh')), $mcache);
+ // Удаление поддомена
+ if($aData['type'] != 'mysql')
+ {
+ $result = json_decode(file_get_contents(sys::updtext($aWebUnit['isp']['domain']['delete'], array('subdomain' => $web['domain'], 'domain' => end($aDomain).'.'.$zone, 'ip' => $ip))), true);
- $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
- $tarif = $sql->get();
+ if(!isset($result['result']) || strtolower($result['result']) != 'ok')
+ sys::outjs(array('e' => 'Не удалось удалить поддомен, обратитесь в тех.поддержку.'), $mcache);
+ }
- // Директория игр. сервера
- $dir = $tarif['install'].$server['uid'].'/';
+ // Удаление задания crontab
+ if(isset($aWebUnit['isp']['crontab'][$aData['type']]['delete']) && isset($aData['cron']))
+ {
+ $result = json_decode(file_get_contents(sys::updtext($aWebUnit['isp']['crontab'][$aData['type']]['delete'], array('data' => $aData['cron']))), true);
+ if(!isset($result['result']) || strtolower($result['result']) != 'ok')
+ sys::outjs(array('e' => 'Не удалось удалить задание, обратитесь в тех.поддержку.'), $mcache);
+ }
- // Взять rcon_password
- $get = explode(' ', str_replace('"', '', trim($ssh->get('cat '.$dir.$aData['cfg'].' | grep rcon_password'))));
+ $sql_q = isset($aWebSQL[$aData['type']]) ? "mysql --login-path=local -e \"DROP DATABASE IF EXISTS ".$web['login']."; DROP USER ".$web['login']."\"" : '';
- $rcon = trim(end($get));
+ $ssh->set('rm /etc/apache2/sites-enabled/'.$web['domain'].';' // Удаление настроек апач
+ .$delete // Удаление файлов
+ .'userdel web'.$web['uid'].';' // Удаление пользователя
+ .'screen -dmS apache_reload_'.$web['uid'].' service apache2 reload;' // Перезагрузить конфигурации апач
+ .$sql_q); // sql запрос
- if(!isset($rcon{0}))
- sys::outjs(array('r' => 'Необходимо установить rcon пароль (rcon_password).', 'url' => $cfg['http'].'servers/id/'.$server['id'].'/section/settings/subsection/server'), $mcache);
+ $sql->query('DELETE FROM `web` WHERE `id`="'.$web['id'].'" LIMIT 1');
- $temp = sys::temp(sys::updtext(base64_decode($web['config']), $aData['orcfg']));
+ sys::outjs(array('s' => 'ok'), $mcache);
+ }
- $ssh->setfile($temp, $dir.$aData['file'], 0644);
+ public static function connect($aData = array(), $mcache)
+ {
+ global $cfg, $sql, $start_point;
- $unit = web::unit($aWebUnit, $aData['type'], $web['unit']);
+ include(DATA.'web.php');
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- sys::outjs(array('e' => sys::text('error', 'ssh')), $mcache);
+ $sql->query('SELECT `id`, `uid`, `unit`, `game`, `user`, `tarif`, `address`, `status`, `name` FROM `servers` WHERE `id`="'.$aData['server'].'" AND `user`="'.$aData['user'].'" LIMIT 1');
+ if(!$sql->num())
+ sys::outjs(array('e' => 'Игровой сервер не найден.'), $mcache);
- // sql запросы
- $sql_q = '';
+ $server = $sql->get();
- list($ip, $port) = explode(':', $server['address']);
+ // Проверка статуса игрового сервера
+ if(!in_array($server['status'], array('working', 'off', 'start', 'restart', 'change')))
+ sys::outjs(array('e' => 'Игровой сервер недоступен для подключения.'), $mcache);
- if(isset($aWebSQL[$aData['type']]['connect']))
- foreach($aWebSQL[$aData['type']]['connect'] as $query)
- $sql_q .= "mysql --login-path=local ".$web['login']." -e \"".sys::updtext($query,
- array_merge(array('id' => $aData['server']['id'], 'rcon' => $rcon, 'address' => $server['address'], 'ip' => $ip, 'port' => $port, 'name' => $server['name'], 'time' => $start_point), $aData['orsql']))."\";";
+ // Проверка установки плагина
+ $sql->query('SELECT `id` FROM `plugins_install` WHERE `server`="'.$server['id'].'" AND `plugin`="'.$aWebConnect[$aData['type']][$server['game']].'" LIMIT 1');
+ if(!$sql->num())
+ sys::outjs(array('i' => 'Для подключения, необходимо установить плагин.', 'pid' => $aWebConnect[$aData['type']][$server['game']]), $mcache);
- $ssh->set('chown server'.$server['uid'].':servers '.$dir.$aData['file'].';' // Смена владельца файла
- .$sql_q); // sql запросы
+ $aData['server'] = array_merge($server, array('id' => $aData['server']));
- unlink($temp);
+ $stack = web::stack($aData, '`config`, `unit`, `login`');
- sys::outjs(array('s' => 'ok'), $mcache);
- }
+ if(!$sql->num($stack))
+ sys::outjs(array('e' => 'Дополнительная услуга не установлена.'), $mcache);
- public static function passwd($aData = array(), $mcache)
- {
- global $sql;
+ $web = $sql->get($stack);
- include(DATA.'web.php');
+ include(LIB.'ssh.php');
- $stack = web::stack($aData);
+ $sql->query('SELECT `passwd`, `address` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- if(!$sql->num($stack))
- sys::outjs(array('e' => 'Дополнительная услуга не установлена.'), $mcache);
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ sys::outjs(array('e' => sys::text('error', 'ssh')), $mcache);
- $web = $sql->get($stack);
+ $sql->query('SELECT `install` FROM `tarifs` WHERE `id`="'.$server['tarif'].'" LIMIT 1');
+ $tarif = $sql->get();
- $passwd = sys::passwd($aWebParam[$aData['type']]['passwd']);
+ // Директория игр. сервера
+ $dir = $tarif['install'].$server['uid'].'/';
- include(LIB.'ssh.php');
+ // Взять rcon_password
+ $get = explode(' ', str_replace('"', '', trim($ssh->get('cat '.$dir.$aData['cfg'].' | grep rcon_password'))));
- $unit = web::unit($aWebUnit, $aData['type'], $web['unit']);
+ $rcon = trim(end($get));
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- sys::outjs(array('e' => sys::text('error', 'ssh')), $mcache);
+ if(!isset($rcon{0}))
+ sys::outjs(array('r' => 'Необходимо установить rcon пароль (rcon_password).', 'url' => $cfg['http'].'servers/id/'.$server['id'].'/section/settings/subsection/server'), $mcache);
- $sql_q = '';
+ $temp = sys::temp(sys::updtext(base64_decode($web['config']), $aData['orcfg']));
- if(isset($aWebSQL[$aData['type']]['passwd']))
- foreach($aWebSQL[$aData['type']]['passwd'] as $query)
- $sql_q .= "mysql --login-path=local ".$web['login']." -e \"".sys::updtext($query, array('passwd' => $passwd))."\";";
+ $ssh->setfile($temp, $dir.$aData['file'], 0644);
- $ssh->set($sql_q);
+ $unit = web::unit($aWebUnit, $aData['type'], $web['unit']);
- $sql->query('UPDATE `web` set `passwd`="'.$passwd.'" WHERE `id`="'.$web['id'].'" LIMIT 1');
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ sys::outjs(array('e' => sys::text('error', 'ssh')), $mcache);
- sys::outjs(array('s' => 'ok'), $mcache);
- }
+ // sql запросы
+ $sql_q = '';
- public static function stack($aData, $select = '`id`, `unit`, `login`')
- {
- global $sql;
+ list($ip, $port) = explode(':', $server['address']);
- include(DATA.'web.php');
+ if(isset($aWebSQL[$aData['type']]['connect']))
+ foreach($aWebSQL[$aData['type']]['connect'] as $query)
+ $sql_q .= "mysql --login-path=local ".$web['login']." -e \"".sys::updtext($query,
+ array_merge(array('id' => $aData['server']['id'], 'rcon' => $rcon, 'address' => $server['address'], 'ip' => $ip, 'port' => $port, 'name' => $server['name'], 'time' => $start_point), $aData['orsql']))."\";";
- switch($aWebInstall[$aData['server']['game']][$aData['type']])
- {
- case 'server':
- return $sql->query('SELECT '.$select.' FROM `web` WHERE `type`="'.$aData['type'].'" AND `server`="'.$aData['server']['id'].'" LIMIT 1');
+ $ssh->set('chown server'.$server['uid'].':servers '.$dir.$aData['file'].';' // Смена владельца файла
+ .$sql_q); // sql запросы
- case 'user':
- return $sql->query('SELECT '.$select.' FROM `web` WHERE `type`="'.$aData['type'].'" AND `user`="'.$aData['server']['user'].'" LIMIT 1');
+ unlink($temp);
- case 'unit':
- return $sql->query('SELECT '.$select.' FROM `web` WHERE `type`="'.$aData['type'].'" AND `user`="'.$aData['server']['user'].'" AND `unit`="'.$aData['server']['unit'].'" LIMIT 1');
- }
+ sys::outjs(array('s' => 'ok'), $mcache);
+ }
- return NULL;
- }
+ public static function passwd($aData = array(), $mcache)
+ {
+ global $sql;
- public static function unit($aWebUnit, $type, $id)
- {
- global $sql;
+ include(DATA.'web.php');
- if($aWebUnit['unit'][$type] == 'local')
- {
- $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$id.'" LIMIT 1');
+ $stack = web::stack($aData);
- return $sql->get();
- }
+ if(!$sql->num($stack))
+ sys::outjs(array('e' => 'Дополнительная услуга не установлена.'), $mcache);
- return array('address' => $aWebUnit['address'], 'passwd' => $aWebUnit['passwd']);
- }
+ $web = $sql->get($stack);
+
+ $passwd = sys::passwd($aWebParam[$aData['type']]['passwd']);
+
+ include(LIB.'ssh.php');
+
+ $unit = web::unit($aWebUnit, $aData['type'], $web['unit']);
+
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ sys::outjs(array('e' => sys::text('error', 'ssh')), $mcache);
+
+ $sql_q = '';
+
+ if(isset($aWebSQL[$aData['type']]['passwd']))
+ foreach($aWebSQL[$aData['type']]['passwd'] as $query)
+ $sql_q .= "mysql --login-path=local ".$web['login']." -e \"".sys::updtext($query, array('passwd' => $passwd))."\";";
+
+ $ssh->set($sql_q);
+
+ $sql->query('UPDATE `web` set `passwd`="'.$passwd.'" WHERE `id`="'.$web['id'].'" LIMIT 1');
+
+ sys::outjs(array('s' => 'ok'), $mcache);
+ }
+
+ public static function stack($aData, $select = '`id`, `unit`, `login`')
+ {
+ global $sql;
+
+ include(DATA.'web.php');
+
+ switch($aWebInstall[$aData['server']['game']][$aData['type']])
+ {
+ case 'server':
+ return $sql->query('SELECT '.$select.' FROM `web` WHERE `type`="'.$aData['type'].'" AND `server`="'.$aData['server']['id'].'" LIMIT 1');
+
+ case 'user':
+ return $sql->query('SELECT '.$select.' FROM `web` WHERE `type`="'.$aData['type'].'" AND `user`="'.$aData['server']['user'].'" LIMIT 1');
+
+ case 'unit':
+ return $sql->query('SELECT '.$select.' FROM `web` WHERE `type`="'.$aData['type'].'" AND `user`="'.$aData['server']['user'].'" AND `unit`="'.$aData['server']['unit'].'" LIMIT 1');
+ }
+
+ return NULL;
+ }
+
+ public static function unit($aWebUnit, $type, $id)
+ {
+ global $sql;
+
+ if($aWebUnit['unit'][$type] == 'local')
+ {
+ $sql->query('SELECT `address`, `passwd` FROM `units` WHERE `id`="'.$id.'" LIMIT 1');
+
+ return $sql->get();
+ }
+
+ return array('address' => $aWebUnit['address'], 'passwd' => $aWebUnit['passwd']);
+ }
}
?>
\ No newline at end of file
diff --git a/system/library/zip.php b/system/library/zip.php
index 8f46a05..e378695 100644
--- a/system/library/zip.php
+++ b/system/library/zip.php
@@ -1,6 +1,6 @@
2) {
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER,
- "Invalid number / type of arguments");
+ "Invalid number / type of arguments");
return 0;
}
}
@@ -390,7 +390,7 @@
,PCLZIP_ATT_FILE_MTIME => 'optional'
,PCLZIP_ATT_FILE_CONTENT => 'optional'
,PCLZIP_ATT_FILE_COMMENT => 'optional'
- );
+ );
foreach ($v_att_list as $v_entry) {
$v_result = $this->privFileDescrParseAtt($v_entry,
$v_filedescr_list[],
@@ -494,7 +494,7 @@
PCLZIP_OPT_TEMP_FILE_ON => 'optional',
PCLZIP_OPT_TEMP_FILE_OFF => 'optional'
//, PCLZIP_OPT_CRYPT => 'optional'
- ));
+ ));
if ($v_result != 1) {
return 0;
}
@@ -573,7 +573,7 @@
,PCLZIP_ATT_FILE_MTIME => 'optional'
,PCLZIP_ATT_FILE_CONTENT => 'optional'
,PCLZIP_ATT_FILE_COMMENT => 'optional'
- );
+ );
foreach ($v_att_list as $v_entry) {
$v_result = $this->privFileDescrParseAtt($v_entry,
$v_filedescr_list[],
@@ -753,7 +753,7 @@
PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional',
PCLZIP_OPT_TEMP_FILE_ON => 'optional',
PCLZIP_OPT_TEMP_FILE_OFF => 'optional'
- ));
+ ));
if ($v_result != 1) {
return 0;
}
@@ -807,7 +807,7 @@
// ----- Call the extracting fct
$p_list = array();
$v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path,
- $v_remove_all_path, $v_options);
+ $v_remove_all_path, $v_options);
if ($v_result < 1) {
unset($p_list);
return(0);
@@ -909,7 +909,7 @@
PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional',
PCLZIP_OPT_TEMP_FILE_ON => 'optional',
PCLZIP_OPT_TEMP_FILE_OFF => 'optional'
- ));
+ ));
if ($v_result != 1) {
return 0;
}
@@ -1376,7 +1376,7 @@
{
$v_result = true;
- // ----- Reset the file system cache
+ // ----- Reset the file system cache
clearstatcache();
// ----- Reset the error handler
@@ -1598,9 +1598,9 @@
if (($i+1) >= $p_size) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE,
- "Missing parameter value for option '"
- .PclZipUtilOptionText($p_options_list[$i])
- ."'");
+ "Missing parameter value for option '"
+ .PclZipUtilOptionText($p_options_list[$i])
+ ."'");
// ----- Return
return PclZip::errorCode();
@@ -1613,9 +1613,9 @@
else {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE,
- "Wrong parameter value for option '"
- .PclZipUtilOptionText($p_options_list[$i])
- ."'");
+ "Wrong parameter value for option '"
+ .PclZipUtilOptionText($p_options_list[$i])
+ ."'");
// ----- Return
return PclZip::errorCode();
@@ -1781,8 +1781,8 @@
default :
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER,
- "Unknown parameter '"
- .$p_options_list[$i]."'");
+ "Unknown parameter '"
+ .$p_options_list[$i]."'");
// ----- Return
return PclZip::errorCode();
@@ -1956,7 +1956,7 @@
default :
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER,
- "Unknown parameter '".$v_key."'");
+ "Unknown parameter '".$v_key."'");
// ----- Return
return PclZip::errorCode();
@@ -3035,12 +3035,12 @@
// ----- Packed data
$v_binary_data = pack("VvvvvvVVVvv", 0x04034b50,
- $p_header['version_extracted'], $p_header['flag'],
+ $p_header['version_extracted'], $p_header['flag'],
$p_header['compression'], $v_mtime, $v_mdate,
$p_header['crc'], $p_header['compressed_size'],
- $p_header['size'],
+ $p_header['size'],
strlen($p_header['stored_filename']),
- $p_header['extra_len']);
+ $p_header['extra_len']);
// ----- Write the first 148 bytes of the header in the archive
fputs($this->zip_fd, $v_binary_data, 30);
@@ -3082,14 +3082,14 @@
// ----- Packed data
$v_binary_data = pack("VvvvvvvVVVvvvvvVV", 0x02014b50,
- $p_header['version'], $p_header['version_extracted'],
+ $p_header['version'], $p_header['version_extracted'],
$p_header['flag'], $p_header['compression'],
- $v_mtime, $v_mdate, $p_header['crc'],
+ $v_mtime, $v_mdate, $p_header['crc'],
$p_header['compressed_size'], $p_header['size'],
strlen($p_header['stored_filename']),
- $p_header['extra_len'], $p_header['comment_len'],
+ $p_header['extra_len'], $p_header['comment_len'],
$p_header['disk'], $p_header['internal'],
- $p_header['external'], $p_header['offset']);
+ $p_header['external'], $p_header['offset']);
// ----- Write the 42 bytes of the header in the zip file
fputs($this->zip_fd, $v_binary_data, 46);
@@ -3125,8 +3125,8 @@
// ----- Packed data
$v_binary_data = pack("VvvvvVVv", 0x06054b50, 0, 0, $p_nb_entries,
- $p_nb_entries, $p_size,
- $p_offset, strlen($p_comment));
+ $p_nb_entries, $p_size,
+ $p_offset, strlen($p_comment));
// ----- Write the 22 bytes of the header in the zip file
fputs($this->zip_fd, $v_binary_data, 22);
@@ -3283,9 +3283,9 @@
// ----- Check the path
if ( ($p_path == "")
- || ( (substr($p_path, 0, 1) != "/")
- && (substr($p_path, 0, 3) != "../")
- && (substr($p_path,1,2)!=":/")))
+ || ( (substr($p_path, 0, 1) != "/")
+ && (substr($p_path, 0, 3) != "../")
+ && (substr($p_path,1,2)!=":/")))
$p_path = "./".$p_path;
// ----- Reduce the path last (and duplicated) '/'
@@ -3435,50 +3435,50 @@
$v_extract = true;
}
- // ----- Check compression method
- if ( ($v_extract)
- && ( ($v_header['compression'] != 8)
- && ($v_header['compression'] != 0))) {
+ // ----- Check compression method
+ if ( ($v_extract)
+ && ( ($v_header['compression'] != 8)
+ && ($v_header['compression'] != 0))) {
$v_header['status'] = 'unsupported_compression';
// ----- Look for PCLZIP_OPT_STOP_ON_ERROR
if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
- && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
+ && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
$this->privSwapBackMagicQuotes();
PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_COMPRESSION,
- "Filename '".$v_header['stored_filename']."' is "
- ."compressed by an unsupported compression "
- ."method (".$v_header['compression'].") ");
+ "Filename '".$v_header['stored_filename']."' is "
+ ."compressed by an unsupported compression "
+ ."method (".$v_header['compression'].") ");
return PclZip::errorCode();
- }
- }
-
- // ----- Check encrypted files
- if (($v_extract) && (($v_header['flag'] & 1) == 1)) {
+ }
+ }
+
+ // ----- Check encrypted files
+ if (($v_extract) && (($v_header['flag'] & 1) == 1)) {
$v_header['status'] = 'unsupported_encryption';
// ----- Look for PCLZIP_OPT_STOP_ON_ERROR
if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
- && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
+ && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
$this->privSwapBackMagicQuotes();
PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION,
- "Unsupported encryption for "
- ." filename '".$v_header['stored_filename']
- ."'");
+ "Unsupported encryption for "
+ ." filename '".$v_header['stored_filename']
+ ."'");
return PclZip::errorCode();
- }
+ }
}
// ----- Look for real extraction
if (($v_extract) && ($v_header['status'] != 'ok')) {
$v_result = $this->privConvertHeader2FileInfo($v_header,
- $p_file_list[$v_nb_extracted++]);
+ $p_file_list[$v_nb_extracted++]);
if ($v_result != 1) {
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
@@ -3539,12 +3539,12 @@
// ----- Look for user callback abort
if ($v_result1 == 2) {
- break;
+ break;
}
}
// ----- Look for extraction in standard output
elseif ( (isset($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT]))
- && ($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) {
+ && ($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) {
// ----- Extracting the file in standard output
$v_result1 = $this->privExtractFileInOutput($v_header, $p_options);
if ($v_result1 < 1) {
@@ -3562,16 +3562,16 @@
// ----- Look for user callback abort
if ($v_result1 == 2) {
- break;
+ break;
}
}
// ----- Look for normal extraction
else {
// ----- Extracting the file
$v_result1 = $this->privExtractFile($v_header,
- $p_path, $p_remove_path,
- $p_remove_all_path,
- $p_options);
+ $p_path, $p_remove_path,
+ $p_remove_all_path,
+ $p_options);
if ($v_result1 < 1) {
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
@@ -3590,7 +3590,7 @@
// ----- Look for user callback abort
if ($v_result1 == 2) {
- break;
+ break;
}
}
}
@@ -3681,8 +3681,8 @@
if ($v_inclusion == 0) {
PclZip::privErrorLog(PCLZIP_ERR_DIRECTORY_RESTRICTION,
- "Filename '".$p_entry['filename']."' is "
- ."outside PCLZIP_OPT_EXTRACT_DIR_RESTRICTION");
+ "Filename '".$p_entry['filename']."' is "
+ ."outside PCLZIP_OPT_EXTRACT_DIR_RESTRICTION");
return PclZip::errorCode();
}
@@ -3710,7 +3710,7 @@
if ($v_result == 2) {
// ----- This status is internal and will be changed in 'skipped'
$p_entry['status'] = "aborted";
- $v_result = PCLZIP_ERR_USER_ABORTED;
+ $v_result = PCLZIP_ERR_USER_ABORTED;
}
// ----- Update the informations
@@ -3737,14 +3737,14 @@
// For historical reason first PclZip implementation does not stop
// when this kind of error occurs.
if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
- && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
+ && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
PclZip::privErrorLog(PCLZIP_ERR_ALREADY_A_DIRECTORY,
- "Filename '".$p_entry['filename']."' is "
- ."already used by an existing directory");
+ "Filename '".$p_entry['filename']."' is "
+ ."already used by an existing directory");
return PclZip::errorCode();
- }
+ }
}
// ----- Look if file is write protected
else if (!is_writeable($p_entry['filename']))
@@ -3757,14 +3757,14 @@
// For historical reason first PclZip implementation does not stop
// when this kind of error occurs.
if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
- && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
+ && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL,
- "Filename '".$p_entry['filename']."' exists "
- ."and is write protected");
+ "Filename '".$p_entry['filename']."' exists "
+ ."and is write protected");
return PclZip::errorCode();
- }
+ }
}
// ----- Look if the extracted file is older
@@ -3772,24 +3772,24 @@
{
// ----- Change the file status
if ( (isset($p_options[PCLZIP_OPT_REPLACE_NEWER]))
- && ($p_options[PCLZIP_OPT_REPLACE_NEWER]===true)) {
- }
- else {
+ && ($p_options[PCLZIP_OPT_REPLACE_NEWER]===true)) {
+ }
+ else {
$p_entry['status'] = "newer_exist";
// ----- Look for PCLZIP_OPT_STOP_ON_ERROR
// For historical reason first PclZip implementation does not stop
// when this kind of error occurs.
if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
- && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
+ && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL,
- "Newer version of '".$p_entry['filename']."' exists "
- ."and option PCLZIP_OPT_REPLACE_NEWER is not selected");
+ "Newer version of '".$p_entry['filename']."' exists "
+ ."and option PCLZIP_OPT_REPLACE_NEWER is not selected");
return PclZip::errorCode();
- }
- }
+ }
+ }
}
else {
}
@@ -3825,7 +3825,7 @@
// ----- Look for not compressed file
if ($p_entry['compression'] == 0) {
- // ----- Opening destination file
+ // ----- Opening destination file
if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0)
{
@@ -3930,11 +3930,11 @@
}
}
- // ----- Change abort status
- if ($p_entry['status'] == "aborted") {
+ // ----- Change abort status
+ if ($p_entry['status'] == "aborted") {
$p_entry['status'] = "skipped";
- }
-
+ }
+
// ----- Look for post-extract callback
elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) {
@@ -3950,7 +3950,7 @@
// ----- Look for abort result
if ($v_result == 2) {
- $v_result = PCLZIP_ERR_USER_ABORTED;
+ $v_result = PCLZIP_ERR_USER_ABORTED;
}
}
@@ -4078,7 +4078,7 @@
if ($v_result == 2) {
// ----- This status is internal and will be changed in 'skipped'
$p_entry['status'] = "aborted";
- $v_result = PCLZIP_ERR_USER_ABORTED;
+ $v_result = PCLZIP_ERR_USER_ABORTED;
}
// ----- Update the informations
@@ -4119,10 +4119,10 @@
}
}
- // ----- Change abort status
- if ($p_entry['status'] == "aborted") {
+ // ----- Change abort status
+ if ($p_entry['status'] == "aborted") {
$p_entry['status'] = "skipped";
- }
+ }
// ----- Look for post-extract callback
elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) {
@@ -4139,7 +4139,7 @@
// ----- Look for abort result
if ($v_result == 2) {
- $v_result = PCLZIP_ERR_USER_ABORTED;
+ $v_result = PCLZIP_ERR_USER_ABORTED;
}
}
@@ -4193,7 +4193,7 @@
if ($v_result == 2) {
// ----- This status is internal and will be changed in 'skipped'
$p_entry['status'] = "aborted";
- $v_result = PCLZIP_ERR_USER_ABORTED;
+ $v_result = PCLZIP_ERR_USER_ABORTED;
}
// ----- Update the informations
@@ -4233,11 +4233,11 @@
}
- // ----- Change abort status
- if ($p_entry['status'] == "aborted") {
+ // ----- Change abort status
+ if ($p_entry['status'] == "aborted") {
$p_entry['status'] = "skipped";
- }
-
+ }
+
// ----- Look for post-extract callback
elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) {
@@ -4261,7 +4261,7 @@
// ----- Look for abort result
if ($v_result == 2) {
- $v_result = PCLZIP_ERR_USER_ABORTED;
+ $v_result = PCLZIP_ERR_USER_ABORTED;
}
}
@@ -4491,27 +4491,27 @@
{
$v_result=1;
- // ----- Check the static values
- // TBC
- if ($p_local_header['filename'] != $p_central_header['filename']) {
- }
- if ($p_local_header['version_extracted'] != $p_central_header['version_extracted']) {
- }
- if ($p_local_header['flag'] != $p_central_header['flag']) {
- }
- if ($p_local_header['compression'] != $p_central_header['compression']) {
- }
- if ($p_local_header['mtime'] != $p_central_header['mtime']) {
- }
- if ($p_local_header['filename_len'] != $p_central_header['filename_len']) {
- }
+ // ----- Check the static values
+ // TBC
+ if ($p_local_header['filename'] != $p_central_header['filename']) {
+ }
+ if ($p_local_header['version_extracted'] != $p_central_header['version_extracted']) {
+ }
+ if ($p_local_header['flag'] != $p_central_header['flag']) {
+ }
+ if ($p_local_header['compression'] != $p_central_header['compression']) {
+ }
+ if ($p_local_header['mtime'] != $p_central_header['mtime']) {
+ }
+ if ($p_local_header['filename_len'] != $p_central_header['filename_len']) {
+ }
- // ----- Look for flag bit 3
- if (($p_local_header['flag'] & 8) == 8) {
+ // ----- Look for flag bit 3
+ if (($p_local_header['flag'] & 8) == 8) {
$p_local_header['size'] = $p_central_header['size'];
$p_local_header['compressed_size'] = $p_central_header['compressed_size'];
$p_local_header['crc'] = $p_central_header['crc'];
- }
+ }
// ----- Return
return $v_result;
@@ -4637,19 +4637,19 @@
// ----- Check the global size
if (($v_pos + $v_data['comment_size'] + 18) != $v_size) {
- // ----- Removed in release 2.2 see readme file
- // The check of the file size is a little too strict.
- // Some bugs where found when a zip is encrypted/decrypted with 'crypt'.
- // While decrypted, zip has training 0 bytes
- if (0) {
+ // ----- Removed in release 2.2 see readme file
+ // The check of the file size is a little too strict.
+ // Some bugs where found when a zip is encrypted/decrypted with 'crypt'.
+ // While decrypted, zip has training 0 bytes
+ if (0) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT,
- 'The central dir is not at the end of the archive.'
- .' Some trailing bytes exists after the archive.');
+ 'The central dir is not at the end of the archive.'
+ .' Some trailing bytes exists after the archive.');
// ----- Return
return PclZip::errorCode();
- }
+ }
}
// ----- Get comment
@@ -4811,7 +4811,7 @@
}
}
else {
- $v_found = true;
+ $v_found = true;
}
// ----- Look for deletion
@@ -4874,7 +4874,7 @@
// ----- Check that local file header is same as central file header
if ($this->privCheckFileHeaders($v_local_header,
- $v_header_list[$i]) != 1) {
+ $v_header_list[$i]) != 1) {
// TBC
}
unset($v_local_header);
@@ -5332,22 +5332,22 @@
// ----- Look if function exists
if ( (!function_exists("get_magic_quotes_runtime"))
- || (!function_exists("set_magic_quotes_runtime"))) {
+ || (!function_exists("set_magic_quotes_runtime"))) {
return $v_result;
- }
+ }
// ----- Look if already done
if ($this->magic_quotes_status != -1) {
return $v_result;
- }
+ }
- // ----- Get and memorize the magic_quote value
- $this->magic_quotes_status = @get_magic_quotes_runtime();
+ // ----- Get and memorize the magic_quote value
+ $this->magic_quotes_status = @get_magic_quotes_runtime();
- // ----- Disable magic_quotes
- if ($this->magic_quotes_status == 1) {
- @set_magic_quotes_runtime(0);
- }
+ // ----- Disable magic_quotes
+ if ($this->magic_quotes_status == 1) {
+ @set_magic_quotes_runtime(0);
+ }
// ----- Return
return $v_result;
@@ -5366,19 +5366,19 @@
// ----- Look if function exists
if ( (!function_exists("get_magic_quotes_runtime"))
- || (!function_exists("set_magic_quotes_runtime"))) {
+ || (!function_exists("set_magic_quotes_runtime"))) {
return $v_result;
- }
+ }
// ----- Look if something to do
if ($this->magic_quotes_status != -1) {
return $v_result;
- }
+ }
- // ----- Swap back magic_quotes
- if ($this->magic_quotes_status == 1) {
- @set_magic_quotes_runtime($this->magic_quotes_status);
- }
+ // ----- Swap back magic_quotes
+ if ($this->magic_quotes_status == 1) {
+ @set_magic_quotes_runtime($this->magic_quotes_status);
+ }
// ----- Return
return $v_result;
@@ -5413,37 +5413,37 @@
// Should be the first $i=0, but no check is done
}
else if ($v_list[$i] == "..") {
- $v_skip++;
+ $v_skip++;
}
else if ($v_list[$i] == "") {
- // ----- First '/' i.e. root slash
- if ($i == 0) {
+ // ----- First '/' i.e. root slash
+ if ($i == 0) {
$v_result = "/".$v_result;
- if ($v_skip > 0) {
- // ----- It is an invalid path, so the path is not modified
- // TBC
- $v_result = $p_dir;
+ if ($v_skip > 0) {
+ // ----- It is an invalid path, so the path is not modified
+ // TBC
+ $v_result = $p_dir;
$v_skip = 0;
- }
- }
- // ----- Last '/' i.e. indicates a directory
- else if ($i == (sizeof($v_list)-1)) {
+ }
+ }
+ // ----- Last '/' i.e. indicates a directory
+ else if ($i == (sizeof($v_list)-1)) {
$v_result = $v_list[$i];
- }
- // ----- Double '/' inside the path
- else {
+ }
+ // ----- Double '/' inside the path
+ else {
// ----- Ignore only the double '//' in path,
// but not the first and last '/'
- }
+ }
}
else {
- // ----- Look for item to skip
- if ($v_skip > 0) {
- $v_skip--;
- }
- else {
+ // ----- Look for item to skip
+ if ($v_skip > 0) {
+ $v_skip--;
+ }
+ else {
$v_result = $v_list[$i].($i!=(sizeof($v_list)-1)?"/".$v_result:"");
- }
+ }
}
}
@@ -5650,13 +5650,13 @@
$v_list = get_defined_constants();
for (reset($v_list); $v_key = key($v_list); next($v_list)) {
- $v_prefix = substr($v_key, 0, 10);
- if (( ($v_prefix == 'PCLZIP_OPT')
+ $v_prefix = substr($v_key, 0, 10);
+ if (( ($v_prefix == 'PCLZIP_OPT')
|| ($v_prefix == 'PCLZIP_CB_')
|| ($v_prefix == 'PCLZIP_ATT'))
- && ($v_list[$v_key] == $p_option)) {
+ && ($v_list[$v_key] == $p_option)) {
return $v_key;
- }
+ }
}
$v_result = 'Unknown';
diff --git a/system/sections/web/aes/free/connect.php b/system/sections/web/aes/free/connect.php
index bb68efa..26ac934 100644
--- a/system/sections/web/aes/free/connect.php
+++ b/system/sections/web/aes/free/connect.php
@@ -1,30 +1,30 @@
'Длина ключа не должна превышать 32 символа.'), $nmch);
+ if(isset($key[32]))
+ sys::outjs(array('e' => 'Длина ключа не должна превышать 32 символа.'), $nmch);
- include(LIB.'web/free.php');
+ include(LIB.'web/free.php');
- $aData = array();
+ $aData = array();
- $aData['server'] = sys::int($url['server']);
- $aData['type'] = $url['subsection'];
- $aData['user'] = $server['user'];
- $aData['file'] = 'cstrike/addons/amxmodx/configs/csstats_mysql.cfg';
- $aData['cfg'] = 'cstrike/server.cfg';
+ $aData['server'] = sys::int($url['server']);
+ $aData['type'] = $url['subsection'];
+ $aData['user'] = $server['user'];
+ $aData['file'] = 'cstrike/addons/amxmodx/configs/csstats_mysql.cfg';
+ $aData['cfg'] = 'cstrike/server.cfg';
- $aData['orcfg'] = array(
- 'key' => $key
- );
+ $aData['orcfg'] = array(
+ 'key' => $key
+ );
- $aData['orsql'] = array();
+ $aData['orsql'] = array();
- web::connect($aData, $nmch);
+ web::connect($aData, $nmch);
?>
\ No newline at end of file
diff --git a/system/sections/web/mysql/free/install.php b/system/sections/web/mysql/free/install.php
index 4e0d6fa..3d05d32 100644
--- a/system/sections/web/mysql/free/install.php
+++ b/system/sections/web/mysql/free/install.php
@@ -1,99 +1,99 @@
'Дополнительная услуга недоступна для установки.'), $nmch);
+ // Установка
+ if($go)
+ {
+ if(!$aWeb[$server['game']][$url['subsection']])
+ sys::outjs(array('e' => 'Дополнительная услуга недоступна для установки.'), $nmch);
- // Проверка на наличие уже установленной выбранной услуги
- switch($aWebInstall[$server['game']][$url['subsection']])
- {
- case 'server':
- $sql->query('SELECT `id` FROM `web` WHERE `type`="'.$url['subsection'].'" AND `server`="'.$id.'" LIMIT 1');
- break;
+ // Проверка на наличие уже установленной выбранной услуги
+ switch($aWebInstall[$server['game']][$url['subsection']])
+ {
+ case 'server':
+ $sql->query('SELECT `id` FROM `web` WHERE `type`="'.$url['subsection'].'" AND `server`="'.$id.'" LIMIT 1');
+ break;
- case 'user':
- $sql->query('SELECT `id` FROM `web` WHERE `type`="'.$url['subsection'].'" AND `user`="'.$server['user'].'" LIMIT 1');
- break;
+ case 'user':
+ $sql->query('SELECT `id` FROM `web` WHERE `type`="'.$url['subsection'].'" AND `user`="'.$server['user'].'" LIMIT 1');
+ break;
- case 'unit':
- $sql->query('SELECT `id` FROM `web` WHERE `type`="'.$url['subsection'].'" AND `user`="'.$server['user'].'" AND `unit`="'.$server['unit'].'" LIMIT 1');
- break;
- }
+ case 'unit':
+ $sql->query('SELECT `id` FROM `web` WHERE `type`="'.$url['subsection'].'" AND `user`="'.$server['user'].'" AND `unit`="'.$server['unit'].'" LIMIT 1');
+ break;
+ }
- if($sql->num())
- sys::outjs(array('s' => 'ok'), $nmch);
+ if($sql->num())
+ sys::outjs(array('s' => 'ok'), $nmch);
- include(LIB.'ssh.php');
+ include(LIB.'ssh.php');
- if($aWebUnit['unit'][$url['subsection']] == 'local')
- {
- $sql->query('SELECT `address`, `passwd`, `domain` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
- $unit = $sql->get();
+ if($aWebUnit['unit'][$url['subsection']] == 'local')
+ {
+ $sql->query('SELECT `address`, `passwd`, `domain` FROM `units` WHERE `id`="'.$server['unit'].'" LIMIT 1');
+ $unit = $sql->get();
- $pma = $unit['domain'];
- }else{
- $unit = array(
- 'address' => $aWebUnit['address'],
- 'passwd' => $aWebUnit['passwd'],
- );
+ $pma = $unit['domain'];
+ }else{
+ $unit = array(
+ 'address' => $aWebUnit['address'],
+ 'passwd' => $aWebUnit['passwd'],
+ );
- $pma = $aWebUnit['pma'];
- }
+ $pma = $aWebUnit['pma'];
+ }
- if(!$ssh->auth($unit['passwd'], $unit['address']))
- sys::outjs(array('e' => sys::text('ssh', 'error')), $nmch);
+ if(!$ssh->auth($unit['passwd'], $unit['address']))
+ sys::outjs(array('e' => sys::text('ssh', 'error')), $nmch);
- if(isset($_POST['passwd']))
- {
- // Если не указан пароль сгенерировать
- if($_POST['passwd'] == '')
- $passwd = sys::passwd($aWebParam[$url['subsection']]['passwd']);
- else{
- // Проверка длинны пароля
- if(!isset($_POST['passwd'][5]) || isset($_POST['passwd'][16]))
- sys::outjs(array('e' => 'Необходимо указать пароль длинной не менее 6-и символов и не более 16-и.'), $nmch);
+ if(isset($_POST['passwd']))
+ {
+ // Если не указан пароль сгенерировать
+ if($_POST['passwd'] == '')
+ $passwd = sys::passwd($aWebParam[$url['subsection']]['passwd']);
+ else{
+ // Проверка длинны пароля
+ if(!isset($_POST['passwd'][5]) || isset($_POST['passwd'][16]))
+ sys::outjs(array('e' => 'Необходимо указать пароль длинной не менее 6-и символов и не более 16-и.'), $nmch);
- // Проверка валидности пароля
- if(sys::valid($_POST['passwd'], 'other', "/^[A-Za-z0-9]{6,16}$/"))
- sys::outjs(array('e' => 'Пароль должен состоять из букв a-z и цифр.'), $nmch);
+ // Проверка валидности пароля
+ if(sys::valid($_POST['passwd'], 'other', "/^[A-Za-z0-9]{6,16}$/"))
+ sys::outjs(array('e' => 'Пароль должен состоять из букв a-z и цифр.'), $nmch);
- $passwd = $_POST['passwd'];
- }
- }else
- $passwd = sys::passwd($aWebParam[$url['subsection']]['passwd']);
+ $passwd = $_POST['passwd'];
+ }
+ }else
+ $passwd = sys::passwd($aWebParam[$url['subsection']]['passwd']);
- $sql->query('INSERT INTO `web` set `type`="'.$url['subsection'].'", `server`="'.$id.'", `user`="'.$server['user'].'", `unit`="'.$server['unit'].'", `config`=""');
- $wid = $sql->id();
- $uid = $wid+10000;
+ $sql->query('INSERT INTO `web` set `type`="'.$url['subsection'].'", `server`="'.$id.'", `user`="'.$server['user'].'", `unit`="'.$server['unit'].'", `config`=""');
+ $wid = $sql->id();
+ $uid = $wid+10000;
- // Данные
- $login = substr('sql_'.$wid.'_free', 0, 14);
+ // Данные
+ $login = substr('sql_'.$wid.'_free', 0, 14);
- $sql_q = 'mysql --login-path=local -e "CREATE DATABASE '.$login.';'
- ."CREATE USER '".$login."'@'%' IDENTIFIED BY '".$passwd."';"
- .'GRANT ALL PRIVILEGES ON '.$login.' . * TO \''.$login.'\'@\'%\';";';
+ $sql_q = 'mysql --login-path=local -e "CREATE DATABASE '.$login.';'
+ ."CREATE USER '".$login."'@'%' IDENTIFIED BY '".$passwd."';"
+ .'GRANT ALL PRIVILEGES ON '.$login.' . * TO \''.$login.'\'@\'%\';";';
- $ssh->set($sql_q);
+ $ssh->set($sql_q);
- // Обновление данных
- $sql->query('UPDATE `web` set `uid`="'.$uid.'",'
- .'`domain`="'.$pma.'",'
- .'`passwd`="'.$passwd.'",'
- .'`login`="'.$login.'", `date`="'.$start_point.'" '
- .'WHERE `id`="'.$wid.'" LIMIT 1');
+ // Обновление данных
+ $sql->query('UPDATE `web` set `uid`="'.$uid.'",'
+ .'`domain`="'.$pma.'",'
+ .'`passwd`="'.$passwd.'",'
+ .'`login`="'.$login.'", `date`="'.$start_point.'" '
+ .'WHERE `id`="'.$wid.'" LIMIT 1');
- sys::outjs(array('s' => 'ok'), $nmch);
- }
+ sys::outjs(array('s' => 'ok'), $nmch);
+ }
- $html->nav('Установка '.$aWebname[$url['subsection']]);
+ $html->nav('Установка '.$aWebname[$url['subsection']]);
- $html->get('install', 'sections/web/'.$url['subsection'].'/free');
+ $html->get('install', 'sections/web/'.$url['subsection'].'/free');
- $html->set('id', $id);
+ $html->set('id', $id);
- $html->pack('main');
+ $html->pack('main');
?>
\ No newline at end of file
diff --git a/system/sections/wiki/msearch.php b/system/sections/wiki/msearch.php
index 98031d1..de5aa5f 100644
--- a/system/sections/wiki/msearch.php
+++ b/system/sections/wiki/msearch.php
@@ -1,156 +1,156 @@
'')));
+ $text = isset($_POST['text']) ? $_POST['text'] : (isset($url['tag']) ? urldecode($url['tag']) : sys::outjs(array('none' => '')));
- $mkey = md5($text.'wiki');
+ $mkey = md5($text.'wiki');
- if($mcache->get($mkey) != '' AND !isset($url['tag']))
- sys::outjs(array('s' => $mcache->get($mkey)));
+ if($mcache->get($mkey) != '' AND !isset($url['tag']))
+ sys::outjs(array('s' => $mcache->get($mkey)));
- if(!isset($text[2]) AND !isset($url['tag']))
- sys::outjs(array('s' => 'Для выполнения поиска, необходимо больше данных', $nmch));
+ if(!isset($text[2]) AND !isset($url['tag']))
+ sys::outjs(array('s' => 'Для выполнения поиска, необходимо больше данных', $nmch));
- $aWiki_q = array();
- $aNswer_q = array();
+ $aWiki_q = array();
+ $aNswer_q = array();
- // Поиск по вопросу
- $wiki_q = $sql->query('SELECT `id` FROM `wiki` WHERE `name` LIKE FROM_BASE64(\''.base64_encode('%'.$text.'%').'\') OR `tags` LIKE FROM_BASE64(\''.base64_encode('%'.$text.'%').'\') LIMIT 3');
+ // Поиск по вопросу
+ $wiki_q = $sql->query('SELECT `id` FROM `wiki` WHERE `name` LIKE FROM_BASE64(\''.base64_encode('%'.$text.'%').'\') OR `tags` LIKE FROM_BASE64(\''.base64_encode('%'.$text.'%').'\') LIMIT 3');
- // Поиск по тексту (ответу)
- $answer_q = $sql->query('SELECT `wiki` FROM `wiki_answer` WHERE `text` LIKE FROM_BASE64(\''.base64_encode('%'.$text.'%').'\') LIMIT 5');
+ // Поиск по тексту (ответу)
+ $answer_q = $sql->query('SELECT `wiki` FROM `wiki_answer` WHERE `text` LIKE FROM_BASE64(\''.base64_encode('%'.$text.'%').'\') LIMIT 5');
- // Если нет ниодного совпадения по вводимому тексту
- if(!$sql->num($wiki_q) AND !$sql->num($answer_q) AND !isset($url['tag']))
- {
- // Поиск по словам
- if(!strpos($text, ' '))
- {
- $mcache->set($mkey, 'По вашему запросу ничего не найдено', false, 15);
+ // Если нет ниодного совпадения по вводимому тексту
+ if(!$sql->num($wiki_q) AND !$sql->num($answer_q) AND !isset($url['tag']))
+ {
+ // Поиск по словам
+ if(!strpos($text, ' '))
+ {
+ $mcache->set($mkey, 'По вашему запросу ничего не найдено', false, 15);
- sys::outjs(array('s' => 'По вашему запросу ничего не найдено'));
- }
+ sys::outjs(array('s' => 'По вашему запросу ничего не найдено'));
+ }
- // Массив слов
- $aText = explode(' ', $text);
+ // Массив слов
+ $aText = explode(' ', $text);
- // Метка, которая изменится в процессе, если будет найдено хоть одно совпадение
- $sWord = false;
+ // Метка, которая изменится в процессе, если будет найдено хоть одно совпадение
+ $sWord = false;
- foreach($aText as $word)
- {
- if($word == '' || !isset($word[2]))
- continue;
+ foreach($aText as $word)
+ {
+ if($word == '' || !isset($word[2]))
+ continue;
- // Поиск по вопросу
- $wiki_q = $sql->query('SELECT `id` FROM `wiki` WHERE `name` LIKE FROM_BASE64(\''.base64_encode('%'.$word.'%').'\') OR `tags` LIKE FROM_BASE64(\''.base64_encode('%'.$word.'%').'\') LIMIT 3');
+ // Поиск по вопросу
+ $wiki_q = $sql->query('SELECT `id` FROM `wiki` WHERE `name` LIKE FROM_BASE64(\''.base64_encode('%'.$word.'%').'\') OR `tags` LIKE FROM_BASE64(\''.base64_encode('%'.$word.'%').'\') LIMIT 3');
- // Поиск по тексту (ответу)
- $answer_q = $sql->query('SELECT `wiki` FROM `wiki_answer` WHERE `text` LIKE FROM_BASE64(\''.base64_encode('%'.$word.'%').'\') LIMIT 5');
+ // Поиск по тексту (ответу)
+ $answer_q = $sql->query('SELECT `wiki` FROM `wiki_answer` WHERE `text` LIKE FROM_BASE64(\''.base64_encode('%'.$word.'%').'\') LIMIT 5');
- if($sql->num($wiki_q))
- $aWiki_q[] = $wiki_q;
+ if($sql->num($wiki_q))
+ $aWiki_q[] = $wiki_q;
- if($sql->num($answer_q))
- $aNswer_q[] = $answer_q;
- }
+ if($sql->num($answer_q))
+ $aNswer_q[] = $answer_q;
+ }
- }else{
- $aWiki_q[] = $wiki_q;
- $aNswer_q[] = $answer_q;
- }
+ }else{
+ $aWiki_q[] = $wiki_q;
+ $aNswer_q[] = $answer_q;
+ }
- if(!count($aWiki_q) AND !count($aNswer_q) AND !isset($url['tag']))
- {
- $mcache->set($mkey, 'По вашему запросу ничего не найдено', false, 15);
+ if(!count($aWiki_q) AND !count($aNswer_q) AND !isset($url['tag']))
+ {
+ $mcache->set($mkey, 'По вашему запросу ничего не найдено', false, 15);
- sys::outjs(array('s' => 'По вашему запросу ничего не найдено'));
- }
+ sys::outjs(array('s' => 'По вашему запросу ничего не найдено'));
+ }
- // Защита от дублирования
- $aResult = array();
+ // Защита от дублирования
+ $aResult = array();
- foreach($aWiki_q as $index => $wiki_q)
- {
- // Генерация списка (совпадение по вопросу)
- while($wiki = $sql->get($wiki_q))
- {
- // Проверка дублирования
- if(in_array($wiki['id'], $aResult))
- continue;
+ foreach($aWiki_q as $index => $wiki_q)
+ {
+ // Генерация списка (совпадение по вопросу)
+ while($wiki = $sql->get($wiki_q))
+ {
+ // Проверка дублирования
+ if(in_array($wiki['id'], $aResult))
+ continue;
- $sql->query('SELECT `id`, `name`, `tags`, `date` FROM `wiki` WHERE `id`="'.$wiki['id'].'" LIMIT 1');
- $quest = $sql->get();
+ $sql->query('SELECT `id`, `name`, `tags`, `date` FROM `wiki` WHERE `id`="'.$wiki['id'].'" LIMIT 1');
+ $quest = $sql->get();
- $aTags = explode(',', $quest['tags']);
+ $aTags = explode(',', $quest['tags']);
- $tags = '';
+ $tags = '';
- foreach($aTags as $tag)
- {
- $tag = trim($tag);
+ foreach($aTags as $tag)
+ {
+ $tag = trim($tag);
- $tags .= ''.$tag.' ';
- }
+ $tags .= ''.$tag.' ';
+ }
- $html->get('list', 'sections/wiki/question');
+ $html->get('list', 'sections/wiki/question');
- $html->set('id', $quest['id']);
- $html->set('name', sys::find($quest['name'], $text));
- $html->set('tags', $tags != '' ? $tags : 'Теги отсутствуют');
- $html->set('date', sys::today($quest['date']));
+ $html->set('id', $quest['id']);
+ $html->set('name', sys::find($quest['name'], $text));
+ $html->set('tags', $tags != '' ? $tags : 'Теги отсутствуют');
+ $html->set('date', sys::today($quest['date']));
- $html->set('home', $cfg['http']);
+ $html->set('home', $cfg['http']);
- $html->pack('question');
+ $html->pack('question');
- array_push($aResult, $wiki['id']);
- }
- }
+ array_push($aResult, $wiki['id']);
+ }
+ }
- foreach($aNswer_q as $index => $answer_q)
- {
- // Генерация списка (совпадение по ответу)
- while($answer = $sql->get($answer_q))
- {
- // Проверка дублирования
- if(in_array($answer['wiki'], $aResult))
- continue;
+ foreach($aNswer_q as $index => $answer_q)
+ {
+ // Генерация списка (совпадение по ответу)
+ while($answer = $sql->get($answer_q))
+ {
+ // Проверка дублирования
+ if(in_array($answer['wiki'], $aResult))
+ continue;
- $sql->query('SELECT `id`, `name`, `tags`, `date` FROM `wiki` WHERE `id`="'.$answer['wiki'].'" LIMIT 1');
- $quest = $sql->get();
+ $sql->query('SELECT `id`, `name`, `tags`, `date` FROM `wiki` WHERE `id`="'.$answer['wiki'].'" LIMIT 1');
+ $quest = $sql->get();
- $aTags = explode(',', $quest['tags']);
+ $aTags = explode(',', $quest['tags']);
- $tags = '';
+ $tags = '';
- foreach($aTags as $tag)
- {
- $tag = trim($tag);
+ foreach($aTags as $tag)
+ {
+ $tag = trim($tag);
- $tags .= ''.$tag.' ';
- }
+ $tags .= ''.$tag.' ';
+ }
- $html->get('list', 'sections/wiki/question');
+ $html->get('list', 'sections/wiki/question');
- $html->set('id', $quest['id']);
- $html->set('name', sys::find($quest['name'], $text));
- $html->set('tags', $tags != '' ? $tags : 'Теги отсутствуют');
- $html->set('date', sys::today($quest['date']));
+ $html->set('id', $quest['id']);
+ $html->set('name', sys::find($quest['name'], $text));
+ $html->set('tags', $tags != '' ? $tags : 'Теги отсутствуют');
+ $html->set('date', sys::today($quest['date']));
- $html->set('home', $cfg['http']);
+ $html->set('home', $cfg['http']);
- $html->pack('question');
- }
- }
+ $html->pack('question');
+ }
+ }
- $html->arr['question'] = isset($html->arr['question']) ? $html->arr['question'] : 'По вашему запросу ничего не найдено';
+ $html->arr['question'] = isset($html->arr['question']) ? $html->arr['question'] : 'По вашему запросу ничего не найдено';
- $mcache->set($mkey, $html->arr['question'], false, 15);
+ $mcache->set($mkey, $html->arr['question'], false, 15);
- sys::outjs(array('s' => $html->arr['question']), $nmch);
+ sys::outjs(array('s' => $html->arr['question']), $nmch);
?>
\ No newline at end of file
diff --git a/template/acp/all.html b/template/acp/all.html
index ce763b9..8fece54 100644
--- a/template/acp/all.html
+++ b/template/acp/all.html
@@ -1,145 +1,145 @@
-
- Панель администатора
-
-
-
-
-
-
+
+ Панель администатора
+
+
+
+
+
+
-
-
-
-
-
+
+
+
+
+
-
-
+ setTimeout(function($){_item.removeClass("jmp"); _item.css({"left": '110%'})}, 150*i);
+ setTimeout(function($){_item.addClass("jmp"); _item.css({"left": '90%'})}, 1000 + 150*i);
+ })
+ }, 1500);
+ });
+
+
-
-
-
- |section|
-
- |_section|
-
-
+
+
+
+ |section|
+
+ |_section|
+
-
+
+
+
-
-
- |section||_section|
+ |section||_section|
-
-
+
+
-
+
-
-
+
+
\ No newline at end of file
diff --git a/template/acp/cashback.html b/template/acp/cashback.html
index a62d9f8..732c8eb 100644
--- a/template/acp/cashback.html
+++ b/template/acp/cashback.html
@@ -1,9 +1,9 @@
- #[id]
- USER_[user]
- [mail]
- [purse]
- [money] (Выводить: [cashback])
- [type]
- Вывести
+ #[id]
+ USER_[user]
+ [mail]
+ [purse]
+ [money] (Выводить: [cashback])
+ [type]
+ Вывести
\ No newline at end of file
diff --git a/template/acp/css/bootbox.css b/template/acp/css/bootbox.css
index 2e7cbcd..cd0b6f9 100644
--- a/template/acp/css/bootbox.css
+++ b/template/acp/css/bootbox.css
@@ -1,26 +1,26 @@
.fade
{
- opacity:0;
- -webkit-transition:opacity .15s linear;
- -moz-transition:opacity .15s linear;
- -o-transition:opacity .15s linear;
- transition:opacity .15s linear
+ opacity:0;
+ -webkit-transition:opacity .15s linear;
+ -moz-transition:opacity .15s linear;
+ -o-transition:opacity .15s linear;
+ transition:opacity .15s linear
}
.fade.in{
- opacity:1
+ opacity:1
}
.modal-backdrop
{
- position:fixed;
- top:0;
- right:0;
- bottom:0;
- left:0;
- z-index:1040;
- background-color:#000
+ position:fixed;
+ top:0;
+ right:0;
+ bottom:0;
+ left:0;
+ z-index:1040;
+ background-color:#000
}
.modal-backdrop.fade{
- opacity:0
+ opacity:0
}
.modal-backdrop,.modal-backdrop.fade.in
{
@@ -30,94 +30,94 @@
}
.modal
{
- position:fixed;
- top:40%;
- left:45%;
- z-index:1050;
- width:560px;
- margin-left:-280px;
- background-color:#fff;
- border:1px solid #EEE;
- *border:1px solid #EEE;
- outline:0;
- -webkit-background-clip:padding-box;
- -moz-background-clip:padding-box;
- background-clip:padding-box
+ position:fixed;
+ top:40%;
+ left:45%;
+ z-index:1050;
+ width:560px;
+ margin-left:-280px;
+ background-color:#fff;
+ border:1px solid #EEE;
+ *border:1px solid #EEE;
+ outline:0;
+ -webkit-background-clip:padding-box;
+ -moz-background-clip:padding-box;
+ background-clip:padding-box
}
.modal.fade
{
- top:-25%;
- -webkit-transition:opacity .3s linear,top .3s ease-out;
- -moz-transition:opacity .3s linear,top .3s ease-out;
- -o-transition:opacity .3s linear,top .3s ease-out;
- transition:opacity .3s linear,top .3s ease-out
+ top:-25%;
+ -webkit-transition:opacity .3s linear,top .3s ease-out;
+ -moz-transition:opacity .3s linear,top .3s ease-out;
+ -o-transition:opacity .3s linear,top .3s ease-out;
+ transition:opacity .3s linear,top .3s ease-out
}
.modal.fade.in
{
- top:40%;
- left: 50%;
+ top:40%;
+ left: 50%;
}
.modal-header
{
- padding:9px 15px;
- border-bottom:1px solid #eee
+ padding:9px 15px;
+ border-bottom:1px solid #eee
}
.modal-header .close
{
- margin-top:2px
+ margin-top:2px
}
.modal-header h3
{
- margin:0;
- line-height:30px
+ margin:0;
+ line-height:30px
}
.modal-body
{
- position:relative;
- max-height:400px;
- padding:15px;
- overflow-y:auto
+ position:relative;
+ max-height:400px;
+ padding:15px;
+ overflow-y:auto
}
.modal-form
{
- margin-bottom:0
+ margin-bottom:0
}
.modal-footer
{
- padding:14px 15px 15px;
- margin-bottom:0;
- text-align:right;
- background-color:#f5f5f5;
- border-top:1px solid #ddd;
- -webkit-border-radius:0 0 6px 6px;
- -moz-border-radius:0 0 6px 6px;
- border-radius:0 0 6px 6px;
- *zoom:1;
- -webkit-box-shadow:inset 0 1px 0 #fff;
- -moz-box-shadow:inset 0 1px 0 #fff;
- box-shadow:inset 0 1px 0 #fff
+ padding:14px 15px 15px;
+ margin-bottom:0;
+ text-align:right;
+ background-color:#f5f5f5;
+ border-top:1px solid #ddd;
+ -webkit-border-radius:0 0 6px 6px;
+ -moz-border-radius:0 0 6px 6px;
+ border-radius:0 0 6px 6px;
+ *zoom:1;
+ -webkit-box-shadow:inset 0 1px 0 #fff;
+ -moz-box-shadow:inset 0 1px 0 #fff;
+ box-shadow:inset 0 1px 0 #fff
}
.modal-footer:before,.modal-footer:after
{
- display:table;
- line-height:0;
- content:""
+ display:table;
+ line-height:0;
+ content:""
}
.modal-footer:after
{
- clear:both
+ clear:both
}
.modal-footer .btn+.btn
{
- margin-bottom:0;
- margin-left:5px
+ margin-bottom:0;
+ margin-left:5px
}
.modal-footer .btn-group .btn+.btn
{
- margin-left:-1px
+ margin-left:-1px
}
.modal-footer .btn-block+.btn-block
{
- margin-left:0
+ margin-left:0
}
diff --git a/template/acp/css/jquery.datetimepicker.css b/template/acp/css/jquery.datetimepicker.css
index 4ed981a..4dd8d26 100644
--- a/template/acp/css/jquery.datetimepicker.css
+++ b/template/acp/css/jquery.datetimepicker.css
@@ -1,509 +1,509 @@
.xdsoft_datetimepicker {
- box-shadow: 0 5px 15px -5px rgba(0, 0, 0, 0.506);
- background: #fff;
- border-bottom: 1px solid #bbb;
- border-left: 1px solid #ccc;
- border-right: 1px solid #ccc;
- border-top: 1px solid #ccc;
- color: #333;
- font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
- padding: 8px;
- padding-left: 0;
- padding-top: 2px;
- position: absolute;
- z-index: 9999;
- -moz-box-sizing: border-box;
- box-sizing: border-box;
- display: none;
+ box-shadow: 0 5px 15px -5px rgba(0, 0, 0, 0.506);
+ background: #fff;
+ border-bottom: 1px solid #bbb;
+ border-left: 1px solid #ccc;
+ border-right: 1px solid #ccc;
+ border-top: 1px solid #ccc;
+ color: #333;
+ font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
+ padding: 8px;
+ padding-left: 0;
+ padding-top: 2px;
+ position: absolute;
+ z-index: 9999;
+ -moz-box-sizing: border-box;
+ box-sizing: border-box;
+ display: none;
}
.xdsoft_datetimepicker.xdsoft_rtl {
- padding: 8px 0 8px 8px;
+ padding: 8px 0 8px 8px;
}
.xdsoft_datetimepicker iframe {
- position: absolute;
- left: 0;
- top: 0;
- width: 75px;
- height: 210px;
- background: transparent;
- border: none;
+ position: absolute;
+ left: 0;
+ top: 0;
+ width: 75px;
+ height: 210px;
+ background: transparent;
+ border: none;
}
/*For IE8 or lower*/
.xdsoft_datetimepicker button {
- border: none !important;
+ border: none !important;
}
.xdsoft_noselect {
- -webkit-touch-callout: none;
- -webkit-user-select: none;
- -khtml-user-select: none;
- -moz-user-select: none;
- -ms-user-select: none;
- -o-user-select: none;
- user-select: none;
+ -webkit-touch-callout: none;
+ -webkit-user-select: none;
+ -khtml-user-select: none;
+ -moz-user-select: none;
+ -ms-user-select: none;
+ -o-user-select: none;
+ user-select: none;
}
.xdsoft_noselect::selection { background: transparent }
.xdsoft_noselect::-moz-selection { background: transparent }
.xdsoft_datetimepicker.xdsoft_inline {
- display: inline-block;
- position: static;
- box-shadow: none;
+ display: inline-block;
+ position: static;
+ box-shadow: none;
}
.xdsoft_datetimepicker * {
- -moz-box-sizing: border-box;
- box-sizing: border-box;
- padding: 0;
- margin: 0;
+ -moz-box-sizing: border-box;
+ box-sizing: border-box;
+ padding: 0;
+ margin: 0;
}
.xdsoft_datetimepicker .xdsoft_datepicker, .xdsoft_datetimepicker .xdsoft_timepicker {
- display: none;
+ display: none;
}
.xdsoft_datetimepicker .xdsoft_datepicker.active, .xdsoft_datetimepicker .xdsoft_timepicker.active {
- display: block;
+ display: block;
}
.xdsoft_datetimepicker .xdsoft_datepicker {
- width: 224px;
- float: left;
- margin-left: 8px;
+ width: 224px;
+ float: left;
+ margin-left: 8px;
}
.xdsoft_datetimepicker.xdsoft_rtl .xdsoft_datepicker {
- float: right;
- margin-right: 8px;
- margin-left: 0;
+ float: right;
+ margin-right: 8px;
+ margin-left: 0;
}
.xdsoft_datetimepicker.xdsoft_showweeks .xdsoft_datepicker {
- width: 256px;
+ width: 256px;
}
.xdsoft_datetimepicker .xdsoft_timepicker {
- width: 58px;
- float: left;
- text-align: center;
- margin-left: 8px;
- margin-top: 0;
+ width: 58px;
+ float: left;
+ text-align: center;
+ margin-left: 8px;
+ margin-top: 0;
}
.xdsoft_datetimepicker.xdsoft_rtl .xdsoft_timepicker {
- float: right;
- margin-right: 8px;
- margin-left: 0;
+ float: right;
+ margin-right: 8px;
+ margin-left: 0;
}
.xdsoft_datetimepicker .xdsoft_datepicker.active+.xdsoft_timepicker {
- margin-top: 8px;
- margin-bottom: 3px
+ margin-top: 8px;
+ margin-bottom: 3px
}
.xdsoft_datetimepicker .xdsoft_monthpicker {
- position: relative;
- text-align: center;
+ position: relative;
+ text-align: center;
}
.xdsoft_datetimepicker .xdsoft_label i,
.xdsoft_datetimepicker .xdsoft_prev,
.xdsoft_datetimepicker .xdsoft_next,
.xdsoft_datetimepicker .xdsoft_today_button {
- background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAAAeCAYAAADaW7vzAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNiAoV2luZG93cykiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6Q0NBRjI1NjM0M0UwMTFFNDk4NkFGMzJFQkQzQjEwRUIiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6Q0NBRjI1NjQ0M0UwMTFFNDk4NkFGMzJFQkQzQjEwRUIiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDpDQ0FGMjU2MTQzRTAxMUU0OTg2QUYzMkVCRDNCMTBFQiIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDpDQ0FGMjU2MjQzRTAxMUU0OTg2QUYzMkVCRDNCMTBFQiIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PoNEP54AAAIOSURBVHja7Jq9TsMwEMcxrZD4WpBYeKUCe+kTMCACHZh4BFfHO/AAIHZGFhYkBBsSEqxsLCAgXKhbXYOTxh9pfJVP+qutnZ5s/5Lz2Y5I03QhWji2GIcgAokWgfCxNvcOCCGKqiSqhUp0laHOne05vdEyGMfkdxJDVjgwDlEQgYQBgx+ULJaWSXXS6r/ER5FBVR8VfGftTKcITNs+a1XpcFoExREIDF14AVIFxgQUS+h520cdud6wNkC0UBw6BCO/HoCYwBhD8QCkQ/x1mwDyD4plh4D6DDV0TAGyo4HcawLIBBSLDkHeH0Mg2yVP3l4TQMZQDDsEOl/MgHQqhMNuE0D+oBh0CIr8MAKyazBH9WyBuKxDWgbXfjNf32TZ1KWm/Ap1oSk/R53UtQ5xTh3LUlMmT8gt6g51Q9p+SobxgJQ/qmsfZhWywGFSl0yBjCLJCMgXail3b7+rumdVJ2YRss4cN+r6qAHDkPWjPjdJCF4n9RmAD/V9A/Wp4NQassDjwlB6XBiCxcJQWmZZb8THFilfy/lfrTvLghq2TqTHrRMTKNJ0sIhdo15RT+RpyWwFdY96UZ/LdQKBGjcXpcc1AlSFEfLmouD+1knuxBDUVrvOBmoOC/rEcN7OQxKVeJTCiAdUzUJhA2Oez9QTkp72OTVcxDcXY8iKNkxGAJXmJCOQwOa6dhyXsOa6XwEGAKdeb5ET3rQdAAAAAElFTkSuQmCC);
+ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAAAeCAYAAADaW7vzAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNiAoV2luZG93cykiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6Q0NBRjI1NjM0M0UwMTFFNDk4NkFGMzJFQkQzQjEwRUIiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6Q0NBRjI1NjQ0M0UwMTFFNDk4NkFGMzJFQkQzQjEwRUIiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDpDQ0FGMjU2MTQzRTAxMUU0OTg2QUYzMkVCRDNCMTBFQiIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDpDQ0FGMjU2MjQzRTAxMUU0OTg2QUYzMkVCRDNCMTBFQiIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PoNEP54AAAIOSURBVHja7Jq9TsMwEMcxrZD4WpBYeKUCe+kTMCACHZh4BFfHO/AAIHZGFhYkBBsSEqxsLCAgXKhbXYOTxh9pfJVP+qutnZ5s/5Lz2Y5I03QhWji2GIcgAokWgfCxNvcOCCGKqiSqhUp0laHOne05vdEyGMfkdxJDVjgwDlEQgYQBgx+ULJaWSXXS6r/ER5FBVR8VfGftTKcITNs+a1XpcFoExREIDF14AVIFxgQUS+h520cdud6wNkC0UBw6BCO/HoCYwBhD8QCkQ/x1mwDyD4plh4D6DDV0TAGyo4HcawLIBBSLDkHeH0Mg2yVP3l4TQMZQDDsEOl/MgHQqhMNuE0D+oBh0CIr8MAKyazBH9WyBuKxDWgbXfjNf32TZ1KWm/Ap1oSk/R53UtQ5xTh3LUlMmT8gt6g51Q9p+SobxgJQ/qmsfZhWywGFSl0yBjCLJCMgXail3b7+rumdVJ2YRss4cN+r6qAHDkPWjPjdJCF4n9RmAD/V9A/Wp4NQassDjwlB6XBiCxcJQWmZZb8THFilfy/lfrTvLghq2TqTHrRMTKNJ0sIhdo15RT+RpyWwFdY96UZ/LdQKBGjcXpcc1AlSFEfLmouD+1knuxBDUVrvOBmoOC/rEcN7OQxKVeJTCiAdUzUJhA2Oez9QTkp72OTVcxDcXY8iKNkxGAJXmJCOQwOa6dhyXsOa6XwEGAKdeb5ET3rQdAAAAAElFTkSuQmCC);
}
.xdsoft_datetimepicker .xdsoft_label i {
- opacity: 0.5;
- background-position: -92px -19px;
- display: inline-block;
- width: 9px;
- height: 20px;
- vertical-align: middle;
+ opacity: 0.5;
+ background-position: -92px -19px;
+ display: inline-block;
+ width: 9px;
+ height: 20px;
+ vertical-align: middle;
}
.xdsoft_datetimepicker .xdsoft_prev {
- float: left;
- background-position: -20px 0;
+ float: left;
+ background-position: -20px 0;
}
.xdsoft_datetimepicker .xdsoft_today_button {
- float: left;
- background-position: -70px 0;
- margin-left: 5px;
+ float: left;
+ background-position: -70px 0;
+ margin-left: 5px;
}
.xdsoft_datetimepicker .xdsoft_next {
- float: right;
- background-position: 0 0;
+ float: right;
+ background-position: 0 0;
}
.xdsoft_datetimepicker .xdsoft_next,
.xdsoft_datetimepicker .xdsoft_prev ,
.xdsoft_datetimepicker .xdsoft_today_button {
- background-color: transparent;
- background-repeat: no-repeat;
- border: 0 none;
- cursor: pointer;
- display: block;
- height: 30px;
- opacity: 0.5;
- -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
- outline: medium none;
- overflow: hidden;
- padding: 0;
- position: relative;
- text-indent: 100%;
- white-space: nowrap;
- width: 20px;
- min-width: 0;
+ background-color: transparent;
+ background-repeat: no-repeat;
+ border: 0 none;
+ cursor: pointer;
+ display: block;
+ height: 30px;
+ opacity: 0.5;
+ -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
+ outline: medium none;
+ overflow: hidden;
+ padding: 0;
+ position: relative;
+ text-indent: 100%;
+ white-space: nowrap;
+ width: 20px;
+ min-width: 0;
}
.xdsoft_datetimepicker .xdsoft_timepicker .xdsoft_prev,
.xdsoft_datetimepicker .xdsoft_timepicker .xdsoft_next {
- float: none;
- background-position: -40px -15px;
- height: 15px;
- width: 30px;
- display: block;
- margin-left: 14px;
- margin-top: 7px;
+ float: none;
+ background-position: -40px -15px;
+ height: 15px;
+ width: 30px;
+ display: block;
+ margin-left: 14px;
+ margin-top: 7px;
}
.xdsoft_datetimepicker.xdsoft_rtl .xdsoft_timepicker .xdsoft_prev,
.xdsoft_datetimepicker.xdsoft_rtl .xdsoft_timepicker .xdsoft_next {
- float: none;
- margin-left: 0;
- margin-right: 14px;
+ float: none;
+ margin-left: 0;
+ margin-right: 14px;
}
.xdsoft_datetimepicker .xdsoft_timepicker .xdsoft_prev {
- background-position: -40px 0;
- margin-bottom: 7px;
- margin-top: 0;
+ background-position: -40px 0;
+ margin-bottom: 7px;
+ margin-top: 0;
}
.xdsoft_datetimepicker .xdsoft_timepicker .xdsoft_time_box {
- height: 151px;
- overflow: hidden;
- border-bottom: 1px solid #ddd;
+ height: 151px;
+ overflow: hidden;
+ border-bottom: 1px solid #ddd;
}
.xdsoft_datetimepicker .xdsoft_timepicker .xdsoft_time_box >div >div {
- background: #f5f5f5;
- border-top: 1px solid #ddd;
- color: #666;
- font-size: 12px;
- text-align: center;
- border-collapse: collapse;
- cursor: pointer;
- border-bottom-width: 0;
- height: 25px;
- line-height: 25px;
+ background: #f5f5f5;
+ border-top: 1px solid #ddd;
+ color: #666;
+ font-size: 12px;
+ text-align: center;
+ border-collapse: collapse;
+ cursor: pointer;
+ border-bottom-width: 0;
+ height: 25px;
+ line-height: 25px;
}
.xdsoft_datetimepicker .xdsoft_timepicker .xdsoft_time_box >div > div:first-child {
- border-top-width: 0;
+ border-top-width: 0;
}
.xdsoft_datetimepicker .xdsoft_today_button:hover,
.xdsoft_datetimepicker .xdsoft_next:hover,
.xdsoft_datetimepicker .xdsoft_prev:hover {
- opacity: 1;
- -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";
+ opacity: 1;
+ -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";
}
.xdsoft_datetimepicker .xdsoft_label {
- display: inline;
- position: relative;
- z-index: 9999;
- margin: 0;
- padding: 5px 3px;
- font-size: 14px;
- line-height: 20px;
- font-weight: bold;
- background-color: #fff;
- float: left;
- width: 182px;
- text-align: center;
- cursor: pointer;
+ display: inline;
+ position: relative;
+ z-index: 9999;
+ margin: 0;
+ padding: 5px 3px;
+ font-size: 14px;
+ line-height: 20px;
+ font-weight: bold;
+ background-color: #fff;
+ float: left;
+ width: 182px;
+ text-align: center;
+ cursor: pointer;
}
.xdsoft_datetimepicker .xdsoft_label:hover>span {
- text-decoration: underline;
+ text-decoration: underline;
}
.xdsoft_datetimepicker .xdsoft_label:hover i {
- opacity: 1.0;
+ opacity: 1.0;
}
.xdsoft_datetimepicker .xdsoft_label > .xdsoft_select {
- border: 1px solid #ccc;
- position: absolute;
- right: 0;
- top: 30px;
- z-index: 101;
- display: none;
- background: #fff;
- max-height: 160px;
- overflow-y: hidden;
+ border: 1px solid #ccc;
+ position: absolute;
+ right: 0;
+ top: 30px;
+ z-index: 101;
+ display: none;
+ background: #fff;
+ max-height: 160px;
+ overflow-y: hidden;
}
.xdsoft_datetimepicker .xdsoft_label > .xdsoft_select.xdsoft_monthselect{ right: -7px }
.xdsoft_datetimepicker .xdsoft_label > .xdsoft_select.xdsoft_yearselect{ right: 2px }
.xdsoft_datetimepicker .xdsoft_label > .xdsoft_select > div > .xdsoft_option:hover {
- color: #fff;
- background: #ff8000;
+ color: #fff;
+ background: #ff8000;
}
.xdsoft_datetimepicker .xdsoft_label > .xdsoft_select > div > .xdsoft_option {
- padding: 2px 10px 2px 5px;
- text-decoration: none !important;
+ padding: 2px 10px 2px 5px;
+ text-decoration: none !important;
}
.xdsoft_datetimepicker .xdsoft_label > .xdsoft_select > div > .xdsoft_option.xdsoft_current {
- background: #33aaff;
- box-shadow: #178fe5 0 1px 3px 0 inset;
- color: #fff;
- font-weight: 700;
+ background: #33aaff;
+ box-shadow: #178fe5 0 1px 3px 0 inset;
+ color: #fff;
+ font-weight: 700;
}
.xdsoft_datetimepicker .xdsoft_month {
- width: 100px;
- text-align: right;
+ width: 100px;
+ text-align: right;
}
.xdsoft_datetimepicker .xdsoft_calendar {
- clear: both;
+ clear: both;
}
.xdsoft_datetimepicker .xdsoft_year{
- width: 48px;
- margin-left: 5px;
+ width: 48px;
+ margin-left: 5px;
}
.xdsoft_datetimepicker .xdsoft_calendar table {
- border-collapse: collapse;
- width: 100%;
+ border-collapse: collapse;
+ width: 100%;
}
.xdsoft_datetimepicker .xdsoft_calendar td > div {
- padding-right: 5px;
+ padding-right: 5px;
}
.xdsoft_datetimepicker .xdsoft_calendar th {
- height: 25px;
+ height: 25px;
}
.xdsoft_datetimepicker .xdsoft_calendar td,.xdsoft_datetimepicker .xdsoft_calendar th {
- width: 14.2857142%;
- background: #f5f5f5;
- border: 1px solid #ddd;
- color: #666;
- font-size: 12px;
- text-align: right;
- vertical-align: middle;
- padding: 0;
- border-collapse: collapse;
- cursor: pointer;
- height: 25px;
+ width: 14.2857142%;
+ background: #f5f5f5;
+ border: 1px solid #ddd;
+ color: #666;
+ font-size: 12px;
+ text-align: right;
+ vertical-align: middle;
+ padding: 0;
+ border-collapse: collapse;
+ cursor: pointer;
+ height: 25px;
}
.xdsoft_datetimepicker.xdsoft_showweeks .xdsoft_calendar td,.xdsoft_datetimepicker.xdsoft_showweeks .xdsoft_calendar th {
- width: 12.5%;
+ width: 12.5%;
}
.xdsoft_datetimepicker .xdsoft_calendar th {
- background: #f1f1f1;
+ background: #f1f1f1;
}
.xdsoft_datetimepicker .xdsoft_calendar td.xdsoft_today {
- color: #33aaff;
+ color: #33aaff;
}
.xdsoft_datetimepicker .xdsoft_calendar td.xdsoft_highlighted_default {
- background: #ffe9d2;
- box-shadow: #ffb871 0 1px 4px 0 inset;
- color: #000;
+ background: #ffe9d2;
+ box-shadow: #ffb871 0 1px 4px 0 inset;
+ color: #000;
}
.xdsoft_datetimepicker .xdsoft_calendar td.xdsoft_highlighted_mint {
- background: #c1ffc9;
- box-shadow: #00dd1c 0 1px 4px 0 inset;
- color: #000;
+ background: #c1ffc9;
+ box-shadow: #00dd1c 0 1px 4px 0 inset;
+ color: #000;
}
.xdsoft_datetimepicker .xdsoft_calendar td.xdsoft_default,
.xdsoft_datetimepicker .xdsoft_calendar td.xdsoft_current,
.xdsoft_datetimepicker .xdsoft_timepicker .xdsoft_time_box >div >div.xdsoft_current {
- background: #33aaff;
- box-shadow: #178fe5 0 1px 3px 0 inset;
- color: #fff;
- font-weight: 700;
+ background: #33aaff;
+ box-shadow: #178fe5 0 1px 3px 0 inset;
+ color: #fff;
+ font-weight: 700;
}
.xdsoft_datetimepicker .xdsoft_calendar td.xdsoft_other_month,
.xdsoft_datetimepicker .xdsoft_calendar td.xdsoft_disabled,
.xdsoft_datetimepicker .xdsoft_time_box >div >div.xdsoft_disabled {
- opacity: 0.5;
- -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
- cursor: default;
+ opacity: 0.5;
+ -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
+ cursor: default;
}
.xdsoft_datetimepicker .xdsoft_calendar td.xdsoft_other_month.xdsoft_disabled {
- opacity: 0.2;
- -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=20)";
+ opacity: 0.2;
+ -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=20)";
}
.xdsoft_datetimepicker .xdsoft_calendar td:hover,
.xdsoft_datetimepicker .xdsoft_timepicker .xdsoft_time_box >div >div:hover {
- color: #fff !important;
- background: #ff8000 !important;
- box-shadow: none !important;
+ color: #fff !important;
+ background: #ff8000 !important;
+ box-shadow: none !important;
}
.xdsoft_datetimepicker .xdsoft_calendar td.xdsoft_current.xdsoft_disabled:hover,
.xdsoft_datetimepicker .xdsoft_timepicker .xdsoft_time_box>div>div.xdsoft_current.xdsoft_disabled:hover {
- background: #33aaff !important;
- box-shadow: #178fe5 0 1px 3px 0 inset !important;
- color: #fff !important;
+ background: #33aaff !important;
+ box-shadow: #178fe5 0 1px 3px 0 inset !important;
+ color: #fff !important;
}
.xdsoft_datetimepicker .xdsoft_calendar td.xdsoft_disabled:hover,
.xdsoft_datetimepicker .xdsoft_timepicker .xdsoft_time_box >div >div.xdsoft_disabled:hover {
- color: inherit !important;
- background: inherit !important;
- box-shadow: inherit !important;
+ color: inherit !important;
+ background: inherit !important;
+ box-shadow: inherit !important;
}
.xdsoft_datetimepicker .xdsoft_calendar th {
- font-weight: 700;
- text-align: center;
- color: #999;
- cursor: default;
+ font-weight: 700;
+ text-align: center;
+ color: #999;
+ cursor: default;
}
.xdsoft_datetimepicker .xdsoft_copyright {
- color: #ccc !important;
- font-size: 10px;
- clear: both;
- float: none;
- margin-left: 8px;
+ color: #ccc !important;
+ font-size: 10px;
+ clear: both;
+ float: none;
+ margin-left: 8px;
}
.xdsoft_datetimepicker .xdsoft_copyright a { color: #eee !important }
.xdsoft_datetimepicker .xdsoft_copyright a:hover { color: #aaa !important }
.xdsoft_time_box {
- position: relative;
- border: 1px solid #ccc;
+ position: relative;
+ border: 1px solid #ccc;
}
.xdsoft_scrollbar >.xdsoft_scroller {
- background: #ccc !important;
- height: 20px;
- border-radius: 3px;
+ background: #ccc !important;
+ height: 20px;
+ border-radius: 3px;
}
.xdsoft_scrollbar {
- position: absolute;
- width: 7px;
- right: 0;
- top: 0;
- bottom: 0;
- cursor: pointer;
+ position: absolute;
+ width: 7px;
+ right: 0;
+ top: 0;
+ bottom: 0;
+ cursor: pointer;
}
.xdsoft_datetimepicker.xdsoft_rtl .xdsoft_scrollbar {
- left: 0;
- right: auto;
+ left: 0;
+ right: auto;
}
.xdsoft_scroller_box {
- position: relative;
+ position: relative;
}
.xdsoft_datetimepicker.xdsoft_dark {
- box-shadow: 0 5px 15px -5px rgba(255, 255, 255, 0.506);
- background: #000;
- border-bottom: 1px solid #444;
- border-left: 1px solid #333;
- border-right: 1px solid #333;
- border-top: 1px solid #333;
- color: #ccc;
+ box-shadow: 0 5px 15px -5px rgba(255, 255, 255, 0.506);
+ background: #000;
+ border-bottom: 1px solid #444;
+ border-left: 1px solid #333;
+ border-right: 1px solid #333;
+ border-top: 1px solid #333;
+ color: #ccc;
}
.xdsoft_datetimepicker.xdsoft_dark .xdsoft_timepicker .xdsoft_time_box {
- border-bottom: 1px solid #222;
+ border-bottom: 1px solid #222;
}
.xdsoft_datetimepicker.xdsoft_dark .xdsoft_timepicker .xdsoft_time_box >div >div {
- background: #0a0a0a;
- border-top: 1px solid #222;
- color: #999;
+ background: #0a0a0a;
+ border-top: 1px solid #222;
+ color: #999;
}
.xdsoft_datetimepicker.xdsoft_dark .xdsoft_label {
- background-color: #000;
+ background-color: #000;
}
.xdsoft_datetimepicker.xdsoft_dark .xdsoft_label > .xdsoft_select {
- border: 1px solid #333;
- background: #000;
+ border: 1px solid #333;
+ background: #000;
}
.xdsoft_datetimepicker.xdsoft_dark .xdsoft_label > .xdsoft_select > div > .xdsoft_option:hover {
- color: #000;
- background: #007fff;
+ color: #000;
+ background: #007fff;
}
.xdsoft_datetimepicker.xdsoft_dark .xdsoft_label > .xdsoft_select > div > .xdsoft_option.xdsoft_current {
- background: #cc5500;
- box-shadow: #b03e00 0 1px 3px 0 inset;
- color: #000;
+ background: #cc5500;
+ box-shadow: #b03e00 0 1px 3px 0 inset;
+ color: #000;
}
.xdsoft_datetimepicker.xdsoft_dark .xdsoft_label i,
.xdsoft_datetimepicker.xdsoft_dark .xdsoft_prev,
.xdsoft_datetimepicker.xdsoft_dark .xdsoft_next,
.xdsoft_datetimepicker.xdsoft_dark .xdsoft_today_button {
- background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAAAeCAYAAADaW7vzAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNiAoV2luZG93cykiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6QUExQUUzOTA0M0UyMTFFNDlBM0FFQTJENTExRDVBODYiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6QUExQUUzOTE0M0UyMTFFNDlBM0FFQTJENTExRDVBODYiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDpBQTFBRTM4RTQzRTIxMUU0OUEzQUVBMkQ1MTFENUE4NiIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDpBQTFBRTM4RjQzRTIxMUU0OUEzQUVBMkQ1MTFENUE4NiIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/Pp0VxGEAAAIASURBVHja7JrNSgMxEMebtgh+3MSLr1T1Xn2CHoSKB08+QmR8Bx9A8e7RixdB9CKCoNdexIugxFlJa7rNZneTbLIpM/CnNLsdMvNjM8l0mRCiQ9Ye61IKCAgZAUnH+mU3MMZaHYChBnJUDzWOFZdVfc5+ZFLbrWDeXPwbxIqrLLfaeS0hEBVGIRQCEiZoHQwtlGSByCCdYBl8g8egTTAWoKQMRBRBcZxYlhzhKegqMOageErsCHVkk3hXIFooDgHB1KkHIHVgzKB4ADJQ/A1jAFmAYhkQqA5TOBtocrKrgXwQA8gcFIuAIO8sQSA7hidvPwaQGZSaAYHOUWJABhWWw2EMIH9QagQERU4SArJXo0ZZL18uvaxejXt/Em8xjVBXmvFr1KVm/AJ10tRe2XnraNqaJvKE3KHuUbfK1E+VHB0q40/y3sdQSxY4FHWeKJCunP8UyDdqJZenT3ntVV5jIYCAh20vT7ioP8tpf6E2lfEMwERe+whV1MHjwZB7PBiCxcGQWwKZKD62lfGNnP/1poFAA60T7rF1UgcKd2id3KDeUS+oLWV8DfWAepOfq00CgQabi9zjcgJVYVD7PVzQUAUGAQkbNJTBICDhgwYTjDYD6XeW08ZKh+A4pYkzenOxXUbvZcWz7E8ykRMnIHGX1XPl+1m2vPYpL+2qdb8CDAARlKFEz/ZVkAAAAABJRU5ErkJggg==);
+ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAAAeCAYAAADaW7vzAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNiAoV2luZG93cykiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6QUExQUUzOTA0M0UyMTFFNDlBM0FFQTJENTExRDVBODYiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6QUExQUUzOTE0M0UyMTFFNDlBM0FFQTJENTExRDVBODYiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDpBQTFBRTM4RTQzRTIxMUU0OUEzQUVBMkQ1MTFENUE4NiIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDpBQTFBRTM4RjQzRTIxMUU0OUEzQUVBMkQ1MTFENUE4NiIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/Pp0VxGEAAAIASURBVHja7JrNSgMxEMebtgh+3MSLr1T1Xn2CHoSKB08+QmR8Bx9A8e7RixdB9CKCoNdexIugxFlJa7rNZneTbLIpM/CnNLsdMvNjM8l0mRCiQ9Ye61IKCAgZAUnH+mU3MMZaHYChBnJUDzWOFZdVfc5+ZFLbrWDeXPwbxIqrLLfaeS0hEBVGIRQCEiZoHQwtlGSByCCdYBl8g8egTTAWoKQMRBRBcZxYlhzhKegqMOageErsCHVkk3hXIFooDgHB1KkHIHVgzKB4ADJQ/A1jAFmAYhkQqA5TOBtocrKrgXwQA8gcFIuAIO8sQSA7hidvPwaQGZSaAYHOUWJABhWWw2EMIH9QagQERU4SArJXo0ZZL18uvaxejXt/Em8xjVBXmvFr1KVm/AJ10tRe2XnraNqaJvKE3KHuUbfK1E+VHB0q40/y3sdQSxY4FHWeKJCunP8UyDdqJZenT3ntVV5jIYCAh20vT7ioP8tpf6E2lfEMwERe+whV1MHjwZB7PBiCxcGQWwKZKD62lfGNnP/1poFAA60T7rF1UgcKd2id3KDeUS+oLWV8DfWAepOfq00CgQabi9zjcgJVYVD7PVzQUAUGAQkbNJTBICDhgwYTjDYD6XeW08ZKh+A4pYkzenOxXUbvZcWz7E8ykRMnIHGX1XPl+1m2vPYpL+2qdb8CDAARlKFEz/ZVkAAAAABJRU5ErkJggg==);
}
.xdsoft_datetimepicker.xdsoft_dark .xdsoft_calendar td,
.xdsoft_datetimepicker.xdsoft_dark .xdsoft_calendar th {
- background: #0a0a0a;
- border: 1px solid #222;
- color: #999;
+ background: #0a0a0a;
+ border: 1px solid #222;
+ color: #999;
}
.xdsoft_datetimepicker.xdsoft_dark .xdsoft_calendar th {
- background: #0e0e0e;
+ background: #0e0e0e;
}
.xdsoft_datetimepicker.xdsoft_dark .xdsoft_calendar td.xdsoft_today {
- color: #cc5500;
+ color: #cc5500;
}
.xdsoft_datetimepicker.xdsoft_dark .xdsoft_calendar td.xdsoft_highlighted_default {
- background: #ffe9d2;
- box-shadow: #ffb871 0 1px 4px 0 inset;
- color:#000;
+ background: #ffe9d2;
+ box-shadow: #ffb871 0 1px 4px 0 inset;
+ color:#000;
}
.xdsoft_datetimepicker.xdsoft_dark .xdsoft_calendar td.xdsoft_highlighted_mint {
- background: #c1ffc9;
- box-shadow: #00dd1c 0 1px 4px 0 inset;
- color:#000;
+ background: #c1ffc9;
+ box-shadow: #00dd1c 0 1px 4px 0 inset;
+ color:#000;
}
.xdsoft_datetimepicker.xdsoft_dark .xdsoft_calendar td.xdsoft_default,
.xdsoft_datetimepicker.xdsoft_dark .xdsoft_calendar td.xdsoft_current,
.xdsoft_datetimepicker.xdsoft_dark .xdsoft_timepicker .xdsoft_time_box >div >div.xdsoft_current {
- background: #cc5500;
- box-shadow: #b03e00 0 1px 3px 0 inset;
- color: #000;
+ background: #cc5500;
+ box-shadow: #b03e00 0 1px 3px 0 inset;
+ color: #000;
}
.xdsoft_datetimepicker.xdsoft_dark .xdsoft_calendar td:hover,
.xdsoft_datetimepicker.xdsoft_dark .xdsoft_timepicker .xdsoft_time_box >div >div:hover {
- color: #000 !important;
- background: #007fff !important;
+ color: #000 !important;
+ background: #007fff !important;
}
.xdsoft_datetimepicker.xdsoft_dark .xdsoft_calendar th {
- color: #666;
+ color: #666;
}
.xdsoft_datetimepicker.xdsoft_dark .xdsoft_copyright { color: #333 !important }
@@ -511,11 +511,11 @@
.xdsoft_datetimepicker.xdsoft_dark .xdsoft_copyright a:hover { color: #555 !important }
.xdsoft_dark .xdsoft_time_box {
- border: 1px solid #333;
+ border: 1px solid #333;
}
.xdsoft_dark .xdsoft_scrollbar >.xdsoft_scroller {
- background: #333 !important;
+ background: #333 !important;
}
.xdsoft_datetimepicker .xdsoft_save_selected {
display: block;
@@ -526,27 +526,27 @@
font-size: 13px;
}
.xdsoft_datetimepicker .blue-gradient-button {
- font-family: "museo-sans", "Book Antiqua", sans-serif;
- font-size: 12px;
- font-weight: 300;
- color: #82878c;
- height: 28px;
- position: relative;
- padding: 4px 17px 4px 33px;
- border: 1px solid #d7d8da;
- background: -moz-linear-gradient(top, #fff 0%, #f4f8fa 73%);
- /* FF3.6+ */
- background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #fff), color-stop(73%, #f4f8fa));
- /* Chrome,Safari4+ */
- background: -webkit-linear-gradient(top, #fff 0%, #f4f8fa 73%);
- /* Chrome10+,Safari5.1+ */
- background: -o-linear-gradient(top, #fff 0%, #f4f8fa 73%);
- /* Opera 11.10+ */
- background: -ms-linear-gradient(top, #fff 0%, #f4f8fa 73%);
- /* IE10+ */
- background: linear-gradient(to bottom, #fff 0%, #f4f8fa 73%);
- /* W3C */
- filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fff', endColorstr='#f4f8fa',GradientType=0 );
+ font-family: "museo-sans", "Book Antiqua", sans-serif;
+ font-size: 12px;
+ font-weight: 300;
+ color: #82878c;
+ height: 28px;
+ position: relative;
+ padding: 4px 17px 4px 33px;
+ border: 1px solid #d7d8da;
+ background: -moz-linear-gradient(top, #fff 0%, #f4f8fa 73%);
+ /* FF3.6+ */
+ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #fff), color-stop(73%, #f4f8fa));
+ /* Chrome,Safari4+ */
+ background: -webkit-linear-gradient(top, #fff 0%, #f4f8fa 73%);
+ /* Chrome10+,Safari5.1+ */
+ background: -o-linear-gradient(top, #fff 0%, #f4f8fa 73%);
+ /* Opera 11.10+ */
+ background: -ms-linear-gradient(top, #fff 0%, #f4f8fa 73%);
+ /* IE10+ */
+ background: linear-gradient(to bottom, #fff 0%, #f4f8fa 73%);
+ /* W3C */
+ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fff', endColorstr='#f4f8fa',GradientType=0 );
/* IE6-9 */
}
.xdsoft_datetimepicker .blue-gradient-button:hover, .xdsoft_datetimepicker .blue-gradient-button:focus, .xdsoft_datetimepicker .blue-gradient-button:hover span, .xdsoft_datetimepicker .blue-gradient-button:focus span {
diff --git a/template/acp/css/style.css b/template/acp/css/style.css
index 9319cc2..a7914a3 100644
--- a/template/acp/css/style.css
+++ b/template/acp/css/style.css
@@ -24,7 +24,7 @@
}
*
{
- padding: 0;
+ padding: 0;
margin: 0;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
@@ -34,46 +34,46 @@
}
html
{
- background-color: #252b30;
+ background-color: #252b30;
}
body, header, main, footer
{
- width: 1200px;
+ width: 1200px;
}
main
{
- display: flex
+ display: flex
}
html, body, main, .content, .sidebar, .sidebar-second, .height-max
{
- height: 100%;
- font: 13px Cuprum;
+ height: 100%;
+ font: 13px Cuprum;
}
body
{
- margin: 0 auto
+ margin: 0 auto
}
main, header
{
- margin: 0 auto;
+ margin: 0 auto;
}
main
{
- display: table-cell;
+ display: table-cell;
background-color: #eef0f2;
}
header
{
- height: 43px;
+ height: 43px;
}
a
{
- text-decoration: underline;
- color: #222;
+ text-decoration: underline;
+ color: #222;
}
a:hover
{
- text-decoration: none;
+ text-decoration: none;
}
input::-webkit-input-placeholder {color: #d1d1d1; text-overflow: ellipsis; text-indent: 0px; transition: text-indent 0.3s ease;}
input::-moz-placeholder {color: #d1d1d1; text-overflow: ellipsis; text-indent: 0px; transition: text-indent 0.3s ease;}
@@ -90,78 +90,78 @@ textarea:-ms-input-placeholder {color: #d1d1d1;}
.sidebar, .sidebar-second, .content
{
- padding: 5px;
- float: left;
+ padding: 5px;
+ float: left;
}
.sidebar, .sidebar-second
{
- width: 200px;
+ width: 200px;
}
.content
{
- width: 1000px;
+ width: 1000px;
}
.content-mini
{
- width: 800px;
+ width: 800px;
}
.main
{
- margin: 5px;
+ margin: 5px;
}
.bg-gray
{
- background-color: #2e3439;
- color: #8e9ca8;
+ background-color: #2e3439;
+ color: #8e9ca8;
}
.bg-gray-mild
{
- background-color: #3f464c;
+ background-color: #3f464c;
}
.bg-white
{
- background-color: #ffffff;
+ background-color: #ffffff;
}
.bg-green
{
- background-color: #00c09e;
+ background-color: #00c09e;
}
.br-gray-top
{
- border-top: 1px solid #282e33;
+ border-top: 1px solid #282e33;
}
.br-gray-bot
{
- border-bottom: 1px solid #282e33;
+ border-bottom: 1px solid #282e33;
}
.hr-gray, .hr-white
{
- margin: 15px 0;
- width: 100%;
- height: 1px;
+ margin: 15px 0;
+ width: 100%;
+ height: 1px;
}
.hr-gray
{
- background-color: #282e33;
+ background-color: #282e33;
}
.hr-white
{
- background-color: #f3f4f7;
+ background-color: #f3f4f7;
}
.sidebar > h3
{
- font-size: 15px;
+ font-size: 15px;
text-align: center;
line-height: 33px;
}
.sidebar > h5, .sidebar-second > h5
{
- padding: 5px 10px;
+ padding: 5px 10px;
font-size: 11px;
}
.sidebar > ul li, .sidebar-second > ul li
{
- list-style: none;
+ list-style: none;
}
.sidebar > ul li a
{
@@ -174,17 +174,17 @@ textarea:-ms-input-placeholder {color: #d1d1d1;}
.sidebar > ul li a:hover
{
background-color: #293035;
- color: #c1d6e3;
+ color: #c1d6e3;
}
.sidebar > ul li a:active, .sidebar .active
{
background-color: #252b30;
- color: #c1d6e3;
+ color: #c1d6e3;
}
.sidebar > ul li a i
{
- font-size: 14px;
- width: 22px;
+ font-size: 14px;
+ width: 22px;
}
.sidebar-second > h3
{
@@ -196,8 +196,8 @@ textarea:-ms-input-placeholder {color: #d1d1d1;}
}
.sidebar-second > h3 i
{
- font-size: 14px;
- float: left;
+ font-size: 14px;
+ float: left;
margin-top: 8px;
}
.sidebar-second > ul li a
@@ -211,21 +211,21 @@ textarea:-ms-input-placeholder {color: #d1d1d1;}
.sidebar-second > ul li a:hover
{
background-color: #fafbfc;
- color: #78858f;
+ color: #78858f;
}
.sidebar-second > ul li a:active, .sidebar-second .active
{
background-color: #f3f4f7;
- color: #78858f;
+ color: #78858f;
}
.sidebar-second > ul li a i
{
- font-size: 14px;
- width: 22px;
+ font-size: 14px;
+ width: 22px;
}
.sidebar-second > ul li a span
{
- float: right;
+ float: right;
font-size: 10px;
background-color: #EEE;
padding: 2px 5px;
@@ -233,14 +233,14 @@ textarea:-ms-input-placeholder {color: #d1d1d1;}
}
.sidebar-second > h5
{
- font-size: 14px;
+ font-size: 14px;
color: #7e8890;
}
header > .content a
{
color: #7b8893;
background-color: #2e3439;
- padding: 5px 7px;
+ padding: 5px 7px;
font-size: 14px;
text-decoration: none;
border-radius: 2px;
@@ -248,7 +248,7 @@ header > .content a
}
header > .content a:hover
{
- color: #abb7bf;
+ color: #abb7bf;
background-color: #2b3135;
}
header .fl-right
@@ -273,13 +273,13 @@ header .fl-left
}
.inputs textarea
{
- resize: vertical;
+ resize: vertical;
width: 100%;
}
.inputs-max input[type="text"], .inputs-max select
{
- width: 100%;
+ width: 100%;
}
label
@@ -290,7 +290,7 @@ label
border-radius: 10px;
border: 1px solid #EEE;
background-color: #FAFAFA;
- margin-right: 5px;
+ margin-right: 5px;
}
label input
@@ -305,7 +305,7 @@ table
width: 100%;
background-color: #ffffff;
box-shadow: 1px 1px 10px #e0e0e0;
- border-collapse: collapse;
+ border-collapse: collapse;
}
table th
@@ -320,16 +320,16 @@ table th span
}
table td
{
- color: #000;
+ color: #000;
}
table th, table td
{
- padding: 8px;
+ padding: 8px;
}
table tr:nth-child(even) td
{
- background-color: #f7f8f8;
+ background-color: #f7f8f8;
}
table a
@@ -339,12 +339,12 @@ table a
.trh tr:hover td
{
- background-color: #f9fae5;
+ background-color: #f9fae5;
}
.search
{
- width: 300px;
+ width: 300px;
float: right;
margin-bottom: 10px;
}
@@ -353,7 +353,7 @@ table a
padding: 5px;
width: 300px;
font-size: 12px;
- color: #000;
+ color: #000;
background-color: #fff;
border: 1px solid #dedede;
outline: 0;
@@ -374,94 +374,94 @@ table a
height: 24px;
margin: -25px 0 0 274px;
overflow: hidden;
- line-height: 24px;
+ line-height: 24px;
text-overflow: ellipsis;
- transition: all 0.23s ease-in-out;
+ transition: all 0.23s ease-in-out;
-moz-transition: all 0.23s ease-in-out;
-webkit-transition: all 0.23s ease-in-out;
-o-transition: all 0.23s ease-in-out;
}
.search button:hover
{
- width: 70px;
- margin-left: 229px;
+ width: 70px;
+ margin-left: 229px;
}
.w5p
{
- width: 5% !important;
+ width: 5% !important;
}
.w10p
{
- width: 10% !important;
+ width: 10% !important;
}
.w15p
{
- width: 15% !important;
+ width: 15% !important;
}
.w20p
{
- width: 20% !important;
+ width: 20% !important;
}
.w25p
{
- width: 25% !important;
+ width: 25% !important;
}
.w35p
{
- width: 35% !important;
+ width: 35% !important;
}
.w50p
{
- width: 50% !important;
+ width: 50% !important;
}
.left
{
- float: left;
+ float: left;
}
.right
{
- float: right;
+ float: right;
}
.text-left
{
- text-align: left;
+ text-align: left;
}
.text-center
{
- text-align: center;
+ text-align: center;
}
.text-right
{
- text-align: right;
+ text-align: right;
}
.text-red
{
- color: #bd2727;
+ color: #bd2727;
}
.text-green
{
- color: #27bd32;
+ color: #27bd32;
}
.vtop
{
- vertical-align: top;
+ vertical-align: top;
}
.space
{
- clear: both;
- margin-top: 15px;
+ clear: both;
+ margin-top: 15px;
}
.informer
{
- margin-bottom: 10px;
+ margin-bottom: 10px;
border-left: 5px solid #29a3f2;
padding: 5px;
font-size: 14px;
@@ -472,12 +472,12 @@ table a
.informer.green
{
- border-color: #28b727;
+ border-color: #28b727;
}
.informer.red
{
- border-color: #f22929;
+ border-color: #f22929;
}
.pages
@@ -492,7 +492,7 @@ table a
}
.pages > i
{
- margin: 0 2px;
+ margin: 0 2px;
}
.pages a
{
@@ -508,13 +508,13 @@ table a
}
.pages a:hover, .pages a.active
{
- background-color: #252b30;
- color: #c1d6e3;
+ background-color: #252b30;
+ color: #c1d6e3;
}
#search_error
{
- display: none;
+ display: none;
width: 100%;
background-color: #dadde0;
padding: 10px;
@@ -578,21 +578,21 @@ table a
.p_info p
{
- padding: 5px;
- border-bottom: 1px dotted #EEE;
+ padding: 5px;
+ border-bottom: 1px dotted #EEE;
}
.pointer
{
- cursor: pointer;
+ cursor: pointer;
}
.none
{
- display: none;
+ display: none;
}
.btn
{
- font-size: 12px;
+ font-size: 12px;
padding: 5px;
background-color: #2e3439;
border: 1px solid #3f464c;
@@ -603,42 +603,42 @@ table a
.btn:hover
{
- color: #abb7bf;
+ color: #abb7bf;
background-color: #2b3135;
}
.btn-green
{
- background-color: #41d192;
+ background-color: #41d192;
border: 1px solid #55ac5e;
- color: #ffffff;
+ color: #ffffff;
}
.btn-green:hover
{
- background-color: #37da92;
- border: 1px solid #55ac5e;
- color: #ffffff;
+ background-color: #37da92;
+ border: 1px solid #55ac5e;
+ color: #ffffff;
}
.btn-red
{
background-color: #d14141;
border: 1px solid #ac5555;
- color: #ffffff;
+ color: #ffffff;
}
.btn-red:hover
{
background-color: #da1010;
- border: 1px solid #ac5555;
- color: #ffffff;
+ border: 1px solid #ac5555;
+ color: #ffffff;
}
.double-color td
{
- background-color: #ffffff !important;
+ background-color: #ffffff !important;
}
.double-color tr:nth-child(2n) td
{
- border-bottom: 2px solid #3f464c;
+ border-bottom: 2px solid #3f464c;
}
\ No newline at end of file
diff --git a/template/acp/js/addons.js b/template/acp/js/addons.js
index 4a0921a..5261338 100644
--- a/template/acp/js/addons.js
+++ b/template/acp/js/addons.js
@@ -1,233 +1,233 @@
$('#addons').ajaxForm({
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- bootbox.dialog('Ошибка '+val,
- [{
- "label" : "Продолжить"
- }]
- );
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ bootbox.dialog('Ошибка '+val,
+ [{
+ "label" : "Продолжить"
+ }]
+ );
- if(i == 's')
- location.reload();
- });
+ if(i == 's')
+ location.reload();
+ });
- loading(0)
- }
+ loading(0)
+ }
});
function maps_reset_game()
{
- $('#game').prop('selectedIndex', 0);
+ $('#game').prop('selectedIndex', 0);
}
function maps_list()
{
- $.get(home+'addons/section/updmp/get/list/unit/'+$('#unit').val()+'/game/'+$('#game').val(),
- function(data)
- {
- $('#maps').val(data);
- });
+ $.get(home+'addons/section/updmp/get/list/unit/'+$('#unit').val()+'/game/'+$('#game').val(),
+ function(data)
+ {
+ $('#maps').val(data);
+ });
- return false;
+ return false;
}
function maps_update()
{
- loading(1);
+ loading(1);
- $.get(home+'addons/section/updmp/unit/'+$('#unit').val()+'/game/'+$('#game').val()+'/go',
- function(data)
- {
- location.reload();
- });
+ $.get(home+'addons/section/updmp/unit/'+$('#unit').val()+'/game/'+$('#game').val()+'/go',
+ function(data)
+ {
+ location.reload();
+ });
- return false;
+ return false;
}
function plugins_category()
{
- $.get(home+'addons/section/addpl/get/cat/game/'+$('#game').val(),
- function(data)
- {
- $('#category').html('Выберете категорию '+data);
- });
+ $.get(home+'addons/section/addpl/get/cat/game/'+$('#game').val(),
+ function(data)
+ {
+ $('#category').html('Выберете категорию '+data);
+ });
- return false;
+ return false;
}
function plugins_update_del(id)
{
- bootbox.dialog('Внимание Вы уверены, что хотите удалить обновление плагина?',
- [{
- "label" : "Удалить",
- callback : function(){plugins_update_del_go(id)}
- },{
- "label" : "Отмена",
- }]
- );
+ bootbox.dialog('Внимание Вы уверены, что хотите удалить обновление плагина?',
+ [{
+ "label" : "Удалить",
+ callback : function(){plugins_update_del_go(id)}
+ },{
+ "label" : "Отмена",
+ }]
+ );
- return false;
+ return false;
}
function plugins_update_del_go(id)
{
- $.get(home+'addons/section/delete/type/update/id/'+id,
- function(data)
- {
- location.reload();
- });
+ $.get(home+'addons/section/delete/type/update/id/'+id,
+ function(data)
+ {
+ location.reload();
+ });
}
function cats_delete(id)
{
- $.get(home+'addons/section/delete/type/cat/id/'+id,
- function(data)
- {
- location.reload();
- });
+ $.get(home+'addons/section/delete/type/cat/id/'+id,
+ function(data)
+ {
+ location.reload();
+ });
- return false;
+ return false;
}
function plugins_sort(sort)
{
- switch(sort)
- {
- case 'id':
- if(sort_id == 'asc')
- sort_id = 'desc';
- else
- sort_id = 'asc';
+ switch(sort)
+ {
+ case 'id':
+ if(sort_id == 'asc')
+ sort_id = 'desc';
+ else
+ sort_id = 'asc';
- sorting = sort_id;
+ sorting = sort_id;
- break;
+ break;
- case 'cat':
- sort_cat = sort_cat == 'asc' ? 'desc' : 'asc';
- sorting = sort_cat;
+ case 'cat':
+ sort_cat = sort_cat == 'asc' ? 'desc' : 'asc';
+ sorting = sort_cat;
- break;
+ break;
- case 'game':
- sort_game = sort_game == 'asc' ? 'desc' : 'asc';
- sorting = sort_game;
+ case 'game':
+ sort_game = sort_game == 'asc' ? 'desc' : 'asc';
+ sorting = sort_game;
- }
+ }
- location.href=home+'addons/sort/'+sort+'/sorting/'+sorting;
+ location.href=home+'addons/sort/'+sort+'/sorting/'+sorting;
}
function plugins_search(go)
{
- if($('#search').val() == '')
- {
- $('#search_error').css('display', 'none');
+ if($('#search').val() == '')
+ {
+ $('#search_error').css('display', 'none');
- return;
- }
+ return;
+ }
- loading(1);
+ loading(1);
- if(go) go = '/go'; else go = '';
+ if(go) go = '/go'; else go = '';
- $.ajax({
- type: 'POST',
- url: home+'addons/subsection/search'+go,
- data: 'text='+$('#search').val(),
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- {
- if(val != '')
- {
- $('#search_error').css('display', 'inline-block');
- $('#search_error').html(val);
- }else
- $('#search_error').css('display', 'none');
- }
+ $.ajax({
+ type: 'POST',
+ url: home+'addons/subsection/search'+go,
+ data: 'text='+$('#search').val(),
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ {
+ if(val != '')
+ {
+ $('#search_error').css('display', 'inline-block');
+ $('#search_error').html(val);
+ }else
+ $('#search_error').css('display', 'none');
+ }
- if(i == 's')
- {
- $('#search_error').css('display', 'none');
- $('#search_result').html(val);
- }
- });
+ if(i == 's')
+ {
+ $('#search_error').css('display', 'none');
+ $('#search_result').html(val);
+ }
+ });
- loading(0);
- }
- });
+ loading(0);
+ }
+ });
}
function plugins_delete(id)
{
- bootbox.dialog('Внимание Вы уверены, что хотите удалить плагин?',
- [{
- "label" : "Удалить",
- callback : function(){plugins_delete_go(id)}
- },{
- "label" : "Отмена",
- }]
- );
+ bootbox.dialog('Внимание Вы уверены, что хотите удалить плагин?',
+ [{
+ "label" : "Удалить",
+ callback : function(){plugins_delete_go(id)}
+ },{
+ "label" : "Отмена",
+ }]
+ );
- return false;
+ return false;
}
function plugins_delete_go(id)
{
- loading(1);
+ loading(1);
- $.ajax({
- type: 'POST',
- url: home+'addons/section/delete/type/plugin/id/'+id,
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- bootbox.dialog('Ошибка '+val,
- [{
- "label" : "Продолжить"
- }]
- );
+ $.ajax({
+ type: 'POST',
+ url: home+'addons/section/delete/type/plugin/id/'+id,
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ bootbox.dialog('Ошибка '+val,
+ [{
+ "label" : "Продолжить"
+ }]
+ );
- if(i == 's')
- location.reload()
- });
+ if(i == 's')
+ location.reload()
+ });
- loading(0);
- }
- });
+ loading(0);
+ }
+ });
}
function add_plugin_type()
{
- if($("#update").val() == 0)
- {
- $('#new_plugin').css('display', 'table-row');
- $('#upd_plugin').css('display', 'none');
- }else{
- $('#new_plugin').css('display', 'none');
- $('#upd_plugin').css('display', 'table-row');
- }
+ if($("#update").val() == 0)
+ {
+ $('#new_plugin').css('display', 'table-row');
+ $('#upd_plugin').css('display', 'none');
+ }else{
+ $('#new_plugin').css('display', 'none');
+ $('#upd_plugin').css('display', 'table-row');
+ }
}
function config_files_form()
{
- if(!$("#cfa").prop('checked'))
- $('#config_files_form').css('display', 'table');
- else{
- $('#config_files_form').css('display', 'none');
- $('#config_files_all').html('');
- }
+ if(!$("#cfa").prop('checked'))
+ $('#config_files_form').css('display', 'table');
+ else{
+ $('#config_files_form').css('display', 'none');
+ $('#config_files_all').html('');
+ }
}
var cf = 999999;
@@ -238,92 +238,92 @@ var fd = 999999;
function config_files_add()
{
- cf += 1;
+ cf += 1;
- $('#config_files_all').append(''
- +' '
- +' '
- +'Удалить '
- +' ');
+ $('#config_files_all').append(''
+ +' '
+ +' '
+ +'Удалить '
+ +' ');
}
function config_clear_add()
{
- cc += 1;
+ cc += 1;
- $('#config_clear_all').append(''
- +' '
- +' '
- +' '
- +'Удалить '
- +' ');
+ $('#config_clear_all').append(''
+ +' '
+ +' '
+ +' '
+ +'Удалить '
+ +' ');
}
function config_write_add()
{
- cw += 1;
+ cw += 1;
- $('#config_write_all').append(''
- +' '
- +' '
- +' '
- +'Удалить '
- +' ');
+ $('#config_write_all').append(''
+ +' '
+ +' '
+ +' '
+ +'Удалить '
+ +' ');
}
function config_write_del_add()
{
- cwe += 1;
+ cwe += 1;
- $('#config_write_del_all').append(''
- +' '
- +' '
- +' '
- +'Удалить '
- +' ');
+ $('#config_write_del_all').append(''
+ +' '
+ +' '
+ +' '
+ +'Удалить '
+ +' ');
}
function files_delete_add()
{
- fd += 1;
+ fd += 1;
- $('#files_delete_all').append(''
- +' '
- +'Удалить '
- +' ');
+ $('#files_delete_all').append(''
+ +' '
+ +'Удалить '
+ +' ');
}
function config_files_del(id)
{
- $('#cf_'+id).empty();
+ $('#cf_'+id).empty();
- return false;
+ return false;
}
function config_clear_del(id)
{
- $('#cc_'+id).empty();
+ $('#cc_'+id).empty();
- return false;
+ return false;
}
function config_write_del(id)
{
- $('#cw_'+id).empty();
+ $('#cw_'+id).empty();
- return false;
+ return false;
}
function config_write_del_del(id)
{
- $('#cwe_'+id).empty();
+ $('#cwe_'+id).empty();
- return false;
+ return false;
}
function files_delete_del(id)
{
- $('#fd_'+id).empty();
+ $('#fd_'+id).empty();
- return false;
+ return false;
}
\ No newline at end of file
diff --git a/template/acp/js/control.js b/template/acp/js/control.js
index b273644..2014397 100644
--- a/template/acp/js/control.js
+++ b/template/acp/js/control.js
@@ -1,196 +1,196 @@
$('#control').ajaxForm({
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- bootbox.dialog('Ошибка '+val,
- [{
- "label" : "Продолжить"
- }]
- );
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ bootbox.dialog('Ошибка '+val,
+ [{
+ "label" : "Продолжить"
+ }]
+ );
- if(i == 's')
- location.reload();
- });
+ if(i == 's')
+ location.reload();
+ });
- loading(0)
- }
+ loading(0)
+ }
});
function control_search(go)
{
- if($('#search').val() == '')
- {
- $('#search_error').css('display', 'none');
+ if($('#search').val() == '')
+ {
+ $('#search_error').css('display', 'none');
- return;
- }
+ return;
+ }
- loading(1);
+ loading(1);
- if(go) go = '/go'; else go = '';
+ if(go) go = '/go'; else go = '';
- $.ajax({
- type: 'POST',
- url: home+'control/subsection/search'+url_search+go,
- data: 'text='+$('#search').val(),
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- {
- if(val != '')
- {
- $('#search_error').css('display', 'inline-block');
- $('#search_error').html(val);
- }else
- $('#search_error').css('display', 'none');
- }
+ $.ajax({
+ type: 'POST',
+ url: home+'control/subsection/search'+url_search+go,
+ data: 'text='+$('#search').val(),
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ {
+ if(val != '')
+ {
+ $('#search_error').css('display', 'inline-block');
+ $('#search_error').html(val);
+ }else
+ $('#search_error').css('display', 'none');
+ }
- if(i == 's')
- {
- $('#search_error').css('display', 'none');
- $('#search_result').html(val);
- }
+ if(i == 's')
+ {
+ $('#search_error').css('display', 'none');
+ $('#search_result').html(val);
+ }
- if(i == 'url')
- url_search = val;
- });
+ if(i == 'url')
+ url_search = val;
+ });
- loading(0);
- }
- });
+ loading(0);
+ }
+ });
}
function control_overdue(id, time)
{
- bootbox.dialog('Установка даты:
',
- [{
- "label" : "Установить",
- callback : function(){control_overdue_go(id)}
- },{
- "label" : "Отмена",
- }]
- );
+ bootbox.dialog('Установка даты:
',
+ [{
+ "label" : "Установить",
+ callback : function(){control_overdue_go(id)}
+ },{
+ "label" : "Отмена",
+ }]
+ );
- return false;
+ return false;
}
function control_block(id, time)
{
- bootbox.dialog('Установка даты:
',
- [{
- "label" : "Заблокировать",
- callback : function(){control_block_go(id)}
- },{
- "label" : "Отмена",
- }]
- );
+ bootbox.dialog('Установка даты:
',
+ [{
+ "label" : "Заблокировать",
+ callback : function(){control_block_go(id)}
+ },{
+ "label" : "Отмена",
+ }]
+ );
- return false;
+ return false;
}
function datepick(input, time)
{
- if($('#'+input).val() != '')
- time = $('#'+input).val();
+ if($('#'+input).val() != '')
+ time = $('#'+input).val();
- $('#'+input).datetimepicker({value: time, format: 'd/m/Y H:i'});
+ $('#'+input).datetimepicker({value: time, format: 'd/m/Y H:i'});
}
function control_overdue_go(id)
{
- $.ajax({
- type: 'POST',
- url: home+'control/type/overdue/id/'+id+'/go',
- data: 'time='+$('#date_overdue').val(),
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- bootbox.dialog('Ошибка '+val,
- [{
- "label" : "Продолжить"
- }]
- );
+ $.ajax({
+ type: 'POST',
+ url: home+'control/type/overdue/id/'+id+'/go',
+ data: 'time='+$('#date_overdue').val(),
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ bootbox.dialog('Ошибка '+val,
+ [{
+ "label" : "Продолжить"
+ }]
+ );
- if(i == 's')
- location.reload();
- });
- }
- });
+ if(i == 's')
+ location.reload();
+ });
+ }
+ });
}
function control_block_go(id)
{
- $.ajax({
- type: 'POST',
- url: home+'control/type/block/id/'+id+'/go',
- data: 'time='+$('#date_block').val(),
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- bootbox.dialog('Ошибка '+val,
- [{
- "label" : "Продолжить"
- }]
- );
+ $.ajax({
+ type: 'POST',
+ url: home+'control/type/block/id/'+id+'/go',
+ data: 'time='+$('#date_block').val(),
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ bootbox.dialog('Ошибка '+val,
+ [{
+ "label" : "Продолжить"
+ }]
+ );
- if(i == 's')
- location.reload();
- });
- }
- });
+ if(i == 's')
+ location.reload();
+ });
+ }
+ });
}
function control_delete(id)
{
- bootbox.dialog('Внимание Вы уверены, что хотите удалить подключенный сервер?',
- [{
- "label" : "Удалить",
- callback : function(){control_delete_go(id)}
- },{
- "label" : "Отмена",
- }]
- );
+ bootbox.dialog('Внимание Вы уверены, что хотите удалить подключенный сервер?',
+ [{
+ "label" : "Удалить",
+ callback : function(){control_delete_go(id)}
+ },{
+ "label" : "Отмена",
+ }]
+ );
- return false;
+ return false;
}
function control_delete_go(id)
{
-
- loading(1);
+
+ loading(1);
- $.ajax({
- type: 'POST',
- url: home+'control/section/delete/id/'+id,
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- bootbox.dialog('Ошибка '+val,
- [{
- "label" : "Продолжить"
- }]
- );
+ $.ajax({
+ type: 'POST',
+ url: home+'control/section/delete/id/'+id,
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ bootbox.dialog('Ошибка '+val,
+ [{
+ "label" : "Продолжить"
+ }]
+ );
- if(i == 's')
- location.reload()
- });
+ if(i == 's')
+ location.reload()
+ });
- loading(0);
- }
- });
+ loading(0);
+ }
+ });
}
\ No newline at end of file
diff --git a/template/acp/js/date/jquery.datetimepicker.full.js b/template/acp/js/date/jquery.datetimepicker.full.js
index ebed876..3ff99cf 100644
--- a/template/acp/js/date/jquery.datetimepicker.full.js
+++ b/template/acp/js/date/jquery.datetimepicker.full.js
@@ -581,1511 +581,1511 @@ var DateFormatter;
*/
/*global DateFormatter, document,window,jQuery,setTimeout,clearTimeout,HighlightedDate,getCurrentValue*/
;(function (factory) {
- if ( typeof define === 'function' && define.amd ) {
- // AMD. Register as an anonymous module.
- define(['jquery', 'jquery-mousewheel'], factory);
- } else if (typeof exports === 'object') {
- // Node/CommonJS style for Browserify
- module.exports = factory;
- } else {
- // Browser globals
- factory(jQuery);
- }
+ if ( typeof define === 'function' && define.amd ) {
+ // AMD. Register as an anonymous module.
+ define(['jquery', 'jquery-mousewheel'], factory);
+ } else if (typeof exports === 'object') {
+ // Node/CommonJS style for Browserify
+ module.exports = factory;
+ } else {
+ // Browser globals
+ factory(jQuery);
+ }
}(function ($) {
- 'use strict';
-
- var currentlyScrollingTimeDiv = false;
-
- var default_options = {
- i18n: {
- ar: { // Arabic
- months: [
- "كانون الثاني", "شباط", "آذار", "نيسان", "مايو", "حزيران", "تموز", "آب", "أيلول", "تشرين الأول", "تشرين الثاني", "كانون الأول"
- ],
- dayOfWeekShort: [
- "ن", "ث", "ع", "خ", "ج", "س", "ح"
- ],
- dayOfWeek: ["الأحد", "الاثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت", "الأحد"]
- },
- ro: { // Romanian
- months: [
- "Ianuarie", "Februarie", "Martie", "Aprilie", "Mai", "Iunie", "Iulie", "August", "Septembrie", "Octombrie", "Noiembrie", "Decembrie"
- ],
- dayOfWeekShort: [
- "Du", "Lu", "Ma", "Mi", "Jo", "Vi", "Sâ"
- ],
- dayOfWeek: ["Duminică", "Luni", "Marţi", "Miercuri", "Joi", "Vineri", "Sâmbătă"]
- },
- id: { // Indonesian
- months: [
- "Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"
- ],
- dayOfWeekShort: [
- "Min", "Sen", "Sel", "Rab", "Kam", "Jum", "Sab"
- ],
- dayOfWeek: ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"]
- },
- is: { // Icelandic
- months: [
- "Janúar", "Febrúar", "Mars", "Apríl", "Maí", "Júní", "Júlí", "Ágúst", "September", "Október", "Nóvember", "Desember"
- ],
- dayOfWeekShort: [
- "Sun", "Mán", "Þrið", "Mið", "Fim", "Fös", "Lau"
- ],
- dayOfWeek: ["Sunnudagur", "Mánudagur", "Þriðjudagur", "Miðvikudagur", "Fimmtudagur", "Föstudagur", "Laugardagur"]
- },
- bg: { // Bulgarian
- months: [
- "Януари", "Февруари", "Март", "Април", "Май", "Юни", "Юли", "Август", "Септември", "Октомври", "Ноември", "Декември"
- ],
- dayOfWeekShort: [
- "Нд", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"
- ],
- dayOfWeek: ["Неделя", "Понеделник", "Вторник", "Сряда", "Четвъртък", "Петък", "Събота"]
- },
- fa: { // Persian/Farsi
- months: [
- 'فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور', 'مهر', 'آبان', 'آذر', 'دی', 'بهمن', 'اسفند'
- ],
- dayOfWeekShort: [
- 'یکشنبه', 'دوشنبه', 'سه شنبه', 'چهارشنبه', 'پنجشنبه', 'جمعه', 'شنبه'
- ],
- dayOfWeek: ["یکشنبه", "دوشنبه", "سهشنبه", "چهارشنبه", "پنجشنبه", "جمعه", "شنبه", "یکشنبه"]
- },
- ru: { // Russian
- months: [
- 'Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'
- ],
- dayOfWeekShort: [
- "Вс", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"
- ],
- dayOfWeek: ["Воскресенье", "Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота"]
- },
- uk: { // Ukrainian
- months: [
- 'Січень', 'Лютий', 'Березень', 'Квітень', 'Травень', 'Червень', 'Липень', 'Серпень', 'Вересень', 'Жовтень', 'Листопад', 'Грудень'
- ],
- dayOfWeekShort: [
- "Ндл", "Пнд", "Втр", "Срд", "Чтв", "Птн", "Сбт"
- ],
- dayOfWeek: ["Неділя", "Понеділок", "Вівторок", "Середа", "Четвер", "П'ятниця", "Субота"]
- },
- en: { // English
- months: [
- "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
- ],
- dayOfWeekShort: [
- "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
- ],
- dayOfWeek: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
- },
- el: { // Ελληνικά
- months: [
- "Ιανουάριος", "Φεβρουάριος", "Μάρτιος", "Απρίλιος", "Μάιος", "Ιούνιος", "Ιούλιος", "Αύγουστος", "Σεπτέμβριος", "Οκτώβριος", "Νοέμβριος", "Δεκέμβριος"
- ],
- dayOfWeekShort: [
- "Κυρ", "Δευ", "Τρι", "Τετ", "Πεμ", "Παρ", "Σαβ"
- ],
- dayOfWeek: ["Κυριακή", "Δευτέρα", "Τρίτη", "Τετάρτη", "Πέμπτη", "Παρασκευή", "Σάββατο"]
- },
- de: { // German
- months: [
- 'Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'
- ],
- dayOfWeekShort: [
- "So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"
- ],
- dayOfWeek: ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"]
- },
- nl: { // Dutch
- months: [
- "januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december"
- ],
- dayOfWeekShort: [
- "zo", "ma", "di", "wo", "do", "vr", "za"
- ],
- dayOfWeek: ["zondag", "maandag", "dinsdag", "woensdag", "donderdag", "vrijdag", "zaterdag"]
- },
- tr: { // Turkish
- months: [
- "Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık"
- ],
- dayOfWeekShort: [
- "Paz", "Pts", "Sal", "Çar", "Per", "Cum", "Cts"
- ],
- dayOfWeek: ["Pazar", "Pazartesi", "Salı", "Çarşamba", "Perşembe", "Cuma", "Cumartesi"]
- },
- fr: { //French
- months: [
- "Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"
- ],
- dayOfWeekShort: [
- "Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"
- ],
- dayOfWeek: ["dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi"]
- },
- es: { // Spanish
- months: [
- "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"
- ],
- dayOfWeekShort: [
- "Dom", "Lun", "Mar", "Mié", "Jue", "Vie", "Sáb"
- ],
- dayOfWeek: ["Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado"]
- },
- th: { // Thai
- months: [
- 'มกราคม', 'กุมภาพันธ์', 'มีนาคม', 'เมษายน', 'พฤษภาคม', 'มิถุนายน', 'กรกฎาคม', 'สิงหาคม', 'กันยายน', 'ตุลาคม', 'พฤศจิกายน', 'ธันวาคม'
- ],
- dayOfWeekShort: [
- 'อา.', 'จ.', 'อ.', 'พ.', 'พฤ.', 'ศ.', 'ส.'
- ],
- dayOfWeek: ["อาทิตย์", "จันทร์", "อังคาร", "พุธ", "พฤหัส", "ศุกร์", "เสาร์", "อาทิตย์"]
- },
- pl: { // Polish
- months: [
- "styczeń", "luty", "marzec", "kwiecień", "maj", "czerwiec", "lipiec", "sierpień", "wrzesień", "październik", "listopad", "grudzień"
- ],
- dayOfWeekShort: [
- "nd", "pn", "wt", "śr", "cz", "pt", "sb"
- ],
- dayOfWeek: ["niedziela", "poniedziałek", "wtorek", "środa", "czwartek", "piątek", "sobota"]
- },
- pt: { // Portuguese
- months: [
- "Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"
- ],
- dayOfWeekShort: [
- "Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sab"
- ],
- dayOfWeek: ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"]
- },
- ch: { // Simplified Chinese
- months: [
- "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"
- ],
- dayOfWeekShort: [
- "日", "一", "二", "三", "四", "五", "六"
- ]
- },
- se: { // Swedish
- months: [
- "Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December"
- ],
- dayOfWeekShort: [
- "Sön", "Mån", "Tis", "Ons", "Tor", "Fre", "Lör"
- ]
- },
- kr: { // Korean
- months: [
- "1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"
- ],
- dayOfWeekShort: [
- "일", "월", "화", "수", "목", "금", "토"
- ],
- dayOfWeek: ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"]
- },
- it: { // Italian
- months: [
- "Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"
- ],
- dayOfWeekShort: [
- "Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab"
- ],
- dayOfWeek: ["Domenica", "Lunedì", "Martedì", "Mercoledì", "Giovedì", "Venerdì", "Sabato"]
- },
- da: { // Dansk
- months: [
- "January", "Februar", "Marts", "April", "Maj", "Juni", "July", "August", "September", "Oktober", "November", "December"
- ],
- dayOfWeekShort: [
- "Søn", "Man", "Tir", "Ons", "Tor", "Fre", "Lør"
- ],
- dayOfWeek: ["søndag", "mandag", "tirsdag", "onsdag", "torsdag", "fredag", "lørdag"]
- },
- no: { // Norwegian
- months: [
- "Januar", "Februar", "Mars", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Desember"
- ],
- dayOfWeekShort: [
- "Søn", "Man", "Tir", "Ons", "Tor", "Fre", "Lør"
- ],
- dayOfWeek: ['Søndag', 'Mandag', 'Tirsdag', 'Onsdag', 'Torsdag', 'Fredag', 'Lørdag']
- },
- ja: { // Japanese
- months: [
- "1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"
- ],
- dayOfWeekShort: [
- "日", "月", "火", "水", "木", "金", "土"
- ],
- dayOfWeek: ["日曜", "月曜", "火曜", "水曜", "木曜", "金曜", "土曜"]
- },
- vi: { // Vietnamese
- months: [
- "Tháng 1", "Tháng 2", "Tháng 3", "Tháng 4", "Tháng 5", "Tháng 6", "Tháng 7", "Tháng 8", "Tháng 9", "Tháng 10", "Tháng 11", "Tháng 12"
- ],
- dayOfWeekShort: [
- "CN", "T2", "T3", "T4", "T5", "T6", "T7"
- ],
- dayOfWeek: ["Chủ nhật", "Thứ hai", "Thứ ba", "Thứ tư", "Thứ năm", "Thứ sáu", "Thứ bảy"]
- },
- sl: { // Slovenščina
- months: [
- "Januar", "Februar", "Marec", "April", "Maj", "Junij", "Julij", "Avgust", "September", "Oktober", "November", "December"
- ],
- dayOfWeekShort: [
- "Ned", "Pon", "Tor", "Sre", "Čet", "Pet", "Sob"
- ],
- dayOfWeek: ["Nedelja", "Ponedeljek", "Torek", "Sreda", "Četrtek", "Petek", "Sobota"]
- },
- cs: { // Čeština
- months: [
- "Leden", "Únor", "Březen", "Duben", "Květen", "Červen", "Červenec", "Srpen", "Září", "Říjen", "Listopad", "Prosinec"
- ],
- dayOfWeekShort: [
- "Ne", "Po", "Út", "St", "Čt", "Pá", "So"
- ]
- },
- hu: { // Hungarian
- months: [
- "Január", "Február", "Március", "Április", "Május", "Június", "Július", "Augusztus", "Szeptember", "Október", "November", "December"
- ],
- dayOfWeekShort: [
- "Va", "Hé", "Ke", "Sze", "Cs", "Pé", "Szo"
- ],
- dayOfWeek: ["vasárnap", "hétfő", "kedd", "szerda", "csütörtök", "péntek", "szombat"]
- },
- az: { //Azerbaijanian (Azeri)
- months: [
- "Yanvar", "Fevral", "Mart", "Aprel", "May", "Iyun", "Iyul", "Avqust", "Sentyabr", "Oktyabr", "Noyabr", "Dekabr"
- ],
- dayOfWeekShort: [
- "B", "Be", "Ça", "Ç", "Ca", "C", "Ş"
- ],
- dayOfWeek: ["Bazar", "Bazar ertəsi", "Çərşənbə axşamı", "Çərşənbə", "Cümə axşamı", "Cümə", "Şənbə"]
- },
- bs: { //Bosanski
- months: [
- "Januar", "Februar", "Mart", "April", "Maj", "Jun", "Jul", "Avgust", "Septembar", "Oktobar", "Novembar", "Decembar"
- ],
- dayOfWeekShort: [
- "Ned", "Pon", "Uto", "Sri", "Čet", "Pet", "Sub"
- ],
- dayOfWeek: ["Nedjelja","Ponedjeljak", "Utorak", "Srijeda", "Četvrtak", "Petak", "Subota"]
- },
- ca: { //Català
- months: [
- "Gener", "Febrer", "Març", "Abril", "Maig", "Juny", "Juliol", "Agost", "Setembre", "Octubre", "Novembre", "Desembre"
- ],
- dayOfWeekShort: [
- "Dg", "Dl", "Dt", "Dc", "Dj", "Dv", "Ds"
- ],
- dayOfWeek: ["Diumenge", "Dilluns", "Dimarts", "Dimecres", "Dijous", "Divendres", "Dissabte"]
- },
- 'en-GB': { //English (British)
- months: [
- "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
- ],
- dayOfWeekShort: [
- "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
- ],
- dayOfWeek: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
- },
- et: { //"Eesti"
- months: [
- "Jaanuar", "Veebruar", "Märts", "Aprill", "Mai", "Juuni", "Juuli", "August", "September", "Oktoober", "November", "Detsember"
- ],
- dayOfWeekShort: [
- "P", "E", "T", "K", "N", "R", "L"
- ],
- dayOfWeek: ["Pühapäev", "Esmaspäev", "Teisipäev", "Kolmapäev", "Neljapäev", "Reede", "Laupäev"]
- },
- eu: { //Euskara
- months: [
- "Urtarrila", "Otsaila", "Martxoa", "Apirila", "Maiatza", "Ekaina", "Uztaila", "Abuztua", "Iraila", "Urria", "Azaroa", "Abendua"
- ],
- dayOfWeekShort: [
- "Ig.", "Al.", "Ar.", "Az.", "Og.", "Or.", "La."
- ],
- dayOfWeek: ['Igandea', 'Astelehena', 'Asteartea', 'Asteazkena', 'Osteguna', 'Ostirala', 'Larunbata']
- },
- fi: { //Finnish (Suomi)
- months: [
- "Tammikuu", "Helmikuu", "Maaliskuu", "Huhtikuu", "Toukokuu", "Kesäkuu", "Heinäkuu", "Elokuu", "Syyskuu", "Lokakuu", "Marraskuu", "Joulukuu"
- ],
- dayOfWeekShort: [
- "Su", "Ma", "Ti", "Ke", "To", "Pe", "La"
- ],
- dayOfWeek: ["sunnuntai", "maanantai", "tiistai", "keskiviikko", "torstai", "perjantai", "lauantai"]
- },
- gl: { //Galego
- months: [
- "Xan", "Feb", "Maz", "Abr", "Mai", "Xun", "Xul", "Ago", "Set", "Out", "Nov", "Dec"
- ],
- dayOfWeekShort: [
- "Dom", "Lun", "Mar", "Mer", "Xov", "Ven", "Sab"
- ],
- dayOfWeek: ["Domingo", "Luns", "Martes", "Mércores", "Xoves", "Venres", "Sábado"]
- },
- hr: { //Hrvatski
- months: [
- "Siječanj", "Veljača", "Ožujak", "Travanj", "Svibanj", "Lipanj", "Srpanj", "Kolovoz", "Rujan", "Listopad", "Studeni", "Prosinac"
- ],
- dayOfWeekShort: [
- "Ned", "Pon", "Uto", "Sri", "Čet", "Pet", "Sub"
- ],
- dayOfWeek: ["Nedjelja", "Ponedjeljak", "Utorak", "Srijeda", "Četvrtak", "Petak", "Subota"]
- },
- ko: { //Korean (한국어)
- months: [
- "1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"
- ],
- dayOfWeekShort: [
- "일", "월", "화", "수", "목", "금", "토"
- ],
- dayOfWeek: ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"]
- },
- lt: { //Lithuanian (lietuvių)
- months: [
- "Sausio", "Vasario", "Kovo", "Balandžio", "Gegužės", "Birželio", "Liepos", "Rugpjūčio", "Rugsėjo", "Spalio", "Lapkričio", "Gruodžio"
- ],
- dayOfWeekShort: [
- "Sek", "Pir", "Ant", "Tre", "Ket", "Pen", "Šeš"
- ],
- dayOfWeek: ["Sekmadienis", "Pirmadienis", "Antradienis", "Trečiadienis", "Ketvirtadienis", "Penktadienis", "Šeštadienis"]
- },
- lv: { //Latvian (Latviešu)
- months: [
- "Janvāris", "Februāris", "Marts", "Aprīlis ", "Maijs", "Jūnijs", "Jūlijs", "Augusts", "Septembris", "Oktobris", "Novembris", "Decembris"
- ],
- dayOfWeekShort: [
- "Sv", "Pr", "Ot", "Tr", "Ct", "Pk", "St"
- ],
- dayOfWeek: ["Svētdiena", "Pirmdiena", "Otrdiena", "Trešdiena", "Ceturtdiena", "Piektdiena", "Sestdiena"]
- },
- mk: { //Macedonian (Македонски)
- months: [
- "јануари", "февруари", "март", "април", "мај", "јуни", "јули", "август", "септември", "октомври", "ноември", "декември"
- ],
- dayOfWeekShort: [
- "нед", "пон", "вто", "сре", "чет", "пет", "саб"
- ],
- dayOfWeek: ["Недела", "Понеделник", "Вторник", "Среда", "Четврток", "Петок", "Сабота"]
- },
- mn: { //Mongolian (Монгол)
- months: [
- "1-р сар", "2-р сар", "3-р сар", "4-р сар", "5-р сар", "6-р сар", "7-р сар", "8-р сар", "9-р сар", "10-р сар", "11-р сар", "12-р сар"
- ],
- dayOfWeekShort: [
- "Дав", "Мяг", "Лха", "Пүр", "Бсн", "Бям", "Ням"
- ],
- dayOfWeek: ["Даваа", "Мягмар", "Лхагва", "Пүрэв", "Баасан", "Бямба", "Ням"]
- },
- 'pt-BR': { //Português(Brasil)
- months: [
- "Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"
- ],
- dayOfWeekShort: [
- "Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb"
- ],
- dayOfWeek: ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"]
- },
- sk: { //Slovenčina
- months: [
- "Január", "Február", "Marec", "Apríl", "Máj", "Jún", "Júl", "August", "September", "Október", "November", "December"
- ],
- dayOfWeekShort: [
- "Ne", "Po", "Ut", "St", "Št", "Pi", "So"
- ],
- dayOfWeek: ["Nedeľa", "Pondelok", "Utorok", "Streda", "Štvrtok", "Piatok", "Sobota"]
- },
- sq: { //Albanian (Shqip)
- months: [
- "Janar", "Shkurt", "Mars", "Prill", "Maj", "Qershor", "Korrik", "Gusht", "Shtator", "Tetor", "Nëntor", "Dhjetor"
- ],
- dayOfWeekShort: [
- "Die", "Hën", "Mar", "Mër", "Enj", "Pre", "Shtu"
- ],
- dayOfWeek: ["E Diel", "E Hënë", "E Martē", "E Mërkurë", "E Enjte", "E Premte", "E Shtunë"]
- },
- 'sr-YU': { //Serbian (Srpski)
- months: [
- "Januar", "Februar", "Mart", "April", "Maj", "Jun", "Jul", "Avgust", "Septembar", "Oktobar", "Novembar", "Decembar"
- ],
- dayOfWeekShort: [
- "Ned", "Pon", "Uto", "Sre", "čet", "Pet", "Sub"
- ],
- dayOfWeek: ["Nedelja","Ponedeljak", "Utorak", "Sreda", "Četvrtak", "Petak", "Subota"]
- },
- sr: { //Serbian Cyrillic (Српски)
- months: [
- "јануар", "фебруар", "март", "април", "мај", "јун", "јул", "август", "септембар", "октобар", "новембар", "децембар"
- ],
- dayOfWeekShort: [
- "нед", "пон", "уто", "сре", "чет", "пет", "суб"
- ],
- dayOfWeek: ["Недеља","Понедељак", "Уторак", "Среда", "Четвртак", "Петак", "Субота"]
- },
- sv: { //Svenska
- months: [
- "Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December"
- ],
- dayOfWeekShort: [
- "Sön", "Mån", "Tis", "Ons", "Tor", "Fre", "Lör"
- ],
- dayOfWeek: ["Söndag", "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag"]
- },
- 'zh-TW': { //Traditional Chinese (繁體中文)
- months: [
- "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"
- ],
- dayOfWeekShort: [
- "日", "一", "二", "三", "四", "五", "六"
- ],
- dayOfWeek: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]
- },
- zh: { //Simplified Chinese (简体中文)
- months: [
- "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"
- ],
- dayOfWeekShort: [
- "日", "一", "二", "三", "四", "五", "六"
- ],
- dayOfWeek: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]
- },
- he: { //Hebrew (עברית)
- months: [
- 'ינואר', 'פברואר', 'מרץ', 'אפריל', 'מאי', 'יוני', 'יולי', 'אוגוסט', 'ספטמבר', 'אוקטובר', 'נובמבר', 'דצמבר'
- ],
- dayOfWeekShort: [
- 'א\'', 'ב\'', 'ג\'', 'ד\'', 'ה\'', 'ו\'', 'שבת'
- ],
- dayOfWeek: ["ראשון", "שני", "שלישי", "רביעי", "חמישי", "שישי", "שבת", "ראשון"]
- },
- hy: { // Armenian
- months: [
- "Հունվար", "Փետրվար", "Մարտ", "Ապրիլ", "Մայիս", "Հունիս", "Հուլիս", "Օգոստոս", "Սեպտեմբեր", "Հոկտեմբեր", "Նոյեմբեր", "Դեկտեմբեր"
- ],
- dayOfWeekShort: [
- "Կի", "Երկ", "Երք", "Չոր", "Հնգ", "Ուրբ", "Շբթ"
- ],
- dayOfWeek: ["Կիրակի", "Երկուշաբթի", "Երեքշաբթի", "Չորեքշաբթի", "Հինգշաբթի", "Ուրբաթ", "Շաբաթ"]
- },
- kg: { // Kyrgyz
- months: [
- 'Үчтүн айы', 'Бирдин айы', 'Жалган Куран', 'Чын Куран', 'Бугу', 'Кулжа', 'Теке', 'Баш Оона', 'Аяк Оона', 'Тогуздун айы', 'Жетинин айы', 'Бештин айы'
- ],
- dayOfWeekShort: [
- "Жек", "Дүй", "Шей", "Шар", "Бей", "Жум", "Ише"
- ],
- dayOfWeek: [
- "Жекшемб", "Дүйшөмб", "Шейшемб", "Шаршемб", "Бейшемби", "Жума", "Ишенб"
- ]
- },
- rm: { // Romansh
- months: [
- "Schaner", "Favrer", "Mars", "Avrigl", "Matg", "Zercladur", "Fanadur", "Avust", "Settember", "October", "November", "December"
- ],
- dayOfWeekShort: [
- "Du", "Gli", "Ma", "Me", "Gie", "Ve", "So"
- ],
- dayOfWeek: [
- "Dumengia", "Glindesdi", "Mardi", "Mesemna", "Gievgia", "Venderdi", "Sonda"
- ]
- },
- ka: { // Georgian
- months: [
- 'იანვარი', 'თებერვალი', 'მარტი', 'აპრილი', 'მაისი', 'ივნისი', 'ივლისი', 'აგვისტო', 'სექტემბერი', 'ოქტომბერი', 'ნოემბერი', 'დეკემბერი'
- ],
- dayOfWeekShort: [
- "კვ", "ორშ", "სამშ", "ოთხ", "ხუთ", "პარ", "შაბ"
- ],
- dayOfWeek: ["კვირა", "ორშაბათი", "სამშაბათი", "ოთხშაბათი", "ხუთშაბათი", "პარასკევი", "შაბათი"]
- },
- },
- value: '',
- rtl: false,
-
- format: 'Y/m/d H:i',
- formatTime: 'H:i',
- formatDate: 'Y/m/d',
-
- startDate: false, // new Date(), '1986/12/08', '-1970/01/05','-1970/01/05',
- step: 60,
- monthChangeSpinner: true,
-
- closeOnDateSelect: false,
- closeOnTimeSelect: true,
- closeOnWithoutClick: true,
- closeOnInputClick: true,
-
- timepicker: true,
- datepicker: true,
- weeks: false,
-
- defaultTime: false, // use formatTime format (ex. '10:00' for formatTime: 'H:i')
- defaultDate: false, // use formatDate format (ex new Date() or '1986/12/08' or '-1970/01/05' or '-1970/01/05')
-
- minDate: false,
- maxDate: false,
- minTime: false,
- maxTime: false,
- disabledMinTime: false,
- disabledMaxTime: false,
-
- allowTimes: [],
- opened: false,
- initTime: true,
- inline: false,
- theme: '',
-
- onSelectDate: function () {},
- onSelectTime: function () {},
- onChangeMonth: function () {},
- onGetWeekOfYear: function () {},
- onChangeYear: function () {},
- onChangeDateTime: function () {},
- onShow: function () {},
- onClose: function () {},
- onGenerate: function () {},
-
- withoutCopyright: true,
- inverseButton: false,
- hours12: false,
- next: 'xdsoft_next',
- prev : 'xdsoft_prev',
- dayOfWeekStart: 0,
- parentID: 'body',
- timeHeightInTimePicker: 25,
- timepickerScrollbar: true,
- todayButton: true,
- prevButton: true,
- nextButton: true,
- defaultSelect: true,
-
- scrollMonth: true,
- scrollTime: true,
- scrollInput: true,
-
- lazyInit: false,
- mask: false,
- validateOnBlur: true,
- allowBlank: true,
- yearStart: 1950,
- yearEnd: 2050,
- monthStart: 0,
- monthEnd: 11,
- style: '',
- id: '',
- fixed: false,
- roundTime: 'round', // ceil, floor
- className: '',
- weekends: [],
- highlightedDates: [],
- highlightedPeriods: [],
- allowDates : [],
- allowDateRe : null,
- disabledDates : [],
- disabledWeekDays: [],
- yearOffset: 0,
- beforeShowDay: null,
-
- enterLikeTab: true,
- showApplyButton: false
- };
-
- var dateHelper = null,
- globalLocaleDefault = 'en',
- globalLocale = 'en';
-
- var dateFormatterOptionsDefault = {
- meridiem: ['AM', 'PM']
- };
-
- var initDateFormatter = function(){
- var locale = default_options.i18n[globalLocale],
- opts = {
- days: locale.dayOfWeek,
- daysShort: locale.dayOfWeekShort,
- months: locale.months,
- monthsShort: $.map(locale.months, function(n){ return n.substring(0, 3) }),
- };
-
- dateHelper = new DateFormatter({
- dateSettings: $.extend({}, dateFormatterOptionsDefault, opts)
- });
- };
-
- // for locale settings
- $.datetimepicker = {
- setLocale: function(locale){
- var newLocale = default_options.i18n[locale]?locale:globalLocaleDefault;
- if(globalLocale != newLocale){
- globalLocale = newLocale;
- // reinit date formatter
- initDateFormatter();
- }
- },
- setDateFormatter: function(dateFormatter) {
- dateHelper = dateFormatter;
- },
- RFC_2822: 'D, d M Y H:i:s O',
- ATOM: 'Y-m-d\TH:i:sP',
- ISO_8601: 'Y-m-d\TH:i:sO',
- RFC_822: 'D, d M y H:i:s O',
- RFC_850: 'l, d-M-y H:i:s T',
- RFC_1036: 'D, d M y H:i:s O',
- RFC_1123: 'D, d M Y H:i:s O',
- RSS: 'D, d M Y H:i:s O',
- W3C: 'Y-m-d\TH:i:sP'
- };
-
- // first init date formatter
- initDateFormatter();
-
- // fix for ie8
- if (!window.getComputedStyle) {
- window.getComputedStyle = function (el, pseudo) {
- this.el = el;
- this.getPropertyValue = function (prop) {
- var re = /(\-([a-z]){1})/g;
- if (prop === 'float') {
- prop = 'styleFloat';
- }
- if (re.test(prop)) {
- prop = prop.replace(re, function (a, b, c) {
- return c.toUpperCase();
- });
- }
- return el.currentStyle[prop] || null;
- };
- return this;
- };
- }
- if (!Array.prototype.indexOf) {
- Array.prototype.indexOf = function (obj, start) {
- var i, j;
- for (i = (start || 0), j = this.length; i < j; i += 1) {
- if (this[i] === obj) { return i; }
- }
- return -1;
- };
- }
- Date.prototype.countDaysInMonth = function () {
- return new Date(this.getFullYear(), this.getMonth() + 1, 0).getDate();
- };
- $.fn.xdsoftScroller = function (percent) {
- return this.each(function () {
- var timeboxparent = $(this),
- pointerEventToXY = function (e) {
- var out = {x: 0, y: 0},
- touch;
- if (e.type === 'touchstart' || e.type === 'touchmove' || e.type === 'touchend' || e.type === 'touchcancel') {
- touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
- out.x = touch.clientX;
- out.y = touch.clientY;
- } else if (e.type === 'mousedown' || e.type === 'mouseup' || e.type === 'mousemove' || e.type === 'mouseover' || e.type === 'mouseout' || e.type === 'mouseenter' || e.type === 'mouseleave') {
- out.x = e.clientX;
- out.y = e.clientY;
- }
- return out;
- },
- timebox,
- parentHeight,
- height,
- scrollbar,
- scroller,
- maximumOffset = 100,
- start = false,
- startY = 0,
- startTop = 0,
- h1 = 0,
- touchStart = false,
- startTopScroll = 0,
- calcOffset = function () {};
- if (percent === 'hide') {
- timeboxparent.find('.xdsoft_scrollbar').hide();
- return;
- }
- if (!$(this).hasClass('xdsoft_scroller_box')) {
- timebox = timeboxparent.children().eq(0);
- parentHeight = timeboxparent[0].clientHeight;
- height = timebox[0].offsetHeight;
- scrollbar = $('
');
- scroller = $('
');
- scrollbar.append(scroller);
-
- timeboxparent.addClass('xdsoft_scroller_box').append(scrollbar);
- calcOffset = function calcOffset(event) {
- var offset = pointerEventToXY(event).y - startY + startTopScroll;
- if (offset < 0) {
- offset = 0;
- }
- if (offset + scroller[0].offsetHeight > h1) {
- offset = h1 - scroller[0].offsetHeight;
- }
- timeboxparent.trigger('scroll_element.xdsoft_scroller', [maximumOffset ? offset / maximumOffset : 0]);
- };
-
- scroller
- .on('touchstart.xdsoft_scroller mousedown.xdsoft_scroller', function (event) {
- if (!parentHeight) {
- timeboxparent.trigger('resize_scroll.xdsoft_scroller', [percent]);
- }
-
- startY = pointerEventToXY(event).y;
- startTopScroll = parseInt(scroller.css('margin-top'), 10);
- h1 = scrollbar[0].offsetHeight;
-
- if (event.type === 'mousedown' || event.type === 'touchstart') {
- if (document) {
- $(document.body).addClass('xdsoft_noselect');
- }
- $([document.body, window]).on('touchend mouseup.xdsoft_scroller', function arguments_callee() {
- $([document.body, window]).off('touchend mouseup.xdsoft_scroller', arguments_callee)
- .off('mousemove.xdsoft_scroller', calcOffset)
- .removeClass('xdsoft_noselect');
- });
- $(document.body).on('mousemove.xdsoft_scroller', calcOffset);
- } else {
- touchStart = true;
- event.stopPropagation();
- event.preventDefault();
- }
- })
- .on('touchmove', function (event) {
- if (touchStart) {
- event.preventDefault();
- calcOffset(event);
- }
- })
- .on('touchend touchcancel', function () {
- touchStart = false;
- startTopScroll = 0;
- });
-
- timeboxparent
- .on('scroll_element.xdsoft_scroller', function (event, percentage) {
- if (!parentHeight) {
- timeboxparent.trigger('resize_scroll.xdsoft_scroller', [percentage, true]);
- }
- percentage = percentage > 1 ? 1 : (percentage < 0 || isNaN(percentage)) ? 0 : percentage;
-
- scroller.css('margin-top', maximumOffset * percentage);
-
- setTimeout(function () {
- timebox.css('marginTop', -parseInt((timebox[0].offsetHeight - parentHeight) * percentage, 10));
- }, 10);
- })
- .on('resize_scroll.xdsoft_scroller', function (event, percentage, noTriggerScroll) {
- var percent, sh;
- parentHeight = timeboxparent[0].clientHeight;
- height = timebox[0].offsetHeight;
- percent = parentHeight / height;
- sh = percent * scrollbar[0].offsetHeight;
- if (percent > 1) {
- scroller.hide();
- } else {
- scroller.show();
- scroller.css('height', parseInt(sh > 10 ? sh : 10, 10));
- maximumOffset = scrollbar[0].offsetHeight - scroller[0].offsetHeight;
- if (noTriggerScroll !== true) {
- timeboxparent.trigger('scroll_element.xdsoft_scroller', [percentage || Math.abs(parseInt(timebox.css('marginTop'), 10)) / (height - parentHeight)]);
- }
- }
- });
-
- timeboxparent.on('mousewheel', function (event) {
- var top = Math.abs(parseInt(timebox.css('marginTop'), 10));
-
- top = top - (event.deltaY * 20);
- if (top < 0) {
- top = 0;
- }
-
- timeboxparent.trigger('scroll_element.xdsoft_scroller', [top / (height - parentHeight)]);
- event.stopPropagation();
- return false;
- });
-
- timeboxparent.on('touchstart', function (event) {
- start = pointerEventToXY(event);
- startTop = Math.abs(parseInt(timebox.css('marginTop'), 10));
- });
-
- timeboxparent.on('touchmove', function (event) {
- if (start) {
- event.preventDefault();
- var coord = pointerEventToXY(event);
- timeboxparent.trigger('scroll_element.xdsoft_scroller', [(startTop - (coord.y - start.y)) / (height - parentHeight)]);
- }
- });
-
- timeboxparent.on('touchend touchcancel', function () {
- start = false;
- startTop = 0;
- });
- }
- timeboxparent.trigger('resize_scroll.xdsoft_scroller', [percent]);
- });
- };
-
- $.fn.datetimepicker = function (opt, opt2) {
- var result = this,
- KEY0 = 48,
- KEY9 = 57,
- _KEY0 = 96,
- _KEY9 = 105,
- CTRLKEY = 17,
- DEL = 46,
- ENTER = 13,
- ESC = 27,
- BACKSPACE = 8,
- ARROWLEFT = 37,
- ARROWUP = 38,
- ARROWRIGHT = 39,
- ARROWDOWN = 40,
- TAB = 9,
- F5 = 116,
- AKEY = 65,
- CKEY = 67,
- VKEY = 86,
- ZKEY = 90,
- YKEY = 89,
- ctrlDown = false,
- options = ($.isPlainObject(opt) || !opt) ? $.extend(true, {}, default_options, opt) : $.extend(true, {}, default_options),
-
- lazyInitTimer = 0,
- createDateTimePicker,
- destroyDateTimePicker,
-
- lazyInit = function (input) {
- input
- .on('open.xdsoft focusin.xdsoft mousedown.xdsoft touchstart', function initOnActionCallback() {
- if (input.is(':disabled') || input.data('xdsoft_datetimepicker')) {
- return;
- }
- clearTimeout(lazyInitTimer);
- lazyInitTimer = setTimeout(function () {
-
- if (!input.data('xdsoft_datetimepicker')) {
- createDateTimePicker(input);
- }
- input
- .off('open.xdsoft focusin.xdsoft mousedown.xdsoft touchstart', initOnActionCallback)
- .trigger('open.xdsoft');
- }, 100);
- });
- };
-
- createDateTimePicker = function (input) {
- var datetimepicker = $('
'),
- xdsoft_copyright = $(''),
- datepicker = $('
'),
- month_picker = $(''),
- calendar = $('
'),
- timepicker = $(''),
- timeboxparent = timepicker.find('.xdsoft_time_box').eq(0),
- timebox = $('
'),
- applyButton = $('Save Selected '),
-
- monthselect = $(''),
- yearselect = $(''),
- triggerAfterOpen = false,
- XDSoft_datetime,
-
- xchangeTimer,
- timerclick,
- current_time_index,
- setPos,
- timer = 0,
- _xdsoft_datetime,
- forEachAncestorOf,
- throttle;
-
- if (options.id) {
- datetimepicker.attr('id', options.id);
- }
- if (options.style) {
- datetimepicker.attr('style', options.style);
- }
- if (options.weeks) {
- datetimepicker.addClass('xdsoft_showweeks');
- }
- if (options.rtl) {
- datetimepicker.addClass('xdsoft_rtl');
- }
-
- datetimepicker.addClass('xdsoft_' + options.theme);
- datetimepicker.addClass(options.className);
-
- month_picker
- .find('.xdsoft_month span')
- .after(monthselect);
- month_picker
- .find('.xdsoft_year span')
- .after(yearselect);
-
- month_picker
- .find('.xdsoft_month,.xdsoft_year')
- .on('touchstart mousedown.xdsoft', function (event) {
- var select = $(this).find('.xdsoft_select').eq(0),
- val = 0,
- top = 0,
- visible = select.is(':visible'),
- items,
- i;
-
- month_picker
- .find('.xdsoft_select')
- .hide();
- if (_xdsoft_datetime.currentTime) {
- val = _xdsoft_datetime.currentTime[$(this).hasClass('xdsoft_month') ? 'getMonth' : 'getFullYear']();
- }
-
- select[visible ? 'hide' : 'show']();
- for (items = select.find('div.xdsoft_option'), i = 0; i < items.length; i += 1) {
- if (items.eq(i).data('value') === val) {
- break;
- } else {
- top += items[0].offsetHeight;
- }
- }
-
- select.xdsoftScroller(top / (select.children()[0].offsetHeight - (select[0].clientHeight)));
- event.stopPropagation();
- return false;
- });
-
- month_picker
- .find('.xdsoft_select')
- .xdsoftScroller()
- .on('touchstart mousedown.xdsoft', function (event) {
- event.stopPropagation();
- event.preventDefault();
- })
- .on('touchstart mousedown.xdsoft', '.xdsoft_option', function () {
- if (_xdsoft_datetime.currentTime === undefined || _xdsoft_datetime.currentTime === null) {
- _xdsoft_datetime.currentTime = _xdsoft_datetime.now();
- }
-
- var year = _xdsoft_datetime.currentTime.getFullYear();
- if (_xdsoft_datetime && _xdsoft_datetime.currentTime) {
- _xdsoft_datetime.currentTime[$(this).parent().parent().hasClass('xdsoft_monthselect') ? 'setMonth' : 'setFullYear']($(this).data('value'));
- }
-
- $(this).parent().parent().hide();
-
- datetimepicker.trigger('xchange.xdsoft');
- if (options.onChangeMonth && $.isFunction(options.onChangeMonth)) {
- options.onChangeMonth.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
- }
-
- if (year !== _xdsoft_datetime.currentTime.getFullYear() && $.isFunction(options.onChangeYear)) {
- options.onChangeYear.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
- }
- });
-
- datetimepicker.getValue = function () {
- return _xdsoft_datetime.getCurrentTime();
- };
-
- datetimepicker.setOptions = function (_options) {
- var highlightedDates = {};
-
- options = $.extend(true, {}, options, _options);
-
- if (_options.allowTimes && $.isArray(_options.allowTimes) && _options.allowTimes.length) {
- options.allowTimes = $.extend(true, [], _options.allowTimes);
- }
-
- if (_options.weekends && $.isArray(_options.weekends) && _options.weekends.length) {
- options.weekends = $.extend(true, [], _options.weekends);
- }
-
- if (_options.allowDates && $.isArray(_options.allowDates) && _options.allowDates.length) {
- options.allowDates = $.extend(true, [], _options.allowDates);
- }
-
- if (_options.allowDateRe && Object.prototype.toString.call(_options.allowDateRe)==="[object String]") {
- options.allowDateRe = new RegExp(_options.allowDateRe);
- }
-
- if (_options.highlightedDates && $.isArray(_options.highlightedDates) && _options.highlightedDates.length) {
- $.each(_options.highlightedDates, function (index, value) {
- var splitData = $.map(value.split(','), $.trim),
- exDesc,
- hDate = new HighlightedDate(dateHelper.parseDate(splitData[0], options.formatDate), splitData[1], splitData[2]), // date, desc, style
- keyDate = dateHelper.formatDate(hDate.date, options.formatDate);
- if (highlightedDates[keyDate] !== undefined) {
- exDesc = highlightedDates[keyDate].desc;
- if (exDesc && exDesc.length && hDate.desc && hDate.desc.length) {
- highlightedDates[keyDate].desc = exDesc + "\n" + hDate.desc;
- }
- } else {
- highlightedDates[keyDate] = hDate;
- }
- });
-
- options.highlightedDates = $.extend(true, [], highlightedDates);
- }
-
- if (_options.highlightedPeriods && $.isArray(_options.highlightedPeriods) && _options.highlightedPeriods.length) {
- highlightedDates = $.extend(true, [], options.highlightedDates);
- $.each(_options.highlightedPeriods, function (index, value) {
- var dateTest, // start date
- dateEnd,
- desc,
- hDate,
- keyDate,
- exDesc,
- style;
- if ($.isArray(value)) {
- dateTest = value[0];
- dateEnd = value[1];
- desc = value[2];
- style = value[3];
- }
- else {
- var splitData = $.map(value.split(','), $.trim);
- dateTest = dateHelper.parseDate(splitData[0], options.formatDate);
- dateEnd = dateHelper.parseDate(splitData[1], options.formatDate);
- desc = splitData[2];
- style = splitData[3];
- }
-
- while (dateTest <= dateEnd) {
- hDate = new HighlightedDate(dateTest, desc, style);
- keyDate = dateHelper.formatDate(dateTest, options.formatDate);
- dateTest.setDate(dateTest.getDate() + 1);
- if (highlightedDates[keyDate] !== undefined) {
- exDesc = highlightedDates[keyDate].desc;
- if (exDesc && exDesc.length && hDate.desc && hDate.desc.length) {
- highlightedDates[keyDate].desc = exDesc + "\n" + hDate.desc;
- }
- } else {
- highlightedDates[keyDate] = hDate;
- }
- }
- });
-
- options.highlightedDates = $.extend(true, [], highlightedDates);
- }
-
- if (_options.disabledDates && $.isArray(_options.disabledDates) && _options.disabledDates.length) {
- options.disabledDates = $.extend(true, [], _options.disabledDates);
- }
-
- if (_options.disabledWeekDays && $.isArray(_options.disabledWeekDays) && _options.disabledWeekDays.length) {
- options.disabledWeekDays = $.extend(true, [], _options.disabledWeekDays);
- }
-
- if ((options.open || options.opened) && (!options.inline)) {
- input.trigger('open.xdsoft');
- }
-
- if (options.inline) {
- triggerAfterOpen = true;
- datetimepicker.addClass('xdsoft_inline');
- input.after(datetimepicker).hide();
- }
-
- if (options.inverseButton) {
- options.next = 'xdsoft_prev';
- options.prev = 'xdsoft_next';
- }
-
- if (options.datepicker) {
- datepicker.addClass('active');
- } else {
- datepicker.removeClass('active');
- }
-
- if (options.timepicker) {
- timepicker.addClass('active');
- } else {
- timepicker.removeClass('active');
- }
-
- if (options.value) {
- _xdsoft_datetime.setCurrentTime(options.value);
- if (input && input.val) {
- input.val(_xdsoft_datetime.str);
- }
- }
-
- if (isNaN(options.dayOfWeekStart)) {
- options.dayOfWeekStart = 0;
- } else {
- options.dayOfWeekStart = parseInt(options.dayOfWeekStart, 10) % 7;
- }
-
- if (!options.timepickerScrollbar) {
- timeboxparent.xdsoftScroller('hide');
- }
-
- if (options.minDate && /^[\+\-](.*)$/.test(options.minDate)) {
- options.minDate = dateHelper.formatDate(_xdsoft_datetime.strToDateTime(options.minDate), options.formatDate);
- }
-
- if (options.maxDate && /^[\+\-](.*)$/.test(options.maxDate)) {
- options.maxDate = dateHelper.formatDate(_xdsoft_datetime.strToDateTime(options.maxDate), options.formatDate);
- }
-
- applyButton.toggle(options.showApplyButton);
-
- month_picker
- .find('.xdsoft_today_button')
- .css('visibility', !options.todayButton ? 'hidden' : 'visible');
-
- month_picker
- .find('.' + options.prev)
- .css('visibility', !options.prevButton ? 'hidden' : 'visible');
-
- month_picker
- .find('.' + options.next)
- .css('visibility', !options.nextButton ? 'hidden' : 'visible');
-
- setMask(options);
-
- if (options.validateOnBlur) {
- input
- .off('blur.xdsoft')
- .on('blur.xdsoft', function () {
- if (options.allowBlank && (!$.trim($(this).val()).length || (typeof options.mask == "string" && $.trim($(this).val()) === options.mask.replace(/[0-9]/g, '_')))) {
- $(this).val(null);
- datetimepicker.data('xdsoft_datetime').empty();
- } else {
- var d = dateHelper.parseDate($(this).val(), options.format);
- if (d) { // parseDate() may skip some invalid parts like date or time, so make it clear for user: show parsed date/time
- $(this).val(dateHelper.formatDate(d, options.format));
- } else {
- var splittedHours = +([$(this).val()[0], $(this).val()[1]].join('')),
- splittedMinutes = +([$(this).val()[2], $(this).val()[3]].join(''));
-
- // parse the numbers as 0312 => 03:12
- if (!options.datepicker && options.timepicker && splittedHours >= 0 && splittedHours < 24 && splittedMinutes >= 0 && splittedMinutes < 60) {
- $(this).val([splittedHours, splittedMinutes].map(function (item) {
- return item > 9 ? item : '0' + item;
- }).join(':'));
- } else {
- $(this).val(dateHelper.formatDate(_xdsoft_datetime.now(), options.format));
- }
- }
- datetimepicker.data('xdsoft_datetime').setCurrentTime($(this).val());
- }
-
- datetimepicker.trigger('changedatetime.xdsoft');
- datetimepicker.trigger('close.xdsoft');
- });
- }
- options.dayOfWeekStartPrev = (options.dayOfWeekStart === 0) ? 6 : options.dayOfWeekStart - 1;
-
- datetimepicker
- .trigger('xchange.xdsoft')
- .trigger('afterOpen.xdsoft');
- };
-
- datetimepicker
- .data('options', options)
- .on('touchstart mousedown.xdsoft', function (event) {
- event.stopPropagation();
- event.preventDefault();
- yearselect.hide();
- monthselect.hide();
- return false;
- });
-
- //scroll_element = timepicker.find('.xdsoft_time_box');
- timeboxparent.append(timebox);
- timeboxparent.xdsoftScroller();
-
- datetimepicker.on('afterOpen.xdsoft', function () {
- timeboxparent.xdsoftScroller();
- });
-
- datetimepicker
- .append(datepicker)
- .append(timepicker);
-
- if (options.withoutCopyright !== true) {
- datetimepicker
- .append(xdsoft_copyright);
- }
-
- datepicker
- .append(month_picker)
- .append(calendar)
- .append(applyButton);
-
- $(options.parentID)
- .append(datetimepicker);
-
- XDSoft_datetime = function () {
- var _this = this;
- _this.now = function (norecursion) {
- var d = new Date(),
- date,
- time;
-
- if (!norecursion && options.defaultDate) {
- date = _this.strToDateTime(options.defaultDate);
- d.setFullYear(date.getFullYear());
- d.setMonth(date.getMonth());
- d.setDate(date.getDate());
- }
-
- if (options.yearOffset) {
- d.setFullYear(d.getFullYear() + options.yearOffset);
- }
-
- if (!norecursion && options.defaultTime) {
- time = _this.strtotime(options.defaultTime);
- d.setHours(time.getHours());
- d.setMinutes(time.getMinutes());
- }
- return d;
- };
-
- _this.isValidDate = function (d) {
- if (Object.prototype.toString.call(d) !== "[object Date]") {
- return false;
- }
- return !isNaN(d.getTime());
- };
-
- _this.setCurrentTime = function (dTime, requireValidDate) {
- if (typeof dTime === 'string') {
- _this.currentTime = _this.strToDateTime(dTime);
- }
- else if (_this.isValidDate(dTime)) {
- _this.currentTime = dTime;
- }
- else if (!dTime && !requireValidDate && options.allowBlank) {
- _this.currentTime = null;
- }
- else {
- _this.currentTime = _this.now();
- }
-
- datetimepicker.trigger('xchange.xdsoft');
- };
-
- _this.empty = function () {
- _this.currentTime = null;
- };
-
- _this.getCurrentTime = function (dTime) {
- return _this.currentTime;
- };
-
- _this.nextMonth = function () {
-
- if (_this.currentTime === undefined || _this.currentTime === null) {
- _this.currentTime = _this.now();
- }
-
- var month = _this.currentTime.getMonth() + 1,
- year;
- if (month === 12) {
- _this.currentTime.setFullYear(_this.currentTime.getFullYear() + 1);
- month = 0;
- }
-
- year = _this.currentTime.getFullYear();
-
- _this.currentTime.setDate(
- Math.min(
- new Date(_this.currentTime.getFullYear(), month + 1, 0).getDate(),
- _this.currentTime.getDate()
- )
- );
- _this.currentTime.setMonth(month);
-
- if (options.onChangeMonth && $.isFunction(options.onChangeMonth)) {
- options.onChangeMonth.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
- }
-
- if (year !== _this.currentTime.getFullYear() && $.isFunction(options.onChangeYear)) {
- options.onChangeYear.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
- }
-
- datetimepicker.trigger('xchange.xdsoft');
- return month;
- };
-
- _this.prevMonth = function () {
-
- if (_this.currentTime === undefined || _this.currentTime === null) {
- _this.currentTime = _this.now();
- }
-
- var month = _this.currentTime.getMonth() - 1;
- if (month === -1) {
- _this.currentTime.setFullYear(_this.currentTime.getFullYear() - 1);
- month = 11;
- }
- _this.currentTime.setDate(
- Math.min(
- new Date(_this.currentTime.getFullYear(), month + 1, 0).getDate(),
- _this.currentTime.getDate()
- )
- );
- _this.currentTime.setMonth(month);
- if (options.onChangeMonth && $.isFunction(options.onChangeMonth)) {
- options.onChangeMonth.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
- }
- datetimepicker.trigger('xchange.xdsoft');
- return month;
- };
-
- _this.getWeekOfYear = function (datetime) {
- if (options.onGetWeekOfYear && $.isFunction(options.onGetWeekOfYear)) {
- var week = options.onGetWeekOfYear.call(datetimepicker, datetime);
- if (typeof week !== 'undefined') {
- return week;
- }
- }
- var onejan = new Date(datetime.getFullYear(), 0, 1);
- //First week of the year is th one with the first Thursday according to ISO8601
- if(onejan.getDay()!=4)
- onejan.setMonth(0, 1 + ((4 - onejan.getDay()+ 7) % 7));
- return Math.ceil((((datetime - onejan) / 86400000) + onejan.getDay() + 1) / 7);
- };
-
- _this.strToDateTime = function (sDateTime) {
- var tmpDate = [], timeOffset, currentTime;
-
- if (sDateTime && sDateTime instanceof Date && _this.isValidDate(sDateTime)) {
- return sDateTime;
- }
-
- tmpDate = /^(\+|\-)(.*)$/.exec(sDateTime);
- if (tmpDate) {
- tmpDate[2] = dateHelper.parseDate(tmpDate[2], options.formatDate);
- }
- if (tmpDate && tmpDate[2]) {
- timeOffset = tmpDate[2].getTime() - (tmpDate[2].getTimezoneOffset()) * 60000;
- currentTime = new Date((_this.now(true)).getTime() + parseInt(tmpDate[1] + '1', 10) * timeOffset);
- } else {
- currentTime = sDateTime ? dateHelper.parseDate(sDateTime, options.format) : _this.now();
- }
-
- if (!_this.isValidDate(currentTime)) {
- currentTime = _this.now();
- }
-
- return currentTime;
- };
-
- _this.strToDate = function (sDate) {
- if (sDate && sDate instanceof Date && _this.isValidDate(sDate)) {
- return sDate;
- }
-
- var currentTime = sDate ? dateHelper.parseDate(sDate, options.formatDate) : _this.now(true);
- if (!_this.isValidDate(currentTime)) {
- currentTime = _this.now(true);
- }
- return currentTime;
- };
-
- _this.strtotime = function (sTime) {
- if (sTime && sTime instanceof Date && _this.isValidDate(sTime)) {
- return sTime;
- }
- var currentTime = sTime ? dateHelper.parseDate(sTime, options.formatTime) : _this.now(true);
- if (!_this.isValidDate(currentTime)) {
- currentTime = _this.now(true);
- }
- return currentTime;
- };
-
- _this.str = function () {
- return dateHelper.formatDate(_this.currentTime, options.format);
- };
- _this.currentTime = this.now();
- };
-
- _xdsoft_datetime = new XDSoft_datetime();
-
- applyButton.on('touchend click', function (e) {//pathbrite
- e.preventDefault();
- datetimepicker.data('changed', true);
- _xdsoft_datetime.setCurrentTime(getCurrentValue());
- input.val(_xdsoft_datetime.str());
- datetimepicker.trigger('close.xdsoft');
- });
- month_picker
- .find('.xdsoft_today_button')
- .on('touchend mousedown.xdsoft', function () {
- datetimepicker.data('changed', true);
- _xdsoft_datetime.setCurrentTime(0, true);
- datetimepicker.trigger('afterOpen.xdsoft');
- }).on('dblclick.xdsoft', function () {
- var currentDate = _xdsoft_datetime.getCurrentTime(), minDate, maxDate;
- currentDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate());
- minDate = _xdsoft_datetime.strToDate(options.minDate);
- minDate = new Date(minDate.getFullYear(), minDate.getMonth(), minDate.getDate());
- if (currentDate < minDate) {
- return;
- }
- maxDate = _xdsoft_datetime.strToDate(options.maxDate);
- maxDate = new Date(maxDate.getFullYear(), maxDate.getMonth(), maxDate.getDate());
- if (currentDate > maxDate) {
- return;
- }
- input.val(_xdsoft_datetime.str());
- input.trigger('change');
- datetimepicker.trigger('close.xdsoft');
- });
- month_picker
- .find('.xdsoft_prev,.xdsoft_next')
- .on('touchend mousedown.xdsoft', function () {
- var $this = $(this),
- timer = 0,
- stop = false;
-
- (function arguments_callee1(v) {
- if ($this.hasClass(options.next)) {
- _xdsoft_datetime.nextMonth();
- } else if ($this.hasClass(options.prev)) {
- _xdsoft_datetime.prevMonth();
- }
- if (options.monthChangeSpinner) {
- if (!stop) {
- timer = setTimeout(arguments_callee1, v || 100);
- }
- }
- }(500));
-
- $([document.body, window]).on('touchend mouseup.xdsoft', function arguments_callee2() {
- clearTimeout(timer);
- stop = true;
- $([document.body, window]).off('touchend mouseup.xdsoft', arguments_callee2);
- });
- });
-
- timepicker
- .find('.xdsoft_prev,.xdsoft_next')
- .on('touchend mousedown.xdsoft', function () {
- var $this = $(this),
- timer = 0,
- stop = false,
- period = 110;
- (function arguments_callee4(v) {
- var pheight = timeboxparent[0].clientHeight,
- height = timebox[0].offsetHeight,
- top = Math.abs(parseInt(timebox.css('marginTop'), 10));
- if ($this.hasClass(options.next) && (height - pheight) - options.timeHeightInTimePicker >= top) {
- timebox.css('marginTop', '-' + (top + options.timeHeightInTimePicker) + 'px');
- } else if ($this.hasClass(options.prev) && top - options.timeHeightInTimePicker >= 0) {
- timebox.css('marginTop', '-' + (top - options.timeHeightInTimePicker) + 'px');
- }
+ 'use strict';
+
+ var currentlyScrollingTimeDiv = false;
+
+ var default_options = {
+ i18n: {
+ ar: { // Arabic
+ months: [
+ "كانون الثاني", "شباط", "آذار", "نيسان", "مايو", "حزيران", "تموز", "آب", "أيلول", "تشرين الأول", "تشرين الثاني", "كانون الأول"
+ ],
+ dayOfWeekShort: [
+ "ن", "ث", "ع", "خ", "ج", "س", "ح"
+ ],
+ dayOfWeek: ["الأحد", "الاثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت", "الأحد"]
+ },
+ ro: { // Romanian
+ months: [
+ "Ianuarie", "Februarie", "Martie", "Aprilie", "Mai", "Iunie", "Iulie", "August", "Septembrie", "Octombrie", "Noiembrie", "Decembrie"
+ ],
+ dayOfWeekShort: [
+ "Du", "Lu", "Ma", "Mi", "Jo", "Vi", "Sâ"
+ ],
+ dayOfWeek: ["Duminică", "Luni", "Marţi", "Miercuri", "Joi", "Vineri", "Sâmbătă"]
+ },
+ id: { // Indonesian
+ months: [
+ "Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"
+ ],
+ dayOfWeekShort: [
+ "Min", "Sen", "Sel", "Rab", "Kam", "Jum", "Sab"
+ ],
+ dayOfWeek: ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"]
+ },
+ is: { // Icelandic
+ months: [
+ "Janúar", "Febrúar", "Mars", "Apríl", "Maí", "Júní", "Júlí", "Ágúst", "September", "Október", "Nóvember", "Desember"
+ ],
+ dayOfWeekShort: [
+ "Sun", "Mán", "Þrið", "Mið", "Fim", "Fös", "Lau"
+ ],
+ dayOfWeek: ["Sunnudagur", "Mánudagur", "Þriðjudagur", "Miðvikudagur", "Fimmtudagur", "Föstudagur", "Laugardagur"]
+ },
+ bg: { // Bulgarian
+ months: [
+ "Януари", "Февруари", "Март", "Април", "Май", "Юни", "Юли", "Август", "Септември", "Октомври", "Ноември", "Декември"
+ ],
+ dayOfWeekShort: [
+ "Нд", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"
+ ],
+ dayOfWeek: ["Неделя", "Понеделник", "Вторник", "Сряда", "Четвъртък", "Петък", "Събота"]
+ },
+ fa: { // Persian/Farsi
+ months: [
+ 'فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور', 'مهر', 'آبان', 'آذر', 'دی', 'بهمن', 'اسفند'
+ ],
+ dayOfWeekShort: [
+ 'یکشنبه', 'دوشنبه', 'سه شنبه', 'چهارشنبه', 'پنجشنبه', 'جمعه', 'شنبه'
+ ],
+ dayOfWeek: ["یکشنبه", "دوشنبه", "سهشنبه", "چهارشنبه", "پنجشنبه", "جمعه", "شنبه", "یکشنبه"]
+ },
+ ru: { // Russian
+ months: [
+ 'Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'
+ ],
+ dayOfWeekShort: [
+ "Вс", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"
+ ],
+ dayOfWeek: ["Воскресенье", "Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота"]
+ },
+ uk: { // Ukrainian
+ months: [
+ 'Січень', 'Лютий', 'Березень', 'Квітень', 'Травень', 'Червень', 'Липень', 'Серпень', 'Вересень', 'Жовтень', 'Листопад', 'Грудень'
+ ],
+ dayOfWeekShort: [
+ "Ндл", "Пнд", "Втр", "Срд", "Чтв", "Птн", "Сбт"
+ ],
+ dayOfWeek: ["Неділя", "Понеділок", "Вівторок", "Середа", "Четвер", "П'ятниця", "Субота"]
+ },
+ en: { // English
+ months: [
+ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
+ ],
+ dayOfWeekShort: [
+ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
+ ],
+ dayOfWeek: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
+ },
+ el: { // Ελληνικά
+ months: [
+ "Ιανουάριος", "Φεβρουάριος", "Μάρτιος", "Απρίλιος", "Μάιος", "Ιούνιος", "Ιούλιος", "Αύγουστος", "Σεπτέμβριος", "Οκτώβριος", "Νοέμβριος", "Δεκέμβριος"
+ ],
+ dayOfWeekShort: [
+ "Κυρ", "Δευ", "Τρι", "Τετ", "Πεμ", "Παρ", "Σαβ"
+ ],
+ dayOfWeek: ["Κυριακή", "Δευτέρα", "Τρίτη", "Τετάρτη", "Πέμπτη", "Παρασκευή", "Σάββατο"]
+ },
+ de: { // German
+ months: [
+ 'Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'
+ ],
+ dayOfWeekShort: [
+ "So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"
+ ],
+ dayOfWeek: ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"]
+ },
+ nl: { // Dutch
+ months: [
+ "januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december"
+ ],
+ dayOfWeekShort: [
+ "zo", "ma", "di", "wo", "do", "vr", "za"
+ ],
+ dayOfWeek: ["zondag", "maandag", "dinsdag", "woensdag", "donderdag", "vrijdag", "zaterdag"]
+ },
+ tr: { // Turkish
+ months: [
+ "Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık"
+ ],
+ dayOfWeekShort: [
+ "Paz", "Pts", "Sal", "Çar", "Per", "Cum", "Cts"
+ ],
+ dayOfWeek: ["Pazar", "Pazartesi", "Salı", "Çarşamba", "Perşembe", "Cuma", "Cumartesi"]
+ },
+ fr: { //French
+ months: [
+ "Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"
+ ],
+ dayOfWeekShort: [
+ "Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"
+ ],
+ dayOfWeek: ["dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi"]
+ },
+ es: { // Spanish
+ months: [
+ "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"
+ ],
+ dayOfWeekShort: [
+ "Dom", "Lun", "Mar", "Mié", "Jue", "Vie", "Sáb"
+ ],
+ dayOfWeek: ["Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado"]
+ },
+ th: { // Thai
+ months: [
+ 'มกราคม', 'กุมภาพันธ์', 'มีนาคม', 'เมษายน', 'พฤษภาคม', 'มิถุนายน', 'กรกฎาคม', 'สิงหาคม', 'กันยายน', 'ตุลาคม', 'พฤศจิกายน', 'ธันวาคม'
+ ],
+ dayOfWeekShort: [
+ 'อา.', 'จ.', 'อ.', 'พ.', 'พฤ.', 'ศ.', 'ส.'
+ ],
+ dayOfWeek: ["อาทิตย์", "จันทร์", "อังคาร", "พุธ", "พฤหัส", "ศุกร์", "เสาร์", "อาทิตย์"]
+ },
+ pl: { // Polish
+ months: [
+ "styczeń", "luty", "marzec", "kwiecień", "maj", "czerwiec", "lipiec", "sierpień", "wrzesień", "październik", "listopad", "grudzień"
+ ],
+ dayOfWeekShort: [
+ "nd", "pn", "wt", "śr", "cz", "pt", "sb"
+ ],
+ dayOfWeek: ["niedziela", "poniedziałek", "wtorek", "środa", "czwartek", "piątek", "sobota"]
+ },
+ pt: { // Portuguese
+ months: [
+ "Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"
+ ],
+ dayOfWeekShort: [
+ "Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sab"
+ ],
+ dayOfWeek: ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"]
+ },
+ ch: { // Simplified Chinese
+ months: [
+ "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"
+ ],
+ dayOfWeekShort: [
+ "日", "一", "二", "三", "四", "五", "六"
+ ]
+ },
+ se: { // Swedish
+ months: [
+ "Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December"
+ ],
+ dayOfWeekShort: [
+ "Sön", "Mån", "Tis", "Ons", "Tor", "Fre", "Lör"
+ ]
+ },
+ kr: { // Korean
+ months: [
+ "1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"
+ ],
+ dayOfWeekShort: [
+ "일", "월", "화", "수", "목", "금", "토"
+ ],
+ dayOfWeek: ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"]
+ },
+ it: { // Italian
+ months: [
+ "Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"
+ ],
+ dayOfWeekShort: [
+ "Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab"
+ ],
+ dayOfWeek: ["Domenica", "Lunedì", "Martedì", "Mercoledì", "Giovedì", "Venerdì", "Sabato"]
+ },
+ da: { // Dansk
+ months: [
+ "January", "Februar", "Marts", "April", "Maj", "Juni", "July", "August", "September", "Oktober", "November", "December"
+ ],
+ dayOfWeekShort: [
+ "Søn", "Man", "Tir", "Ons", "Tor", "Fre", "Lør"
+ ],
+ dayOfWeek: ["søndag", "mandag", "tirsdag", "onsdag", "torsdag", "fredag", "lørdag"]
+ },
+ no: { // Norwegian
+ months: [
+ "Januar", "Februar", "Mars", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Desember"
+ ],
+ dayOfWeekShort: [
+ "Søn", "Man", "Tir", "Ons", "Tor", "Fre", "Lør"
+ ],
+ dayOfWeek: ['Søndag', 'Mandag', 'Tirsdag', 'Onsdag', 'Torsdag', 'Fredag', 'Lørdag']
+ },
+ ja: { // Japanese
+ months: [
+ "1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"
+ ],
+ dayOfWeekShort: [
+ "日", "月", "火", "水", "木", "金", "土"
+ ],
+ dayOfWeek: ["日曜", "月曜", "火曜", "水曜", "木曜", "金曜", "土曜"]
+ },
+ vi: { // Vietnamese
+ months: [
+ "Tháng 1", "Tháng 2", "Tháng 3", "Tháng 4", "Tháng 5", "Tháng 6", "Tháng 7", "Tháng 8", "Tháng 9", "Tháng 10", "Tháng 11", "Tháng 12"
+ ],
+ dayOfWeekShort: [
+ "CN", "T2", "T3", "T4", "T5", "T6", "T7"
+ ],
+ dayOfWeek: ["Chủ nhật", "Thứ hai", "Thứ ba", "Thứ tư", "Thứ năm", "Thứ sáu", "Thứ bảy"]
+ },
+ sl: { // Slovenščina
+ months: [
+ "Januar", "Februar", "Marec", "April", "Maj", "Junij", "Julij", "Avgust", "September", "Oktober", "November", "December"
+ ],
+ dayOfWeekShort: [
+ "Ned", "Pon", "Tor", "Sre", "Čet", "Pet", "Sob"
+ ],
+ dayOfWeek: ["Nedelja", "Ponedeljek", "Torek", "Sreda", "Četrtek", "Petek", "Sobota"]
+ },
+ cs: { // Čeština
+ months: [
+ "Leden", "Únor", "Březen", "Duben", "Květen", "Červen", "Červenec", "Srpen", "Září", "Říjen", "Listopad", "Prosinec"
+ ],
+ dayOfWeekShort: [
+ "Ne", "Po", "Út", "St", "Čt", "Pá", "So"
+ ]
+ },
+ hu: { // Hungarian
+ months: [
+ "Január", "Február", "Március", "Április", "Május", "Június", "Július", "Augusztus", "Szeptember", "Október", "November", "December"
+ ],
+ dayOfWeekShort: [
+ "Va", "Hé", "Ke", "Sze", "Cs", "Pé", "Szo"
+ ],
+ dayOfWeek: ["vasárnap", "hétfő", "kedd", "szerda", "csütörtök", "péntek", "szombat"]
+ },
+ az: { //Azerbaijanian (Azeri)
+ months: [
+ "Yanvar", "Fevral", "Mart", "Aprel", "May", "Iyun", "Iyul", "Avqust", "Sentyabr", "Oktyabr", "Noyabr", "Dekabr"
+ ],
+ dayOfWeekShort: [
+ "B", "Be", "Ça", "Ç", "Ca", "C", "Ş"
+ ],
+ dayOfWeek: ["Bazar", "Bazar ertəsi", "Çərşənbə axşamı", "Çərşənbə", "Cümə axşamı", "Cümə", "Şənbə"]
+ },
+ bs: { //Bosanski
+ months: [
+ "Januar", "Februar", "Mart", "April", "Maj", "Jun", "Jul", "Avgust", "Septembar", "Oktobar", "Novembar", "Decembar"
+ ],
+ dayOfWeekShort: [
+ "Ned", "Pon", "Uto", "Sri", "Čet", "Pet", "Sub"
+ ],
+ dayOfWeek: ["Nedjelja","Ponedjeljak", "Utorak", "Srijeda", "Četvrtak", "Petak", "Subota"]
+ },
+ ca: { //Català
+ months: [
+ "Gener", "Febrer", "Març", "Abril", "Maig", "Juny", "Juliol", "Agost", "Setembre", "Octubre", "Novembre", "Desembre"
+ ],
+ dayOfWeekShort: [
+ "Dg", "Dl", "Dt", "Dc", "Dj", "Dv", "Ds"
+ ],
+ dayOfWeek: ["Diumenge", "Dilluns", "Dimarts", "Dimecres", "Dijous", "Divendres", "Dissabte"]
+ },
+ 'en-GB': { //English (British)
+ months: [
+ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
+ ],
+ dayOfWeekShort: [
+ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
+ ],
+ dayOfWeek: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
+ },
+ et: { //"Eesti"
+ months: [
+ "Jaanuar", "Veebruar", "Märts", "Aprill", "Mai", "Juuni", "Juuli", "August", "September", "Oktoober", "November", "Detsember"
+ ],
+ dayOfWeekShort: [
+ "P", "E", "T", "K", "N", "R", "L"
+ ],
+ dayOfWeek: ["Pühapäev", "Esmaspäev", "Teisipäev", "Kolmapäev", "Neljapäev", "Reede", "Laupäev"]
+ },
+ eu: { //Euskara
+ months: [
+ "Urtarrila", "Otsaila", "Martxoa", "Apirila", "Maiatza", "Ekaina", "Uztaila", "Abuztua", "Iraila", "Urria", "Azaroa", "Abendua"
+ ],
+ dayOfWeekShort: [
+ "Ig.", "Al.", "Ar.", "Az.", "Og.", "Or.", "La."
+ ],
+ dayOfWeek: ['Igandea', 'Astelehena', 'Asteartea', 'Asteazkena', 'Osteguna', 'Ostirala', 'Larunbata']
+ },
+ fi: { //Finnish (Suomi)
+ months: [
+ "Tammikuu", "Helmikuu", "Maaliskuu", "Huhtikuu", "Toukokuu", "Kesäkuu", "Heinäkuu", "Elokuu", "Syyskuu", "Lokakuu", "Marraskuu", "Joulukuu"
+ ],
+ dayOfWeekShort: [
+ "Su", "Ma", "Ti", "Ke", "To", "Pe", "La"
+ ],
+ dayOfWeek: ["sunnuntai", "maanantai", "tiistai", "keskiviikko", "torstai", "perjantai", "lauantai"]
+ },
+ gl: { //Galego
+ months: [
+ "Xan", "Feb", "Maz", "Abr", "Mai", "Xun", "Xul", "Ago", "Set", "Out", "Nov", "Dec"
+ ],
+ dayOfWeekShort: [
+ "Dom", "Lun", "Mar", "Mer", "Xov", "Ven", "Sab"
+ ],
+ dayOfWeek: ["Domingo", "Luns", "Martes", "Mércores", "Xoves", "Venres", "Sábado"]
+ },
+ hr: { //Hrvatski
+ months: [
+ "Siječanj", "Veljača", "Ožujak", "Travanj", "Svibanj", "Lipanj", "Srpanj", "Kolovoz", "Rujan", "Listopad", "Studeni", "Prosinac"
+ ],
+ dayOfWeekShort: [
+ "Ned", "Pon", "Uto", "Sri", "Čet", "Pet", "Sub"
+ ],
+ dayOfWeek: ["Nedjelja", "Ponedjeljak", "Utorak", "Srijeda", "Četvrtak", "Petak", "Subota"]
+ },
+ ko: { //Korean (한국어)
+ months: [
+ "1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"
+ ],
+ dayOfWeekShort: [
+ "일", "월", "화", "수", "목", "금", "토"
+ ],
+ dayOfWeek: ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"]
+ },
+ lt: { //Lithuanian (lietuvių)
+ months: [
+ "Sausio", "Vasario", "Kovo", "Balandžio", "Gegužės", "Birželio", "Liepos", "Rugpjūčio", "Rugsėjo", "Spalio", "Lapkričio", "Gruodžio"
+ ],
+ dayOfWeekShort: [
+ "Sek", "Pir", "Ant", "Tre", "Ket", "Pen", "Šeš"
+ ],
+ dayOfWeek: ["Sekmadienis", "Pirmadienis", "Antradienis", "Trečiadienis", "Ketvirtadienis", "Penktadienis", "Šeštadienis"]
+ },
+ lv: { //Latvian (Latviešu)
+ months: [
+ "Janvāris", "Februāris", "Marts", "Aprīlis ", "Maijs", "Jūnijs", "Jūlijs", "Augusts", "Septembris", "Oktobris", "Novembris", "Decembris"
+ ],
+ dayOfWeekShort: [
+ "Sv", "Pr", "Ot", "Tr", "Ct", "Pk", "St"
+ ],
+ dayOfWeek: ["Svētdiena", "Pirmdiena", "Otrdiena", "Trešdiena", "Ceturtdiena", "Piektdiena", "Sestdiena"]
+ },
+ mk: { //Macedonian (Македонски)
+ months: [
+ "јануари", "февруари", "март", "април", "мај", "јуни", "јули", "август", "септември", "октомври", "ноември", "декември"
+ ],
+ dayOfWeekShort: [
+ "нед", "пон", "вто", "сре", "чет", "пет", "саб"
+ ],
+ dayOfWeek: ["Недела", "Понеделник", "Вторник", "Среда", "Четврток", "Петок", "Сабота"]
+ },
+ mn: { //Mongolian (Монгол)
+ months: [
+ "1-р сар", "2-р сар", "3-р сар", "4-р сар", "5-р сар", "6-р сар", "7-р сар", "8-р сар", "9-р сар", "10-р сар", "11-р сар", "12-р сар"
+ ],
+ dayOfWeekShort: [
+ "Дав", "Мяг", "Лха", "Пүр", "Бсн", "Бям", "Ням"
+ ],
+ dayOfWeek: ["Даваа", "Мягмар", "Лхагва", "Пүрэв", "Баасан", "Бямба", "Ням"]
+ },
+ 'pt-BR': { //Português(Brasil)
+ months: [
+ "Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"
+ ],
+ dayOfWeekShort: [
+ "Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb"
+ ],
+ dayOfWeek: ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"]
+ },
+ sk: { //Slovenčina
+ months: [
+ "Január", "Február", "Marec", "Apríl", "Máj", "Jún", "Júl", "August", "September", "Október", "November", "December"
+ ],
+ dayOfWeekShort: [
+ "Ne", "Po", "Ut", "St", "Št", "Pi", "So"
+ ],
+ dayOfWeek: ["Nedeľa", "Pondelok", "Utorok", "Streda", "Štvrtok", "Piatok", "Sobota"]
+ },
+ sq: { //Albanian (Shqip)
+ months: [
+ "Janar", "Shkurt", "Mars", "Prill", "Maj", "Qershor", "Korrik", "Gusht", "Shtator", "Tetor", "Nëntor", "Dhjetor"
+ ],
+ dayOfWeekShort: [
+ "Die", "Hën", "Mar", "Mër", "Enj", "Pre", "Shtu"
+ ],
+ dayOfWeek: ["E Diel", "E Hënë", "E Martē", "E Mërkurë", "E Enjte", "E Premte", "E Shtunë"]
+ },
+ 'sr-YU': { //Serbian (Srpski)
+ months: [
+ "Januar", "Februar", "Mart", "April", "Maj", "Jun", "Jul", "Avgust", "Septembar", "Oktobar", "Novembar", "Decembar"
+ ],
+ dayOfWeekShort: [
+ "Ned", "Pon", "Uto", "Sre", "čet", "Pet", "Sub"
+ ],
+ dayOfWeek: ["Nedelja","Ponedeljak", "Utorak", "Sreda", "Četvrtak", "Petak", "Subota"]
+ },
+ sr: { //Serbian Cyrillic (Српски)
+ months: [
+ "јануар", "фебруар", "март", "април", "мај", "јун", "јул", "август", "септембар", "октобар", "новембар", "децембар"
+ ],
+ dayOfWeekShort: [
+ "нед", "пон", "уто", "сре", "чет", "пет", "суб"
+ ],
+ dayOfWeek: ["Недеља","Понедељак", "Уторак", "Среда", "Четвртак", "Петак", "Субота"]
+ },
+ sv: { //Svenska
+ months: [
+ "Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December"
+ ],
+ dayOfWeekShort: [
+ "Sön", "Mån", "Tis", "Ons", "Tor", "Fre", "Lör"
+ ],
+ dayOfWeek: ["Söndag", "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag"]
+ },
+ 'zh-TW': { //Traditional Chinese (繁體中文)
+ months: [
+ "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"
+ ],
+ dayOfWeekShort: [
+ "日", "一", "二", "三", "四", "五", "六"
+ ],
+ dayOfWeek: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]
+ },
+ zh: { //Simplified Chinese (简体中文)
+ months: [
+ "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"
+ ],
+ dayOfWeekShort: [
+ "日", "一", "二", "三", "四", "五", "六"
+ ],
+ dayOfWeek: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]
+ },
+ he: { //Hebrew (עברית)
+ months: [
+ 'ינואר', 'פברואר', 'מרץ', 'אפריל', 'מאי', 'יוני', 'יולי', 'אוגוסט', 'ספטמבר', 'אוקטובר', 'נובמבר', 'דצמבר'
+ ],
+ dayOfWeekShort: [
+ 'א\'', 'ב\'', 'ג\'', 'ד\'', 'ה\'', 'ו\'', 'שבת'
+ ],
+ dayOfWeek: ["ראשון", "שני", "שלישי", "רביעי", "חמישי", "שישי", "שבת", "ראשון"]
+ },
+ hy: { // Armenian
+ months: [
+ "Հունվար", "Փետրվար", "Մարտ", "Ապրիլ", "Մայիս", "Հունիս", "Հուլիս", "Օգոստոս", "Սեպտեմբեր", "Հոկտեմբեր", "Նոյեմբեր", "Դեկտեմբեր"
+ ],
+ dayOfWeekShort: [
+ "Կի", "Երկ", "Երք", "Չոր", "Հնգ", "Ուրբ", "Շբթ"
+ ],
+ dayOfWeek: ["Կիրակի", "Երկուշաբթի", "Երեքշաբթի", "Չորեքշաբթի", "Հինգշաբթի", "Ուրբաթ", "Շաբաթ"]
+ },
+ kg: { // Kyrgyz
+ months: [
+ 'Үчтүн айы', 'Бирдин айы', 'Жалган Куран', 'Чын Куран', 'Бугу', 'Кулжа', 'Теке', 'Баш Оона', 'Аяк Оона', 'Тогуздун айы', 'Жетинин айы', 'Бештин айы'
+ ],
+ dayOfWeekShort: [
+ "Жек", "Дүй", "Шей", "Шар", "Бей", "Жум", "Ише"
+ ],
+ dayOfWeek: [
+ "Жекшемб", "Дүйшөмб", "Шейшемб", "Шаршемб", "Бейшемби", "Жума", "Ишенб"
+ ]
+ },
+ rm: { // Romansh
+ months: [
+ "Schaner", "Favrer", "Mars", "Avrigl", "Matg", "Zercladur", "Fanadur", "Avust", "Settember", "October", "November", "December"
+ ],
+ dayOfWeekShort: [
+ "Du", "Gli", "Ma", "Me", "Gie", "Ve", "So"
+ ],
+ dayOfWeek: [
+ "Dumengia", "Glindesdi", "Mardi", "Mesemna", "Gievgia", "Venderdi", "Sonda"
+ ]
+ },
+ ka: { // Georgian
+ months: [
+ 'იანვარი', 'თებერვალი', 'მარტი', 'აპრილი', 'მაისი', 'ივნისი', 'ივლისი', 'აგვისტო', 'სექტემბერი', 'ოქტომბერი', 'ნოემბერი', 'დეკემბერი'
+ ],
+ dayOfWeekShort: [
+ "კვ", "ორშ", "სამშ", "ოთხ", "ხუთ", "პარ", "შაბ"
+ ],
+ dayOfWeek: ["კვირა", "ორშაბათი", "სამშაბათი", "ოთხშაბათი", "ხუთშაბათი", "პარასკევი", "შაბათი"]
+ },
+ },
+ value: '',
+ rtl: false,
+
+ format: 'Y/m/d H:i',
+ formatTime: 'H:i',
+ formatDate: 'Y/m/d',
+
+ startDate: false, // new Date(), '1986/12/08', '-1970/01/05','-1970/01/05',
+ step: 60,
+ monthChangeSpinner: true,
+
+ closeOnDateSelect: false,
+ closeOnTimeSelect: true,
+ closeOnWithoutClick: true,
+ closeOnInputClick: true,
+
+ timepicker: true,
+ datepicker: true,
+ weeks: false,
+
+ defaultTime: false, // use formatTime format (ex. '10:00' for formatTime: 'H:i')
+ defaultDate: false, // use formatDate format (ex new Date() or '1986/12/08' or '-1970/01/05' or '-1970/01/05')
+
+ minDate: false,
+ maxDate: false,
+ minTime: false,
+ maxTime: false,
+ disabledMinTime: false,
+ disabledMaxTime: false,
+
+ allowTimes: [],
+ opened: false,
+ initTime: true,
+ inline: false,
+ theme: '',
+
+ onSelectDate: function () {},
+ onSelectTime: function () {},
+ onChangeMonth: function () {},
+ onGetWeekOfYear: function () {},
+ onChangeYear: function () {},
+ onChangeDateTime: function () {},
+ onShow: function () {},
+ onClose: function () {},
+ onGenerate: function () {},
+
+ withoutCopyright: true,
+ inverseButton: false,
+ hours12: false,
+ next: 'xdsoft_next',
+ prev : 'xdsoft_prev',
+ dayOfWeekStart: 0,
+ parentID: 'body',
+ timeHeightInTimePicker: 25,
+ timepickerScrollbar: true,
+ todayButton: true,
+ prevButton: true,
+ nextButton: true,
+ defaultSelect: true,
+
+ scrollMonth: true,
+ scrollTime: true,
+ scrollInput: true,
+
+ lazyInit: false,
+ mask: false,
+ validateOnBlur: true,
+ allowBlank: true,
+ yearStart: 1950,
+ yearEnd: 2050,
+ monthStart: 0,
+ monthEnd: 11,
+ style: '',
+ id: '',
+ fixed: false,
+ roundTime: 'round', // ceil, floor
+ className: '',
+ weekends: [],
+ highlightedDates: [],
+ highlightedPeriods: [],
+ allowDates : [],
+ allowDateRe : null,
+ disabledDates : [],
+ disabledWeekDays: [],
+ yearOffset: 0,
+ beforeShowDay: null,
+
+ enterLikeTab: true,
+ showApplyButton: false
+ };
+
+ var dateHelper = null,
+ globalLocaleDefault = 'en',
+ globalLocale = 'en';
+
+ var dateFormatterOptionsDefault = {
+ meridiem: ['AM', 'PM']
+ };
+
+ var initDateFormatter = function(){
+ var locale = default_options.i18n[globalLocale],
+ opts = {
+ days: locale.dayOfWeek,
+ daysShort: locale.dayOfWeekShort,
+ months: locale.months,
+ monthsShort: $.map(locale.months, function(n){ return n.substring(0, 3) }),
+ };
+
+ dateHelper = new DateFormatter({
+ dateSettings: $.extend({}, dateFormatterOptionsDefault, opts)
+ });
+ };
+
+ // for locale settings
+ $.datetimepicker = {
+ setLocale: function(locale){
+ var newLocale = default_options.i18n[locale]?locale:globalLocaleDefault;
+ if(globalLocale != newLocale){
+ globalLocale = newLocale;
+ // reinit date formatter
+ initDateFormatter();
+ }
+ },
+ setDateFormatter: function(dateFormatter) {
+ dateHelper = dateFormatter;
+ },
+ RFC_2822: 'D, d M Y H:i:s O',
+ ATOM: 'Y-m-d\TH:i:sP',
+ ISO_8601: 'Y-m-d\TH:i:sO',
+ RFC_822: 'D, d M y H:i:s O',
+ RFC_850: 'l, d-M-y H:i:s T',
+ RFC_1036: 'D, d M y H:i:s O',
+ RFC_1123: 'D, d M Y H:i:s O',
+ RSS: 'D, d M Y H:i:s O',
+ W3C: 'Y-m-d\TH:i:sP'
+ };
+
+ // first init date formatter
+ initDateFormatter();
+
+ // fix for ie8
+ if (!window.getComputedStyle) {
+ window.getComputedStyle = function (el, pseudo) {
+ this.el = el;
+ this.getPropertyValue = function (prop) {
+ var re = /(\-([a-z]){1})/g;
+ if (prop === 'float') {
+ prop = 'styleFloat';
+ }
+ if (re.test(prop)) {
+ prop = prop.replace(re, function (a, b, c) {
+ return c.toUpperCase();
+ });
+ }
+ return el.currentStyle[prop] || null;
+ };
+ return this;
+ };
+ }
+ if (!Array.prototype.indexOf) {
+ Array.prototype.indexOf = function (obj, start) {
+ var i, j;
+ for (i = (start || 0), j = this.length; i < j; i += 1) {
+ if (this[i] === obj) { return i; }
+ }
+ return -1;
+ };
+ }
+ Date.prototype.countDaysInMonth = function () {
+ return new Date(this.getFullYear(), this.getMonth() + 1, 0).getDate();
+ };
+ $.fn.xdsoftScroller = function (percent) {
+ return this.each(function () {
+ var timeboxparent = $(this),
+ pointerEventToXY = function (e) {
+ var out = {x: 0, y: 0},
+ touch;
+ if (e.type === 'touchstart' || e.type === 'touchmove' || e.type === 'touchend' || e.type === 'touchcancel') {
+ touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
+ out.x = touch.clientX;
+ out.y = touch.clientY;
+ } else if (e.type === 'mousedown' || e.type === 'mouseup' || e.type === 'mousemove' || e.type === 'mouseover' || e.type === 'mouseout' || e.type === 'mouseenter' || e.type === 'mouseleave') {
+ out.x = e.clientX;
+ out.y = e.clientY;
+ }
+ return out;
+ },
+ timebox,
+ parentHeight,
+ height,
+ scrollbar,
+ scroller,
+ maximumOffset = 100,
+ start = false,
+ startY = 0,
+ startTop = 0,
+ h1 = 0,
+ touchStart = false,
+ startTopScroll = 0,
+ calcOffset = function () {};
+ if (percent === 'hide') {
+ timeboxparent.find('.xdsoft_scrollbar').hide();
+ return;
+ }
+ if (!$(this).hasClass('xdsoft_scroller_box')) {
+ timebox = timeboxparent.children().eq(0);
+ parentHeight = timeboxparent[0].clientHeight;
+ height = timebox[0].offsetHeight;
+ scrollbar = $('
');
+ scroller = $('
');
+ scrollbar.append(scroller);
+
+ timeboxparent.addClass('xdsoft_scroller_box').append(scrollbar);
+ calcOffset = function calcOffset(event) {
+ var offset = pointerEventToXY(event).y - startY + startTopScroll;
+ if (offset < 0) {
+ offset = 0;
+ }
+ if (offset + scroller[0].offsetHeight > h1) {
+ offset = h1 - scroller[0].offsetHeight;
+ }
+ timeboxparent.trigger('scroll_element.xdsoft_scroller', [maximumOffset ? offset / maximumOffset : 0]);
+ };
+
+ scroller
+ .on('touchstart.xdsoft_scroller mousedown.xdsoft_scroller', function (event) {
+ if (!parentHeight) {
+ timeboxparent.trigger('resize_scroll.xdsoft_scroller', [percent]);
+ }
+
+ startY = pointerEventToXY(event).y;
+ startTopScroll = parseInt(scroller.css('margin-top'), 10);
+ h1 = scrollbar[0].offsetHeight;
+
+ if (event.type === 'mousedown' || event.type === 'touchstart') {
+ if (document) {
+ $(document.body).addClass('xdsoft_noselect');
+ }
+ $([document.body, window]).on('touchend mouseup.xdsoft_scroller', function arguments_callee() {
+ $([document.body, window]).off('touchend mouseup.xdsoft_scroller', arguments_callee)
+ .off('mousemove.xdsoft_scroller', calcOffset)
+ .removeClass('xdsoft_noselect');
+ });
+ $(document.body).on('mousemove.xdsoft_scroller', calcOffset);
+ } else {
+ touchStart = true;
+ event.stopPropagation();
+ event.preventDefault();
+ }
+ })
+ .on('touchmove', function (event) {
+ if (touchStart) {
+ event.preventDefault();
+ calcOffset(event);
+ }
+ })
+ .on('touchend touchcancel', function () {
+ touchStart = false;
+ startTopScroll = 0;
+ });
+
+ timeboxparent
+ .on('scroll_element.xdsoft_scroller', function (event, percentage) {
+ if (!parentHeight) {
+ timeboxparent.trigger('resize_scroll.xdsoft_scroller', [percentage, true]);
+ }
+ percentage = percentage > 1 ? 1 : (percentage < 0 || isNaN(percentage)) ? 0 : percentage;
+
+ scroller.css('margin-top', maximumOffset * percentage);
+
+ setTimeout(function () {
+ timebox.css('marginTop', -parseInt((timebox[0].offsetHeight - parentHeight) * percentage, 10));
+ }, 10);
+ })
+ .on('resize_scroll.xdsoft_scroller', function (event, percentage, noTriggerScroll) {
+ var percent, sh;
+ parentHeight = timeboxparent[0].clientHeight;
+ height = timebox[0].offsetHeight;
+ percent = parentHeight / height;
+ sh = percent * scrollbar[0].offsetHeight;
+ if (percent > 1) {
+ scroller.hide();
+ } else {
+ scroller.show();
+ scroller.css('height', parseInt(sh > 10 ? sh : 10, 10));
+ maximumOffset = scrollbar[0].offsetHeight - scroller[0].offsetHeight;
+ if (noTriggerScroll !== true) {
+ timeboxparent.trigger('scroll_element.xdsoft_scroller', [percentage || Math.abs(parseInt(timebox.css('marginTop'), 10)) / (height - parentHeight)]);
+ }
+ }
+ });
+
+ timeboxparent.on('mousewheel', function (event) {
+ var top = Math.abs(parseInt(timebox.css('marginTop'), 10));
+
+ top = top - (event.deltaY * 20);
+ if (top < 0) {
+ top = 0;
+ }
+
+ timeboxparent.trigger('scroll_element.xdsoft_scroller', [top / (height - parentHeight)]);
+ event.stopPropagation();
+ return false;
+ });
+
+ timeboxparent.on('touchstart', function (event) {
+ start = pointerEventToXY(event);
+ startTop = Math.abs(parseInt(timebox.css('marginTop'), 10));
+ });
+
+ timeboxparent.on('touchmove', function (event) {
+ if (start) {
+ event.preventDefault();
+ var coord = pointerEventToXY(event);
+ timeboxparent.trigger('scroll_element.xdsoft_scroller', [(startTop - (coord.y - start.y)) / (height - parentHeight)]);
+ }
+ });
+
+ timeboxparent.on('touchend touchcancel', function () {
+ start = false;
+ startTop = 0;
+ });
+ }
+ timeboxparent.trigger('resize_scroll.xdsoft_scroller', [percent]);
+ });
+ };
+
+ $.fn.datetimepicker = function (opt, opt2) {
+ var result = this,
+ KEY0 = 48,
+ KEY9 = 57,
+ _KEY0 = 96,
+ _KEY9 = 105,
+ CTRLKEY = 17,
+ DEL = 46,
+ ENTER = 13,
+ ESC = 27,
+ BACKSPACE = 8,
+ ARROWLEFT = 37,
+ ARROWUP = 38,
+ ARROWRIGHT = 39,
+ ARROWDOWN = 40,
+ TAB = 9,
+ F5 = 116,
+ AKEY = 65,
+ CKEY = 67,
+ VKEY = 86,
+ ZKEY = 90,
+ YKEY = 89,
+ ctrlDown = false,
+ options = ($.isPlainObject(opt) || !opt) ? $.extend(true, {}, default_options, opt) : $.extend(true, {}, default_options),
+
+ lazyInitTimer = 0,
+ createDateTimePicker,
+ destroyDateTimePicker,
+
+ lazyInit = function (input) {
+ input
+ .on('open.xdsoft focusin.xdsoft mousedown.xdsoft touchstart', function initOnActionCallback() {
+ if (input.is(':disabled') || input.data('xdsoft_datetimepicker')) {
+ return;
+ }
+ clearTimeout(lazyInitTimer);
+ lazyInitTimer = setTimeout(function () {
+
+ if (!input.data('xdsoft_datetimepicker')) {
+ createDateTimePicker(input);
+ }
+ input
+ .off('open.xdsoft focusin.xdsoft mousedown.xdsoft touchstart', initOnActionCallback)
+ .trigger('open.xdsoft');
+ }, 100);
+ });
+ };
+
+ createDateTimePicker = function (input) {
+ var datetimepicker = $('
'),
+ xdsoft_copyright = $(''),
+ datepicker = $('
'),
+ month_picker = $(''),
+ calendar = $('
'),
+ timepicker = $(''),
+ timeboxparent = timepicker.find('.xdsoft_time_box').eq(0),
+ timebox = $('
'),
+ applyButton = $('Save Selected '),
+
+ monthselect = $(''),
+ yearselect = $(''),
+ triggerAfterOpen = false,
+ XDSoft_datetime,
+
+ xchangeTimer,
+ timerclick,
+ current_time_index,
+ setPos,
+ timer = 0,
+ _xdsoft_datetime,
+ forEachAncestorOf,
+ throttle;
+
+ if (options.id) {
+ datetimepicker.attr('id', options.id);
+ }
+ if (options.style) {
+ datetimepicker.attr('style', options.style);
+ }
+ if (options.weeks) {
+ datetimepicker.addClass('xdsoft_showweeks');
+ }
+ if (options.rtl) {
+ datetimepicker.addClass('xdsoft_rtl');
+ }
+
+ datetimepicker.addClass('xdsoft_' + options.theme);
+ datetimepicker.addClass(options.className);
+
+ month_picker
+ .find('.xdsoft_month span')
+ .after(monthselect);
+ month_picker
+ .find('.xdsoft_year span')
+ .after(yearselect);
+
+ month_picker
+ .find('.xdsoft_month,.xdsoft_year')
+ .on('touchstart mousedown.xdsoft', function (event) {
+ var select = $(this).find('.xdsoft_select').eq(0),
+ val = 0,
+ top = 0,
+ visible = select.is(':visible'),
+ items,
+ i;
+
+ month_picker
+ .find('.xdsoft_select')
+ .hide();
+ if (_xdsoft_datetime.currentTime) {
+ val = _xdsoft_datetime.currentTime[$(this).hasClass('xdsoft_month') ? 'getMonth' : 'getFullYear']();
+ }
+
+ select[visible ? 'hide' : 'show']();
+ for (items = select.find('div.xdsoft_option'), i = 0; i < items.length; i += 1) {
+ if (items.eq(i).data('value') === val) {
+ break;
+ } else {
+ top += items[0].offsetHeight;
+ }
+ }
+
+ select.xdsoftScroller(top / (select.children()[0].offsetHeight - (select[0].clientHeight)));
+ event.stopPropagation();
+ return false;
+ });
+
+ month_picker
+ .find('.xdsoft_select')
+ .xdsoftScroller()
+ .on('touchstart mousedown.xdsoft', function (event) {
+ event.stopPropagation();
+ event.preventDefault();
+ })
+ .on('touchstart mousedown.xdsoft', '.xdsoft_option', function () {
+ if (_xdsoft_datetime.currentTime === undefined || _xdsoft_datetime.currentTime === null) {
+ _xdsoft_datetime.currentTime = _xdsoft_datetime.now();
+ }
+
+ var year = _xdsoft_datetime.currentTime.getFullYear();
+ if (_xdsoft_datetime && _xdsoft_datetime.currentTime) {
+ _xdsoft_datetime.currentTime[$(this).parent().parent().hasClass('xdsoft_monthselect') ? 'setMonth' : 'setFullYear']($(this).data('value'));
+ }
+
+ $(this).parent().parent().hide();
+
+ datetimepicker.trigger('xchange.xdsoft');
+ if (options.onChangeMonth && $.isFunction(options.onChangeMonth)) {
+ options.onChangeMonth.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
+ }
+
+ if (year !== _xdsoft_datetime.currentTime.getFullYear() && $.isFunction(options.onChangeYear)) {
+ options.onChangeYear.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
+ }
+ });
+
+ datetimepicker.getValue = function () {
+ return _xdsoft_datetime.getCurrentTime();
+ };
+
+ datetimepicker.setOptions = function (_options) {
+ var highlightedDates = {};
+
+ options = $.extend(true, {}, options, _options);
+
+ if (_options.allowTimes && $.isArray(_options.allowTimes) && _options.allowTimes.length) {
+ options.allowTimes = $.extend(true, [], _options.allowTimes);
+ }
+
+ if (_options.weekends && $.isArray(_options.weekends) && _options.weekends.length) {
+ options.weekends = $.extend(true, [], _options.weekends);
+ }
+
+ if (_options.allowDates && $.isArray(_options.allowDates) && _options.allowDates.length) {
+ options.allowDates = $.extend(true, [], _options.allowDates);
+ }
+
+ if (_options.allowDateRe && Object.prototype.toString.call(_options.allowDateRe)==="[object String]") {
+ options.allowDateRe = new RegExp(_options.allowDateRe);
+ }
+
+ if (_options.highlightedDates && $.isArray(_options.highlightedDates) && _options.highlightedDates.length) {
+ $.each(_options.highlightedDates, function (index, value) {
+ var splitData = $.map(value.split(','), $.trim),
+ exDesc,
+ hDate = new HighlightedDate(dateHelper.parseDate(splitData[0], options.formatDate), splitData[1], splitData[2]), // date, desc, style
+ keyDate = dateHelper.formatDate(hDate.date, options.formatDate);
+ if (highlightedDates[keyDate] !== undefined) {
+ exDesc = highlightedDates[keyDate].desc;
+ if (exDesc && exDesc.length && hDate.desc && hDate.desc.length) {
+ highlightedDates[keyDate].desc = exDesc + "\n" + hDate.desc;
+ }
+ } else {
+ highlightedDates[keyDate] = hDate;
+ }
+ });
+
+ options.highlightedDates = $.extend(true, [], highlightedDates);
+ }
+
+ if (_options.highlightedPeriods && $.isArray(_options.highlightedPeriods) && _options.highlightedPeriods.length) {
+ highlightedDates = $.extend(true, [], options.highlightedDates);
+ $.each(_options.highlightedPeriods, function (index, value) {
+ var dateTest, // start date
+ dateEnd,
+ desc,
+ hDate,
+ keyDate,
+ exDesc,
+ style;
+ if ($.isArray(value)) {
+ dateTest = value[0];
+ dateEnd = value[1];
+ desc = value[2];
+ style = value[3];
+ }
+ else {
+ var splitData = $.map(value.split(','), $.trim);
+ dateTest = dateHelper.parseDate(splitData[0], options.formatDate);
+ dateEnd = dateHelper.parseDate(splitData[1], options.formatDate);
+ desc = splitData[2];
+ style = splitData[3];
+ }
+
+ while (dateTest <= dateEnd) {
+ hDate = new HighlightedDate(dateTest, desc, style);
+ keyDate = dateHelper.formatDate(dateTest, options.formatDate);
+ dateTest.setDate(dateTest.getDate() + 1);
+ if (highlightedDates[keyDate] !== undefined) {
+ exDesc = highlightedDates[keyDate].desc;
+ if (exDesc && exDesc.length && hDate.desc && hDate.desc.length) {
+ highlightedDates[keyDate].desc = exDesc + "\n" + hDate.desc;
+ }
+ } else {
+ highlightedDates[keyDate] = hDate;
+ }
+ }
+ });
+
+ options.highlightedDates = $.extend(true, [], highlightedDates);
+ }
+
+ if (_options.disabledDates && $.isArray(_options.disabledDates) && _options.disabledDates.length) {
+ options.disabledDates = $.extend(true, [], _options.disabledDates);
+ }
+
+ if (_options.disabledWeekDays && $.isArray(_options.disabledWeekDays) && _options.disabledWeekDays.length) {
+ options.disabledWeekDays = $.extend(true, [], _options.disabledWeekDays);
+ }
+
+ if ((options.open || options.opened) && (!options.inline)) {
+ input.trigger('open.xdsoft');
+ }
+
+ if (options.inline) {
+ triggerAfterOpen = true;
+ datetimepicker.addClass('xdsoft_inline');
+ input.after(datetimepicker).hide();
+ }
+
+ if (options.inverseButton) {
+ options.next = 'xdsoft_prev';
+ options.prev = 'xdsoft_next';
+ }
+
+ if (options.datepicker) {
+ datepicker.addClass('active');
+ } else {
+ datepicker.removeClass('active');
+ }
+
+ if (options.timepicker) {
+ timepicker.addClass('active');
+ } else {
+ timepicker.removeClass('active');
+ }
+
+ if (options.value) {
+ _xdsoft_datetime.setCurrentTime(options.value);
+ if (input && input.val) {
+ input.val(_xdsoft_datetime.str);
+ }
+ }
+
+ if (isNaN(options.dayOfWeekStart)) {
+ options.dayOfWeekStart = 0;
+ } else {
+ options.dayOfWeekStart = parseInt(options.dayOfWeekStart, 10) % 7;
+ }
+
+ if (!options.timepickerScrollbar) {
+ timeboxparent.xdsoftScroller('hide');
+ }
+
+ if (options.minDate && /^[\+\-](.*)$/.test(options.minDate)) {
+ options.minDate = dateHelper.formatDate(_xdsoft_datetime.strToDateTime(options.minDate), options.formatDate);
+ }
+
+ if (options.maxDate && /^[\+\-](.*)$/.test(options.maxDate)) {
+ options.maxDate = dateHelper.formatDate(_xdsoft_datetime.strToDateTime(options.maxDate), options.formatDate);
+ }
+
+ applyButton.toggle(options.showApplyButton);
+
+ month_picker
+ .find('.xdsoft_today_button')
+ .css('visibility', !options.todayButton ? 'hidden' : 'visible');
+
+ month_picker
+ .find('.' + options.prev)
+ .css('visibility', !options.prevButton ? 'hidden' : 'visible');
+
+ month_picker
+ .find('.' + options.next)
+ .css('visibility', !options.nextButton ? 'hidden' : 'visible');
+
+ setMask(options);
+
+ if (options.validateOnBlur) {
+ input
+ .off('blur.xdsoft')
+ .on('blur.xdsoft', function () {
+ if (options.allowBlank && (!$.trim($(this).val()).length || (typeof options.mask == "string" && $.trim($(this).val()) === options.mask.replace(/[0-9]/g, '_')))) {
+ $(this).val(null);
+ datetimepicker.data('xdsoft_datetime').empty();
+ } else {
+ var d = dateHelper.parseDate($(this).val(), options.format);
+ if (d) { // parseDate() may skip some invalid parts like date or time, so make it clear for user: show parsed date/time
+ $(this).val(dateHelper.formatDate(d, options.format));
+ } else {
+ var splittedHours = +([$(this).val()[0], $(this).val()[1]].join('')),
+ splittedMinutes = +([$(this).val()[2], $(this).val()[3]].join(''));
+
+ // parse the numbers as 0312 => 03:12
+ if (!options.datepicker && options.timepicker && splittedHours >= 0 && splittedHours < 24 && splittedMinutes >= 0 && splittedMinutes < 60) {
+ $(this).val([splittedHours, splittedMinutes].map(function (item) {
+ return item > 9 ? item : '0' + item;
+ }).join(':'));
+ } else {
+ $(this).val(dateHelper.formatDate(_xdsoft_datetime.now(), options.format));
+ }
+ }
+ datetimepicker.data('xdsoft_datetime').setCurrentTime($(this).val());
+ }
+
+ datetimepicker.trigger('changedatetime.xdsoft');
+ datetimepicker.trigger('close.xdsoft');
+ });
+ }
+ options.dayOfWeekStartPrev = (options.dayOfWeekStart === 0) ? 6 : options.dayOfWeekStart - 1;
+
+ datetimepicker
+ .trigger('xchange.xdsoft')
+ .trigger('afterOpen.xdsoft');
+ };
+
+ datetimepicker
+ .data('options', options)
+ .on('touchstart mousedown.xdsoft', function (event) {
+ event.stopPropagation();
+ event.preventDefault();
+ yearselect.hide();
+ monthselect.hide();
+ return false;
+ });
+
+ //scroll_element = timepicker.find('.xdsoft_time_box');
+ timeboxparent.append(timebox);
+ timeboxparent.xdsoftScroller();
+
+ datetimepicker.on('afterOpen.xdsoft', function () {
+ timeboxparent.xdsoftScroller();
+ });
+
+ datetimepicker
+ .append(datepicker)
+ .append(timepicker);
+
+ if (options.withoutCopyright !== true) {
+ datetimepicker
+ .append(xdsoft_copyright);
+ }
+
+ datepicker
+ .append(month_picker)
+ .append(calendar)
+ .append(applyButton);
+
+ $(options.parentID)
+ .append(datetimepicker);
+
+ XDSoft_datetime = function () {
+ var _this = this;
+ _this.now = function (norecursion) {
+ var d = new Date(),
+ date,
+ time;
+
+ if (!norecursion && options.defaultDate) {
+ date = _this.strToDateTime(options.defaultDate);
+ d.setFullYear(date.getFullYear());
+ d.setMonth(date.getMonth());
+ d.setDate(date.getDate());
+ }
+
+ if (options.yearOffset) {
+ d.setFullYear(d.getFullYear() + options.yearOffset);
+ }
+
+ if (!norecursion && options.defaultTime) {
+ time = _this.strtotime(options.defaultTime);
+ d.setHours(time.getHours());
+ d.setMinutes(time.getMinutes());
+ }
+ return d;
+ };
+
+ _this.isValidDate = function (d) {
+ if (Object.prototype.toString.call(d) !== "[object Date]") {
+ return false;
+ }
+ return !isNaN(d.getTime());
+ };
+
+ _this.setCurrentTime = function (dTime, requireValidDate) {
+ if (typeof dTime === 'string') {
+ _this.currentTime = _this.strToDateTime(dTime);
+ }
+ else if (_this.isValidDate(dTime)) {
+ _this.currentTime = dTime;
+ }
+ else if (!dTime && !requireValidDate && options.allowBlank) {
+ _this.currentTime = null;
+ }
+ else {
+ _this.currentTime = _this.now();
+ }
+
+ datetimepicker.trigger('xchange.xdsoft');
+ };
+
+ _this.empty = function () {
+ _this.currentTime = null;
+ };
+
+ _this.getCurrentTime = function (dTime) {
+ return _this.currentTime;
+ };
+
+ _this.nextMonth = function () {
+
+ if (_this.currentTime === undefined || _this.currentTime === null) {
+ _this.currentTime = _this.now();
+ }
+
+ var month = _this.currentTime.getMonth() + 1,
+ year;
+ if (month === 12) {
+ _this.currentTime.setFullYear(_this.currentTime.getFullYear() + 1);
+ month = 0;
+ }
+
+ year = _this.currentTime.getFullYear();
+
+ _this.currentTime.setDate(
+ Math.min(
+ new Date(_this.currentTime.getFullYear(), month + 1, 0).getDate(),
+ _this.currentTime.getDate()
+ )
+ );
+ _this.currentTime.setMonth(month);
+
+ if (options.onChangeMonth && $.isFunction(options.onChangeMonth)) {
+ options.onChangeMonth.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
+ }
+
+ if (year !== _this.currentTime.getFullYear() && $.isFunction(options.onChangeYear)) {
+ options.onChangeYear.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
+ }
+
+ datetimepicker.trigger('xchange.xdsoft');
+ return month;
+ };
+
+ _this.prevMonth = function () {
+
+ if (_this.currentTime === undefined || _this.currentTime === null) {
+ _this.currentTime = _this.now();
+ }
+
+ var month = _this.currentTime.getMonth() - 1;
+ if (month === -1) {
+ _this.currentTime.setFullYear(_this.currentTime.getFullYear() - 1);
+ month = 11;
+ }
+ _this.currentTime.setDate(
+ Math.min(
+ new Date(_this.currentTime.getFullYear(), month + 1, 0).getDate(),
+ _this.currentTime.getDate()
+ )
+ );
+ _this.currentTime.setMonth(month);
+ if (options.onChangeMonth && $.isFunction(options.onChangeMonth)) {
+ options.onChangeMonth.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
+ }
+ datetimepicker.trigger('xchange.xdsoft');
+ return month;
+ };
+
+ _this.getWeekOfYear = function (datetime) {
+ if (options.onGetWeekOfYear && $.isFunction(options.onGetWeekOfYear)) {
+ var week = options.onGetWeekOfYear.call(datetimepicker, datetime);
+ if (typeof week !== 'undefined') {
+ return week;
+ }
+ }
+ var onejan = new Date(datetime.getFullYear(), 0, 1);
+ //First week of the year is th one with the first Thursday according to ISO8601
+ if(onejan.getDay()!=4)
+ onejan.setMonth(0, 1 + ((4 - onejan.getDay()+ 7) % 7));
+ return Math.ceil((((datetime - onejan) / 86400000) + onejan.getDay() + 1) / 7);
+ };
+
+ _this.strToDateTime = function (sDateTime) {
+ var tmpDate = [], timeOffset, currentTime;
+
+ if (sDateTime && sDateTime instanceof Date && _this.isValidDate(sDateTime)) {
+ return sDateTime;
+ }
+
+ tmpDate = /^(\+|\-)(.*)$/.exec(sDateTime);
+ if (tmpDate) {
+ tmpDate[2] = dateHelper.parseDate(tmpDate[2], options.formatDate);
+ }
+ if (tmpDate && tmpDate[2]) {
+ timeOffset = tmpDate[2].getTime() - (tmpDate[2].getTimezoneOffset()) * 60000;
+ currentTime = new Date((_this.now(true)).getTime() + parseInt(tmpDate[1] + '1', 10) * timeOffset);
+ } else {
+ currentTime = sDateTime ? dateHelper.parseDate(sDateTime, options.format) : _this.now();
+ }
+
+ if (!_this.isValidDate(currentTime)) {
+ currentTime = _this.now();
+ }
+
+ return currentTime;
+ };
+
+ _this.strToDate = function (sDate) {
+ if (sDate && sDate instanceof Date && _this.isValidDate(sDate)) {
+ return sDate;
+ }
+
+ var currentTime = sDate ? dateHelper.parseDate(sDate, options.formatDate) : _this.now(true);
+ if (!_this.isValidDate(currentTime)) {
+ currentTime = _this.now(true);
+ }
+ return currentTime;
+ };
+
+ _this.strtotime = function (sTime) {
+ if (sTime && sTime instanceof Date && _this.isValidDate(sTime)) {
+ return sTime;
+ }
+ var currentTime = sTime ? dateHelper.parseDate(sTime, options.formatTime) : _this.now(true);
+ if (!_this.isValidDate(currentTime)) {
+ currentTime = _this.now(true);
+ }
+ return currentTime;
+ };
+
+ _this.str = function () {
+ return dateHelper.formatDate(_this.currentTime, options.format);
+ };
+ _this.currentTime = this.now();
+ };
+
+ _xdsoft_datetime = new XDSoft_datetime();
+
+ applyButton.on('touchend click', function (e) {//pathbrite
+ e.preventDefault();
+ datetimepicker.data('changed', true);
+ _xdsoft_datetime.setCurrentTime(getCurrentValue());
+ input.val(_xdsoft_datetime.str());
+ datetimepicker.trigger('close.xdsoft');
+ });
+ month_picker
+ .find('.xdsoft_today_button')
+ .on('touchend mousedown.xdsoft', function () {
+ datetimepicker.data('changed', true);
+ _xdsoft_datetime.setCurrentTime(0, true);
+ datetimepicker.trigger('afterOpen.xdsoft');
+ }).on('dblclick.xdsoft', function () {
+ var currentDate = _xdsoft_datetime.getCurrentTime(), minDate, maxDate;
+ currentDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate());
+ minDate = _xdsoft_datetime.strToDate(options.minDate);
+ minDate = new Date(minDate.getFullYear(), minDate.getMonth(), minDate.getDate());
+ if (currentDate < minDate) {
+ return;
+ }
+ maxDate = _xdsoft_datetime.strToDate(options.maxDate);
+ maxDate = new Date(maxDate.getFullYear(), maxDate.getMonth(), maxDate.getDate());
+ if (currentDate > maxDate) {
+ return;
+ }
+ input.val(_xdsoft_datetime.str());
+ input.trigger('change');
+ datetimepicker.trigger('close.xdsoft');
+ });
+ month_picker
+ .find('.xdsoft_prev,.xdsoft_next')
+ .on('touchend mousedown.xdsoft', function () {
+ var $this = $(this),
+ timer = 0,
+ stop = false;
+
+ (function arguments_callee1(v) {
+ if ($this.hasClass(options.next)) {
+ _xdsoft_datetime.nextMonth();
+ } else if ($this.hasClass(options.prev)) {
+ _xdsoft_datetime.prevMonth();
+ }
+ if (options.monthChangeSpinner) {
+ if (!stop) {
+ timer = setTimeout(arguments_callee1, v || 100);
+ }
+ }
+ }(500));
+
+ $([document.body, window]).on('touchend mouseup.xdsoft', function arguments_callee2() {
+ clearTimeout(timer);
+ stop = true;
+ $([document.body, window]).off('touchend mouseup.xdsoft', arguments_callee2);
+ });
+ });
+
+ timepicker
+ .find('.xdsoft_prev,.xdsoft_next')
+ .on('touchend mousedown.xdsoft', function () {
+ var $this = $(this),
+ timer = 0,
+ stop = false,
+ period = 110;
+ (function arguments_callee4(v) {
+ var pheight = timeboxparent[0].clientHeight,
+ height = timebox[0].offsetHeight,
+ top = Math.abs(parseInt(timebox.css('marginTop'), 10));
+ if ($this.hasClass(options.next) && (height - pheight) - options.timeHeightInTimePicker >= top) {
+ timebox.css('marginTop', '-' + (top + options.timeHeightInTimePicker) + 'px');
+ } else if ($this.hasClass(options.prev) && top - options.timeHeightInTimePicker >= 0) {
+ timebox.css('marginTop', '-' + (top - options.timeHeightInTimePicker) + 'px');
+ }
/**
* Fixed bug:
* When using css3 transition, it will cause a bug that you cannot scroll the timepicker list.
@@ -2100,874 +2100,874 @@ var DateFormatter;
* Replace timebox.css('marginTop') with timebox[0].style.marginTop.
*/
timeboxparent.trigger('scroll_element.xdsoft_scroller', [Math.abs(parseInt(timebox[0].style.marginTop, 10) / (height - pheight))]);
- period = (period > 10) ? 10 : period - 10;
- if (!stop) {
- timer = setTimeout(arguments_callee4, v || period);
- }
- }(500));
- $([document.body, window]).on('touchend mouseup.xdsoft', function arguments_callee5() {
- clearTimeout(timer);
- stop = true;
- $([document.body, window])
- .off('touchend mouseup.xdsoft', arguments_callee5);
- });
- });
-
- xchangeTimer = 0;
- // base handler - generating a calendar and timepicker
- datetimepicker
- .on('xchange.xdsoft', function (event) {
- clearTimeout(xchangeTimer);
- xchangeTimer = setTimeout(function () {
-
- if (_xdsoft_datetime.currentTime === undefined || _xdsoft_datetime.currentTime === null) {
- //In case blanks are allowed, delay construction until we have a valid date
- if (options.allowBlank)
- return;
-
- _xdsoft_datetime.currentTime = _xdsoft_datetime.now();
- }
-
- var table = '',
- start = new Date(_xdsoft_datetime.currentTime.getFullYear(), _xdsoft_datetime.currentTime.getMonth(), 1, 12, 0, 0),
- i = 0,
- j,
- today = _xdsoft_datetime.now(),
- maxDate = false,
- minDate = false,
- hDate,
- day,
- d,
- y,
- m,
- w,
- classes = [],
- customDateSettings,
- newRow = true,
- time = '',
- h = '',
- line_time,
- description;
-
- while (start.getDay() !== options.dayOfWeekStart) {
- start.setDate(start.getDate() - 1);
- }
-
- table += '';
-
- if (options.weeks) {
- table += ' ';
- }
-
- for (j = 0; j < 7; j += 1) {
- table += '' + options.i18n[globalLocale].dayOfWeekShort[(j + options.dayOfWeekStart) % 7] + ' ';
- }
-
- table += ' ';
- table += '';
-
- if (options.maxDate !== false) {
- maxDate = _xdsoft_datetime.strToDate(options.maxDate);
- maxDate = new Date(maxDate.getFullYear(), maxDate.getMonth(), maxDate.getDate(), 23, 59, 59, 999);
- }
-
- if (options.minDate !== false) {
- minDate = _xdsoft_datetime.strToDate(options.minDate);
- minDate = new Date(minDate.getFullYear(), minDate.getMonth(), minDate.getDate());
- }
-
- while (i < _xdsoft_datetime.currentTime.countDaysInMonth() || start.getDay() !== options.dayOfWeekStart || _xdsoft_datetime.currentTime.getMonth() === start.getMonth()) {
- classes = [];
- i += 1;
-
- day = start.getDay();
- d = start.getDate();
- y = start.getFullYear();
- m = start.getMonth();
- w = _xdsoft_datetime.getWeekOfYear(start);
- description = '';
-
- classes.push('xdsoft_date');
-
- if (options.beforeShowDay && $.isFunction(options.beforeShowDay.call)) {
- customDateSettings = options.beforeShowDay.call(datetimepicker, start);
- } else {
- customDateSettings = null;
- }
-
- if(options.allowDateRe && Object.prototype.toString.call(options.allowDateRe) === "[object RegExp]"){
- if(!options.allowDateRe.test(dateHelper.formatDate(start, options.formatDate))){
- classes.push('xdsoft_disabled');
- }
- } else if(options.allowDates && options.allowDates.length>0){
- if(options.allowDates.indexOf(dateHelper.formatDate(start, options.formatDate)) === -1){
- classes.push('xdsoft_disabled');
- }
- } else if ((maxDate !== false && start > maxDate) || (minDate !== false && start < minDate) || (customDateSettings && customDateSettings[0] === false)) {
- classes.push('xdsoft_disabled');
- } else if (options.disabledDates.indexOf(dateHelper.formatDate(start, options.formatDate)) !== -1) {
- classes.push('xdsoft_disabled');
- } else if (options.disabledWeekDays.indexOf(day) !== -1) {
- classes.push('xdsoft_disabled');
- }else if (input.is('[readonly]')) {
- classes.push('xdsoft_disabled');
- }
-
- if (customDateSettings && customDateSettings[1] !== "") {
- classes.push(customDateSettings[1]);
- }
-
- if (_xdsoft_datetime.currentTime.getMonth() !== m) {
- classes.push('xdsoft_other_month');
- }
-
- if ((options.defaultSelect || datetimepicker.data('changed')) && dateHelper.formatDate(_xdsoft_datetime.currentTime, options.formatDate) === dateHelper.formatDate(start, options.formatDate)) {
- classes.push('xdsoft_current');
- }
-
- if (dateHelper.formatDate(today, options.formatDate) === dateHelper.formatDate(start, options.formatDate)) {
- classes.push('xdsoft_today');
- }
-
- if (start.getDay() === 0 || start.getDay() === 6 || options.weekends.indexOf(dateHelper.formatDate(start, options.formatDate)) !== -1) {
- classes.push('xdsoft_weekend');
- }
-
- if (options.highlightedDates[dateHelper.formatDate(start, options.formatDate)] !== undefined) {
- hDate = options.highlightedDates[dateHelper.formatDate(start, options.formatDate)];
- classes.push(hDate.style === undefined ? 'xdsoft_highlighted_default' : hDate.style);
- description = hDate.desc === undefined ? '' : hDate.desc;
- }
-
- if (options.beforeShowDay && $.isFunction(options.beforeShowDay)) {
- classes.push(options.beforeShowDay(start));
- }
-
- if (newRow) {
- table += '';
- newRow = false;
- if (options.weeks) {
- table += '' + w + ' ';
- }
- }
-
- table += '' +
- '' + d + '
' +
- ' ';
-
- if (start.getDay() === options.dayOfWeekStartPrev) {
- table += ' ';
- newRow = true;
- }
-
- start.setDate(d + 1);
- }
- table += '
';
-
- calendar.html(table);
-
- month_picker.find('.xdsoft_label span').eq(0).text(options.i18n[globalLocale].months[_xdsoft_datetime.currentTime.getMonth()]);
- month_picker.find('.xdsoft_label span').eq(1).text(_xdsoft_datetime.currentTime.getFullYear());
-
- // generate timebox
- time = '';
- h = '';
- m = '';
-
- line_time = function line_time(h, m) {
- var now = _xdsoft_datetime.now(), optionDateTime, current_time,
- isALlowTimesInit = options.allowTimes && $.isArray(options.allowTimes) && options.allowTimes.length;
- now.setHours(h);
- h = parseInt(now.getHours(), 10);
- now.setMinutes(m);
- m = parseInt(now.getMinutes(), 10);
- optionDateTime = new Date(_xdsoft_datetime.currentTime);
- optionDateTime.setHours(h);
- optionDateTime.setMinutes(m);
- classes = [];
- if ((options.minDateTime !== false && options.minDateTime > optionDateTime) || (options.maxTime !== false && _xdsoft_datetime.strtotime(options.maxTime).getTime() < now.getTime()) || (options.minTime !== false && _xdsoft_datetime.strtotime(options.minTime).getTime() > now.getTime())) {
- classes.push('xdsoft_disabled');
- } else if ((options.minDateTime !== false && options.minDateTime > optionDateTime) || ((options.disabledMinTime !== false && now.getTime() > _xdsoft_datetime.strtotime(options.disabledMinTime).getTime()) && (options.disabledMaxTime !== false && now.getTime() < _xdsoft_datetime.strtotime(options.disabledMaxTime).getTime()))) {
- classes.push('xdsoft_disabled');
- } else if (input.is('[readonly]')) {
- classes.push('xdsoft_disabled');
- }
-
- current_time = new Date(_xdsoft_datetime.currentTime);
- current_time.setHours(parseInt(_xdsoft_datetime.currentTime.getHours(), 10));
-
- if (!isALlowTimesInit) {
- current_time.setMinutes(Math[options.roundTime](_xdsoft_datetime.currentTime.getMinutes() / options.step) * options.step);
- }
-
- if ((options.initTime || options.defaultSelect || datetimepicker.data('changed')) && current_time.getHours() === parseInt(h, 10) && ((!isALlowTimesInit && options.step > 59) || current_time.getMinutes() === parseInt(m, 10))) {
- if (options.defaultSelect || datetimepicker.data('changed')) {
- classes.push('xdsoft_current');
- } else if (options.initTime) {
- classes.push('xdsoft_init_time');
- }
- }
- if (parseInt(today.getHours(), 10) === parseInt(h, 10) && parseInt(today.getMinutes(), 10) === parseInt(m, 10)) {
- classes.push('xdsoft_today');
- }
- time += '' + dateHelper.formatDate(now, options.formatTime) + '
';
- };
-
- if (!options.allowTimes || !$.isArray(options.allowTimes) || !options.allowTimes.length) {
- for (i = 0, j = 0; i < (options.hours12 ? 12 : 24); i += 1) {
- for (j = 0; j < 60; j += options.step) {
- h = (i < 10 ? '0' : '') + i;
- m = (j < 10 ? '0' : '') + j;
- line_time(h, m);
- }
- }
- } else {
- for (i = 0; i < options.allowTimes.length; i += 1) {
- h = _xdsoft_datetime.strtotime(options.allowTimes[i]).getHours();
- m = _xdsoft_datetime.strtotime(options.allowTimes[i]).getMinutes();
- line_time(h, m);
- }
- }
-
- timebox.html(time);
-
- opt = '';
- i = 0;
-
- for (i = parseInt(options.yearStart, 10) + options.yearOffset; i <= parseInt(options.yearEnd, 10) + options.yearOffset; i += 1) {
- opt += '' + i + '
';
- }
- yearselect.children().eq(0)
- .html(opt);
-
- for (i = parseInt(options.monthStart, 10), opt = ''; i <= parseInt(options.monthEnd, 10); i += 1) {
- opt += '' + options.i18n[globalLocale].months[i] + '
';
- }
- monthselect.children().eq(0).html(opt);
- $(datetimepicker)
- .trigger('generate.xdsoft');
- }, 10);
- event.stopPropagation();
- })
- .on('afterOpen.xdsoft', function () {
- if (options.timepicker) {
- var classType, pheight, height, top;
- if (timebox.find('.xdsoft_current').length) {
- classType = '.xdsoft_current';
- } else if (timebox.find('.xdsoft_init_time').length) {
- classType = '.xdsoft_init_time';
- }
- if (classType) {
- pheight = timeboxparent[0].clientHeight;
- height = timebox[0].offsetHeight;
- top = timebox.find(classType).index() * options.timeHeightInTimePicker + 1;
- if ((height - pheight) < top) {
- top = height - pheight;
- }
- timeboxparent.trigger('scroll_element.xdsoft_scroller', [parseInt(top, 10) / (height - pheight)]);
- } else {
- timeboxparent.trigger('scroll_element.xdsoft_scroller', [0]);
- }
- }
- });
-
- timerclick = 0;
- calendar
- .on('touchend click.xdsoft', 'td', function (xdevent) {
- xdevent.stopPropagation(); // Prevents closing of Pop-ups, Modals and Flyouts in Bootstrap
- timerclick += 1;
- var $this = $(this),
- currentTime = _xdsoft_datetime.currentTime;
-
- if (currentTime === undefined || currentTime === null) {
- _xdsoft_datetime.currentTime = _xdsoft_datetime.now();
- currentTime = _xdsoft_datetime.currentTime;
- }
-
- if ($this.hasClass('xdsoft_disabled')) {
- return false;
- }
-
- currentTime.setDate(1);
- currentTime.setFullYear($this.data('year'));
- currentTime.setMonth($this.data('month'));
- currentTime.setDate($this.data('date'));
-
- datetimepicker.trigger('select.xdsoft', [currentTime]);
-
- input.val(_xdsoft_datetime.str());
-
- if (options.onSelectDate && $.isFunction(options.onSelectDate)) {
- options.onSelectDate.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'), xdevent);
- }
-
- datetimepicker.data('changed', true);
- datetimepicker.trigger('xchange.xdsoft');
- datetimepicker.trigger('changedatetime.xdsoft');
- if ((timerclick > 1 || (options.closeOnDateSelect === true || (options.closeOnDateSelect === false && !options.timepicker))) && !options.inline) {
- datetimepicker.trigger('close.xdsoft');
- }
- setTimeout(function () {
- timerclick = 0;
- }, 200);
- });
-
- timebox
- .on('touchmove', 'div', function () { currentlyScrollingTimeDiv = true; })
- .on('touchend click.xdsoft', 'div', function (xdevent) {
- xdevent.stopPropagation();
- if (currentlyScrollingTimeDiv) {
- currentlyScrollingTimeDiv = false;
- return;
- }
- var $this = $(this),
- currentTime = _xdsoft_datetime.currentTime;
-
- if (currentTime === undefined || currentTime === null) {
- _xdsoft_datetime.currentTime = _xdsoft_datetime.now();
- currentTime = _xdsoft_datetime.currentTime;
- }
-
- if ($this.hasClass('xdsoft_disabled')) {
- return false;
- }
- currentTime.setHours($this.data('hour'));
- currentTime.setMinutes($this.data('minute'));
- datetimepicker.trigger('select.xdsoft', [currentTime]);
-
- datetimepicker.data('input').val(_xdsoft_datetime.str());
-
- if (options.onSelectTime && $.isFunction(options.onSelectTime)) {
- options.onSelectTime.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'), xdevent);
- }
- datetimepicker.data('changed', true);
- datetimepicker.trigger('xchange.xdsoft');
- datetimepicker.trigger('changedatetime.xdsoft');
- if (options.inline !== true && options.closeOnTimeSelect === true) {
- datetimepicker.trigger('close.xdsoft');
- }
- });
-
- datepicker
- .on('mousewheel.xdsoft', function (event) {
- if (!options.scrollMonth) {
- return true;
- }
- if (event.deltaY < 0) {
- _xdsoft_datetime.nextMonth();
- } else {
- _xdsoft_datetime.prevMonth();
- }
- return false;
- });
-
- input
- .on('mousewheel.xdsoft', function (event) {
- if (!options.scrollInput) {
- return true;
- }
- if (!options.datepicker && options.timepicker) {
- current_time_index = timebox.find('.xdsoft_current').length ? timebox.find('.xdsoft_current').eq(0).index() : 0;
- if (current_time_index + event.deltaY >= 0 && current_time_index + event.deltaY < timebox.children().length) {
- current_time_index += event.deltaY;
- }
- if (timebox.children().eq(current_time_index).length) {
- timebox.children().eq(current_time_index).trigger('mousedown');
- }
- return false;
- }
- if (options.datepicker && !options.timepicker) {
- datepicker.trigger(event, [event.deltaY, event.deltaX, event.deltaY]);
- if (input.val) {
- input.val(_xdsoft_datetime.str());
- }
- datetimepicker.trigger('changedatetime.xdsoft');
- return false;
- }
- });
-
- datetimepicker
- .on('changedatetime.xdsoft', function (event) {
- if (options.onChangeDateTime && $.isFunction(options.onChangeDateTime)) {
- var $input = datetimepicker.data('input');
- options.onChangeDateTime.call(datetimepicker, _xdsoft_datetime.currentTime, $input, event);
- delete options.value;
- $input.trigger('change');
- }
- })
- .on('generate.xdsoft', function () {
- if (options.onGenerate && $.isFunction(options.onGenerate)) {
- options.onGenerate.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
- }
- if (triggerAfterOpen) {
- datetimepicker.trigger('afterOpen.xdsoft');
- triggerAfterOpen = false;
- }
- })
- .on('click.xdsoft', function (xdevent) {
- xdevent.stopPropagation();
- });
-
- current_time_index = 0;
-
- /**
- * Runs the callback for each of the specified node's ancestors.
- *
- * Return FALSE from the callback to stop ascending.
- *
- * @param {DOMNode} node
- * @param {Function} callback
- * @returns {undefined}
- */
- forEachAncestorOf = function (node, callback) {
- do {
- node = node.parentNode;
-
- if (callback(node) === false) {
- break;
- }
- } while (node.nodeName !== 'HTML');
- };
-
- /**
- * Sets the position of the picker.
- *
- * @returns {undefined}
- */
- setPos = function () {
- var dateInputOffset,
- dateInputElem,
- verticalPosition,
- left,
- position,
- datetimepickerElem,
- dateInputHasFixedAncestor,
- $dateInput,
- windowWidth,
- verticalAnchorEdge,
- datetimepickerCss,
- windowHeight,
- windowScrollTop;
-
- $dateInput = datetimepicker.data('input');
- dateInputOffset = $dateInput.offset();
- dateInputElem = $dateInput[0];
-
- verticalAnchorEdge = 'top';
- verticalPosition = (dateInputOffset.top + dateInputElem.offsetHeight) - 1;
- left = dateInputOffset.left;
- position = "absolute";
-
- windowWidth = $(window).width();
- windowHeight = $(window).height();
- windowScrollTop = $(window).scrollTop();
-
- if ((document.documentElement.clientWidth - dateInputOffset.left) < datepicker.parent().outerWidth(true)) {
- var diff = datepicker.parent().outerWidth(true) - dateInputElem.offsetWidth;
- left = left - diff;
- }
-
- if ($dateInput.parent().css('direction') === 'rtl') {
- left -= (datetimepicker.outerWidth() - $dateInput.outerWidth());
- }
-
- if (options.fixed) {
- verticalPosition -= windowScrollTop;
- left -= $(window).scrollLeft();
- position = "fixed";
- } else {
- dateInputHasFixedAncestor = false;
-
- forEachAncestorOf(dateInputElem, function (ancestorNode) {
- if (window.getComputedStyle(ancestorNode).getPropertyValue('position') === 'fixed') {
- dateInputHasFixedAncestor = true;
- return false;
- }
- });
-
- if (dateInputHasFixedAncestor) {
- position = 'fixed';
-
- //If the picker won't fit entirely within the viewport then display it above the date input.
- if (verticalPosition + datetimepicker.outerHeight() > windowHeight + windowScrollTop) {
- verticalAnchorEdge = 'bottom';
- verticalPosition = (windowHeight + windowScrollTop) - dateInputOffset.top;
- } else {
- verticalPosition -= windowScrollTop;
- }
- } else {
- if (verticalPosition + dateInputElem.offsetHeight > windowHeight + windowScrollTop) {
- verticalPosition = dateInputOffset.top - dateInputElem.offsetHeight + 1;
- }
- }
-
- if (verticalPosition < 0) {
- verticalPosition = 0;
- }
-
- if (left + dateInputElem.offsetWidth > windowWidth) {
- left = windowWidth - dateInputElem.offsetWidth;
- }
- }
-
- datetimepickerElem = datetimepicker[0];
-
- forEachAncestorOf(datetimepickerElem, function (ancestorNode) {
- var ancestorNodePosition;
-
- ancestorNodePosition = window.getComputedStyle(ancestorNode).getPropertyValue('position');
-
- if (ancestorNodePosition === 'relative' && windowWidth >= ancestorNode.offsetWidth) {
- left = left - ((windowWidth - ancestorNode.offsetWidth) / 2);
- return false;
- }
- });
-
- datetimepickerCss = {
- position: position,
- left: left,
- top: '', //Initialize to prevent previous values interfering with new ones.
- bottom: '' //Initialize to prevent previous values interfering with new ones.
- };
-
- datetimepickerCss[verticalAnchorEdge] = verticalPosition;
-
- datetimepicker.css(datetimepickerCss);
- };
-
- datetimepicker
- .on('open.xdsoft', function (event) {
- var onShow = true;
- if (options.onShow && $.isFunction(options.onShow)) {
- onShow = options.onShow.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'), event);
- }
- if (onShow !== false) {
- datetimepicker.show();
- setPos();
- $(window)
- .off('resize.xdsoft', setPos)
- .on('resize.xdsoft', setPos);
-
- if (options.closeOnWithoutClick) {
- $([document.body, window]).on('touchstart mousedown.xdsoft', function arguments_callee6() {
- datetimepicker.trigger('close.xdsoft');
- $([document.body, window]).off('touchstart mousedown.xdsoft', arguments_callee6);
- });
- }
- }
- })
- .on('close.xdsoft', function (event) {
- var onClose = true;
- month_picker
- .find('.xdsoft_month,.xdsoft_year')
- .find('.xdsoft_select')
- .hide();
- if (options.onClose && $.isFunction(options.onClose)) {
- onClose = options.onClose.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'), event);
- }
- if (onClose !== false && !options.opened && !options.inline) {
- datetimepicker.hide();
- }
- event.stopPropagation();
- })
- .on('toggle.xdsoft', function () {
- if (datetimepicker.is(':visible')) {
- datetimepicker.trigger('close.xdsoft');
- } else {
- datetimepicker.trigger('open.xdsoft');
- }
- })
- .data('input', input);
-
- timer = 0;
-
- datetimepicker.data('xdsoft_datetime', _xdsoft_datetime);
- datetimepicker.setOptions(options);
-
- function getCurrentValue() {
- var ct = false, time;
-
- if (options.startDate) {
- ct = _xdsoft_datetime.strToDate(options.startDate);
- } else {
- ct = options.value || ((input && input.val && input.val()) ? input.val() : '');
- if (ct) {
- ct = _xdsoft_datetime.strToDateTime(ct);
- } else if (options.defaultDate) {
- ct = _xdsoft_datetime.strToDateTime(options.defaultDate);
- if (options.defaultTime) {
- time = _xdsoft_datetime.strtotime(options.defaultTime);
- ct.setHours(time.getHours());
- ct.setMinutes(time.getMinutes());
- }
- }
- }
-
- if (ct && _xdsoft_datetime.isValidDate(ct)) {
- datetimepicker.data('changed', true);
- } else {
- ct = '';
- }
-
- return ct || 0;
- }
-
- function setMask(options) {
-
- var isValidValue = function (mask, value) {
- var reg = mask
- .replace(/([\[\]\/\{\}\(\)\-\.\+]{1})/g, '\\$1')
- .replace(/_/g, '{digit+}')
- .replace(/([0-9]{1})/g, '{digit$1}')
- .replace(/\{digit([0-9]{1})\}/g, '[0-$1_]{1}')
- .replace(/\{digit[\+]\}/g, '[0-9_]{1}');
- return (new RegExp(reg)).test(value);
- },
- getCaretPos = function (input) {
- try {
- if (document.selection && document.selection.createRange) {
- var range = document.selection.createRange();
- return range.getBookmark().charCodeAt(2) - 2;
- }
- if (input.setSelectionRange) {
- return input.selectionStart;
- }
- } catch (e) {
- return 0;
- }
- },
- setCaretPos = function (node, pos) {
- node = (typeof node === "string" || node instanceof String) ? document.getElementById(node) : node;
- if (!node) {
- return false;
- }
- if (node.createTextRange) {
- var textRange = node.createTextRange();
- textRange.collapse(true);
- textRange.moveEnd('character', pos);
- textRange.moveStart('character', pos);
- textRange.select();
- return true;
- }
- if (node.setSelectionRange) {
- node.setSelectionRange(pos, pos);
- return true;
- }
- return false;
- };
- if(options.mask) {
- input.off('keydown.xdsoft');
- }
- if (options.mask === true) {
- if (typeof moment != 'undefined') {
- options.mask = options.format
- .replace(/Y{4}/g, '9999')
- .replace(/Y{2}/g, '99')
- .replace(/M{2}/g, '19')
- .replace(/D{2}/g, '39')
- .replace(/H{2}/g, '29')
- .replace(/m{2}/g, '59')
- .replace(/s{2}/g, '59');
- } else {
- options.mask = options.format
- .replace(/Y/g, '9999')
- .replace(/F/g, '9999')
- .replace(/m/g, '19')
- .replace(/d/g, '39')
- .replace(/H/g, '29')
- .replace(/i/g, '59')
- .replace(/s/g, '59');
- }
- }
-
- if ($.type(options.mask) === 'string') {
- if (!isValidValue(options.mask, input.val())) {
- input.val(options.mask.replace(/[0-9]/g, '_'));
- setCaretPos(input[0], 0);
- }
-
- input.on('keydown.xdsoft', function (event) {
- var val = this.value,
- key = event.which,
- pos,
- digit;
-
- if (((key >= KEY0 && key <= KEY9) || (key >= _KEY0 && key <= _KEY9)) || (key === BACKSPACE || key === DEL)) {
- pos = getCaretPos(this);
- digit = (key !== BACKSPACE && key !== DEL) ? String.fromCharCode((_KEY0 <= key && key <= _KEY9) ? key - KEY0 : key) : '_';
-
- if ((key === BACKSPACE || key === DEL) && pos) {
- pos -= 1;
- digit = '_';
- }
-
- while (/[^0-9_]/.test(options.mask.substr(pos, 1)) && pos < options.mask.length && pos > 0) {
- pos += (key === BACKSPACE || key === DEL) ? -1 : 1;
- }
-
- val = val.substr(0, pos) + digit + val.substr(pos + 1);
- if ($.trim(val) === '') {
- val = options.mask.replace(/[0-9]/g, '_');
- } else {
- if (pos === options.mask.length) {
- event.preventDefault();
- return false;
- }
- }
-
- pos += (key === BACKSPACE || key === DEL) ? 0 : 1;
- while (/[^0-9_]/.test(options.mask.substr(pos, 1)) && pos < options.mask.length && pos > 0) {
- pos += (key === BACKSPACE || key === DEL) ? -1 : 1;
- }
-
- if (isValidValue(options.mask, val)) {
- this.value = val;
- setCaretPos(this, pos);
- } else if ($.trim(val) === '') {
- this.value = options.mask.replace(/[0-9]/g, '_');
- } else {
- input.trigger('error_input.xdsoft');
- }
- } else {
- if (([AKEY, CKEY, VKEY, ZKEY, YKEY].indexOf(key) !== -1 && ctrlDown) || [ESC, ARROWUP, ARROWDOWN, ARROWLEFT, ARROWRIGHT, F5, CTRLKEY, TAB, ENTER].indexOf(key) !== -1) {
- return true;
- }
- }
-
- event.preventDefault();
- return false;
- });
- }
- }
-
- _xdsoft_datetime.setCurrentTime(getCurrentValue());
-
- input
- .data('xdsoft_datetimepicker', datetimepicker)
- .on('open.xdsoft focusin.xdsoft mousedown.xdsoft touchstart', function () {
- if (input.is(':disabled') || (input.data('xdsoft_datetimepicker').is(':visible') && options.closeOnInputClick)) {
- return;
- }
- clearTimeout(timer);
- timer = setTimeout(function () {
- if (input.is(':disabled')) {
- return;
- }
-
- triggerAfterOpen = true;
- _xdsoft_datetime.setCurrentTime(getCurrentValue(), true);
- if(options.mask) {
- setMask(options);
- }
- datetimepicker.trigger('open.xdsoft');
- }, 100);
- })
- .on('keydown.xdsoft', function (event) {
- var elementSelector,
- key = event.which;
- if ([ENTER].indexOf(key) !== -1 && options.enterLikeTab) {
- elementSelector = $("input:visible,textarea:visible,button:visible,a:visible");
- datetimepicker.trigger('close.xdsoft');
- elementSelector.eq(elementSelector.index(this) + 1).focus();
- return false;
- }
- if ([TAB].indexOf(key) !== -1) {
- datetimepicker.trigger('close.xdsoft');
- return true;
- }
- })
- .on('blur.xdsoft', function () {
- datetimepicker.trigger('close.xdsoft');
- });
- };
- destroyDateTimePicker = function (input) {
- var datetimepicker = input.data('xdsoft_datetimepicker');
- if (datetimepicker) {
- datetimepicker.data('xdsoft_datetime', null);
- datetimepicker.remove();
- input
- .data('xdsoft_datetimepicker', null)
- .off('.xdsoft');
- $(window).off('resize.xdsoft');
- $([window, document.body]).off('mousedown.xdsoft touchstart');
- if (input.unmousewheel) {
- input.unmousewheel();
- }
- }
- };
- $(document)
- .off('keydown.xdsoftctrl keyup.xdsoftctrl')
- .on('keydown.xdsoftctrl', function (e) {
- if (e.keyCode === CTRLKEY) {
- ctrlDown = true;
- }
- })
- .on('keyup.xdsoftctrl', function (e) {
- if (e.keyCode === CTRLKEY) {
- ctrlDown = false;
- }
- });
-
- this.each(function () {
- var datetimepicker = $(this).data('xdsoft_datetimepicker'), $input;
- if (datetimepicker) {
- if ($.type(opt) === 'string') {
- switch (opt) {
- case 'show':
- $(this).select().focus();
- datetimepicker.trigger('open.xdsoft');
- break;
- case 'hide':
- datetimepicker.trigger('close.xdsoft');
- break;
- case 'toggle':
- datetimepicker.trigger('toggle.xdsoft');
- break;
- case 'destroy':
- destroyDateTimePicker($(this));
- break;
- case 'reset':
- this.value = this.defaultValue;
- if (!this.value || !datetimepicker.data('xdsoft_datetime').isValidDate(dateHelper.parseDate(this.value, options.format))) {
- datetimepicker.data('changed', false);
- }
- datetimepicker.data('xdsoft_datetime').setCurrentTime(this.value);
- break;
- case 'validate':
- $input = datetimepicker.data('input');
- $input.trigger('blur.xdsoft');
- break;
- default:
- if (datetimepicker[opt] && $.isFunction(datetimepicker[opt])) {
- result = datetimepicker[opt](opt2);
- }
- }
- } else {
- datetimepicker
- .setOptions(opt);
- }
- return 0;
- }
- if ($.type(opt) !== 'string') {
- if (!options.lazyInit || options.open || options.inline) {
- createDateTimePicker($(this));
- } else {
- lazyInit($(this));
- }
- }
- });
-
- return result;
- };
-
- $.fn.datetimepicker.defaults = default_options;
-
- function HighlightedDate(date, desc, style) {
- "use strict";
- this.date = date;
- this.desc = desc;
- this.style = style;
- }
+ period = (period > 10) ? 10 : period - 10;
+ if (!stop) {
+ timer = setTimeout(arguments_callee4, v || period);
+ }
+ }(500));
+ $([document.body, window]).on('touchend mouseup.xdsoft', function arguments_callee5() {
+ clearTimeout(timer);
+ stop = true;
+ $([document.body, window])
+ .off('touchend mouseup.xdsoft', arguments_callee5);
+ });
+ });
+
+ xchangeTimer = 0;
+ // base handler - generating a calendar and timepicker
+ datetimepicker
+ .on('xchange.xdsoft', function (event) {
+ clearTimeout(xchangeTimer);
+ xchangeTimer = setTimeout(function () {
+
+ if (_xdsoft_datetime.currentTime === undefined || _xdsoft_datetime.currentTime === null) {
+ //In case blanks are allowed, delay construction until we have a valid date
+ if (options.allowBlank)
+ return;
+
+ _xdsoft_datetime.currentTime = _xdsoft_datetime.now();
+ }
+
+ var table = '',
+ start = new Date(_xdsoft_datetime.currentTime.getFullYear(), _xdsoft_datetime.currentTime.getMonth(), 1, 12, 0, 0),
+ i = 0,
+ j,
+ today = _xdsoft_datetime.now(),
+ maxDate = false,
+ minDate = false,
+ hDate,
+ day,
+ d,
+ y,
+ m,
+ w,
+ classes = [],
+ customDateSettings,
+ newRow = true,
+ time = '',
+ h = '',
+ line_time,
+ description;
+
+ while (start.getDay() !== options.dayOfWeekStart) {
+ start.setDate(start.getDate() - 1);
+ }
+
+ table += '';
+
+ if (options.weeks) {
+ table += ' ';
+ }
+
+ for (j = 0; j < 7; j += 1) {
+ table += '' + options.i18n[globalLocale].dayOfWeekShort[(j + options.dayOfWeekStart) % 7] + ' ';
+ }
+
+ table += ' ';
+ table += '';
+
+ if (options.maxDate !== false) {
+ maxDate = _xdsoft_datetime.strToDate(options.maxDate);
+ maxDate = new Date(maxDate.getFullYear(), maxDate.getMonth(), maxDate.getDate(), 23, 59, 59, 999);
+ }
+
+ if (options.minDate !== false) {
+ minDate = _xdsoft_datetime.strToDate(options.minDate);
+ minDate = new Date(minDate.getFullYear(), minDate.getMonth(), minDate.getDate());
+ }
+
+ while (i < _xdsoft_datetime.currentTime.countDaysInMonth() || start.getDay() !== options.dayOfWeekStart || _xdsoft_datetime.currentTime.getMonth() === start.getMonth()) {
+ classes = [];
+ i += 1;
+
+ day = start.getDay();
+ d = start.getDate();
+ y = start.getFullYear();
+ m = start.getMonth();
+ w = _xdsoft_datetime.getWeekOfYear(start);
+ description = '';
+
+ classes.push('xdsoft_date');
+
+ if (options.beforeShowDay && $.isFunction(options.beforeShowDay.call)) {
+ customDateSettings = options.beforeShowDay.call(datetimepicker, start);
+ } else {
+ customDateSettings = null;
+ }
+
+ if(options.allowDateRe && Object.prototype.toString.call(options.allowDateRe) === "[object RegExp]"){
+ if(!options.allowDateRe.test(dateHelper.formatDate(start, options.formatDate))){
+ classes.push('xdsoft_disabled');
+ }
+ } else if(options.allowDates && options.allowDates.length>0){
+ if(options.allowDates.indexOf(dateHelper.formatDate(start, options.formatDate)) === -1){
+ classes.push('xdsoft_disabled');
+ }
+ } else if ((maxDate !== false && start > maxDate) || (minDate !== false && start < minDate) || (customDateSettings && customDateSettings[0] === false)) {
+ classes.push('xdsoft_disabled');
+ } else if (options.disabledDates.indexOf(dateHelper.formatDate(start, options.formatDate)) !== -1) {
+ classes.push('xdsoft_disabled');
+ } else if (options.disabledWeekDays.indexOf(day) !== -1) {
+ classes.push('xdsoft_disabled');
+ }else if (input.is('[readonly]')) {
+ classes.push('xdsoft_disabled');
+ }
+
+ if (customDateSettings && customDateSettings[1] !== "") {
+ classes.push(customDateSettings[1]);
+ }
+
+ if (_xdsoft_datetime.currentTime.getMonth() !== m) {
+ classes.push('xdsoft_other_month');
+ }
+
+ if ((options.defaultSelect || datetimepicker.data('changed')) && dateHelper.formatDate(_xdsoft_datetime.currentTime, options.formatDate) === dateHelper.formatDate(start, options.formatDate)) {
+ classes.push('xdsoft_current');
+ }
+
+ if (dateHelper.formatDate(today, options.formatDate) === dateHelper.formatDate(start, options.formatDate)) {
+ classes.push('xdsoft_today');
+ }
+
+ if (start.getDay() === 0 || start.getDay() === 6 || options.weekends.indexOf(dateHelper.formatDate(start, options.formatDate)) !== -1) {
+ classes.push('xdsoft_weekend');
+ }
+
+ if (options.highlightedDates[dateHelper.formatDate(start, options.formatDate)] !== undefined) {
+ hDate = options.highlightedDates[dateHelper.formatDate(start, options.formatDate)];
+ classes.push(hDate.style === undefined ? 'xdsoft_highlighted_default' : hDate.style);
+ description = hDate.desc === undefined ? '' : hDate.desc;
+ }
+
+ if (options.beforeShowDay && $.isFunction(options.beforeShowDay)) {
+ classes.push(options.beforeShowDay(start));
+ }
+
+ if (newRow) {
+ table += '';
+ newRow = false;
+ if (options.weeks) {
+ table += '' + w + ' ';
+ }
+ }
+
+ table += '' +
+ '' + d + '
' +
+ ' ';
+
+ if (start.getDay() === options.dayOfWeekStartPrev) {
+ table += ' ';
+ newRow = true;
+ }
+
+ start.setDate(d + 1);
+ }
+ table += '
';
+
+ calendar.html(table);
+
+ month_picker.find('.xdsoft_label span').eq(0).text(options.i18n[globalLocale].months[_xdsoft_datetime.currentTime.getMonth()]);
+ month_picker.find('.xdsoft_label span').eq(1).text(_xdsoft_datetime.currentTime.getFullYear());
+
+ // generate timebox
+ time = '';
+ h = '';
+ m = '';
+
+ line_time = function line_time(h, m) {
+ var now = _xdsoft_datetime.now(), optionDateTime, current_time,
+ isALlowTimesInit = options.allowTimes && $.isArray(options.allowTimes) && options.allowTimes.length;
+ now.setHours(h);
+ h = parseInt(now.getHours(), 10);
+ now.setMinutes(m);
+ m = parseInt(now.getMinutes(), 10);
+ optionDateTime = new Date(_xdsoft_datetime.currentTime);
+ optionDateTime.setHours(h);
+ optionDateTime.setMinutes(m);
+ classes = [];
+ if ((options.minDateTime !== false && options.minDateTime > optionDateTime) || (options.maxTime !== false && _xdsoft_datetime.strtotime(options.maxTime).getTime() < now.getTime()) || (options.minTime !== false && _xdsoft_datetime.strtotime(options.minTime).getTime() > now.getTime())) {
+ classes.push('xdsoft_disabled');
+ } else if ((options.minDateTime !== false && options.minDateTime > optionDateTime) || ((options.disabledMinTime !== false && now.getTime() > _xdsoft_datetime.strtotime(options.disabledMinTime).getTime()) && (options.disabledMaxTime !== false && now.getTime() < _xdsoft_datetime.strtotime(options.disabledMaxTime).getTime()))) {
+ classes.push('xdsoft_disabled');
+ } else if (input.is('[readonly]')) {
+ classes.push('xdsoft_disabled');
+ }
+
+ current_time = new Date(_xdsoft_datetime.currentTime);
+ current_time.setHours(parseInt(_xdsoft_datetime.currentTime.getHours(), 10));
+
+ if (!isALlowTimesInit) {
+ current_time.setMinutes(Math[options.roundTime](_xdsoft_datetime.currentTime.getMinutes() / options.step) * options.step);
+ }
+
+ if ((options.initTime || options.defaultSelect || datetimepicker.data('changed')) && current_time.getHours() === parseInt(h, 10) && ((!isALlowTimesInit && options.step > 59) || current_time.getMinutes() === parseInt(m, 10))) {
+ if (options.defaultSelect || datetimepicker.data('changed')) {
+ classes.push('xdsoft_current');
+ } else if (options.initTime) {
+ classes.push('xdsoft_init_time');
+ }
+ }
+ if (parseInt(today.getHours(), 10) === parseInt(h, 10) && parseInt(today.getMinutes(), 10) === parseInt(m, 10)) {
+ classes.push('xdsoft_today');
+ }
+ time += '' + dateHelper.formatDate(now, options.formatTime) + '
';
+ };
+
+ if (!options.allowTimes || !$.isArray(options.allowTimes) || !options.allowTimes.length) {
+ for (i = 0, j = 0; i < (options.hours12 ? 12 : 24); i += 1) {
+ for (j = 0; j < 60; j += options.step) {
+ h = (i < 10 ? '0' : '') + i;
+ m = (j < 10 ? '0' : '') + j;
+ line_time(h, m);
+ }
+ }
+ } else {
+ for (i = 0; i < options.allowTimes.length; i += 1) {
+ h = _xdsoft_datetime.strtotime(options.allowTimes[i]).getHours();
+ m = _xdsoft_datetime.strtotime(options.allowTimes[i]).getMinutes();
+ line_time(h, m);
+ }
+ }
+
+ timebox.html(time);
+
+ opt = '';
+ i = 0;
+
+ for (i = parseInt(options.yearStart, 10) + options.yearOffset; i <= parseInt(options.yearEnd, 10) + options.yearOffset; i += 1) {
+ opt += '' + i + '
';
+ }
+ yearselect.children().eq(0)
+ .html(opt);
+
+ for (i = parseInt(options.monthStart, 10), opt = ''; i <= parseInt(options.monthEnd, 10); i += 1) {
+ opt += '' + options.i18n[globalLocale].months[i] + '
';
+ }
+ monthselect.children().eq(0).html(opt);
+ $(datetimepicker)
+ .trigger('generate.xdsoft');
+ }, 10);
+ event.stopPropagation();
+ })
+ .on('afterOpen.xdsoft', function () {
+ if (options.timepicker) {
+ var classType, pheight, height, top;
+ if (timebox.find('.xdsoft_current').length) {
+ classType = '.xdsoft_current';
+ } else if (timebox.find('.xdsoft_init_time').length) {
+ classType = '.xdsoft_init_time';
+ }
+ if (classType) {
+ pheight = timeboxparent[0].clientHeight;
+ height = timebox[0].offsetHeight;
+ top = timebox.find(classType).index() * options.timeHeightInTimePicker + 1;
+ if ((height - pheight) < top) {
+ top = height - pheight;
+ }
+ timeboxparent.trigger('scroll_element.xdsoft_scroller', [parseInt(top, 10) / (height - pheight)]);
+ } else {
+ timeboxparent.trigger('scroll_element.xdsoft_scroller', [0]);
+ }
+ }
+ });
+
+ timerclick = 0;
+ calendar
+ .on('touchend click.xdsoft', 'td', function (xdevent) {
+ xdevent.stopPropagation(); // Prevents closing of Pop-ups, Modals and Flyouts in Bootstrap
+ timerclick += 1;
+ var $this = $(this),
+ currentTime = _xdsoft_datetime.currentTime;
+
+ if (currentTime === undefined || currentTime === null) {
+ _xdsoft_datetime.currentTime = _xdsoft_datetime.now();
+ currentTime = _xdsoft_datetime.currentTime;
+ }
+
+ if ($this.hasClass('xdsoft_disabled')) {
+ return false;
+ }
+
+ currentTime.setDate(1);
+ currentTime.setFullYear($this.data('year'));
+ currentTime.setMonth($this.data('month'));
+ currentTime.setDate($this.data('date'));
+
+ datetimepicker.trigger('select.xdsoft', [currentTime]);
+
+ input.val(_xdsoft_datetime.str());
+
+ if (options.onSelectDate && $.isFunction(options.onSelectDate)) {
+ options.onSelectDate.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'), xdevent);
+ }
+
+ datetimepicker.data('changed', true);
+ datetimepicker.trigger('xchange.xdsoft');
+ datetimepicker.trigger('changedatetime.xdsoft');
+ if ((timerclick > 1 || (options.closeOnDateSelect === true || (options.closeOnDateSelect === false && !options.timepicker))) && !options.inline) {
+ datetimepicker.trigger('close.xdsoft');
+ }
+ setTimeout(function () {
+ timerclick = 0;
+ }, 200);
+ });
+
+ timebox
+ .on('touchmove', 'div', function () { currentlyScrollingTimeDiv = true; })
+ .on('touchend click.xdsoft', 'div', function (xdevent) {
+ xdevent.stopPropagation();
+ if (currentlyScrollingTimeDiv) {
+ currentlyScrollingTimeDiv = false;
+ return;
+ }
+ var $this = $(this),
+ currentTime = _xdsoft_datetime.currentTime;
+
+ if (currentTime === undefined || currentTime === null) {
+ _xdsoft_datetime.currentTime = _xdsoft_datetime.now();
+ currentTime = _xdsoft_datetime.currentTime;
+ }
+
+ if ($this.hasClass('xdsoft_disabled')) {
+ return false;
+ }
+ currentTime.setHours($this.data('hour'));
+ currentTime.setMinutes($this.data('minute'));
+ datetimepicker.trigger('select.xdsoft', [currentTime]);
+
+ datetimepicker.data('input').val(_xdsoft_datetime.str());
+
+ if (options.onSelectTime && $.isFunction(options.onSelectTime)) {
+ options.onSelectTime.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'), xdevent);
+ }
+ datetimepicker.data('changed', true);
+ datetimepicker.trigger('xchange.xdsoft');
+ datetimepicker.trigger('changedatetime.xdsoft');
+ if (options.inline !== true && options.closeOnTimeSelect === true) {
+ datetimepicker.trigger('close.xdsoft');
+ }
+ });
+
+ datepicker
+ .on('mousewheel.xdsoft', function (event) {
+ if (!options.scrollMonth) {
+ return true;
+ }
+ if (event.deltaY < 0) {
+ _xdsoft_datetime.nextMonth();
+ } else {
+ _xdsoft_datetime.prevMonth();
+ }
+ return false;
+ });
+
+ input
+ .on('mousewheel.xdsoft', function (event) {
+ if (!options.scrollInput) {
+ return true;
+ }
+ if (!options.datepicker && options.timepicker) {
+ current_time_index = timebox.find('.xdsoft_current').length ? timebox.find('.xdsoft_current').eq(0).index() : 0;
+ if (current_time_index + event.deltaY >= 0 && current_time_index + event.deltaY < timebox.children().length) {
+ current_time_index += event.deltaY;
+ }
+ if (timebox.children().eq(current_time_index).length) {
+ timebox.children().eq(current_time_index).trigger('mousedown');
+ }
+ return false;
+ }
+ if (options.datepicker && !options.timepicker) {
+ datepicker.trigger(event, [event.deltaY, event.deltaX, event.deltaY]);
+ if (input.val) {
+ input.val(_xdsoft_datetime.str());
+ }
+ datetimepicker.trigger('changedatetime.xdsoft');
+ return false;
+ }
+ });
+
+ datetimepicker
+ .on('changedatetime.xdsoft', function (event) {
+ if (options.onChangeDateTime && $.isFunction(options.onChangeDateTime)) {
+ var $input = datetimepicker.data('input');
+ options.onChangeDateTime.call(datetimepicker, _xdsoft_datetime.currentTime, $input, event);
+ delete options.value;
+ $input.trigger('change');
+ }
+ })
+ .on('generate.xdsoft', function () {
+ if (options.onGenerate && $.isFunction(options.onGenerate)) {
+ options.onGenerate.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'));
+ }
+ if (triggerAfterOpen) {
+ datetimepicker.trigger('afterOpen.xdsoft');
+ triggerAfterOpen = false;
+ }
+ })
+ .on('click.xdsoft', function (xdevent) {
+ xdevent.stopPropagation();
+ });
+
+ current_time_index = 0;
+
+ /**
+ * Runs the callback for each of the specified node's ancestors.
+ *
+ * Return FALSE from the callback to stop ascending.
+ *
+ * @param {DOMNode} node
+ * @param {Function} callback
+ * @returns {undefined}
+ */
+ forEachAncestorOf = function (node, callback) {
+ do {
+ node = node.parentNode;
+
+ if (callback(node) === false) {
+ break;
+ }
+ } while (node.nodeName !== 'HTML');
+ };
+
+ /**
+ * Sets the position of the picker.
+ *
+ * @returns {undefined}
+ */
+ setPos = function () {
+ var dateInputOffset,
+ dateInputElem,
+ verticalPosition,
+ left,
+ position,
+ datetimepickerElem,
+ dateInputHasFixedAncestor,
+ $dateInput,
+ windowWidth,
+ verticalAnchorEdge,
+ datetimepickerCss,
+ windowHeight,
+ windowScrollTop;
+
+ $dateInput = datetimepicker.data('input');
+ dateInputOffset = $dateInput.offset();
+ dateInputElem = $dateInput[0];
+
+ verticalAnchorEdge = 'top';
+ verticalPosition = (dateInputOffset.top + dateInputElem.offsetHeight) - 1;
+ left = dateInputOffset.left;
+ position = "absolute";
+
+ windowWidth = $(window).width();
+ windowHeight = $(window).height();
+ windowScrollTop = $(window).scrollTop();
+
+ if ((document.documentElement.clientWidth - dateInputOffset.left) < datepicker.parent().outerWidth(true)) {
+ var diff = datepicker.parent().outerWidth(true) - dateInputElem.offsetWidth;
+ left = left - diff;
+ }
+
+ if ($dateInput.parent().css('direction') === 'rtl') {
+ left -= (datetimepicker.outerWidth() - $dateInput.outerWidth());
+ }
+
+ if (options.fixed) {
+ verticalPosition -= windowScrollTop;
+ left -= $(window).scrollLeft();
+ position = "fixed";
+ } else {
+ dateInputHasFixedAncestor = false;
+
+ forEachAncestorOf(dateInputElem, function (ancestorNode) {
+ if (window.getComputedStyle(ancestorNode).getPropertyValue('position') === 'fixed') {
+ dateInputHasFixedAncestor = true;
+ return false;
+ }
+ });
+
+ if (dateInputHasFixedAncestor) {
+ position = 'fixed';
+
+ //If the picker won't fit entirely within the viewport then display it above the date input.
+ if (verticalPosition + datetimepicker.outerHeight() > windowHeight + windowScrollTop) {
+ verticalAnchorEdge = 'bottom';
+ verticalPosition = (windowHeight + windowScrollTop) - dateInputOffset.top;
+ } else {
+ verticalPosition -= windowScrollTop;
+ }
+ } else {
+ if (verticalPosition + dateInputElem.offsetHeight > windowHeight + windowScrollTop) {
+ verticalPosition = dateInputOffset.top - dateInputElem.offsetHeight + 1;
+ }
+ }
+
+ if (verticalPosition < 0) {
+ verticalPosition = 0;
+ }
+
+ if (left + dateInputElem.offsetWidth > windowWidth) {
+ left = windowWidth - dateInputElem.offsetWidth;
+ }
+ }
+
+ datetimepickerElem = datetimepicker[0];
+
+ forEachAncestorOf(datetimepickerElem, function (ancestorNode) {
+ var ancestorNodePosition;
+
+ ancestorNodePosition = window.getComputedStyle(ancestorNode).getPropertyValue('position');
+
+ if (ancestorNodePosition === 'relative' && windowWidth >= ancestorNode.offsetWidth) {
+ left = left - ((windowWidth - ancestorNode.offsetWidth) / 2);
+ return false;
+ }
+ });
+
+ datetimepickerCss = {
+ position: position,
+ left: left,
+ top: '', //Initialize to prevent previous values interfering with new ones.
+ bottom: '' //Initialize to prevent previous values interfering with new ones.
+ };
+
+ datetimepickerCss[verticalAnchorEdge] = verticalPosition;
+
+ datetimepicker.css(datetimepickerCss);
+ };
+
+ datetimepicker
+ .on('open.xdsoft', function (event) {
+ var onShow = true;
+ if (options.onShow && $.isFunction(options.onShow)) {
+ onShow = options.onShow.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'), event);
+ }
+ if (onShow !== false) {
+ datetimepicker.show();
+ setPos();
+ $(window)
+ .off('resize.xdsoft', setPos)
+ .on('resize.xdsoft', setPos);
+
+ if (options.closeOnWithoutClick) {
+ $([document.body, window]).on('touchstart mousedown.xdsoft', function arguments_callee6() {
+ datetimepicker.trigger('close.xdsoft');
+ $([document.body, window]).off('touchstart mousedown.xdsoft', arguments_callee6);
+ });
+ }
+ }
+ })
+ .on('close.xdsoft', function (event) {
+ var onClose = true;
+ month_picker
+ .find('.xdsoft_month,.xdsoft_year')
+ .find('.xdsoft_select')
+ .hide();
+ if (options.onClose && $.isFunction(options.onClose)) {
+ onClose = options.onClose.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'), event);
+ }
+ if (onClose !== false && !options.opened && !options.inline) {
+ datetimepicker.hide();
+ }
+ event.stopPropagation();
+ })
+ .on('toggle.xdsoft', function () {
+ if (datetimepicker.is(':visible')) {
+ datetimepicker.trigger('close.xdsoft');
+ } else {
+ datetimepicker.trigger('open.xdsoft');
+ }
+ })
+ .data('input', input);
+
+ timer = 0;
+
+ datetimepicker.data('xdsoft_datetime', _xdsoft_datetime);
+ datetimepicker.setOptions(options);
+
+ function getCurrentValue() {
+ var ct = false, time;
+
+ if (options.startDate) {
+ ct = _xdsoft_datetime.strToDate(options.startDate);
+ } else {
+ ct = options.value || ((input && input.val && input.val()) ? input.val() : '');
+ if (ct) {
+ ct = _xdsoft_datetime.strToDateTime(ct);
+ } else if (options.defaultDate) {
+ ct = _xdsoft_datetime.strToDateTime(options.defaultDate);
+ if (options.defaultTime) {
+ time = _xdsoft_datetime.strtotime(options.defaultTime);
+ ct.setHours(time.getHours());
+ ct.setMinutes(time.getMinutes());
+ }
+ }
+ }
+
+ if (ct && _xdsoft_datetime.isValidDate(ct)) {
+ datetimepicker.data('changed', true);
+ } else {
+ ct = '';
+ }
+
+ return ct || 0;
+ }
+
+ function setMask(options) {
+
+ var isValidValue = function (mask, value) {
+ var reg = mask
+ .replace(/([\[\]\/\{\}\(\)\-\.\+]{1})/g, '\\$1')
+ .replace(/_/g, '{digit+}')
+ .replace(/([0-9]{1})/g, '{digit$1}')
+ .replace(/\{digit([0-9]{1})\}/g, '[0-$1_]{1}')
+ .replace(/\{digit[\+]\}/g, '[0-9_]{1}');
+ return (new RegExp(reg)).test(value);
+ },
+ getCaretPos = function (input) {
+ try {
+ if (document.selection && document.selection.createRange) {
+ var range = document.selection.createRange();
+ return range.getBookmark().charCodeAt(2) - 2;
+ }
+ if (input.setSelectionRange) {
+ return input.selectionStart;
+ }
+ } catch (e) {
+ return 0;
+ }
+ },
+ setCaretPos = function (node, pos) {
+ node = (typeof node === "string" || node instanceof String) ? document.getElementById(node) : node;
+ if (!node) {
+ return false;
+ }
+ if (node.createTextRange) {
+ var textRange = node.createTextRange();
+ textRange.collapse(true);
+ textRange.moveEnd('character', pos);
+ textRange.moveStart('character', pos);
+ textRange.select();
+ return true;
+ }
+ if (node.setSelectionRange) {
+ node.setSelectionRange(pos, pos);
+ return true;
+ }
+ return false;
+ };
+ if(options.mask) {
+ input.off('keydown.xdsoft');
+ }
+ if (options.mask === true) {
+ if (typeof moment != 'undefined') {
+ options.mask = options.format
+ .replace(/Y{4}/g, '9999')
+ .replace(/Y{2}/g, '99')
+ .replace(/M{2}/g, '19')
+ .replace(/D{2}/g, '39')
+ .replace(/H{2}/g, '29')
+ .replace(/m{2}/g, '59')
+ .replace(/s{2}/g, '59');
+ } else {
+ options.mask = options.format
+ .replace(/Y/g, '9999')
+ .replace(/F/g, '9999')
+ .replace(/m/g, '19')
+ .replace(/d/g, '39')
+ .replace(/H/g, '29')
+ .replace(/i/g, '59')
+ .replace(/s/g, '59');
+ }
+ }
+
+ if ($.type(options.mask) === 'string') {
+ if (!isValidValue(options.mask, input.val())) {
+ input.val(options.mask.replace(/[0-9]/g, '_'));
+ setCaretPos(input[0], 0);
+ }
+
+ input.on('keydown.xdsoft', function (event) {
+ var val = this.value,
+ key = event.which,
+ pos,
+ digit;
+
+ if (((key >= KEY0 && key <= KEY9) || (key >= _KEY0 && key <= _KEY9)) || (key === BACKSPACE || key === DEL)) {
+ pos = getCaretPos(this);
+ digit = (key !== BACKSPACE && key !== DEL) ? String.fromCharCode((_KEY0 <= key && key <= _KEY9) ? key - KEY0 : key) : '_';
+
+ if ((key === BACKSPACE || key === DEL) && pos) {
+ pos -= 1;
+ digit = '_';
+ }
+
+ while (/[^0-9_]/.test(options.mask.substr(pos, 1)) && pos < options.mask.length && pos > 0) {
+ pos += (key === BACKSPACE || key === DEL) ? -1 : 1;
+ }
+
+ val = val.substr(0, pos) + digit + val.substr(pos + 1);
+ if ($.trim(val) === '') {
+ val = options.mask.replace(/[0-9]/g, '_');
+ } else {
+ if (pos === options.mask.length) {
+ event.preventDefault();
+ return false;
+ }
+ }
+
+ pos += (key === BACKSPACE || key === DEL) ? 0 : 1;
+ while (/[^0-9_]/.test(options.mask.substr(pos, 1)) && pos < options.mask.length && pos > 0) {
+ pos += (key === BACKSPACE || key === DEL) ? -1 : 1;
+ }
+
+ if (isValidValue(options.mask, val)) {
+ this.value = val;
+ setCaretPos(this, pos);
+ } else if ($.trim(val) === '') {
+ this.value = options.mask.replace(/[0-9]/g, '_');
+ } else {
+ input.trigger('error_input.xdsoft');
+ }
+ } else {
+ if (([AKEY, CKEY, VKEY, ZKEY, YKEY].indexOf(key) !== -1 && ctrlDown) || [ESC, ARROWUP, ARROWDOWN, ARROWLEFT, ARROWRIGHT, F5, CTRLKEY, TAB, ENTER].indexOf(key) !== -1) {
+ return true;
+ }
+ }
+
+ event.preventDefault();
+ return false;
+ });
+ }
+ }
+
+ _xdsoft_datetime.setCurrentTime(getCurrentValue());
+
+ input
+ .data('xdsoft_datetimepicker', datetimepicker)
+ .on('open.xdsoft focusin.xdsoft mousedown.xdsoft touchstart', function () {
+ if (input.is(':disabled') || (input.data('xdsoft_datetimepicker').is(':visible') && options.closeOnInputClick)) {
+ return;
+ }
+ clearTimeout(timer);
+ timer = setTimeout(function () {
+ if (input.is(':disabled')) {
+ return;
+ }
+
+ triggerAfterOpen = true;
+ _xdsoft_datetime.setCurrentTime(getCurrentValue(), true);
+ if(options.mask) {
+ setMask(options);
+ }
+ datetimepicker.trigger('open.xdsoft');
+ }, 100);
+ })
+ .on('keydown.xdsoft', function (event) {
+ var elementSelector,
+ key = event.which;
+ if ([ENTER].indexOf(key) !== -1 && options.enterLikeTab) {
+ elementSelector = $("input:visible,textarea:visible,button:visible,a:visible");
+ datetimepicker.trigger('close.xdsoft');
+ elementSelector.eq(elementSelector.index(this) + 1).focus();
+ return false;
+ }
+ if ([TAB].indexOf(key) !== -1) {
+ datetimepicker.trigger('close.xdsoft');
+ return true;
+ }
+ })
+ .on('blur.xdsoft', function () {
+ datetimepicker.trigger('close.xdsoft');
+ });
+ };
+ destroyDateTimePicker = function (input) {
+ var datetimepicker = input.data('xdsoft_datetimepicker');
+ if (datetimepicker) {
+ datetimepicker.data('xdsoft_datetime', null);
+ datetimepicker.remove();
+ input
+ .data('xdsoft_datetimepicker', null)
+ .off('.xdsoft');
+ $(window).off('resize.xdsoft');
+ $([window, document.body]).off('mousedown.xdsoft touchstart');
+ if (input.unmousewheel) {
+ input.unmousewheel();
+ }
+ }
+ };
+ $(document)
+ .off('keydown.xdsoftctrl keyup.xdsoftctrl')
+ .on('keydown.xdsoftctrl', function (e) {
+ if (e.keyCode === CTRLKEY) {
+ ctrlDown = true;
+ }
+ })
+ .on('keyup.xdsoftctrl', function (e) {
+ if (e.keyCode === CTRLKEY) {
+ ctrlDown = false;
+ }
+ });
+
+ this.each(function () {
+ var datetimepicker = $(this).data('xdsoft_datetimepicker'), $input;
+ if (datetimepicker) {
+ if ($.type(opt) === 'string') {
+ switch (opt) {
+ case 'show':
+ $(this).select().focus();
+ datetimepicker.trigger('open.xdsoft');
+ break;
+ case 'hide':
+ datetimepicker.trigger('close.xdsoft');
+ break;
+ case 'toggle':
+ datetimepicker.trigger('toggle.xdsoft');
+ break;
+ case 'destroy':
+ destroyDateTimePicker($(this));
+ break;
+ case 'reset':
+ this.value = this.defaultValue;
+ if (!this.value || !datetimepicker.data('xdsoft_datetime').isValidDate(dateHelper.parseDate(this.value, options.format))) {
+ datetimepicker.data('changed', false);
+ }
+ datetimepicker.data('xdsoft_datetime').setCurrentTime(this.value);
+ break;
+ case 'validate':
+ $input = datetimepicker.data('input');
+ $input.trigger('blur.xdsoft');
+ break;
+ default:
+ if (datetimepicker[opt] && $.isFunction(datetimepicker[opt])) {
+ result = datetimepicker[opt](opt2);
+ }
+ }
+ } else {
+ datetimepicker
+ .setOptions(opt);
+ }
+ return 0;
+ }
+ if ($.type(opt) !== 'string') {
+ if (!options.lazyInit || options.open || options.inline) {
+ createDateTimePicker($(this));
+ } else {
+ lazyInit($(this));
+ }
+ }
+ });
+
+ return result;
+ };
+
+ $.fn.datetimepicker.defaults = default_options;
+
+ function HighlightedDate(date, desc, style) {
+ "use strict";
+ this.date = date;
+ this.desc = desc;
+ this.style = style;
+ }
}));
/*!
* jQuery Mousewheel 3.1.13
diff --git a/template/acp/js/functions.js b/template/acp/js/functions.js
index 57d1b69..e3f3f3f 100644
--- a/template/acp/js/functions.js
+++ b/template/acp/js/functions.js
@@ -1,64 +1,64 @@
function loading(show)
{
- if(show)
- $('#loadinginfo').css('display', 'block');
- else
- $('#loadinginfo').css('display', 'none');
+ if(show)
+ $('#loadinginfo').css('display', 'block');
+ else
+ $('#loadinginfo').css('display', 'none');
}
function cashback_output(id, type)
{
- if(type == 'mm')
- bootbox.dialog('Вы подтверждаете, что вывели деньги на эл. кошелек?',
- [{
- "label" : "Подтверждаю",
- callback: function() {
- cashback_output_go(id)
- }
- },{
- "label" : "Отмена"
- }]
- );
- else
- bootbox.dialog('Будет выполнен запрос через шлюз',
- [{
- "label" : "Продолжить",
- callback: function() {
- cashback_output_go(id)
- }
- },{
- "label" : "Отмена"
- }]
- );
+ if(type == 'mm')
+ bootbox.dialog('Вы подтверждаете, что вывели деньги на эл. кошелек?',
+ [{
+ "label" : "Подтверждаю",
+ callback: function() {
+ cashback_output_go(id)
+ }
+ },{
+ "label" : "Отмена"
+ }]
+ );
+ else
+ bootbox.dialog('Будет выполнен запрос через шлюз',
+ [{
+ "label" : "Продолжить",
+ callback: function() {
+ cashback_output_go(id)
+ }
+ },{
+ "label" : "Отмена"
+ }]
+ );
}
function cashback_output_go(id)
{
- $.getJSON(home+'cashback/id/'+id, function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- bootbox.dialog('Ошибка '+val,
- [{
- "label" : "OK",
- "class" : "btn-small btn-primary",
- }]
- );
+ $.getJSON(home+'cashback/id/'+id, function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ bootbox.dialog('Ошибка '+val,
+ [{
+ "label" : "OK",
+ "class" : "btn-small btn-primary",
+ }]
+ );
- if(i == 's')
- {
- bootbox.dialog(val,
- [{
- "label" : "Продолжить",
- callback: function() {
- location.reload()
- }
- }]
- );
- }
- });
- });
+ if(i == 's')
+ {
+ bootbox.dialog(val,
+ [{
+ "label" : "Продолжить",
+ callback: function() {
+ location.reload()
+ }
+ }]
+ );
+ }
+ });
+ });
- return false
+ return false
}
\ No newline at end of file
diff --git a/template/acp/js/letter.js b/template/acp/js/letter.js
index a2124f2..c7bd4e9 100644
--- a/template/acp/js/letter.js
+++ b/template/acp/js/letter.js
@@ -1,49 +1,49 @@
$('#letter').ajaxForm({
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- bootbox.dialog('Ошибка '+val,
- [{
- "label" : "Продолжить"
- }]
- );
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ bootbox.dialog('Ошибка '+val,
+ [{
+ "label" : "Продолжить"
+ }]
+ );
- if(i == 's')
- {
- bootbox.dialog('Внимание Рассылка выполнена. Список почт, на которые не удалось отправить сообщение: '+val,
- [{
- "label" : "Продолжить",
- callback : function(){location.reload()}
- }]
- );
- }
- });
+ if(i == 's')
+ {
+ bootbox.dialog('Внимание Рассылка выполнена. Список почт, на которые не удалось отправить сообщение: '+val,
+ [{
+ "label" : "Продолжить",
+ callback : function(){location.reload()}
+ }]
+ );
+ }
+ });
- loading(0)
- }
+ loading(0)
+ }
});
function checked_all()
{
- if(letter_all)
- {
- for(i=0; i < document.letter.length; i++)
- {
- if(document.letter.elements[i].type == 'checkbox')
- document.letter.elements[i].checked = false;
- }
+ if(letter_all)
+ {
+ for(i=0; i < document.letter.length; i++)
+ {
+ if(document.letter.elements[i].type == 'checkbox')
+ document.letter.elements[i].checked = false;
+ }
- letter_all = false;
- }else{
- for(i=0; i < document.letter.length; i++)
- {
- if(document.letter.elements[i].type == 'checkbox')
- document.letter.elements[i].checked = true;
- }
+ letter_all = false;
+ }else{
+ for(i=0; i < document.letter.length; i++)
+ {
+ if(document.letter.elements[i].type == 'checkbox')
+ document.letter.elements[i].checked = true;
+ }
- letter_all = true;
- }
+ letter_all = true;
+ }
}
diff --git a/template/acp/js/logs.js b/template/acp/js/logs.js
index 461ae29..33e2b00 100644
--- a/template/acp/js/logs.js
+++ b/template/acp/js/logs.js
@@ -1,87 +1,87 @@
function logs_sys_search(go)
{
- if($('#search').val() == '')
- {
- $('#search_error').css('display', 'none');
+ if($('#search').val() == '')
+ {
+ $('#search_error').css('display', 'none');
- return;
- }
+ return;
+ }
- loading(1);
+ loading(1);
- if(go) go = '/go'; else go = '';
+ if(go) go = '/go'; else go = '';
- $.ajax({
- type: 'POST',
- url: home+'logs/subsection/search'+go,
- data: 'text='+$('#search').val(),
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- {
- if(val != '')
- {
- $('#search_error').css('display', 'inline-block');
- $('#search_error').html(val);
- }else
- $('#search_error').css('display', 'none');
- }
+ $.ajax({
+ type: 'POST',
+ url: home+'logs/subsection/search'+go,
+ data: 'text='+$('#search').val(),
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ {
+ if(val != '')
+ {
+ $('#search_error').css('display', 'inline-block');
+ $('#search_error').html(val);
+ }else
+ $('#search_error').css('display', 'none');
+ }
- if(i == 's')
- {
- $('#search_error').css('display', 'none');
- $('#search_result').html(val);
- }
- });
+ if(i == 's')
+ {
+ $('#search_error').css('display', 'none');
+ $('#search_result').html(val);
+ }
+ });
- loading(0);
- }
- });
+ loading(0);
+ }
+ });
}
function logs_search(go)
{
- if($('#search').val() == '')
- {
- $('#search_error').css('display', 'none');
+ if($('#search').val() == '')
+ {
+ $('#search_error').css('display', 'none');
- return;
- }
+ return;
+ }
- loading(1);
+ loading(1);
- if(go) go = '/go'; else go = '';
+ if(go) go = '/go'; else go = '';
- $.ajax({
- type: 'POST',
- url: home+'logs/section/search'+go,
- data: 'text='+$('#search').val(),
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- {
- if(val != '')
- {
- $('#search_error').css('display', 'inline-block');
- $('#search_error').html(val);
- }else
- $('#search_error').css('display', 'none');
- }
+ $.ajax({
+ type: 'POST',
+ url: home+'logs/section/search'+go,
+ data: 'text='+$('#search').val(),
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ {
+ if(val != '')
+ {
+ $('#search_error').css('display', 'inline-block');
+ $('#search_error').html(val);
+ }else
+ $('#search_error').css('display', 'none');
+ }
- if(i == 's')
- {
- $('#search_error').css('display', 'none');
- $('#search_result').html(val);
- }
- });
+ if(i == 's')
+ {
+ $('#search_error').css('display', 'none');
+ $('#search_result').html(val);
+ }
+ });
- loading(0);
- }
- });
+ loading(0);
+ }
+ });
}
\ No newline at end of file
diff --git a/template/acp/js/news.js b/template/acp/js/news.js
index 1e3c2aa..e0661bf 100644
--- a/template/acp/js/news.js
+++ b/template/acp/js/news.js
@@ -1,120 +1,120 @@
$('#news').ajaxForm({
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- bootbox.dialog('Ошибка '+val,
- [{
- "label" : "Продолжить"
- }]
- );
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ bootbox.dialog('Ошибка '+val,
+ [{
+ "label" : "Продолжить"
+ }]
+ );
- if(i == 's')
- location.reload();
- });
+ if(i == 's')
+ location.reload();
+ });
- loading(0)
- }
+ loading(0)
+ }
});
function news_search(go)
{
- if($('#search').val() == '')
- {
- $('#search_error').css('display', 'none');
+ if($('#search').val() == '')
+ {
+ $('#search_error').css('display', 'none');
- return;
- }
+ return;
+ }
- loading(1);
+ loading(1);
- if(go) go = '/go'; else go = '';
+ if(go) go = '/go'; else go = '';
- $.ajax({
- type: 'POST',
- url: home+'news/subsection/search'+go,
- data: 'text='+$('#search').val(),
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- {
- if(val != '')
- {
- $('#search_error').css('display', 'inline-block');
- $('#search_error').html(val);
- }else
- $('#search_error').css('display', 'none');
- }
+ $.ajax({
+ type: 'POST',
+ url: home+'news/subsection/search'+go,
+ data: 'text='+$('#search').val(),
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ {
+ if(val != '')
+ {
+ $('#search_error').css('display', 'inline-block');
+ $('#search_error').html(val);
+ }else
+ $('#search_error').css('display', 'none');
+ }
- if(i == 's')
- {
- $('#search_error').css('display', 'none');
- $('#search_result').html(val);
- }
- });
+ if(i == 's')
+ {
+ $('#search_error').css('display', 'none');
+ $('#search_result').html(val);
+ }
+ });
- loading(0);
- }
- });
+ loading(0);
+ }
+ });
}
function news_delete(id)
{
- bootbox.dialog('Внимание Вы уверены, что хотите удалить новость?',
- [{
- "label" : "Удалить",
- callback : function(){news_delete_go(id)}
- },{
- "label" : "Отмена",
- }]
- );
+ bootbox.dialog('Внимание Вы уверены, что хотите удалить новость?',
+ [{
+ "label" : "Удалить",
+ callback : function(){news_delete_go(id)}
+ },{
+ "label" : "Отмена",
+ }]
+ );
- return false;
+ return false;
}
function news_delete_go(id)
{
- loading(1);
+ loading(1);
- $.ajax({
- type: 'POST',
- url: home+'news/section/delete/id/'+id,
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- bootbox.dialog('Ошибка '+val,
- [{
- "label" : "Продолжить"
- }]
- );
+ $.ajax({
+ type: 'POST',
+ url: home+'news/section/delete/id/'+id,
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ bootbox.dialog('Ошибка '+val,
+ [{
+ "label" : "Продолжить"
+ }]
+ );
- if(i == 's')
- location.reload()
- });
+ if(i == 's')
+ location.reload()
+ });
- loading(0);
- }
- });
+ loading(0);
+ }
+ });
}
function bbcode(bbbegin, bbend, ta)
{
- form = document.getElementById(ta);
- begin = form.value.substr(0, form.selectionStart);
- end = form.value.substr(form.selectionEnd);
- sel = form.value.substr(form.selectionStart, form.selectionEnd-form.selectionStart);
- var text = form.firstChild;
- form.value = begin+bbbegin+sel+bbend+end;
- selPos = bbbegin.length+begin.length+sel.length+bbend.length;
- form.setSelectionRange(begin.length, selPos);
+ form = document.getElementById(ta);
+ begin = form.value.substr(0, form.selectionStart);
+ end = form.value.substr(form.selectionEnd);
+ sel = form.value.substr(form.selectionStart, form.selectionEnd-form.selectionStart);
+ var text = form.firstChild;
+ form.value = begin+bbbegin+sel+bbend+end;
+ selPos = bbbegin.length+begin.length+sel.length+bbend.length;
+ form.setSelectionRange(begin.length, selPos);
- return false;
+ return false;
}
\ No newline at end of file
diff --git a/template/acp/js/notice.js b/template/acp/js/notice.js
index 92aa0f4..557c4e0 100644
--- a/template/acp/js/notice.js
+++ b/template/acp/js/notice.js
@@ -1,118 +1,118 @@
$('#notice').ajaxForm({
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- bootbox.dialog('Ошибка '+val,
- [{
- "label" : "Продолжить"
- }]
- );
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ bootbox.dialog('Ошибка '+val,
+ [{
+ "label" : "Продолжить"
+ }]
+ );
- if(i == 's')
- location.reload();
- });
+ if(i == 's')
+ location.reload();
+ });
- loading(0)
- }
+ loading(0)
+ }
});
function notice_search(go)
{
- if($('#search').val() == '')
- {
- $('#search_error').css('display', 'none');
+ if($('#search').val() == '')
+ {
+ $('#search_error').css('display', 'none');
- return;
- }
+ return;
+ }
- loading(1);
+ loading(1);
- if(go) go = '/go'; else go = '';
+ if(go) go = '/go'; else go = '';
- $.ajax({
- type: 'POST',
- url: home+'notice/subsection/search'+go,
- data: 'text='+$('#search').val(),
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- {
- if(val != '')
- {
- $('#search_error').css('display', 'inline-block');
- $('#search_error').html(val);
- }else
- $('#search_error').css('display', 'none');
- }
+ $.ajax({
+ type: 'POST',
+ url: home+'notice/subsection/search'+go,
+ data: 'text='+$('#search').val(),
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ {
+ if(val != '')
+ {
+ $('#search_error').css('display', 'inline-block');
+ $('#search_error').html(val);
+ }else
+ $('#search_error').css('display', 'none');
+ }
- if(i == 's')
- {
- $('#search_error').css('display', 'none');
- $('#search_result').html(val);
- }
- });
+ if(i == 's')
+ {
+ $('#search_error').css('display', 'none');
+ $('#search_result').html(val);
+ }
+ });
- loading(0);
- }
- });
+ loading(0);
+ }
+ });
}
function change_notice_type()
{
- if($('#type').val() == 'unit')
- {
- $('#notice_unit').css('display', 'block');
- $('#notice_server').css('display', 'none');
- }else{
- $('#notice_unit').css('display', 'none');
- $('#notice_server').css('display', 'block');
- }
+ if($('#type').val() == 'unit')
+ {
+ $('#notice_unit').css('display', 'block');
+ $('#notice_server').css('display', 'none');
+ }else{
+ $('#notice_unit').css('display', 'none');
+ $('#notice_server').css('display', 'block');
+ }
}
function notice_delete(id)
{
- bootbox.dialog('Внимание Вы уверены, что хотите удалить уведомление?',
- [{
- "label" : "Удалить",
- callback : function(){notice_delete_go(id)}
- },{
- "label" : "Отмена",
- }]
- );
+ bootbox.dialog('Внимание Вы уверены, что хотите удалить уведомление?',
+ [{
+ "label" : "Удалить",
+ callback : function(){notice_delete_go(id)}
+ },{
+ "label" : "Отмена",
+ }]
+ );
- return false;
+ return false;
}
function notice_delete_go(id)
{
- loading(1);
+ loading(1);
- $.ajax({
- type: 'POST',
- url: home+'notice/section/delete/id/'+id,
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- bootbox.dialog('Ошибка '+val,
- [{
- "label" : "Продолжить"
- }]
- );
+ $.ajax({
+ type: 'POST',
+ url: home+'notice/section/delete/id/'+id,
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ bootbox.dialog('Ошибка '+val,
+ [{
+ "label" : "Продолжить"
+ }]
+ );
- if(i == 's')
- location.reload()
- });
+ if(i == 's')
+ location.reload()
+ });
- loading(0);
- }
- });
+ loading(0);
+ }
+ });
}
\ No newline at end of file
diff --git a/template/acp/js/pages.js b/template/acp/js/pages.js
index 21e5fb1..3c3b450 100644
--- a/template/acp/js/pages.js
+++ b/template/acp/js/pages.js
@@ -1,62 +1,62 @@
$('#page').ajaxForm({
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- bootbox.dialog('Ошибка '+val,
- [{
- "label" : "Продолжить"
- }]
- );
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ bootbox.dialog('Ошибка '+val,
+ [{
+ "label" : "Продолжить"
+ }]
+ );
- if(i == 's')
- location.reload();
- });
+ if(i == 's')
+ location.reload();
+ });
- loading(0)
- }
+ loading(0)
+ }
});
function page_delete(id)
{
- bootbox.dialog('Внимание Вы уверены, что хотите удалить страницу?',
- [{
- "label" : "Удалить",
- callback : function(){page_delete_go(id)}
- },{
- "label" : "Отмена",
- }]
- );
+ bootbox.dialog('Внимание Вы уверены, что хотите удалить страницу?',
+ [{
+ "label" : "Удалить",
+ callback : function(){page_delete_go(id)}
+ },{
+ "label" : "Отмена",
+ }]
+ );
- return false;
+ return false;
}
function page_delete_go(id)
{
- loading(1);
+ loading(1);
- $.ajax({
- type: 'POST',
- url: home+'pages/section/delete/id/'+id,
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- bootbox.dialog('Ошибка '+val,
- [{
- "label" : "Продолжить"
- }]
- );
+ $.ajax({
+ type: 'POST',
+ url: home+'pages/section/delete/id/'+id,
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ bootbox.dialog('Ошибка '+val,
+ [{
+ "label" : "Продолжить"
+ }]
+ );
- if(i == 's')
- location.reload()
- });
+ if(i == 's')
+ location.reload()
+ });
- loading(0);
- }
- });
+ loading(0);
+ }
+ });
}
\ No newline at end of file
diff --git a/template/acp/js/promo.js b/template/acp/js/promo.js
index cd3c9a3..a7f1d5d 100644
--- a/template/acp/js/promo.js
+++ b/template/acp/js/promo.js
@@ -1,148 +1,148 @@
$('#promo').ajaxForm({
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- bootbox.dialog('Ошибка '+val,
- [{
- "label" : "Продолжить"
- }]
- );
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ bootbox.dialog('Ошибка '+val,
+ [{
+ "label" : "Продолжить"
+ }]
+ );
- if(i == 's')
- location.reload();
- });
+ if(i == 's')
+ location.reload();
+ });
- loading(0)
- }
+ loading(0)
+ }
});
function promo_search(go)
{
- if($('#search').val() == '')
- {
- $('#search_error').css('display', 'none');
+ if($('#search').val() == '')
+ {
+ $('#search_error').css('display', 'none');
- return;
- }
+ return;
+ }
- loading(1);
+ loading(1);
- if(go) go = '/go'; else go = '';
+ if(go) go = '/go'; else go = '';
- $.ajax({
- type: 'POST',
- url: home+'promo/subsection/search'+go,
- data: 'text='+$('#search').val(),
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- {
- if(val != '')
- {
- $('#search_error').css('display', 'inline-block');
- $('#search_error').html(val);
- }else
- $('#search_error').css('display', 'none');
- }
+ $.ajax({
+ type: 'POST',
+ url: home+'promo/subsection/search'+go,
+ data: 'text='+$('#search').val(),
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ {
+ if(val != '')
+ {
+ $('#search_error').css('display', 'inline-block');
+ $('#search_error').html(val);
+ }else
+ $('#search_error').css('display', 'none');
+ }
- if(i == 's')
- {
- $('#search_error').css('display', 'none');
- $('#search_result').html(val);
- }
- });
+ if(i == 's')
+ {
+ $('#search_error').css('display', 'none');
+ $('#search_result').html(val);
+ }
+ });
- loading(0);
- }
- });
+ loading(0);
+ }
+ });
}
function promo_delete(id)
{
- bootbox.dialog('Внимание Вы уверены, что хотите удалить акцию?',
- [{
- "label" : "Удалить",
- callback : function(){promo_delete_go(id)}
- },{
- "label" : "Отмена",
- }]
- );
+ bootbox.dialog('Внимание Вы уверены, что хотите удалить акцию?',
+ [{
+ "label" : "Удалить",
+ callback : function(){promo_delete_go(id)}
+ },{
+ "label" : "Отмена",
+ }]
+ );
- return false;
+ return false;
}
function promo_delete_go(id)
{
- loading(1);
+ loading(1);
- $.ajax({
- type: 'POST',
- url: home+'promo/section/delete/id/'+id,
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- bootbox.dialog('Ошибка '+val,
- [{
- "label" : "Продолжить"
- }]
- );
+ $.ajax({
+ type: 'POST',
+ url: home+'promo/section/delete/id/'+id,
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ bootbox.dialog('Ошибка '+val,
+ [{
+ "label" : "Продолжить"
+ }]
+ );
- if(i == 's')
- location.reload()
- });
+ if(i == 's')
+ location.reload()
+ });
- loading(0);
- }
- });
+ loading(0);
+ }
+ });
}
function promo_use_delete(id)
{
- bootbox.dialog('Внимание Вы уверены, что хотите удалить лог использования акции?',
- [{
- "label" : "Удалить",
- callback : function(){promo_use_delete_go(id)}
- },{
- "label" : "Отмена",
- }]
- );
+ bootbox.dialog('Внимание Вы уверены, что хотите удалить лог использования акции?',
+ [{
+ "label" : "Удалить",
+ callback : function(){promo_use_delete_go(id)}
+ },{
+ "label" : "Отмена",
+ }]
+ );
- return false;
+ return false;
}
function promo_use_delete_go(id)
{
- loading(1);
+ loading(1);
- $.ajax({
- type: 'POST',
- url: home+'promo/section/stats/delete/'+id,
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- bootbox.dialog('Ошибка '+val,
- [{
- "label" : "Продолжить"
- }]
- );
+ $.ajax({
+ type: 'POST',
+ url: home+'promo/section/stats/delete/'+id,
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ bootbox.dialog('Ошибка '+val,
+ [{
+ "label" : "Продолжить"
+ }]
+ );
- if(i == 's')
- location.reload()
- });
+ if(i == 's')
+ location.reload()
+ });
- loading(0);
- }
- });
+ loading(0);
+ }
+ });
}
\ No newline at end of file
diff --git a/template/acp/js/servers.js b/template/acp/js/servers.js
index 3548690..41c71f9 100644
--- a/template/acp/js/servers.js
+++ b/template/acp/js/servers.js
@@ -1,224 +1,224 @@
$('#server').ajaxForm({
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- bootbox.dialog('Ошибка '+val,
- [{
- "label" : "Продолжить"
- }]
- );
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ bootbox.dialog('Ошибка '+val,
+ [{
+ "label" : "Продолжить"
+ }]
+ );
- if(i == 's')
- location.reload();
- });
+ if(i == 's')
+ location.reload();
+ });
- loading(0)
- }
+ loading(0)
+ }
});
function servers_search(go)
{
- if($('#search').val() == '')
- {
- $('#search_error').css('display', 'none');
+ if($('#search').val() == '')
+ {
+ $('#search_error').css('display', 'none');
- return;
- }
+ return;
+ }
- loading(1);
+ loading(1);
- if(go) go = '/go'; else go = '';
+ if(go) go = '/go'; else go = '';
- $.ajax({
- type: 'POST',
- url: home+'servers/subsection/search'+url_search+go,
- data: 'text='+$('#search').val(),
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- {
- if(val != '')
- {
- $('#search_error').css('display', 'inline-block');
- $('#search_error').html(val);
- }else
- $('#search_error').css('display', 'none');
- }
+ $.ajax({
+ type: 'POST',
+ url: home+'servers/subsection/search'+url_search+go,
+ data: 'text='+$('#search').val(),
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ {
+ if(val != '')
+ {
+ $('#search_error').css('display', 'inline-block');
+ $('#search_error').html(val);
+ }else
+ $('#search_error').css('display', 'none');
+ }
- if(i == 's')
- {
- $('#search_error').css('display', 'none');
- $('#search_result').html(val);
- }
+ if(i == 's')
+ {
+ $('#search_error').css('display', 'none');
+ $('#search_result').html(val);
+ }
- if(i == 'url')
- url_search = val;
- });
+ if(i == 'url')
+ url_search = val;
+ });
- loading(0);
- }
- });
+ loading(0);
+ }
+ });
}
function servers_overdue(id, time)
{
- bootbox.dialog('Установка даты:
',
- [{
- "label" : "Установить",
- callback : function(){servers_overdue_go(id)}
- },{
- "label" : "Отмена",
- }]
- );
+ bootbox.dialog('Установка даты:
',
+ [{
+ "label" : "Установить",
+ callback : function(){servers_overdue_go(id)}
+ },{
+ "label" : "Отмена",
+ }]
+ );
- return false;
+ return false;
}
function servers_block(id, time)
{
- bootbox.dialog('Установка даты:
',
- [{
- "label" : "Заблокировать",
- callback : function(){servers_block_go(id)}
- },{
- "label" : "Отмена",
- }]
- );
+ bootbox.dialog('Установка даты:
',
+ [{
+ "label" : "Заблокировать",
+ callback : function(){servers_block_go(id)}
+ },{
+ "label" : "Отмена",
+ }]
+ );
- return false;
+ return false;
}
function datepick(input, time)
{
- if($('#'+input).val() != '')
- time = $('#'+input).val();
+ if($('#'+input).val() != '')
+ time = $('#'+input).val();
- $('#'+input).datetimepicker({value: time, format: 'd/m/Y H:i'});
+ $('#'+input).datetimepicker({value: time, format: 'd/m/Y H:i'});
}
function servers_overdue_go(id)
{
- $.ajax({
- type: 'POST',
- url: home+'servers/type/overdue/id/'+id+'/go',
- data: 'time='+$('#date_overdue').val(),
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- bootbox.dialog('Ошибка '+val,
- [{
- "label" : "Продолжить"
- }]
- );
+ $.ajax({
+ type: 'POST',
+ url: home+'servers/type/overdue/id/'+id+'/go',
+ data: 'time='+$('#date_overdue').val(),
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ bootbox.dialog('Ошибка '+val,
+ [{
+ "label" : "Продолжить"
+ }]
+ );
- if(i == 's')
- location.reload();
- });
- }
- });
+ if(i == 's')
+ location.reload();
+ });
+ }
+ });
}
function servers_block_go(id)
{
- $.ajax({
- type: 'POST',
- url: home+'servers/type/block/id/'+id+'/go',
- data: 'time='+$('#date_block').val(),
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- bootbox.dialog('Ошибка '+val,
- [{
- "label" : "Продолжить"
- }]
- );
+ $.ajax({
+ type: 'POST',
+ url: home+'servers/type/block/id/'+id+'/go',
+ data: 'time='+$('#date_block').val(),
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ bootbox.dialog('Ошибка '+val,
+ [{
+ "label" : "Продолжить"
+ }]
+ );
- if(i == 's')
- location.reload();
- });
- }
- });
+ if(i == 's')
+ location.reload();
+ });
+ }
+ });
}
function servers_delete(id)
{
- bootbox.dialog('Внимание Вы уверены, что хотите удалить сервер?',
- [{
- "label" : "Удалить",
- callback : function(){servers_delete_go(id)}
- },{
- "label" : "Отмена",
- }]
- );
+ bootbox.dialog('Внимание Вы уверены, что хотите удалить сервер?',
+ [{
+ "label" : "Удалить",
+ callback : function(){servers_delete_go(id)}
+ },{
+ "label" : "Отмена",
+ }]
+ );
- return false;
+ return false;
}
function servers_delete_go(id)
{
-
- loading(1);
+
+ loading(1);
- $.ajax({
- type: 'POST',
- url: home+'servers/section/delete/id/'+id,
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- bootbox.dialog('Ошибка '+val,
- [{
- "label" : "Продолжить"
- }]
- );
+ $.ajax({
+ type: 'POST',
+ url: home+'servers/section/delete/id/'+id,
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ bootbox.dialog('Ошибка '+val,
+ [{
+ "label" : "Продолжить"
+ }]
+ );
- if(i == 's')
- location.reload()
- });
+ if(i == 's')
+ location.reload()
+ });
- loading(0);
- }
- });
+ loading(0);
+ }
+ });
}
function change_tarif(id)
{
- loading(1);
+ loading(1);
- $.ajax({
- url: home+'servers/type/tarif/id/'+id+'/tarif/'+$('#tarif').val()+'/go',
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- bootbox.dialog('Ошибка '+val,
- [{
- "label" : "Продолжить"
- }]
- );
+ $.ajax({
+ url: home+'servers/type/tarif/id/'+id+'/tarif/'+$('#tarif').val()+'/go',
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ bootbox.dialog('Ошибка '+val,
+ [{
+ "label" : "Продолжить"
+ }]
+ );
- if(i == 's')
- location.reload()
- });
+ if(i == 's')
+ location.reload()
+ });
- loading(0);
- }
- });
+ loading(0);
+ }
+ });
}
\ No newline at end of file
diff --git a/template/acp/js/system.js b/template/acp/js/system.js
index e6e90d3..fef9937 100644
--- a/template/acp/js/system.js
+++ b/template/acp/js/system.js
@@ -1,72 +1,72 @@
function system_load(go)
{
- if(go)
- loading(1);
+ if(go)
+ loading(1);
- $.getJSON(home+'system/go/',
- function(data)
- {
- $.each(data, function(i, val)
- {
- $('#'+i).html(val);
- });
+ $.getJSON(home+'system/go/',
+ function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ $('#'+i).html(val);
+ });
- loading(0);
+ loading(0);
- if(!go)
- setTimeout(function() {system_load(false)}, 3000);
- });
+ if(!go)
+ setTimeout(function() {system_load(false)}, 3000);
+ });
}
function system_restart(service)
{
- switch(service)
- {
- case 'apache2':
- type = 'apache2';
- break;
- case 'nginx':
- type = 'nginx';
- break;
- case 'mysql':
- type = 'mysql';
- break;
- case 'unit':
- type = 'локацию';
- break;
- }
+ switch(service)
+ {
+ case 'apache2':
+ type = 'apache2';
+ break;
+ case 'nginx':
+ type = 'nginx';
+ break;
+ case 'mysql':
+ type = 'mysql';
+ break;
+ case 'unit':
+ type = 'локацию';
+ break;
+ }
- bootbox.dialog('Внимание Вы уверены что хотите перезагруить '+type+' ',
- [{
- "label" : "Перезагрузить",
- callback: function(){system_restart_go(service)}
- },{
- "label" : "Отмена"
- }]);
+ bootbox.dialog('Внимание Вы уверены что хотите перезагруить '+type+' ',
+ [{
+ "label" : "Перезагрузить",
+ callback: function(){system_restart_go(service)}
+ },{
+ "label" : "Отмена"
+ }]);
- return false;
+ return false;
}
function system_restart_go(id, service)
{
- loading(1);
+ loading(1);
- $.getJSON(home+'system/service/'+service,
- function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- bootbox.dialog('Ошибка '+val,
- [{
- "label" : "Продолжить"
- }]
- );
+ $.getJSON(home+'system/service/'+service,
+ function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ bootbox.dialog('Ошибка '+val,
+ [{
+ "label" : "Продолжить"
+ }]
+ );
- if(i == 's')
- system_load(true);
- });
+ if(i == 's')
+ system_load(true);
+ });
- loading(0);
- });
+ loading(0);
+ });
}
\ No newline at end of file
diff --git a/template/acp/js/tarifs.js b/template/acp/js/tarifs.js
index 31a910b..90684f1 100644
--- a/template/acp/js/tarifs.js
+++ b/template/acp/js/tarifs.js
@@ -1,141 +1,141 @@
$('#tarif').ajaxForm({
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- bootbox.dialog('Ошибка '+val,
- [{
- "label" : "Продолжить"
- }]
- );
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ bootbox.dialog('Ошибка '+val,
+ [{
+ "label" : "Продолжить"
+ }]
+ );
- if(i == 's')
- location.href=home+'tarifs/id/'+val
- });
+ if(i == 's')
+ location.href=home+'tarifs/id/'+val
+ });
- loading(0)
- }
+ loading(0)
+ }
});
function tarifs_ports(ports)
{
- $('#ports').val(ports);
+ $('#ports').val(ports);
}
function tarifs_sort(sort)
{
- switch(sort)
- {
- case 'id':
- if(sort_id == 'asc')
- sort_id = 'desc';
- else
- sort_id = 'asc';
+ switch(sort)
+ {
+ case 'id':
+ if(sort_id == 'asc')
+ sort_id = 'desc';
+ else
+ sort_id = 'asc';
- sorting = sort_id;
+ sorting = sort_id;
- break;
+ break;
- case 'unit':
- sort_unit = sort_unit == 'asc' ? 'desc' : 'asc';
- sorting = sort_unit;
+ case 'unit':
+ sort_unit = sort_unit == 'asc' ? 'desc' : 'asc';
+ sorting = sort_unit;
- break;
+ break;
- case 'game':
- sort_game = sort_game == 'asc' ? 'desc' : 'asc';
- sorting = sort_game;
+ case 'game':
+ sort_game = sort_game == 'asc' ? 'desc' : 'asc';
+ sorting = sort_game;
- }
+ }
- location.href=home+'tarifs/sort/'+sort+'/sorting/'+sorting;
+ location.href=home+'tarifs/sort/'+sort+'/sorting/'+sorting;
}
function tarifs_search(go)
{
- if($('#search').val() == '')
- {
- $('#search_error').css('display', 'none');
+ if($('#search').val() == '')
+ {
+ $('#search_error').css('display', 'none');
- return;
- }
+ return;
+ }
- loading(1);
+ loading(1);
- if(go) go = '/go'; else go = '';
+ if(go) go = '/go'; else go = '';
- $.ajax({
- type: 'POST',
- url: home+'tarifs/subsection/search'+go,
- data: 'text='+$('#search').val(),
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- {
- if(val != '')
- {
- $('#search_error').css('display', 'inline-block');
- $('#search_error').html(val);
- }else
- $('#search_error').css('display', 'none');
- }
+ $.ajax({
+ type: 'POST',
+ url: home+'tarifs/subsection/search'+go,
+ data: 'text='+$('#search').val(),
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ {
+ if(val != '')
+ {
+ $('#search_error').css('display', 'inline-block');
+ $('#search_error').html(val);
+ }else
+ $('#search_error').css('display', 'none');
+ }
- if(i == 's')
- {
- $('#search_error').css('display', 'none');
- $('#search_result').html(val);
- }
- });
+ if(i == 's')
+ {
+ $('#search_error').css('display', 'none');
+ $('#search_result').html(val);
+ }
+ });
- loading(0);
- }
- });
+ loading(0);
+ }
+ });
}
function tarifs_delete(id)
{
- bootbox.dialog('Внимание Вы уверены, что хотите удалить тариф?',
- [{
- "label" : "Удалить",
- callback : function(){tarifs_delete_go(id)}
- },{
- "label" : "Отмена",
- }]
- );
+ bootbox.dialog('Внимание Вы уверены, что хотите удалить тариф?',
+ [{
+ "label" : "Удалить",
+ callback : function(){tarifs_delete_go(id)}
+ },{
+ "label" : "Отмена",
+ }]
+ );
- return false;
+ return false;
}
function tarifs_delete_go(id)
{
-
- loading(1);
+
+ loading(1);
- $.ajax({
- type: 'POST',
- url: home+'tarifs/section/delete/id/'+id,
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- bootbox.dialog('Ошибка '+val,
- [{
- "label" : "Продолжить"
- }]
- );
+ $.ajax({
+ type: 'POST',
+ url: home+'tarifs/section/delete/id/'+id,
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ bootbox.dialog('Ошибка '+val,
+ [{
+ "label" : "Продолжить"
+ }]
+ );
- if(i == 's')
- location.reload()
- });
+ if(i == 's')
+ location.reload()
+ });
- loading(0);
- }
- });
+ loading(0);
+ }
+ });
}
\ No newline at end of file
diff --git a/template/acp/js/units.js b/template/acp/js/units.js
index b704c5c..45ac792 100644
--- a/template/acp/js/units.js
+++ b/template/acp/js/units.js
@@ -1,142 +1,142 @@
$('#unit').ajaxForm({
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- bootbox.dialog('Ошибка '+val,
- [{
- "label" : "Продолжить"
- }]
- );
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ bootbox.dialog('Ошибка '+val,
+ [{
+ "label" : "Продолжить"
+ }]
+ );
- if(i == 's')
- location.href=home+'units/id/'+val;
- });
+ if(i == 's')
+ location.href=home+'units/id/'+val;
+ });
- loading(0)
- }
+ loading(0)
+ }
});
function units_load(id, go)
{
- if(go)
- loading(1);
+ if(go)
+ loading(1);
- $.getJSON(home+'units/section/loading/id/'+id,
- function(data)
- {
- $.each(data, function(i, val)
- {
- $('#'+i+'_'+id).html(val);
- });
+ $.getJSON(home+'units/section/loading/id/'+id,
+ function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ $('#'+i+'_'+id).html(val);
+ });
- loading(0);
+ loading(0);
- if(!go)
- setTimeout(function() {units_load(id, false)}, 3000);
- });
+ if(!go)
+ setTimeout(function() {units_load(id, false)}, 3000);
+ });
}
function units_restart(id, service)
{
- switch(service)
- {
- case 'apache2':
- type = 'apache2';
- break;
- case 'nginx':
- type = 'nginx';
- break;
- case 'mysql':
- type = 'mysql';
- break;
- case 'unit':
- type = 'локацию';
- break;
- }
+ switch(service)
+ {
+ case 'apache2':
+ type = 'apache2';
+ break;
+ case 'nginx':
+ type = 'nginx';
+ break;
+ case 'mysql':
+ type = 'mysql';
+ break;
+ case 'unit':
+ type = 'локацию';
+ break;
+ }
- bootbox.dialog('Внимание Вы уверены что хотите перезагруить '+type+' ',
- [{
- "label" : "Перезагрузить",
- callback: function(){units_restart_go(id, service)}
- },{
- "label" : "Отмена"
- }]);
+ bootbox.dialog('Внимание Вы уверены что хотите перезагруить '+type+' ',
+ [{
+ "label" : "Перезагрузить",
+ callback: function(){units_restart_go(id, service)}
+ },{
+ "label" : "Отмена"
+ }]);
- return false;
+ return false;
}
function units_restart_go(id, service)
{
- loading(1);
+ loading(1);
- $.getJSON(home+'units/section/loading/id/'+id+'/service/'+service,
- function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- bootbox.dialog('Ошибка '+val,
- [{
- "label" : "Продолжить"
- }]
- );
+ $.getJSON(home+'units/section/loading/id/'+id+'/service/'+service,
+ function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ bootbox.dialog('Ошибка '+val,
+ [{
+ "label" : "Продолжить"
+ }]
+ );
- if(i == 's')
- units_load(id, true);
- });
+ if(i == 's')
+ units_load(id, true);
+ });
- loading(0);
- });
+ loading(0);
+ });
}
function units_delete(id)
{
- bootbox.dialog('Внимание Вы уверены, что хотите удалить локацию?. '
- +'При "Удалить полностью" - удаляются все услуги и их логи, а также тарифы.',
- [{
- "label" : "Удалить",
- callback : function(){units_delete_go(id, false)}
- },{
- "label" : "Удалить полностью",
- callback : function(){units_delete_go(id, true)}
- },{
- "label" : "Отмена",
- }]
- );
+ bootbox.dialog('Внимание Вы уверены, что хотите удалить локацию?. '
+ +'При "Удалить полностью" - удаляются все услуги и их логи, а также тарифы.',
+ [{
+ "label" : "Удалить",
+ callback : function(){units_delete_go(id, false)}
+ },{
+ "label" : "Удалить полностью",
+ callback : function(){units_delete_go(id, true)}
+ },{
+ "label" : "Отмена",
+ }]
+ );
- return false;
+ return false;
}
function units_delete_go(id, all)
{
-
- loading(1);
+
+ loading(1);
- if(all) go = '/delete/all'; else go = '';
+ if(all) go = '/delete/all'; else go = '';
- $.ajax({
- type: 'POST',
- url: home+'units/section/delete/id/'+id+go,
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- bootbox.dialog('Ошибка '+val,
- [{
- "label" : "Продолжить"
- }]
- );
+ $.ajax({
+ type: 'POST',
+ url: home+'units/section/delete/id/'+id+go,
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ bootbox.dialog('Ошибка '+val,
+ [{
+ "label" : "Продолжить"
+ }]
+ );
- if(i == 's')
- location.reload()
- });
+ if(i == 's')
+ location.reload()
+ });
- loading(0);
- }
- });
+ loading(0);
+ }
+ });
}
\ No newline at end of file
diff --git a/template/acp/js/users.js b/template/acp/js/users.js
index c4b7d93..b30335f 100644
--- a/template/acp/js/users.js
+++ b/template/acp/js/users.js
@@ -1,179 +1,179 @@
$('#user').ajaxForm({
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- bootbox.dialog('Ошибка '+val,
- [{
- "label" : "Продолжить"
- }]
- );
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ bootbox.dialog('Ошибка '+val,
+ [{
+ "label" : "Продолжить"
+ }]
+ );
- if(i == 's')
- {
- bootbox.dialog('Внимание Внесенные изменения сохранены.',
- [{
- "label" : "Продолжить",
- callback : function(){location.reload()}
- }]
- );
- }
- });
+ if(i == 's')
+ {
+ bootbox.dialog('Внимание Внесенные изменения сохранены.',
+ [{
+ "label" : "Продолжить",
+ callback : function(){location.reload()}
+ }]
+ );
+ }
+ });
- loading(0)
- }
+ loading(0)
+ }
});
function users_sort(sort)
{
- switch(sort)
- {
- case 'id':
- if(sort_id == 'asc')
- sort_id = 'desc';
- else
- sort_id = 'asc';
+ switch(sort)
+ {
+ case 'id':
+ if(sort_id == 'asc')
+ sort_id = 'desc';
+ else
+ sort_id = 'asc';
- sorting = sort_id;
+ sorting = sort_id;
- break;
+ break;
- case 'balance':
- sort_balance = sort_balance == 'asc' ? 'desc' : 'asc';
- sorting = sort_balance;
+ case 'balance':
+ sort_balance = sort_balance == 'asc' ? 'desc' : 'asc';
+ sorting = sort_balance;
- break;
+ break;
- case 'group':
- sort_group = sort_group == 'asc' ? 'desc' : 'asc';
- sorting = sort_group;
+ case 'group':
+ sort_group = sort_group == 'asc' ? 'desc' : 'asc';
+ sorting = sort_group;
- }
+ }
- location.href=home+'users/sort/'+sort+'/sorting/'+sorting;
+ location.href=home+'users/sort/'+sort+'/sorting/'+sorting;
}
function users_search(go)
{
- if($('#search').val() == '')
- {
- $('#search_error').css('display', 'none');
+ if($('#search').val() == '')
+ {
+ $('#search_error').css('display', 'none');
- return;
- }
+ return;
+ }
- loading(1);
+ loading(1);
- if(go) go = '/go'; else go = '';
+ if(go) go = '/go'; else go = '';
- $.ajax({
- type: 'POST',
- url: home+'users/subsection/search'+go,
- data: 'text='+$('#search').val(),
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- {
- if(val != '')
- {
- $('#search_error').css('display', 'inline-block');
- $('#search_error').html(val);
- }else
- $('#search_error').css('display', 'none');
- }
+ $.ajax({
+ type: 'POST',
+ url: home+'users/subsection/search'+go,
+ data: 'text='+$('#search').val(),
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ {
+ if(val != '')
+ {
+ $('#search_error').css('display', 'inline-block');
+ $('#search_error').html(val);
+ }else
+ $('#search_error').css('display', 'none');
+ }
- if(i == 's')
- {
- $('#search_error').css('display', 'none');
- $('#search_result').html(val);
- }
- });
+ if(i == 's')
+ {
+ $('#search_error').css('display', 'none');
+ $('#search_result').html(val);
+ }
+ });
- loading(0);
- }
- });
+ loading(0);
+ }
+ });
}
function users_delete(id)
{
- bootbox.dialog('Внимание Вы уверены, что хотите удалить этого пользователя? '
- +'При "Удалить полностью" - удаляются все логи, услуги поступают в поток удаления.',
- [{
- "label" : "Удалить",
- callback : function(){users_delete_go(id, false)}
- },{
- "label" : "Удалить полностью",
- callback : function(){users_delete_go(id, true)}
- },{
- "label" : "Отмена",
- }]
- );
+ bootbox.dialog('Внимание Вы уверены, что хотите удалить этого пользователя? '
+ +'При "Удалить полностью" - удаляются все логи, услуги поступают в поток удаления.',
+ [{
+ "label" : "Удалить",
+ callback : function(){users_delete_go(id, false)}
+ },{
+ "label" : "Удалить полностью",
+ callback : function(){users_delete_go(id, true)}
+ },{
+ "label" : "Отмена",
+ }]
+ );
- return false;
+ return false;
}
function users_delete_go(id, all)
{
-
- loading(1);
+
+ loading(1);
- if(all) go = '/delete/all'; else go = '';
+ if(all) go = '/delete/all'; else go = '';
- $.ajax({
- type: 'POST',
- url: home+'users/section/delete/id/'+id+go,
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- bootbox.dialog('Ошибка '+val,
- [{
- "label" : "Продолжить"
- }]
- );
+ $.ajax({
+ type: 'POST',
+ url: home+'users/section/delete/id/'+id+go,
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ bootbox.dialog('Ошибка '+val,
+ [{
+ "label" : "Продолжить"
+ }]
+ );
- if(i == 's')
- location.reload()
- });
+ if(i == 's')
+ location.reload()
+ });
- loading(0);
- }
- });
+ loading(0);
+ }
+ });
}
function users_delete_signup(id)
{
- bootbox.dialog('Внимание Вы уверены, что хотите удалить подачу регистрации?',
- [{
- "label" : "Удалить",
- callback : function(){users_delete_signup_go(id)}
- },{
- "label" : "Отмена",
- }]
- );
+ bootbox.dialog('Внимание Вы уверены, что хотите удалить подачу регистрации?',
+ [{
+ "label" : "Удалить",
+ callback : function(){users_delete_signup_go(id)}
+ },{
+ "label" : "Отмена",
+ }]
+ );
- return false;
+ return false;
}
function users_delete_signup_go(id)
{
-
- loading(1);
+
+ loading(1);
- $.getJSON(home+'users/section/signup/delete/signup/id/'+id,
- function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 's')
- location.reload();
- });
- });
+ $.getJSON(home+'users/section/signup/delete/signup/id/'+id,
+ function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 's')
+ location.reload();
+ });
+ });
}
\ No newline at end of file
diff --git a/template/acp/js/web.js b/template/acp/js/web.js
index 01af6b7..3fbd08f 100644
--- a/template/acp/js/web.js
+++ b/template/acp/js/web.js
@@ -1,87 +1,87 @@
function web_search(go)
{
- if($('#search').val() == '')
- {
- $('#search_error').css('display', 'none');
+ if($('#search').val() == '')
+ {
+ $('#search_error').css('display', 'none');
- return;
- }
+ return;
+ }
- loading(1);
+ loading(1);
- if(go) go = '/go'; else go = '';
+ if(go) go = '/go'; else go = '';
- $.ajax({
- type: 'POST',
- url: home+'web/subsection/search'+go,
- data: 'text='+$('#search').val(),
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- {
- if(val != '')
- {
- $('#search_error').css('display', 'inline-block');
- $('#search_error').html(val);
- }else
- $('#search_error').css('display', 'none');
- }
+ $.ajax({
+ type: 'POST',
+ url: home+'web/subsection/search'+go,
+ data: 'text='+$('#search').val(),
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ {
+ if(val != '')
+ {
+ $('#search_error').css('display', 'inline-block');
+ $('#search_error').html(val);
+ }else
+ $('#search_error').css('display', 'none');
+ }
- if(i == 's')
- {
- $('#search_error').css('display', 'none');
- $('#search_result').html(val);
- }
- });
+ if(i == 's')
+ {
+ $('#search_error').css('display', 'none');
+ $('#search_result').html(val);
+ }
+ });
- loading(0);
- }
- });
+ loading(0);
+ }
+ });
}
function web_delete(server, type)
{
- bootbox.dialog('Внимание Вы уверены, что хотите удалить услугу?',
- [{
- "label" : "Удалить",
- callback : function(){web_delete_go(server, type)}
- },{
- "label" : "Отмена",
- }]
- );
+ bootbox.dialog('Внимание Вы уверены, что хотите удалить услугу?',
+ [{
+ "label" : "Удалить",
+ callback : function(){web_delete_go(server, type)}
+ },{
+ "label" : "Отмена",
+ }]
+ );
- return false;
+ return false;
}
function web_delete_go(server, type)
{
- loading(1);
+ loading(1);
- $.getJSON('/servers/id/'+server+'/section/web/subsection/'+type+'/action/delete/go', function(arr)
- {
- $.each(arr, function(i, val)
- {
- if(i == 'e')
- bootbox.dialog('Ошибка '+val,
- [{
- "label" : "Продолжить",
- }]
- );
+ $.getJSON('/servers/id/'+server+'/section/web/subsection/'+type+'/action/delete/go', function(arr)
+ {
+ $.each(arr, function(i, val)
+ {
+ if(i == 'e')
+ bootbox.dialog('Ошибка '+val,
+ [{
+ "label" : "Продолжить",
+ }]
+ );
- if(i == 'i')
- bootbox.dialog('Внимание '+val,
- [{
- "label" : "Продолжить",
- }]
- );
+ if(i == 'i')
+ bootbox.dialog('Внимание '+val,
+ [{
+ "label" : "Продолжить",
+ }]
+ );
- if(i == 's')
- location.reload();
- });
+ if(i == 's')
+ location.reload();
+ });
- loading(0)
- });
+ loading(0)
+ });
}
\ No newline at end of file
diff --git a/template/acp/js/wiki.js b/template/acp/js/wiki.js
index d88d571..7f1c1f4 100644
--- a/template/acp/js/wiki.js
+++ b/template/acp/js/wiki.js
@@ -1,162 +1,162 @@
$('#wiki').ajaxForm({
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- bootbox.dialog('Ошибка '+val,
- [{
- "label" : "Продолжить"
- }]
- );
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ bootbox.dialog('Ошибка '+val,
+ [{
+ "label" : "Продолжить"
+ }]
+ );
- if(i == 's')
- location.reload();
- });
+ if(i == 's')
+ location.reload();
+ });
- loading(0)
- }
+ loading(0)
+ }
});
function wiki_search(go)
{
- if($('#search').val() == '')
- {
- $('#search_error').css('display', 'none');
+ if($('#search').val() == '')
+ {
+ $('#search_error').css('display', 'none');
- return;
- }
+ return;
+ }
- loading(1);
+ loading(1);
- if(go) go = '/go'; else go = '';
+ if(go) go = '/go'; else go = '';
- $.ajax({
- type: 'POST',
- url: home+'wiki/subsection/search'+go,
- data: 'text='+$('#search').val(),
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- {
- if(val != '')
- {
- $('#search_error').css('display', 'inline-block');
- $('#search_error').html(val);
- }else
- $('#search_error').css('display', 'none');
- }
+ $.ajax({
+ type: 'POST',
+ url: home+'wiki/subsection/search'+go,
+ data: 'text='+$('#search').val(),
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ {
+ if(val != '')
+ {
+ $('#search_error').css('display', 'inline-block');
+ $('#search_error').html(val);
+ }else
+ $('#search_error').css('display', 'none');
+ }
- if(i == 's')
- {
- $('#search_error').css('display', 'none');
- $('#search_result').html(val);
- }
- });
+ if(i == 's')
+ {
+ $('#search_error').css('display', 'none');
+ $('#search_result').html(val);
+ }
+ });
- loading(0);
- }
- });
+ loading(0);
+ }
+ });
}
function wiki_delete(id)
{
- bootbox.dialog('Внимание Вы уверены, что хотите удалить ответ?',
- [{
- "label" : "Удалить",
- callback : function(){wiki_delete_go(id)}
- },{
- "label" : "Отмена",
- }]
- );
+ bootbox.dialog('Внимание Вы уверены, что хотите удалить ответ?',
+ [{
+ "label" : "Удалить",
+ callback : function(){wiki_delete_go(id)}
+ },{
+ "label" : "Отмена",
+ }]
+ );
- return false;
+ return false;
}
function wiki_delete_go(id)
{
- loading(1);
+ loading(1);
- $.ajax({
- type: 'POST',
- url: home+'wiki/section/delete/id/'+id,
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- bootbox.dialog('Ошибка '+val,
- [{
- "label" : "Продолжить"
- }]
- );
+ $.ajax({
+ type: 'POST',
+ url: home+'wiki/section/delete/id/'+id,
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ bootbox.dialog('Ошибка '+val,
+ [{
+ "label" : "Продолжить"
+ }]
+ );
- if(i == 's')
- location.reload()
- });
+ if(i == 's')
+ location.reload()
+ });
- loading(0);
- }
- });
+ loading(0);
+ }
+ });
}
function wiki_cat_delete(id)
{
- bootbox.dialog('Внимание Вы уверены, что хотите удалить категорию?',
- [{
- "label" : "Удалить",
- callback : function(){wiki_cat_delete_go(id)}
- },{
- "label" : "Отмена",
- }]
- );
+ bootbox.dialog('Внимание Вы уверены, что хотите удалить категорию?',
+ [{
+ "label" : "Удалить",
+ callback : function(){wiki_cat_delete_go(id)}
+ },{
+ "label" : "Отмена",
+ }]
+ );
- return false;
+ return false;
}
function wiki_cat_delete_go(id)
{
- loading(1);
+ loading(1);
- $.ajax({
- type: 'POST',
- url: home+'wiki/section/delete/type/cat/id/'+id,
- dataType: 'json',
- success: function(data)
- {
- $.each(data, function(i, val)
- {
- if(i == 'e')
- bootbox.dialog('Ошибка '+val,
- [{
- "label" : "Продолжить"
- }]
- );
+ $.ajax({
+ type: 'POST',
+ url: home+'wiki/section/delete/type/cat/id/'+id,
+ dataType: 'json',
+ success: function(data)
+ {
+ $.each(data, function(i, val)
+ {
+ if(i == 'e')
+ bootbox.dialog('Ошибка '+val,
+ [{
+ "label" : "Продолжить"
+ }]
+ );
- if(i == 's')
- location.reload()
- });
+ if(i == 's')
+ location.reload()
+ });
- loading(0);
- }
- });
+ loading(0);
+ }
+ });
}
function bbcode(bbbegin, bbend)
{
- form = document.getElementById('text');
- begin = form.value.substr(0, form.selectionStart);
- end = form.value.substr(form.selectionEnd);
- sel = form.value.substr(form.selectionStart, form.selectionEnd-form.selectionStart);
- var text = form.firstChild;
- form.value = begin+bbbegin+sel+bbend+end;
- selPos = bbbegin.length+begin.length+sel.length+bbend.length;
- form.setSelectionRange(begin.length, selPos);
+ form = document.getElementById('text');
+ begin = form.value.substr(0, form.selectionStart);
+ end = form.value.substr(form.selectionEnd);
+ sel = form.value.substr(form.selectionStart, form.selectionEnd-form.selectionStart);
+ var text = form.firstChild;
+ form.value = begin+bbbegin+sel+bbend+end;
+ selPos = bbbegin.length+begin.length+sel.length+bbend.length;
+ form.setSelectionRange(begin.length, selPos);
- return false;
+ return false;
}
\ No newline at end of file
diff --git a/template/acp/main.html b/template/acp/main.html
index affcb97..68f7272 100644
--- a/template/acp/main.html
+++ b/template/acp/main.html
@@ -1,14 +1,14 @@
-
-
- Пользователей в базе:
- [users] шт.
-
-
- Серверов в базе:
- [servers] шт.
-
-
+
+
+ Пользователей в базе:
+ [users] шт.
+
+
+ Серверов в базе:
+ [servers] шт.
+
+
@@ -16,9 +16,9 @@
Заявки на вывод денежных средств
-
- [cashback]
-
+
+ [cashback]
+
@@ -26,55 +26,55 @@
Количество слот на серверах
-
-
- Игра
- Серверов
- Слот
-
-
-
-
- Counter-Strike: 1.6
- [cs] шт.
- [slots_cs] шт.
-
-
- Counter-Strike: Source v34
- [cssold] шт.
- [slots_cssold] шт.
-
-
- Counter-Strike: Source
- [css] шт.
- [slots_css] шт.
-
-
- Counter-Strike: Global Offensive
- [csgo] шт.
- [slots_csgo] шт.
-
-
- GTA: SA-MP
- [samp] шт.
- [slots_samp] шт.
-
-
- GTA: CR-MP
- [crmp] шт.
- [slots_crmp] шт.
-
-
- GTA: MTA
- [mta] шт.
- [slots_mta] шт.
-
-
- Minecraft
- [mc] шт.
- [slots_mc] шт.
-
-
+
+
+ Игра
+ Серверов
+ Слот
+
+
+
+
+ Counter-Strike: 1.6
+ [cs] шт.
+ [slots_cs] шт.
+
+
+ Counter-Strike: Source v34
+ [cssold] шт.
+ [slots_cssold] шт.
+
+
+ Counter-Strike: Source
+ [css] шт.
+ [slots_css] шт.
+
+
+ Counter-Strike: Global Offensive
+ [csgo] шт.
+ [slots_csgo] шт.
+
+
+ GTA: SA-MP
+ [samp] шт.
+ [slots_samp] шт.
+
+
+ GTA: CR-MP
+ [crmp] шт.
+ [slots_crmp] шт.
+
+
+ GTA: MTA
+ [mta] шт.
+ [slots_mta] шт.
+
+
+ Minecraft
+ [mc] шт.
+ [slots_mc] шт.
+
+
@@ -82,18 +82,18 @@
Состояние персонала
-
-
-
- Имя
- Группа
- Адрес
- Браузер
- Состояние
- Активность
-
-
-
- [staff]
-
+
+
+
+ Имя
+ Группа
+ Адрес
+ Браузер
+ Состояние
+ Активность
+
+
+
+ [staff]
+
diff --git a/template/acp/pages.html b/template/acp/pages.html
index 486c2a8..7dd56a2 100644
--- a/template/acp/pages.html
+++ b/template/acp/pages.html
@@ -1,5 +1,5 @@
\ No newline at end of file
diff --git a/template/acp/sections/addons/addcat.html b/template/acp/sections/addons/addcat.html
index b7d5f95..f003e49 100644
--- a/template/acp/sections/addons/addcat.html
+++ b/template/acp/sections/addons/addcat.html
@@ -1,54 +1,54 @@
\ No newline at end of file
diff --git a/template/acp/sections/addons/addpl.html b/template/acp/sections/addons/addpl.html
index 2a166ae..986acf2 100644
--- a/template/acp/sections/addons/addpl.html
+++ b/template/acp/sections/addons/addpl.html
@@ -1,179 +1,179 @@
\ No newline at end of file
diff --git a/template/acp/sections/addons/cats.html b/template/acp/sections/addons/cats.html
index 9758f97..25c7026 100644
--- a/template/acp/sections/addons/cats.html
+++ b/template/acp/sections/addons/cats.html
@@ -1,17 +1,17 @@
-
-
- #
- Название
- Игра
- Плагинов
- Положение
-
-
-
-
- [list]
-
+
+
+ #
+ Название
+ Игра
+ Плагинов
+ Положение
+
+
+
+
+ [list]
+
\ No newline at end of file
diff --git a/template/acp/sections/addons/index.html b/template/acp/sections/addons/index.html
index 405150c..d109e04 100644
--- a/template/acp/sections/addons/index.html
+++ b/template/acp/sections/addons/index.html
@@ -1,6 +1,6 @@
-
- Поиск
+
+ Поиск
@@ -8,31 +8,31 @@
-
-
-
- Название
- Категория
- Статус
- Игра
-
-
-
-
- [list]
-
+
+
+
+ Название
+ Категория
+ Статус
+ Игра
+
+
+
+
+ [list]
+
[pages]
\ No newline at end of file
diff --git a/template/acp/sections/addons/menu.html b/template/acp/sections/addons/menu.html
index 29fa6c7..258db8d 100644
--- a/template/acp/sections/addons/menu.html
+++ b/template/acp/sections/addons/menu.html
@@ -1,9 +1,9 @@
Управление
\ No newline at end of file
diff --git a/template/acp/sections/addons/plugin.html b/template/acp/sections/addons/plugin.html
index e92e0eb..fa61ab7 100644
--- a/template/acp/sections/addons/plugin.html
+++ b/template/acp/sections/addons/plugin.html
@@ -1,130 +1,130 @@
- Основные настройки
+ Основные настройки
-
+
-
+
- Редактируемые файлы
+ Редактируемые файлы
-
+
-
+
- Удаление текста из файлов
+ Удаление текста из файлов
-
+
-
+
- Добавление текста в файлы после установки плагина
+ Добавление текста в файлы после установки плагина
-
+
-
+
- Добавление текста в файлы после удаления плагина
+ Добавление текста в файлы после удаления плагина
-
+
-
+
- Удаление файлов после установки плагина
+ Удаление файлов после установки плагина
-
+
@@ -132,14 +132,14 @@
Новые версии плагина
\ No newline at end of file
diff --git a/template/acp/sections/addons/update.html b/template/acp/sections/addons/update.html
index c95b270..f85524b 100644
--- a/template/acp/sections/addons/update.html
+++ b/template/acp/sections/addons/update.html
@@ -3,128 +3,128 @@
- Основные настройки
+ Основные настройки
-
+
-
+
- Редактируемые файлы
+ Редактируемые файлы
-
+
-
+
- Удаление текста из файлов
+ Удаление текста из файлов
-
+
-
+
- Добавление текста в файлы после установки плагина
+ Добавление текста в файлы после установки плагина
-
+
-
+
- Добавление текста в файлы после удаления плагина
+ Добавление текста в файлы после удаления плагина
-
+
-
+
- Удаление файлов после установки плагина
+ Удаление файлов после установки плагина
-
+
\ No newline at end of file
diff --git a/template/acp/sections/addons/updmp.html b/template/acp/sections/addons/updmp.html
index 5ed40f7..bf71600 100644
--- a/template/acp/sections/addons/updmp.html
+++ b/template/acp/sections/addons/updmp.html
@@ -1,30 +1,30 @@
@@ -32,13 +32,13 @@
Список карт выбранной локации и игры
\ No newline at end of file
diff --git a/template/acp/sections/boost/index.html b/template/acp/sections/boost/index.html
index f7b2754..d02ab48 100644
--- a/template/acp/sections/boost/index.html
+++ b/template/acp/sections/boost/index.html
@@ -1,16 +1,16 @@
Статистика за все время
-
-
- Количесто купленных кругов:
- [all_num] шт.
-
-
- Затраченная сумма:
- [all_sum] [cur].
-
-
+
+
+ Количесто купленных кругов:
+ [all_num] шт.
+
+
+ Затраченная сумма:
+ [all_sum] [cur].
+
+
@@ -18,16 +18,16 @@
Статистика за предыдущий месяц [month_old]
-
-
- Количесто купленных кругов:
- [old_num] шт.
-
-
- Затраченная сумма:
- [old_sum] [cur].
-
-
+
+
+ Количесто купленных кругов:
+ [old_num] шт.
+
+
+ Затраченная сумма:
+ [old_sum] [cur].
+
+
@@ -35,23 +35,23 @@
Статистика за текущий месяц [month_now]
-
-
- Количесто купленных кругов:
- [now_num] шт.
-
-
- Затраченная сумма:
- [now_sum] [cur].
-
-
+
+
+ Количесто купленных кругов:
+ [now_num] шт.
+
+
+ Затраченная сумма:
+ [now_sum] [cur].
+
+
-
- Поиск
+
+ Поиск
@@ -59,26 +59,26 @@
-
-
-
- Операция
- Пользователь
- Сервер
- Дата
-
-
-
- [list]
-
+
+
+
+ Операция
+ Пользователь
+ Сервер
+ Дата
+
+
+
+ [list]
+
[pages]
\ No newline at end of file
diff --git a/template/acp/sections/boost/menu.html b/template/acp/sections/boost/menu.html
index 0342045..db34e76 100644
--- a/template/acp/sections/boost/menu.html
+++ b/template/acp/sections/boost/menu.html
@@ -1,6 +1,6 @@
Управление
\ No newline at end of file
diff --git a/template/acp/sections/control/index.html b/template/acp/sections/control/index.html
index 8bd5d22..3dcd888 100644
--- a/template/acp/sections/control/index.html
+++ b/template/acp/sections/control/index.html
@@ -1,6 +1,6 @@
-
- Поиск
+
+ Поиск
@@ -8,28 +8,28 @@
-
-
- Номер / Владелец
- Адрес / Статус
- Добавлен / Аренда
- Лимит / Цена
-
-
-
-
- [list]
-
+
+
+ Номер / Владелец
+ Адрес / Статус
+ Добавлен / Аренда
+ Лимит / Цена
+
+
+
+
+ [list]
+
[pages]
\ No newline at end of file
diff --git a/template/acp/sections/control/menu.html b/template/acp/sections/control/menu.html
index 314695b..7728adc 100644
--- a/template/acp/sections/control/menu.html
+++ b/template/acp/sections/control/menu.html
@@ -1,6 +1,6 @@
Управление
\ No newline at end of file
diff --git a/template/acp/sections/control/server.html b/template/acp/sections/control/server.html
index 003d734..c2e2b69 100644
--- a/template/acp/sections/control/server.html
+++ b/template/acp/sections/control/server.html
@@ -1,46 +1,46 @@
-
+
@@ -49,10 +49,10 @@
\ No newline at end of file
diff --git a/template/acp/sections/hosting/menu.html b/template/acp/sections/hosting/menu.html
index 55d67be..316f99d 100644
--- a/template/acp/sections/hosting/menu.html
+++ b/template/acp/sections/hosting/menu.html
@@ -1,6 +1,6 @@
Управление
\ No newline at end of file
diff --git a/template/acp/sections/jobs/add.html b/template/acp/sections/jobs/add.html
index ea12794..0f6968d 100644
--- a/template/acp/sections/jobs/add.html
+++ b/template/acp/sections/jobs/add.html
@@ -1,58 +1,58 @@
-
+
\ No newline at end of file
diff --git a/template/acp/sections/jobs/edit.html b/template/acp/sections/jobs/edit.html
index 5eebad8..7af983d 100644
--- a/template/acp/sections/jobs/edit.html
+++ b/template/acp/sections/jobs/edit.html
@@ -1,54 +1,54 @@
-
+
\ No newline at end of file
diff --git a/template/acp/sections/jobs/index.html b/template/acp/sections/jobs/index.html
index 2a05bb2..a45eb8d 100644
--- a/template/acp/sections/jobs/index.html
+++ b/template/acp/sections/jobs/index.html
@@ -1,38 +1,38 @@
-
-
- ID
- Название
- Должность
- Описание
- Статус
- Создан
-
-
-
-
-
- [list]
-
+
+
+ ID
+ Название
+ Должность
+ Описание
+ Статус
+ Создан
+
+
+
+
+
+ [list]
+
\ No newline at end of file
diff --git a/template/acp/sections/jobs/menu.html b/template/acp/sections/jobs/menu.html
index 16901fd..b1aaffb 100644
--- a/template/acp/sections/jobs/menu.html
+++ b/template/acp/sections/jobs/menu.html
@@ -1,7 +1,7 @@
Управление
\ No newline at end of file
diff --git a/template/acp/sections/jobs/request.html b/template/acp/sections/jobs/request.html
index ee7deb7..bc63adf 100644
--- a/template/acp/sections/jobs/request.html
+++ b/template/acp/sections/jobs/request.html
@@ -1,38 +1,38 @@
-
-
- ID
- Пользователь
- Ответ
- Контакты
- Вакансия
- Создан
-
-
-
-
-
- [list]
-
+
+
+ ID
+ Пользователь
+ Ответ
+ Контакты
+ Вакансия
+ Создан
+
+
+
+
+
+ [list]
+
\ No newline at end of file
diff --git a/template/acp/sections/jobs/request_edit.html b/template/acp/sections/jobs/request_edit.html
index 9e61e6f..98162b2 100644
--- a/template/acp/sections/jobs/request_edit.html
+++ b/template/acp/sections/jobs/request_edit.html
@@ -1,52 +1,52 @@
-
+
\ No newline at end of file
diff --git a/template/acp/sections/letter/index.html b/template/acp/sections/letter/index.html
index 9e82d69..941b100 100644
--- a/template/acp/sections/letter/index.html
+++ b/template/acp/sections/letter/index.html
@@ -1,39 +1,39 @@
-
+
-
+
-
-
-
-
- Пользователь
- Почта
- Баланс
- Активность
-
-
-
- [list]
-
-
+
+
+
+
+ Пользователь
+ Почта
+ Баланс
+ Активность
+
+
+
+ [list]
+
+
\ No newline at end of file
diff --git a/template/acp/sections/letter/menu.html b/template/acp/sections/letter/menu.html
index 023bfa3..7d91fcb 100644
--- a/template/acp/sections/letter/menu.html
+++ b/template/acp/sections/letter/menu.html
@@ -1,5 +1,5 @@
Управление
\ No newline at end of file
diff --git a/template/acp/sections/logs/index.html b/template/acp/sections/logs/index.html
index dc0d913..a5dfe80 100644
--- a/template/acp/sections/logs/index.html
+++ b/template/acp/sections/logs/index.html
@@ -1,6 +1,6 @@
-
- Поиск
+
+ Поиск
@@ -8,26 +8,26 @@
-
-
-
- Операция
- Пользователь
- Сервер
- Дата
-
-
-
- [list]
-
+
+
+
+ Операция
+ Пользователь
+ Сервер
+ Дата
+
+
+
+ [list]
+
[pages]
\ No newline at end of file
diff --git a/template/acp/sections/logs/logs.html b/template/acp/sections/logs/logs.html
index e92722f..c8414be 100644
--- a/template/acp/sections/logs/logs.html
+++ b/template/acp/sections/logs/logs.html
@@ -1,6 +1,6 @@
-
- Поиск
+
+ Поиск
@@ -8,26 +8,26 @@
-
-
-
- Операция
- Пользователь
- Сумма
- Дата
-
-
-
- [list]
-
+
+
+
+ Операция
+ Пользователь
+ Сумма
+ Дата
+
+
+
+ [list]
+
[pages]
\ No newline at end of file
diff --git a/template/acp/sections/logs/menu.html b/template/acp/sections/logs/menu.html
index 82ea3a9..cfed038 100644
--- a/template/acp/sections/logs/menu.html
+++ b/template/acp/sections/logs/menu.html
@@ -1,10 +1,10 @@
Управление
\ No newline at end of file
diff --git a/template/acp/sections/news/add.html b/template/acp/sections/news/add.html
index 762e292..4854d38 100644
--- a/template/acp/sections/news/add.html
+++ b/template/acp/sections/news/add.html
@@ -1,43 +1,43 @@
-
+
\ No newline at end of file
diff --git a/template/acp/sections/news/index.html b/template/acp/sections/news/index.html
index e89602f..324d114 100644
--- a/template/acp/sections/news/index.html
+++ b/template/acp/sections/news/index.html
@@ -1,6 +1,6 @@
-
- Поиск
+
+ Поиск
@@ -8,27 +8,27 @@
-
-
-
- Заголовок
- Теги
- Просмотров
- Дата
-
-
-
-
- [list]
-
+
+
+
+ Заголовок
+ Теги
+ Просмотров
+ Дата
+
+
+
+
+ [list]
+
[pages]
\ No newline at end of file
diff --git a/template/acp/sections/news/menu.html b/template/acp/sections/news/menu.html
index d902d0f..75abab0 100644
--- a/template/acp/sections/news/menu.html
+++ b/template/acp/sections/news/menu.html
@@ -1,6 +1,6 @@
Управление
\ No newline at end of file
diff --git a/template/acp/sections/news/news.html b/template/acp/sections/news/news.html
index 9df23ad..dab39b4 100644
--- a/template/acp/sections/news/news.html
+++ b/template/acp/sections/news/news.html
@@ -1,43 +1,43 @@
-
+
\ No newline at end of file
diff --git a/template/acp/sections/notice/add.html b/template/acp/sections/notice/add.html
index d334457..07d362a 100644
--- a/template/acp/sections/notice/add.html
+++ b/template/acp/sections/notice/add.html
@@ -1,44 +1,44 @@
-
+
@@ -47,10 +47,10 @@
\ No newline at end of file
diff --git a/template/acp/sections/notice/index.html b/template/acp/sections/notice/index.html
index 50505c6..46e2e7d 100644
--- a/template/acp/sections/notice/index.html
+++ b/template/acp/sections/notice/index.html
@@ -1,6 +1,6 @@
-
- Поиск
+
+ Поиск
@@ -8,25 +8,25 @@
-
-
-
- Уведомления
-
-
-
-
-
- [list]
-
+
+
+
+ Уведомления
+
+
+
+
+
+ [list]
+
[pages]
\ No newline at end of file
diff --git a/template/acp/sections/notice/menu.html b/template/acp/sections/notice/menu.html
index 588f5e0..7e3c340 100644
--- a/template/acp/sections/notice/menu.html
+++ b/template/acp/sections/notice/menu.html
@@ -1,7 +1,7 @@
Управление
\ No newline at end of file
diff --git a/template/acp/sections/notice/notice.html b/template/acp/sections/notice/notice.html
index ee964fd..f7ecae1 100644
--- a/template/acp/sections/notice/notice.html
+++ b/template/acp/sections/notice/notice.html
@@ -1,34 +1,34 @@
-
@@ -37,10 +37,10 @@
\ No newline at end of file
diff --git a/template/acp/sections/pages/add.html b/template/acp/sections/pages/add.html
index 8a51f0f..02065a5 100644
--- a/template/acp/sections/pages/add.html
+++ b/template/acp/sections/pages/add.html
@@ -1,20 +1,20 @@
-
+
\ No newline at end of file
diff --git a/template/acp/sections/pages/index.html b/template/acp/sections/pages/index.html
index d5856c9..ebb1a8f 100644
--- a/template/acp/sections/pages/index.html
+++ b/template/acp/sections/pages/index.html
@@ -1,16 +1,16 @@
-
-
-
- Название
- Файл
-
-
-
-
-
- [list]
-
+
+
+
+ Название
+ Файл
+
+
+
+
+
+ [list]
+
[pages]
diff --git a/template/acp/sections/pages/menu.html b/template/acp/sections/pages/menu.html
index 7a7ebf1..dc6c433 100644
--- a/template/acp/sections/pages/menu.html
+++ b/template/acp/sections/pages/menu.html
@@ -1,6 +1,6 @@
Управление
\ No newline at end of file
diff --git a/template/acp/sections/pages/page.html b/template/acp/sections/pages/page.html
index 8f46188..3b1bdbe 100644
--- a/template/acp/sections/pages/page.html
+++ b/template/acp/sections/pages/page.html
@@ -1,20 +1,20 @@
-
+
\ No newline at end of file
diff --git a/template/acp/sections/promo/add.html b/template/acp/sections/promo/add.html
index a262988..0382229 100644
--- a/template/acp/sections/promo/add.html
+++ b/template/acp/sections/promo/add.html
@@ -1,51 +1,51 @@
-
+
@@ -53,18 +53,18 @@
Информация по условиям
-
-
-
- FPS: "fps":"1000" или "fps":"500:1000"
- RAM: "ram":"50" или "fps":"50:80"
- TickRate: "tickrate":"66" или "fps":"64:128"
- Период: "time":"30" или "time":"30:90"
- Слоты: "slots":"32" или "slots":"20:32" или "slots":"10-20"
- Указывать несколько условий через запятые: "fps":"500:1000","slots":"10-32","time":"30"
-
-
-
+
+
+
+ FPS: "fps":"1000" или "fps":"500:1000"
+ RAM: "ram":"50" или "fps":"50:80"
+ TickRate: "tickrate":"66" или "fps":"64:128"
+ Период: "time":"30" или "time":"30:90"
+ Слоты: "slots":"32" или "slots":"20:32" или "slots":"10-20"
+ Указывать несколько условий через запятые: "fps":"500:1000","slots":"10-32","time":"30"
+
+
+
@@ -73,10 +73,10 @@
\ No newline at end of file
diff --git a/template/acp/sections/promo/index.html b/template/acp/sections/promo/index.html
index aca9fdb..a22b37c 100644
--- a/template/acp/sections/promo/index.html
+++ b/template/acp/sections/promo/index.html
@@ -1,6 +1,6 @@
-
- Поиск
+
+ Поиск
@@ -8,30 +8,30 @@
-
-
-
- Промо-код
- Значение
- Тариф
- Акция
- Тип
- Лимит
- Окончание
-
-
-
-
- [list]
-
+
+
+
+ Промо-код
+ Значение
+ Тариф
+ Акция
+ Тип
+ Лимит
+ Окончание
+
+
+
+
+ [list]
+
[pages]
\ No newline at end of file
diff --git a/template/acp/sections/promo/menu.html b/template/acp/sections/promo/menu.html
index 0cc54df..0a95c45 100644
--- a/template/acp/sections/promo/menu.html
+++ b/template/acp/sections/promo/menu.html
@@ -1,8 +1,8 @@
Управление
\ No newline at end of file
diff --git a/template/acp/sections/promo/promo.html b/template/acp/sections/promo/promo.html
index abae1f7..691a7b6 100644
--- a/template/acp/sections/promo/promo.html
+++ b/template/acp/sections/promo/promo.html
@@ -1,41 +1,41 @@
-
+
@@ -43,18 +43,18 @@
Информация по условиям
-
-
-
- FPS: "fps":"1000" или "fps":"500:1000"
- RAM: "ram":"50" или "fps":"50:80"
- TickRate: "tickrate":"66" или "fps":"64:128"
- Период: "time":"30" или "time":"30:90"
- Слоты: "slots":"32" или "slots":"20:32" или "slots":"10-20"
- Указывать несколько условий через запятые: "fps":"500:1000","slots":"10-32","time":"30"
-
-
-
+
+
+
+ FPS: "fps":"1000" или "fps":"500:1000"
+ RAM: "ram":"50" или "fps":"50:80"
+ TickRate: "tickrate":"66" или "fps":"64:128"
+ Период: "time":"30" или "time":"30:90"
+ Слоты: "slots":"32" или "slots":"20:32" или "slots":"10-20"
+ Указывать несколько условий через запятые: "fps":"500:1000","slots":"10-32","time":"30"
+
+
+
@@ -63,10 +63,10 @@
\ No newline at end of file
diff --git a/template/acp/sections/promo/stats.html b/template/acp/sections/promo/stats.html
index 612d92a..35a72f7 100644
--- a/template/acp/sections/promo/stats.html
+++ b/template/acp/sections/promo/stats.html
@@ -1,17 +1,17 @@
-
-
-
- Акция
- Клиент
- Операция
- Дата
-
-
-
-
- [list]
-
+
+
+
+ Акция
+ Клиент
+ Операция
+ Дата
+
+
+
+
+ [list]
+
\ No newline at end of file
diff --git a/template/acp/sections/servers/index.html b/template/acp/sections/servers/index.html
index 05f5793..377f7dd 100644
--- a/template/acp/sections/servers/index.html
+++ b/template/acp/sections/servers/index.html
@@ -1,6 +1,6 @@
-
- Поиск
+
+ Поиск
@@ -8,29 +8,29 @@
-
-
- Номер / Владелец
- Название / Адрес
- Локация / Тариф
- Слоты / Статус
- Игра / Аренда
-
-
-
-
- [list]
-
+
+
+ Номер / Владелец
+ Название / Адрес
+ Локация / Тариф
+ Слоты / Статус
+ Игра / Аренда
+
+
+
+
+ [list]
+
[pages]
\ No newline at end of file
diff --git a/template/acp/sections/servers/menu.html b/template/acp/sections/servers/menu.html
index 15b8524..9b62977 100644
--- a/template/acp/sections/servers/menu.html
+++ b/template/acp/sections/servers/menu.html
@@ -1,13 +1,13 @@
Управление
\ No newline at end of file
diff --git a/template/acp/sections/servers/overdue.html b/template/acp/sections/servers/overdue.html
index c95c96d..783cde0 100644
--- a/template/acp/sections/servers/overdue.html
+++ b/template/acp/sections/servers/overdue.html
@@ -1,14 +1,14 @@
-
-
- Номер / Владелец
- Название / Адрес
- Локация / Тариф
- Слоты / Статус
- Игра / Удаление
-
-
-
- [list]
-
+
+
+ Номер / Владелец
+ Название / Адрес
+ Локация / Тариф
+ Слоты / Статус
+ Игра / Удаление
+
+
+
+ [list]
+
\ No newline at end of file
diff --git a/template/acp/sections/servers/server.html b/template/acp/sections/servers/server.html
index 6898746..e4ef699 100644
--- a/template/acp/sections/servers/server.html
+++ b/template/acp/sections/servers/server.html
@@ -1,91 +1,91 @@
-
+
@@ -93,10 +93,10 @@
Текущий тарифный план: [tarif]