<?php

# Php include;
defined('_CONSTANT_') or die('Error. You don`t have permision to access.');

# Settings php;
#error_reporting(-1) ; 
ini_set('php_flag display_errors', 'On');     # Show errors;
ini_set('display_errors', 'On');              # Show errors;
ini_set('register_globals', FALSE);           # Register globals; - recomend FALSE;

# Site constants;
define('inc', $_SERVER['DOCUMENT_ROOT'].'/'); # Home directory;
define("HOME", "");                           # Domain;

# Connect to database;
/*
define('DBHOST', 'localhost');                # Host;
define('DBPORT', '3306');                     # Port;
define('DBNAME', '');                # Name;
define('DBUSER', '');                # User;
define('DBPASS', '');              # Password;
require_once ''.inc.'/class/Pdo.php';         # Require pdo class;
*/

define('DBHOST', 'localhost');                # Host;
define('DBPORT', '3306');                     # Port;
define('DBNAME', 'wapgame');                # Name;
define('DBUSER', 'root');                # User;
define('DBPASS', '');              # Password;
require_once ''.inc.'/class/Pdo.php';         # Require pdo class;

# Database tables;
define("USERS", "`users`");                   # All users;
define("SETTINGS", "`settings`");             # Site settings;
define("MAIL", "`mail`");                     # User mail;
define("MAIL_KONT", "`mail_kont`");           # User mail contacts;
define("CHAT", "`chat`");                     # Global chat;
define("BAN", "`ban`");                       # Baned users;
define("BLACKLIST", "`blacklist`");           # Blacklist ip;
define("LOCATION", "`location`");             # Fight locations;
define("NPC", "`npc`");                       # Fight npc;
define("ADMIN_LOG", "`admin_log`");           # Admin log;
define("NEWS", "`news`");                     # News;
define("USER_EXP", "`user_exp`");             # User exp;
define("CLANS", "`clans`");                   # Clans;
define("CLANS_JOURNAL", "`clans_journal`");   # Clans journal;
define("SMILES", "`smiles`");                 # Smiles;
define("DUNGEONS", "`dungeons`");             # Fight dungeons;
define("PARTY", "`party`");                   # Fight dungeons party;
define("DUNGEON_FIGHT", "`dungeon_fight`");   # Fight dungeons list;
define("DUNGEON_NPC", "`dungeon_npc`");       # Fight dungeons npc;
define("DUNGEON_LOG", "`dungeon_log`");       # Fight dungeons log;
define("JOURNAL", "`journal`");                       # Users journal;
define("USERITEM", "`user_item`");                    # User items;
define("ALL_ITEMS", "`all_items`");                   # All items list;
define("FAIR", "`fair`");                             # Fair;
define("CAMPING", "`camping`");                       # Camping;
define("FORUMS", "`forums`");                         # Forums;
define("FORUM_THEME", "`forums_theme`");              # Forums theme;
define("FORUM_POST", "`forums_post`");                # Forums post; 
define("ARENA", "`arena`");                           # Arena;
define("ARENA_BOT", "`arena_bot`");                   # Arena bot;
define("BELT", "`belt`");                             # Potion belt;
define("TASK_NPC", "`task_npc`");                     # Task npc;
define("LOG", "`log`");                               # Log;
define("EVENT_HORSEMAN", "`event_horseman`");         # Horseman;
define("EVENT_HORSEMAN_LOG", "`event_horseman_log`"); # Horseman log;
define("USER_BONUS", "`user_bonus`");                 # User bonus;

# Css div;
define("DIV_BLOCK", '<div class="block">');
define("DIV_ERROR", '<div class="error">');
define("DIV_SUCCESS", '<div class="success">'); 
define("DIV_USPANEL", '<div class="user-panel">'); 
define("DIV_TITLE", '<div class="title">'); 
define("DIV_CONTENT", '<div class="content">'); 
define("DIV_LINK_TOUCH", '<div class="link-touch">');
define("CLOSE_DIV", '</div>');

# Site settings;
$settings = DB::$dbs->queryFetch("SELECT * FROM ".SETTINGS." WHERE `id` = ?", [1]);

# Functions;
# CheckAuth();
# ! Check user session. Logged users;
function checkAuth () 
{
    if (empty($_SESSION['id'])) 
    {
        header("Location: ".HOME."/");
    } 
    return FALSE;
}

# CheckIn();
# ! Check user session. Don`t logged users; 
function checkIn () 
{
    if (!empty($_SESSION['id'])) 
    {
        header("Location: ".HOME."/game/");
    } 
    return FALSE;
} 

# Head();
# ! Site head function;
function head ($title = NULL, $whereUser = NULL) 
{ 
    global $settings, $user, $Filter, $User;
    
    # Title;
    if (empty($title) || $title == NULL) 
    {
        $title = $settings['site_name'];
    } 
    
    $designUser = (!empty($user) ? $Filter->output($user['design']) : 'touch-blue'); // Design: default - touch;
    $ajax = ($user['ajax'] == 1 ? '<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>' : null);
    ?> 
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ru" lang="ru">
        <head>
            <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <?=$ajax?>
            <link rel="stylesheet" type="text/css" href="<?=HOME?>/style/<?=$designUser?>.css">
            <title>
            <?=$Filter->output($title)?>
            </title>
        </head>
        <body>
        <div class="block">
            <div class="content">
            <?php 
            $User->notifier();
            if (!empty($user)) 
            { 
                $User->headNotifier(); # Ban, party or clan invite and other;
                userPanel((!empty($user['in_battle']) ? 'fight' : null)); 

                    if ($user['bonus_time'] < time()) 
                    {
                    ?> 
                    <a href="<?=HOME?>/modules/user/bonus.php" class="link-touch">Ежедневный бонус</a>
                    <?php
                    } 
    
                $User->checkMail();
                title($title);
    
                DB::$dbs->query("UPDATE ".USERS." SET `where_link` = ? WHERE `id` = ?", [$_SERVER['REQUEST_URI'], $user['id']]);

                if (!empty($whereUser)) 
                {
                    $whereUser = $Filter->clearString($whereUser);
                    DB::$dbs->query("UPDATE ".USERS." SET `where` = ? WHERE `id` = ? ",array($whereUser, $_SESSION['id']));
                } 
                else 
                {
                    DB::$dbs->query("UPDATE ".USERS." SET `where` = ? WHERE `id` = ? ",array('Неизвестно', $_SESSION['id']));
                }
            }
} 
/*________________ error()           _________________*/ 
function error ($string, $linkUrl = NULL, $linkName = NULL) 
{
    $directoryHome = (!empty($user) ? '/game/index.php' : '/index.php');
    $link = (empty($linkUrl) ? '?' : HOME . $linkUrl);
    
    if ($link == '/' || $link == '/game/') 
    {
        $link = $directoryHome;
    }
    
    $_SESSION['error'] = $string; // $_SESSION['error'] -> $User->notifier();
    header("Location: " . $link);
    exit();
} 
/*________________ error no exit()   _________________*/ 
function errorNoExit ($string) 
{
    $_SESSION['error'] = $string; // $_SESSION['error'] -> $User->notifier();
    header("Location: ?");
    exit();
} 
/*________________ success()         _________________*/ 
function success ($string, $linkUrl = NULL, $linkName = NULL) 
{
    $directoryHome = (!empty($user) ? '/game/index.php' : '/index.php');
    $link = (empty($linkUrl) ? '?' : HOME . $linkUrl);
    
    if ($link == '/' || $link == '/game/') 
    {
        $link = $directoryHome;
    }

    $_SESSION['success'] = $string; // $_SESSION['success'] -> $User->notifier();
    header("Location: " . $link);
    exit();
} 
/*________________ success no exit() _________________*/ 
function successNoExit ($string) 
{
    $_SESSION['success'] = $string; // $_SESSION['error'] -> $User->notifier();
    header("Location: ?");
    exit();
} 
/*________________ money icon() _________________*/ 
function moneyIcon () 
{ 
    global $Filter;
    global $settings;
    $icon = '<img src="'.HOME.'/ico/'.$Filter->output($settings['money_img']).'" width="18px" height="18px" alt="'.$Filter->output($settings['money_name']).'" />'; 
    return $icon;
} 
/*________________ money name() _________________*/ 
function moneyName () 
{ 
    global $Filter;
    global $settings;
    $moneyName = $Filter->output($settings['money_name']); 
    return $moneyName;
}
/*________________ user link() _________________*/ 
function userLink ($userId, $hrefClass = NULL, $plusText = null) 
{
    global $Filter, $User;
    
    $userId = $Filter->clearInt($userId);
    
    $profile = DB::$dbs->queryFetch("SELECT `id`, `login`, `vip` FROM ".USERS." WHERE `id` = ?", [$userId]);
    
    $url = '<a href="'.HOME.'/modules/user/index.php?userId='.$profile['id'].'" '.(!empty($hrefClass) ? 'class="'.$hrefClass.'"' : NULL).'>'.$User->onlineIcon($profile['id']).' '. $Filter->output($profile['login']) .' ' . $User->userAccess($profile['id'], 1).' ' . ($profile['vip'] > time() ? ico('vip.png') : null) . ' '.(!empty($plusText) ? $plusText : NULL).'</a>';
    
    return $url;
} 


/*
 * Вывод времени;
 */
function dataTime ($time = null) 
{
    if ($time == NULL)$time = time();
    $timep="".date("j M yг. в H:i", $time)."";
    $time_p[0]=date("j n Y", $time);
    $time_p[1]=date("H:i", $time);

    if ($time_p[0] == date("j n Y"))$timep = date("H:i:s", $time);
    if ($time_p[0] == date("j n Y", time()-60*60*24))$timep = "Вчера в $time_p[1]";

    $timep=str_replace("Jan","Янв",$timep);
    $timep=str_replace("Feb","Фев",$timep);
    $timep=str_replace("Mar","Мар",$timep);
    $timep=str_replace("May","Мая",$timep);
    $timep=str_replace("Apr","Апр",$timep);
    $timep=str_replace("Jun","Июня",$timep);
    $timep=str_replace("Jul","Июля",$timep);
    $timep=str_replace("Aug","Авг",$timep);
    $timep=str_replace("Sep","Сент",$timep);
    $timep=str_replace("Oct","Окт",$timep);
    $timep=str_replace("Nov","Нояб",$timep);
    $timep=str_replace("Dec","Дек",$timep);
    return $timep;
}

/*
 * Отсчет времени;
 */
function countTime ($count) 
{
    $d                   = 3600 * 24; 
    $day                 = floor($count / $d);
    $count               = $count - ($d * $day);
    
    $hour                = floor($count / 3600);
    $count               = $count - (3600 * $hour);
    
    $minute              = floor($count / 60);
    $count               = $count - (60 * $minute);
    
    $second              = floor($count);
    
    $dayt                = "" . ($day > 0 ? "$day д. " : null) . "";
    $hourt               = "" . ($hour > 0 ? "$hour ч. " : null) . "";
    $minutet             = "" . ($minute > 0 ? "$minute м. " : null) . "";
    $secondt             = "" . ($second > 0 ? "$second с. " : null) . "";
    
    if ($day > 0) 
    {
        $minutet         = NULL;
	$secondt         = NULL;
    } 
    
    if ($hour > 0 && $day == 0) 
    {
        $secondt         = NULL;
	$dayt            = NULL;
    }
    
    return "$dayt$hourt$minutet$secondt";
}

/* Smiles */
function smiles ($string) 
{
    $sql = DB::$dbs->query("SELECT `url`, `name` FROM " . SMILES . "");

    while ($smile = $sql -> fetch()) 
    {
        $string = str_replace($smile['name'], '<img src="'.HOME.'/img/smiles/' . $smile['url'] . '" alt="'.$smile['name'].'"/>', $string);
    }

    return $string;
}
/*________________ output text() _________________*/ 
function outputText($string, $userId) 
{
    global $Filter, $User;
    
    $string = $Filter->output($string);
    //$string = nl2br($string);
    $string = specialTags($string, $userId);
    $string = $User->outputTextColor($string, $userId);
    $string = smiles($string);
    
    return $string;
}
/*________________ navigation panel() _________________*/ 
/*
 * Description; 
 * Панель навигации;
 * Используется для быстрого вывода ссылок навигации;
 * navigationUrl() - Используется;
 * Пример использования: $array = ['Почта']; navPanel($array);;
 */
function navPanel ($array) 
{ 
    echo '<div class="border-green"><div class="navigation-head-green">Панель навигации</div>';
    if (empty($array)) 
    {
        echo '<table style="width:100%" cellspacing="0" cellpadding="0"><tr>
        <td style="vertical-align:top;width:20%;white-space: nowrap;"><a href="'.HOME.'/" class="link-touch">Главная</a> </td> 
        </tr></table>';
    } 
    else 
    {
        echo '<table style="width:100%" cellspacing="0" cellpadding="0"><tr>
        <td style="vertical-align:top;width:20%;white-space: nowrap;"><a href="'.HOME.'/" class="link-touch">Главная</a> </td>'; 
        foreach ($array as $value) 
        {
            echo '<td style="vertical-align:top;width:20%;white-space: nowrap;">'.navURL($value).'</td>';
        } 
        echo '</tr></table>'; 
    } 
    echo '</div><br/>';
} 
/*________________ navigation Url() _________________*/ 
function navUrl ($value) 
{
    $string = str_replace('Панель Управления', '<a href="'.HOME.'/modules/administrative/index.php" class="link-touch"/>' . $value . '</a>', $value); 
    $string = str_replace('Почта', '<a href="'.HOME.'/modules/mail/index.php" class="link-touch"/>' . $value . '</a>', $string); 
    $string = str_replace('Рейтинг игроков', '<a href="'.HOME.'/modules/rating/index.php" class="link-touch"/>' . $value . '</a>', $string); 
    $string = str_replace('Настройки', '<a href="'.HOME.'/modules/user/settings/index.php" class="link-touch"/>' . $value . '</a>', $string);
    return $string;
} 
/*________________ special Tags() _________________*/ 
function specialTags ($string, $userId) 
{
    global $Filter;

    $userId = $Filter->clearInt($userId);
    
    $ank = DB::$dbs->queryFetch("SELECT `access` FROM ".USERS." WHERE `id` = ?", [$userId]);
    
    if ($ank['access'] == 2) 
    {
        $return = str_replace('#mail', '[<a href="'.HOME.'/modules/mail/index.php">Mail</a>]', $string);
        $return = str_replace('#test', '[<a href="'.HOME.'/modules/mail/index.php">test</a>]', $return);
        
        return $return;
    } 
    else 
    {
        return $string;
    }
}
/*________________ user Panel() _________________*/ 
function userPanel ($type = NULL) 
{
    global $User, $user, $Filter;

    //$User->restoreHealth(); # Enable health restore function;
    $User->updateLvl();       # Enable update lvl;
    $User->checkSkillTime();  # Disable skill;
    $User->checkUserBonus();  # Check all users bonus;

    if ($type == null) 
    {
        ?>  
    <?=DIV_USPANEL?><?=$User->staticHealthIcon() . (!empty($_SESSION['restoreHealth']) ? '<span style="color: #67B267;">+ ' . $_SESSION['restoreHealth'] . '</span>' : NULL)?><span style="float: right;"><?=moneyIcon() . shortNum($User->getQuery('userMoney', $user['id']))?></span><?=CLOSE_DIV?><div class="line"></div>
    <?php 
    $User->expBar();                              // Enable exp bar;
    if (!empty($_SESSION['restoreHealth'])) 
    {
        unset($_SESSION['restoreHealth']);
    }
    } 
    elseif ($type == 'fight') 
    {
        $userHealth = round($user['health'] / $user['max_health'] * 100,2);
        ?> 
        <?=ico('strike.png'), $user['strike'], ico('defend.png'), $user['defend'], ico('health.png'), $user['health']?>/<?=$user['max_health']?><br/>
        <?=($user['skill_1_active'] == 1 ? '<img src="/img/user/skill/1/'.$user['skill_1_lvl'].'.png" width="16px" height="16px">' : NULL)?>
        <div class="npcHealth">
            <div class="npcHealthLine" style="width: <?=$userHealth?>%;">
            </div>
        </div>
        <?php
    }
} 
/*________________ title() _________________*/ 
function title ($title) 
{ 
    global $Filter;
    ?> 
<?=DIV_TITLE?><h1><?=$Filter->output($title)?></h1><?=CLOSE_DIV?>
<?php
}

/*
 * Get IP;
 */ 
function getIP () 
{
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) 
    {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } 
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) 
    {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } 
    else 
    {
        $ip = $_SERVER['REMOTE_ADDR'];
    } 
    
    return $ip;
}

/*
 * Вывод иконки;
 */
function ico ($uri, $alt = NULL, $width = NULL, $height = NULL) 
{
    $ico = '<img src="/ico/'.$uri.'" width="'.($width == null ? '18' : $width).'px" height="'.($height == null ? '18' : $height).'px" alt="'.($alt == null ? 'ico' : $alt).'">';
    return $ico;
}

/*
 * Вычисление времени генерации страницы;
 */ 
function genTimerStart () 
{
    global $timerStartTime; 
    $startTime = microtime();
    $startArray = explode(" ",$startTime);
    $timerStartTime = $startArray[1] + $startArray[0];
    return $timerStartTime;
} 

function genTimerStop () 
{
    global $timerStartTime;
    $endTime = microtime();
    $endArray = explode(" ",$endTime);
    $timerStopTime = $endArray[1] + $endArray[0];
    $time = $timerStopTime - $timerStartTime;
    $time = substr($time,0,5);
    return "$time сек.";
} 

function shortNum ($string) 
{
    if ($string < 100) 
    {
        $string = $string;
    } 
    else if ($string >= 1000 && $string < 1000000) 
    {
        $string = round($string/ 1000, 1) . 'K';
    } 
    else if ($string > 1000000) 
    {
        $string = round(($string / 1000) / 1000, 1) . 'M';
    } 

    return $string;
}

function SubstrMaus($text, $len, $start = 0, $mn = ' (...)') 
{
    $text = trim($text);

    if (function_exists('mb_substr')) 
    {
        return mb_substr($text, $start, $len) . (mb_strlen($text) > $len - $start ? $mn : null);
    } 
    else if (function_exists('iconv')) 
    {
        return iconv_substr($text, $start, $len) . (iconv_strlen($text) > $len - $start ? $mn : null);
    } 
    else 
    {
        return $text;
    }
}