<?php
/*
 * JohnCMS NEXT Mobile Content Management System (http://johncms.com)
 *
 * For copyright and license information, please see the LICENSE.md
 * Installing the system or redistributions of files must retain the above copyright notice.
 *
 * @link        http://johncms.com JohnCMS Project
 * @copyright   Copyright (C) JohnCMS Community
 * @license     GPL-3
 */

namespace Johncms;

use Psr\Container\ContainerInterface;

class Tools implements Api\ToolsInterface
{
    /**
     * @var ContainerInterface
     */
    private $container;

    /**
     * @var \PDO
     */
    private $db;

    /**
     * @var Api\UserInterface::class
     */
    private $user;

    /**
     * @var UserConfig
     */
    private $userConfig;

    /**
     * @var Api\ConfigInterface
     */
    private $config;

    public function __invoke(ContainerInterface $container)
    {
        $this->container = $container;
        $this->config = $container->get(Api\ConfigInterface::class);
        $this->db = $container->get(\PDO::class);
        $this->user = $container->get(Api\UserInterface::class);
        $this->userConfig = $this->user->getConfig();

        return $this;
    }

	public function randomPassword() 
	{
    $alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
    $pass = '';                           //password is a string
    $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
    for ($i = 0; $i < 8; $i++) {
        $n = mt_rand(0, $alphaLength);    
        $pass = $pass.$alphabet[$n];      //append a random character
		}
    return ($pass); 
	}

   public function updateTime($jam) {

   $waktu = $jam + ($this->config->timeshift + $this->userConfig->timeshift * 3600);
   $lama = round((time() - $waktu) / 60);
   if($lama == 0){
      $lama = _t('Few seconds ago');
   }
   if($lama > 0 && $lama < 60){
      $lama = $lama . ' ' . _t('Minutes ago');
   }
   if ($lama >= 60 && $lama < 120){
      $lama = round($lama / 60);
      $lama = $lama . ' ' . _t('Hours ago');
   }
   if($lama >= 120 && $lama < 180){
      $lama = round($lama / 60);
      $lama = $lama . ' ' . _t('Hours ago');
}
   if($lama >= 180 && $lama < 240){
      $lama=round($lama / 60);
      $lama=$lama . ' ' . _t('Hours ago');
   }
   if($lama>=240 && $lama<300){
      $lama=round($lama/60);
      $lama=$lama . ' ' . _t('Hours ago');
   }
   if($lama>=300 && $lama<360){
      $lama=round($lama/60);
      $lama=$lama . ' ' . _t('Hours ago');
   }
   if($lama>=360 && $lama<420){
      $lama=round($lama/60);
      $lama=$lama . ' ' . _t('Hours ago');
   }
   if($lama>=420 && $lama<480){
      $lama=round($lama/60);
      $lama=$lama . ' ' . _t('Hours ago');
   }
   if($lama>=480 && $lama<540){
      $lama=round($lama/60);
      $lama=$lama . ' ' . _t('Hours ago');
   }
   if($lama>=540 && $lama<600){
      $lama=round($lama/60);
      $lama=$lama . ' ' . _t('Hours ago');
   }
   if($lama>=600 && $lama<660){
      $lama=round($lama/60);
      $lama=$lama . ' ' . _t('Hours ago');
   }
   if($lama>=660 && $lama<720){
      $lama=round($lama/60);
      $lama=$lama . ' ' . _t('Hours ago');
   }
   if($lama>=720 && $lama<780){
      $lama=round($lama/60);
      $lama=$lama . ' ' . _t('Hours ago');
   }
   if($lama>=780 && $lama<820){
      $lama=round($lama/60);
      $lama=$lama . ' ' . _t('Hours ago');
   }
   if($lama>=820 && $lama<880){
      $lama=round($lama/60);
      $lama=$lama . ' ' . _t('Hours ago');
   }
   if($lama>=880 && $lama<920){
      $lama=round($lama/60);
      $lama=$lama . ' ' . _t('Hours ago');
   }
   if($lama>=920 && $lama<980){
      $lama=round($lama/60);
      $lama=$lama . ' ' . _t('Hours ago');
   }
   if($lama>=980 && $lama<1020){
      $lama=round($lama/60);
      $lama=$lama . ' ' . _t('Hours ago');
   }
   if($lama>=1020 && $lama<1080){
      $lama=round($lama/60);
      $lama=$lama . ' ' . _t('Hours ago');
   }
   if($lama>=1080 && $lama<1140){
      $lama=round($lama/60);
      $lama=$lama . ' ' . _t('Hours ago');
   }
   if($lama>=1140 && $lama<1200){
      $lama=round($lama/60);
      $lama=$lama . ' ' . _t('Hours ago');
   }
   if($lama>=1200 && $lama<1260){
      $lama=round($lama/60);
      $lama=$lama . ' ' . _t('Hours ago');
   }
   if($lama>=1260 && $lama<1320){
      $lama=round($lama/60);
      $lama=$lama . ' ' . _t('Hours ago');
   }
   if($lama>=1320 && $lama<1380){
      $lama=round($lama/60);
      $lama=$lama . ' ' . _t('Hours ago');
   }
   if($lama>=1380 && $lama<1440){
      $lama=round($lama/60);
      $lama=$lama . ' ' . _t('Hours ago');
   }
   
   // Jika lebih dari 24 jam
   if($lama>=1440 && $lama<2880){
      $lama=round($lama/60/24); 
		$lama = _t('Yesterday');
   }
   // Jika lebih dari 48 jam
   if($lama>=2880){
      $lama = date("d M - Y + g:i a", $waktu);
   }
return $lama;
}


public function rewriteUrl($text)
{
$text = html_entity_decode(trim($text), ENT_QUOTES, 'UTF-8');
$text=str_replace(" ","-", $text);
$text=str_replace("--","-", $text);
$text=str_replace("@","-",$text);
$text=str_replace("/","-",$text);
$text=str_replace("\\","-",$text);
$text=str_replace(":","",$text);
$text=str_replace("\"","",$text);
$text=str_replace("'","",$text);
$text=str_replace("<","",$text);
$text=str_replace(">","",$text);
$text=str_replace(",","",$text);
$text=str_replace("?","",$text);
$text=str_replace(";","",$text);
$text=str_replace(".","",$text);
$text=str_replace("[","",$text);
$text=str_replace("]","",$text);
$text=str_replace("(","",$text);
$text=str_replace(")","",$text);
$text=str_replace("*","",$text);
$text=str_replace("!","",$text);
$text=str_replace("$","-",$text);
$text=str_replace("&","-and-",$text);
$text=str_replace("%","",$text);
$text=str_replace("#","",$text);
$text=str_replace("^","",$text);
$text=str_replace("=","",$text);
$text=str_replace("+","",$text);
$text=str_replace("~","",$text);
$text=str_replace("`","",$text);
$text=str_replace("--","-",$text);
$text = preg_replace("/(ﾐ蕩|ﾐ藤|ﾐｱ ｡|ﾐｱ ｣|ﾐ謄|ﾐ討|ﾐｱ ｧ|ﾐｱ ･|ﾐｱ ｭ|ﾐｱ ｩ|ﾐｱ ｫ|ﾐ買|ﾐｱ ｱ|ﾐｱ ｯ|ﾐｱ ｷ|ﾐｱ ｳ|ﾐｱ ｵ)/", 'a', $text);$text = preg_replace("/(aﾐ怙|aﾐ怐|aﾐ悒|aﾐ怏|aﾐ怎|ﾐ討|ﾐ討ﾐ怙|ﾐ討ﾐ怐|ﾐ討ﾐ悒|ﾐ討ﾐ怏|ﾐ討ﾐ怎|ﾐ買|ﾐ買ﾐ怙|ﾐ買ﾐ怐|ﾐ買ﾐ悒|ﾐ買ﾐ怏|ﾐ買ﾐ怎)/", 'a', $text);
$text = preg_replace("/(ﾐ寅－ﾐ陶|ﾐｱ  |ﾐｱ  |ﾐｱ  |ﾐ頭|ﾐｱ －ﾐｱ  |ﾐｱ �ﾐｱ ポﾐｱ �)/", 'e', $text);
$text = preg_replace("/(eﾐ怙|eﾐ怐|eﾐ悒|eﾐ怏|eﾐ怎|ﾐ頭|ﾐ頭ﾐ怙|ﾐ頭ﾐ怐|ﾐ頭ﾐ悒|ﾐ頭ﾐ怏|ﾐ頭ﾐ怎)/", 'e', $text);
$text = preg_replace("/(ﾐ闘|ﾐ働|ﾐｱ 弓ﾐｱ 榎ﾐ畠)/", 'i', $text);$text = preg_replace("/(iﾐ怙|iﾐ怐|iﾐ悒|iﾐ怏|iﾐ怎)/", 'i', $text);
$text = preg_replace("/(ﾐ憧|ﾐ撞|ﾐｱ 鋼ﾐｱ 楯ﾐ瞳|ﾐ洞|ﾐｱ 倒ﾐｱ 掃ﾐｱ 處ﾐｱ 怖ﾐｱ 慾ﾐ味|ﾐｱ 掟ﾐｱ 斈ﾐｱ ｣|ﾐｱ 毫ﾐｱ ｡)/", 'o', $text);$text = preg_replace("/(oﾐ怙|oﾐ怐|oﾐ悒|oﾐ怏|oﾐ怎|ﾐ洞|ﾐ洞ﾐ怙|ﾐ洞ﾐ怐|ﾐ洞ﾐ悒|ﾐ洞ﾐ怏|ﾐ洞ﾐ怎|ﾐ味|ﾐ味ﾐ怙|ﾐ味ﾐ怐|ﾐ味ﾐ悒|ﾐ味ﾐ怏|ﾐ味ﾐ怎)/", 'o', $text);
$text = preg_replace("/(ﾐ� |ﾐ� |ﾐｱ ･|ﾐｱ ｧ|ﾐ鮒|ﾐ眠|ﾐｱ ｫ|ﾐｱ ｩ|ﾐｱ ｱ|ﾐｱ ｭ|ﾐｱ ｯ)/", 'u', $text);
$text = preg_replace("/(uﾐ怙|uﾐ怐|uﾐ悒|uﾐ怏|uﾐ怎|ﾐ眠|ﾐ眠ﾐ怙|ﾐ眠ﾐ怐|ﾐ眠ﾐ悒|ﾐ眠ﾐ怏|ﾐ眠ﾐ怎)/", 'u', $text);
$text = preg_replace("/(ﾐｱ ｳ|ﾐ� |ﾐｱ ｵ|ﾐｱ ｷ|ﾐｱ  )/", 'y', $text);$text = preg_replace("/(ﾐ泊)/", 'd', $text);
$text = preg_replace("/(yﾐ怙|yﾐ怐|yﾐ悒|yﾐ怏|yﾐ怎)/", 'y', $text);$text = preg_replace("/(ﾐ泊)/", 'd', $text);
$text = preg_replace("/(ﾐ凍|ﾐ刀|ﾐｱ �|ﾐｱ ｢|ﾐ塔|ﾐ唐|ﾐｱ ｦ|ﾐｱ ､|ﾐｱ ｬ|ﾐｱ ﾐ－ﾐｱ ｪ|ﾐ狽|ﾐｱ ｰ|ﾐｱ ｮ|ﾐｱ ｶ|ﾐｱ ｲ|ﾐｱ ｴ)/", 'A', $text);$text = preg_replace("/(Aﾐ怙|Aﾐ怐|Aﾐ悒|Aﾐ怏|Aﾐ怎|ﾐ唐|ﾐ唐ﾐ怙|ﾐ唐ﾐ怐|ﾐ唐ﾐ悒|ﾐ唐ﾐ怏|ﾐ唐ﾐ怎|ﾐ狽|ﾐ狽ﾐ怙|ﾐ狽ﾐ怐|ﾐ狽ﾐ悒|ﾐ狽ﾐ怏|ﾐ狽ﾐ怎)/", 'A', $text);
$text = preg_replace("/(ﾐ嶋|ﾐ悼|ﾐｱ ﾑ掃ﾐｱ  |ﾐｱ  |ﾐ投|ﾐｱ �|ﾐｱ  |ﾐｱ �ﾐｱ �ﾐｱ �)/", 'E', $text);
$text = preg_replace("/(Eﾐ怙|Eﾐ怐|Eﾐ悒|Eﾐ怏|Eﾐ怎|ﾐ投|ﾐ投ﾐ怙|ﾐ投ﾐ怐|ﾐ投ﾐ悒|ﾐ投ﾐ怏|ﾐ投ﾐ怎)/", 'E', $text);
$text = preg_replace("/(ﾐ東|ﾐ桃|ﾐｱ 掛ﾐｱ �ﾐ頒�)/", 'I', $text);$text = preg_replace("/(Iﾐ怙|Iﾐ怐|Iﾐ悒|Iﾐ怏|Iﾐ怎)/", 'I', $text);
$text = preg_replace("/(ﾐ湯|ﾐ涛|ﾐｱ 芸ﾐｱ 旨ﾐ燈|ﾐ灯|ﾐｱ 竹ﾐｱ 酢ﾐｱ �ﾐｱ 培ﾐｱ 翻ﾐ蔓|ﾐｱ 忿ﾐｱ 嘶ﾐｱ ｢|ﾐｱ 桍ﾐｱ �)/", 'O', $text);$text = preg_replace("/(Oﾐ怙|Oﾐ怐|Oﾐ悒|Oﾐ怏|Oﾐ怎|ﾐ灯|ﾐ灯ﾐ怙|ﾐ灯ﾐ怐|ﾐ灯ﾐ悒|ﾐ灯ﾐ怏|ﾐ灯ﾐ怎|ﾐ蔓|ﾐ蔓ﾐ怙|ﾐ蔓ﾐ怐|ﾐ蔓ﾐ悒|ﾐ蔓ﾐ怏|ﾐ蔓ﾐ怎)/", 'O', $text);
$text = preg_replace("/(ﾐ等|ﾐ答|ﾐｱ ､|ﾐｱ ｦ|ﾐ片－ﾐ民|ﾐｱ ｪ|ﾐｱ ﾐ－ﾐｱ ｰ|ﾐｱ ｬ|ﾐｱ ｮ)/", 'U', $text);$text = preg_replace("/(Uﾐ怙|Uﾐ怐|Uﾐ悒|Uﾐ怏|Uﾐ怎|ﾐ民|ﾐ民ﾐ怙|ﾐ民ﾐ怐|ﾐ民ﾐ悒|ﾐ民ﾐ怏|ﾐ民ﾐ怎)/", 'U', $text);
$text = preg_replace("/(ﾐｱ ｲ|ﾐ統|ﾐｱ ｴ|ﾐｱ ｶ|ﾐｱ ﾑ�)/", 'Y', $text);
$text = preg_replace("/(ﾐ柏)/", 'D', $text);
$text = preg_replace("/(Yﾐ怙|Yﾐ怐|Yﾐ悒|Yﾐ怏|Yﾐ怎)/", 'Y', $text);$text = preg_replace("/(ﾐ柏)/", 'D', $text);
$text=strtolower($text);
return $text;
}

public function displayPage($base_url, $start, $max_value, $num_per_page)
{
$neighbors = 2;
if ($start >= $max_value)
$start = max(0, (int)$max_value - (((int)$max_value % (int)$num_per_page) == 0 ? $num_per_page : ((int)$max_value % (int)$num_per_page)));
else
$start = max(0, (int)$start - ((int)$start % (int)$num_per_page));
$base_link = '<a class="pagenav" href="' . strtr($base_url, array('%' => '%%')) . '_p%d.html' . '">%s</a>';
$out[] = $start == 0 ? '' : sprintf($base_link, $start / $num_per_page, 'Prev');
if ($start > $num_per_page * $neighbors)
$out[] = sprintf($base_link, 1, '1');
if ($start > $num_per_page * ($neighbors + 1))
$out[] = '<span style="font-weight: bold;">...</span>';
for ($nCont = $neighbors; $nCont >= 1; $nCont--)
if ($start >= $num_per_page * $nCont) {
$tmpStart = $start - $num_per_page * $nCont;
$out[] = sprintf($base_link, $tmpStart / $num_per_page + 1, $tmpStart / $num_per_page + 1);
}
$out[] = '<span class="currentpage"><b>' . ($start / $num_per_page + 1) . '</b></span>';
$tmpMaxPages = (int)(($max_value - 1) / $num_per_page) * $num_per_page;
for ($nCont = 1; $nCont <= $neighbors; $nCont++)
if ($start + $num_per_page * $nCont <= $tmpMaxPages) {
$tmpStart = $start + $num_per_page * $nCont;
$out[] = sprintf($base_link, $tmpStart / $num_per_page + 1, $tmpStart / $num_per_page + 1);
}
if ($start + $num_per_page * ($neighbors + 1) < $tmpMaxPages)
$out[] = '<span style="font-weight: bold;">...</span>';
if ($start + $num_per_page * $neighbors < $tmpMaxPages)
$out[] = sprintf($base_link, $tmpMaxPages / $num_per_page + 1, $tmpMaxPages / $num_per_page + 1);
if ($start + $num_per_page < $max_value) {
$display_page = ($start + $num_per_page) > $max_value ? $max_value : ($start / $num_per_page + 2);
$out[] = sprintf($base_link, $display_page, 'Next');
}
return implode(' ', $out);
}

    public function displayMenu(array $val = [], $delimiter = ' | ', $end_space = '')
    {
        return implode($delimiter, array_diff($val, [''])) . $end_space;
    }

    public function antiflood()
    {
        $config = $this->config['antiflood'];

        switch ($config['mode']) {
            // Адаптивный режим
            case 1:
                $adm = $this->db->query('SELECT COUNT(*) FROM `users` WHERE `rights` > 0 AND `lastdate` > ' . (time() - 300))->fetchColumn();
                $limit = $adm > 0 ? $config['day'] : $config['night'];
                break;
            // День
            case 3:
                $limit = $config['day'];
                break;
            // Ночь
            case 4:
                $limit = $config['night'];
                break;
            // По умолчанию день / ночь
            default:
                $c_time = date('G', time());
                $limit = $c_time > $config['day'] && $c_time < $config['night'] ? $config['day'] : $config['night'];
        }

        // Для Администрации задаем лимит в 4 секунды
        if ($this->user->rights > 0) {
            $limit = 4;
        }

        $flood = $this->user->lastpost + $limit - time();

        return $flood > 0 ? $flood : false;
    }

    /**
     * Обработка текстов перед выводом на экран
     *
     * @param string $str
     * @param int    $br   Параметр обработки переносов строк
     *                     0 - не обрабатывать (по умолчанию)
     *                     1 - обрабатывать
     *                     2 - вместо переносов строки вставляются пробелы
     * @param int    $tags Параметр обработки тэгов
     *                     0 - не обрабатывать (по умолчанию)
     *                     1 - обрабатывать
     *                     2 - вырезать тэги
     *
     * @return string
     */
    public function checkout($str, $br = 0, $tags = 0)
    {
        $str = htmlentities(trim($str), ENT_QUOTES, 'UTF-8');

        if ($br == 1) {
            $str = nl2br($str);
        } elseif ($br == 2) {
            $str = str_replace("\r\n", ' ', $str);
        }

        if ($tags == 1) {
            $str = $this->container->get(Api\BbcodeInterface::class)->tags($str);
        } elseif ($tags == 2) {
            $str = $this->container->get(Api\BbcodeInterface::class)->notags($str);
        } elseif ($threads == 1) {
            $str = $this->container->get(Api\BbcodeInterface::class)->threads($str);
        } elseif ($threads == 2) {
            $str = $this->container->get(Api\BbcodeInterface::class)->adepeter($str);
        }

        return trim($str);
    }

    /**
     * Показываем дату с учетом сдвига времени
     *
     * @param int $var Время в Unix формате
     * @return string Отформатированное время
     */
    public function displayDate($var)
    {
        $shift = ($this->config->timeshift + $this->userConfig->timeshift) * 3600;

        if (date('Y', $var) == date('Y', time())) {
            if (date('z', $var + $shift) == date('z', time() + $shift)) {
                return _t('Today', 'system') . ', ' . date("g:i a", $var + $shift);
            }
            if (date('z', $var + $shift) == date('z', time() + $shift) - 1) {
                return _t('Yesterday', 'system') . ', ' . date("g:i a", $var + $shift);
            }
        }

        return date("d.m.Y / g:i a", $var + $shift);
    }

    /**
     * Фильтрация строк
     *
     * @param string $str
     *
     * @return string
     */
    public function checkin($str) {
if (function_exists('iconv')) {
$str = iconv("UTF-8", "UTF-8", $str);
}
$str = preg_replace('#(\.|\?|!|\(|\)){3,}#', '\1\1\1', $str);
$str = nl2br($str);
$str = preg_replace('!\p{C}!u', '', $str);
$str = str_replace('<br/>', "\n", $str);
$str = preg_replace('# {2,}#', ' ', $str);
$str = preg_replace("/(\n)+(\n)/i", "\n\n", $str);
return trim($str);
}

    /**
     * Маскировка ссылок в тексте
     *
     * @param $var
     *
     * @return string
     */
    public function antiLink($var) { 

			$var = preg_replace('~\\[url=(https?://.+?)\\](.+?)\\[/url\\]|(https?://(www.)?[0-9a-z\.-]+\.[0-9a-z]{2,6}[0-9a-zA-Z/\?\.\~&amp;_=/%-:#]*)~', '###', $var);
			$replace = [
			'.ru' => ',ru',
			'.com' => ',com',
			'.biz' => ',biz',
			'.cn' => ',cn',
			'.in' => ',in',
			'.net' => ',net',
			'.org' => ',org',
			'.info' => ',info',
			'.mobi' => ',mobi',
			'.wen' => ',wen',
			'.kmx' => ',kmx',
			'.h2m' => ',h2m',
			'.lk' => ',lk',
			'.asia' => ',asia',
			'.free' => ',free',
			'.info' => ',info',
			'.us' => ',us',
			'.co' => ',co',
			'.id' => ',id',
			'.ly' => ',ly',
			'.fly' => ',fly',
			'.tk' => ',tk',
			];
		return strtr($var, $replace);
		}

		public function cleanString ($string) {
			$bad = array("itil","ngentot","ngewe","shit","fuck","ngantok","anjing","bitch","kontol","ngantok","babi","pejuh","memek","ngepet","nonok","jembut","slut","cum","dick","oral","penis","vagina","swinger","threesome","onani","masturbasi","dildo","sex toy","vibrator","foreplay");
return str_replace($bad,":sensor:",$string);
		}

    /**
     * Сообщения об ошибках
     *
     * @param string|array $error Сообщение об ошибке (или массив с сообщениями)
     * @param string       $link  Необязательная ссылка перехода
     * @return string
     */
    public function displayError($error = '', $link = '')
    {
        return '<div class="rmenu"><p><b>' . _t('ERROR', 'system') . '!</b><br>'
            . (is_array($error) ? implode('<br>', $error) : $error) . '</p>'
            . (!empty($link) ? '<p>' . $link . '</p>' : '') . '</div>';
    }

    /**
     * Постраничная навигация
     * За основу взята доработанная функция от форума SMF 2.x.x
     *
     * @param string $url
     * @param int    $start
     * @param int    $total
     * @param int    $kmess
     * @return string
     */
    public function displayPagination($url, $start, $total, $kmess)
    {
        $neighbors = 2;
        if ($start >= $total) {
            $start = max(0, $total - (($total % $kmess) == 0 ? $kmess : ($total % $kmess)));
        } else {
            $start = max(0, (int)$start - ((int)$start % (int)$kmess));
        }

        $base_link = '<a class="pagenav" href="' . strtr($url, ['%' => '%%']) . 'page=%d' . '">%s</a>';
        $out[] = $start == 0 ? '' : sprintf($base_link, $start / $kmess, '&lt;&lt;');

        if ($start > $kmess * $neighbors) {
            $out[] = sprintf($base_link, 1, '1');
        }

        if ($start > $kmess * ($neighbors + 1)) {
            $out[] = '<span style="font-weight: bold;">...</span>';
        }

        for ($nCont = $neighbors; $nCont >= 1; $nCont--) {
            if ($start >= $kmess * $nCont) {
                $tmpStart = $start - $kmess * $nCont;
                $out[] = sprintf($base_link, $tmpStart / $kmess + 1, $tmpStart / $kmess + 1);
            }
        }

        $out[] = '<span class="currentpage"><b>' . ($start / $kmess + 1) . '</b></span>';
        $tmpMaxPages = (int)(($total - 1) / $kmess) * $kmess;

        for ($nCont = 1; $nCont <= $neighbors; $nCont++) {
            if ($start + $kmess * $nCont <= $tmpMaxPages) {
                $tmpStart = $start + $kmess * $nCont;
                $out[] = sprintf($base_link, $tmpStart / $kmess + 1, $tmpStart / $kmess + 1);
            }
        }

        if ($start + $kmess * ($neighbors + 1) < $tmpMaxPages) {
            $out[] = '<span style="font-weight: bold;">...</span>';
        }

        if ($start + $kmess * $neighbors < $tmpMaxPages) {
            $out[] = sprintf($base_link, $tmpMaxPages / $kmess + 1, $tmpMaxPages / $kmess + 1);
        }

        if ($start + $kmess < $total) {
            $display_page = ($start + $kmess) > $total ? $total : ($start / $kmess + 2);
            $out[] = sprintf($base_link, $display_page, '&gt;&gt;');
        }

        return implode(' ', $out);
    }

    /**
     * Показываем местоположение пользователя
     *
     * @param int    $user_id
     * @param string $place
     * @return mixed|string
     */
    public function displayPlace($user_id = 0, $place = '', $headmod = '')
    {
        $place = explode(",", $place);

        $placelist = [
            'admlist'          => '<a href="#home#/users/index.php?act=admlist">' . _t('List of Admins', 'system') . '</a>',
            'album'            => '<a href="#home#/album/index.php">' . _t('Watching the photo album', 'system') . '</a>',
            'birth'            => '<a href="#home#/users/index.php?act=birth">' . _t('List of birthdays', 'system') . '</a>',
            'downloads'        => '<a href="#home#/downloads/index.php">' . _t('Downloads', 'system') . '</a>',
            'faq'              => '<a href="#home#/help/">' . _t('Reading the FAQ', 'system') . '</a>',
            'forum'            => '<a href="#home#/forum/index.php">' . _t('Forum', 'system') . '</a>&#160;/&#160;<a href="#home#/forum/index.php?act=who">&gt;&gt;</a>',
            'forumfiles'       => '<a href="#home#/forum/index.php?act=files">' . _t('Forum Files', 'system') . '</a>',
            'forumwho'         => '<a href="#home#/forum/index.php?act=who">' . _t('Looking, who in Forum?', 'system') . '</a>',
            'guestbook'        => '<a href="#home#/guestbook/index.php">' . _t('Guestbook', 'system') . '</a>',
            'here'             => _t('Here, in the list', 'system'),
            'homepage'         => _t('On the Homepage', 'system'),
            'library'          => '<a href="#home#/library/index.php">' . _t('Library', 'system') . '</a>',
            'mail'             => _t('Personal correspondence', 'system'),
            'news'             => '<a href="#home#/news/index.php">' . _t('Reading the news', 'system') . '</a>',
            'online'           => '<a href="#home#/users/index.php?act=online">' . _t('Who is online?', 'system') . '</a>',
            'profile'          => _t('Profile', 'system'),
            'profile_personal' => _t('Personal Profile', 'system'),
            'registration'     => _t('Registered on the site', 'system'),
            'userlist'         => '<a href="#home#/users/index.php?act=userlist">' . _t('List of users', 'system') . '</a>',
            'userstop'         => '<a href="#home#/users/index.php?act=top">' . _t('Watching Top 10 Users', 'system') . '</a>',
        ];

        if (array_key_exists($place[0], $placelist)) {
            if ($place[0] == 'profile') {
                if ($place[1] == $user_id) {
                    return '<a href="' . $this->config['homeurl'] . '/profile/?user=' . $place[1] . '">' . $placelist['profile_personal'] . '</a>';
                } else {
                    $user = $this->getUser($place[1]);

                    return $placelist['profile'] . ': <a href="' . $this->config['homeurl'] . '/profile/?user=' . $user['id'] . '">' . $user['name'] . '</a>';
                }
            } elseif ($place[0] == 'online' && !empty($headmod) && $headmod == 'online') {
                return $placelist['here'];
            } else {
                return str_replace('#home#', $this->config['homeurl'], $placelist[$place[0]]);
            }
        }

        return '<a href="' . $this->config['homeurl'] . '/index.php">' . $placelist['homepage'] . '</a>';
    }

    /**
     * Отображения личных данных пользователя
     *
     * @param int   $user Массив запроса в таблицу `users`
     * @param array $arg  Массив параметров отображения
     *                    [lastvisit] (boolean)   Дата и время последнего визита
     *                    [stshide]   (boolean)   Скрыть статус (если есть)
     *                    [iphide]    (boolean)   Скрыть (не показывать) IP и UserAgent
     *                    [iphist]    (boolean)   Показывать ссылку на историю IP
     *
     *                    [header]    (string)    Текст в строке после Ника пользователя
     *                    [body]      (string)    Основной текст, под ником пользователя
     *                    [sub]       (string)    Строка выводится вверху области "sub"
     *                    [footer]    (string)    Строка выводится внизу области "sub"
     *
     * @return string
     */
    public function displayUser($user = 0, array $arg = [])
    {
        global $mod;
        $out = false;
        $homeurl = $this->config['homeurl'];

        if (!$user['id']) {
            $out = '<b>' . _t('Guest', 'system') . '</b>';

            if (!empty($user['name'])) {
                $out .= ': ' . $user['name'];
            }

            if (!empty($arg['header'])) {
                $out .= ' ' . $arg['header'];
            }
        } else {
            $out .= '<table cellpadding="0" cellspacing="0"><tr><td>';

            if (file_exists((ROOT_PATH . 'files/users/avatar/' . $user['id'] . '.png'))) {
                $out .= '<img src="' . $homeurl . '/files/users/avatar/' . $user['id'] . '.png" width="32" height="32" alt="" />&#160;';
            } else {
                $out .= '<img src="' . $homeurl . '/images/empty.png" width="36" height="auto" alt="" />&#160;';
            }

            $out .= '</td><td>';
					$height = '8';
					$med = ($user['postforum'] + $user['postguest'] + $user['komm'] + $user['balans'] + $user['karma_plus']) / ($user['karma_minus'] + 100);
					if ($med >= 1 && $med < 20) { 
$medal = ' <img src = "../images/medal/01.png" height="' . $height . '" />'; 
					} 
					if ($med >= 20 && $med < 40) { 
$medal = ' <img src = "../images/medal/02.png" height="' . $height . '" />'; 
					}
					if ($med >= 40 && $med < 60) { 
$medal = ' <img src = "../images/medal/03.png" height="' . $height . '" />'; 
					}
					if ($med >= 60 && $med < 80) { 
$medal = ' <img src = "../images/medal/04.png" height="' . $height . '" />'; 
					}
					if ($med >= 80 && $med < 100) { 
$medal = ' <img src = "../images/medal/05.png" height="' . $height . '" />'; 
					}
					if ($med >= 100) { 
$medal = ' <img src = "../images/medal/06.png" height="' . $height . '" />'; 
					}
					$rating = ($user['postforum'] + $user['postguest'] + $user['komm'] + $user['balans'] + $user['karma_plus']) / ($user['karma_minus'] + 100);


            if ($user['sex']) {
                $out .= $this->image(($user['sex'] == 'm' ? 'm' : 'w') . ($user['datereg'] > time() - 86400 ? '_new' : '') . '.png', ['class' => 'icon-inline']);
            } else {
                $out .= $this->image('del.png');
            }

            $out .= !$this->user->isValid() || $this->user->id == $user['id'] ? '<b>' . $user['name'] . '</b><br/>Points:&nbsp;<span class="red">['. $rating .']</span><br/>Medal:&nbsp;'. $medal .'<br/>' : '<a href="' . $homeurl . '/profile/?user=' . $user['id'] . '"><b>' . $user['name'] . '</b></a><br />';
            $out .= 'Currently:' . (time() > $user['lastdate'] + 300 ? '<br/><span class="red">&nbsp;<img src="' . $homeurl . '/images/offline.gif" width="8" height="10" alt="off"/></span>' : '<span class="green">&nbsp;<img src="' . $homeurl . '/images/online.gif" width="8" height="10" alt="on"/></span><br/>');
            if (!empty($arg['header'])) {
                $out .= ' ' . $arg['header'];
            }

            $rank = [
                0 => '<div class="status">Ranked: <font color="black">Member',
                1 => '<div class="status">Ranked: <font color="black">Guestbook Moderator',
                2 => '<div class="status">Rank: <font color="purple">ShoutBox Moderator',
                3 => '<div class="status">Rank: <font color="green">Forum Moderator',
                4 => '<div class="status">Rank: <font color="#3399ff">Downloads Moderator',
                5 => '<div class="status">Rank: <font color="yellow">Library Moder',
                6 => '<div class="status">Rank: <font color="blue">Super Moderator',
                7 => '<div class="status">Ranked: <font color="orange">Administrator',
                9 => '<div class="status">Ranked as: <font color="red">Founder',
            ];
            $rights = isset($user['rights']) ? $user['rights'] : 0;
            $out .= ' ' . $rank[$user['rights']] . '</font>';

            if (!isset($arg['stshide']) && !empty($user['status'])) {
                $out .= '<div class="status">' . $this->image('label.png', ['class' => 'icon-inline']) . $user['status'] . '</div>';
            }
            $out .= '</div>';
            $out .= '</td></tr></table>';
        }

        if (isset($arg['body'])) {
            $out .= '<div>' . $arg['body'] . '</div>';
        }

        $ipinf = isset($arg['iphide']) ? !$arg['iphide'] : ($this->user->rights ? 1 : 0);
        $lastvisit = time() > $user['lastdate'] + 300 && isset($arg['lastvisit']) ? $this->displayDate($user['lastdate']) : false;

        if ($ipinf || $lastvisit || isset($arg['sub']) && !empty($arg['sub']) || isset($arg['footer'])) {
            $out .= '<div class="sub">';

            if (isset($arg['sub'])) {
                $out .= '<div>' . $arg['sub'] . '</div>';
            }

            if ($lastvisit) {
                $out .= '<div><span class="gray">' . _t('Last Visit', 'system') . ':</span> ' . $lastvisit . '</div>';
            }

            $iphist = '';

            if ($ipinf) {
                $out .= '<div><span class="gray">' . _t('Browser', 'system') . ':</span> ' . htmlspecialchars($user['browser']) . '</div>' .
                    '<div><span class="gray">' . _t('IP address', 'system') . ':</span> ';
                $hist = $mod == 'history' ? '&amp;mod=history' : '';
                $ip = long2ip($user['ip']);

                if ($this->user->rights && isset($user['ip_via_proxy']) && $user['ip_via_proxy']) {
                    $out .= '<b class="red"><a href="' . $homeurl . '/admin/index.php?act=search_ip&amp;ip=' . $ip . $hist . '">' . $ip . '</a></b>';
                    $out .= '&#160;[<a href="' . $homeurl . '/admin/index.php?act=ip_whois&amp;ip=' . $ip . '">?</a>]';
                    $out .= ' / ';
                    $out .= '<a href="' . $homeurl . '/admin/index.php?act=search_ip&amp;ip=' . long2ip($user['ip_via_proxy']) . $hist . '">' . long2ip($user['ip_via_proxy']) . '</a>';
                    $out .= '&#160;[<a href="' . $homeurl . '/admin/index.php?act=ip_whois&amp;ip=' . long2ip($user['ip_via_proxy']) . '">?</a>]';
                } elseif ($this->user->rights) {
                    $out .= '<a href="' . $homeurl . '/admin/index.php?act=search_ip&amp;ip=' . $ip . $hist . '">' . $ip . '</a>';
                    $out .= '&#160;[<a href="' . $homeurl . '/admin/index.php?act=ip_whois&amp;ip=' . $ip . '">?</a>]';
                } else {
                    $out .= $ip . $iphist;
                }

                if (isset($arg['iphist'])) {
                    $iptotal = $this->db->query("SELECT COUNT(*) FROM `cms_users_iphistory` WHERE `user_id` = '" . $user['id'] . "'")->fetchColumn();
                    $out .= '<div><span class="gray">' . _t('IP History', 'system') . ':</span> <a href="' . $homeurl . '/profile/?act=ip&amp;user=' . $user['id'] . '">[' . $iptotal . ']</a></div>';
                }

                $out .= '</div>';
            }

            if (isset($arg['footer'])) {
                $out .= $arg['footer'];
            }
            $out .= '</div>';
        }

        return $out;
    }

    /**
     * Получение флага для выбранной локали
     *
     * @param string $locale
     * @return string
     */
    public function getFlag($locale)
    {
        $file = ROOT_PATH . 'system' . DIRECTORY_SEPARATOR . 'locale' . DIRECTORY_SEPARATOR . $locale . DIRECTORY_SEPARATOR . 'lng.png';
        $flag = is_file($file) ? 'data:image/png;base64,' . base64_encode(file_get_contents($file)) : false;

        return $flag !== false ? '<img src="' . $flag . '" style="margin-right: 8px; vertical-align: middle">' : '';
    }

    /**
     * @return string
     */
    public function getSkin()
    {
        return $this->user->isValid() && !empty($this->userConfig->skin)
            ? $this->userConfig->skin
            : $this->config->skindef;
    }

    /**
     * Получаем данные пользователя
     *
     * @param int $id Идентификатор пользователя
     * @return array|bool
     */
    public function getUser($id = 0)
    {
        if ($id && $id != $this->user->id) {
            $req = $this->db->query("SELECT * FROM `users` WHERE `id` = '$id'");

            if ($req->rowCount()) {
                return $req->fetch();
            } else {
                return false;
            }
        } else {
            return $this->user;
        }
    }

    /**
     * @param string $name
     * @param array  $args
     * @return bool|string
     */
    public function image($name, array $args = [])
    {
        $homeurl = $this->config['homeurl'];

        if (is_file(ROOT_PATH . 'theme/' . $this->getSkin() . '/images/' . $name)) {
            $src = $homeurl . '/theme/' . $this->getSkin() . '/images/' . $name;
        } elseif (is_file(ROOT_PATH . 'images/' . $name)) {
            $src = $homeurl . '/images/' . $name;
        } else {
            return false;
        }

        return '<img src="' . $src . '" alt="' . (isset($args['alt']) ? $args['alt'] : '') . '"' .
            (isset($args['width']) ? ' width="' . $args['width'] . '"' : '') .
            (isset($args['height']) ? ' height="' . $args['height'] . '"' : '') .
            ' class="' . (isset($args['class']) ? $args['class'] : 'icon') . '"/>';
    }




    /**
     * Mod Logo Changer v 0.2
     * Mod By Aan Gabreil Elfha Gymkhana
     * CopyRight CyberGhostNet
     * aan.mukaror@gmail.com
     */
      public function LogoUrl() {
         $homeurl = $this->config['homeurl'];
         $varLogo = $this->config['logourl'];
         if (file_exists(ROOT_PATH . 'images/logo/' . $this->config['logourl'])) {
            $var = $homeurl . '/images/logo/' . $varLogo;
             return $var;
          } else {
        $var = $homeurl . '/images/logo.gif';
         return $var;
         }
       }

    /**
     * Форматирование имени файла
     *
     * @param string $name
     *
     * @return string
     */
    public function format($name)
    {
        $f1 = strrpos($name, ".");
        $f2 = substr($name, $f1 + 1, 999);
        $fname = strtolower($f2);

        return $fname;
    }

    /**
     * Проверка на игнор у получателя
     *
     * @param $id
     * @return bool
     */
    public function isIgnor($id)
    {
        static $user_id = null;
        static $return = false;

        if (!$this->user->isValid() && !$id) {
            return false;
        }

        if (is_null($user_id) || $id != $user_id) {
            $user_id = $id;
            $req = $this->db->query("SELECT * FROM `cms_contact` WHERE `user_id` = '$id' AND `from_id` = " . $this->user->id);

            if ($req->rowCount()) {
                $res = $req->fetch();
                if ($res['ban'] == 1) {
                    $return = true;
                }
            }
        }

        return $return;
    }

    /**
     * Транслитерация с Русского в латиницу
     *
     * @param string $str
     * @return string
     */
    public function rusLat($str)
    {
        $replace = [
            'а' => 'a',
            'б' => 'b',
            'в' => 'v',
            'г' => 'g',
            'д' => 'd',
            'е' => 'e',
            'ё' => 'e',
            'ж' => 'j',
            'з' => 'z',
            'и' => 'i',
            'й' => 'i',
            'к' => 'k',
            'л' => 'l',
            'м' => 'm',
            'н' => 'n',
            'о' => 'o',
            'п' => 'p',
            'р' => 'r',
            'с' => 's',
            'т' => 't',
            'у' => 'u',
            'ф' => 'f',
            'х' => 'h',
            'ц' => 'c',
            'ч' => 'ch',
            'ш' => 'sh',
            'щ' => 'sch',
            'ъ' => "",
            'ы' => 'y',
            'ь' => "",
            'э' => 'ye',
            'ю' => 'yu',
            'я' => 'ya',
        ];

        return strtr(mb_strtolower($str), $replace);
    }

    /**
     * Обработка смайлов
     *
     * @param string $str
     * @param bool   $adm
     * @return string
     */
    public function smilies($str, $adm = false)
    {
        static $smiliesCache = [];

        if (empty($smiliesCache)) {
            $file = ROOT_PATH . 'files/cache/smileys.dat';

            if (file_exists($file) && ($smileys = file_get_contents($file)) !== false) {
                $smiliesCache = unserialize($smileys);

                return strtr($str, ($adm ? array_merge($smiliesCache['usr'], $smiliesCache['adm']) : $smiliesCache['usr']));
            } else {
                return $str;
            }
        } else {
            return strtr($str, ($adm ? array_merge($smiliesCache['usr'], $smiliesCache['adm']) : $smiliesCache['usr']));
        }
    }

    /**
     * Функция пересчета на дни, или часы
     *
     * @param int $var
     * @return bool|string
     */
    public function timecount($var)
    {
        if ($var < 0) {
            $var = 0;
        }

        $day = ceil($var / 86400);

        return $var >= 86400
            ? $day . ' ' . _p('Day', 'Days', $day, 'system')
            : date("G:i:s", mktime(0, 0, $var));
    }

    // Транслитерация текста
    public function trans($str)
    {
        $replace = [
            'a'  => 'а',
            'b'  => 'б',
            'v'  => 'в',
            'g'  => 'г',
            'd'  => 'д',
            'e'  => 'е',
            'yo' => 'ё',
            'zh' => 'ж',
            'z'  => 'з',
            'i'  => 'и',
            'j'  => 'й',
            'k'  => 'к',
            'l'  => 'л',
            'm'  => 'м',
            'n'  => 'н',
            'o'  => 'о',
            'p'  => 'п',
            'r'  => 'р',
            's'  => 'с',
            't'  => 'т',
            'u'  => 'у',
            'f'  => 'ф',
            'h'  => 'х',
            'c'  => 'ц',
            'ch' => 'ч',
            'w'  => 'ш',
            'sh' => 'щ',
            'q'  => 'ъ',
            'y'  => 'ы',
            'x'  => 'э',
            'yu' => 'ю',
            'ya' => 'я',
            'A'  => 'А',
            'B'  => 'Б',
            'V'  => 'В',
            'G'  => 'Г',
            'D'  => 'Д',
            'E'  => 'Е',
            'YO' => 'Ё',
            'ZH' => 'Ж',
            'Z'  => 'З',
            'I'  => 'И',
            'J'  => 'Й',
            'K'  => 'К',
            'L'  => 'Л',
            'M'  => 'М',
            'N'  => 'Н',
            'O'  => 'О',
            'P'  => 'П',
            'R'  => 'Р',
            'S'  => 'С',
            'T'  => 'Т',
            'U'  => 'У',
            'F'  => 'Ф',
            'H'  => 'Х',
            'C'  => 'Ц',
            'CH' => 'Ч',
            'W'  => 'Ш',
            'SH' => 'Щ',
            'Q'  => 'Ъ',
            'Y'  => 'Ы',
            'X'  => 'Э',
            'YU' => 'Ю',
            'YA' => 'Я',
        ];

        return strtr($str, $replace);
    }
    /*
    -----------------------------------------------------------------
    Старая функция проверки переменных.
    В новых разработках не применять!
    Вместо данной функции использовать checkin()
    -----------------------------------------------------------------
    */
    public function check($str)
    {
        $str = htmlentities(trim($str), ENT_QUOTES, 'UTF-8');
        $str = $this->checkin($str);
        $str = nl2br($str);
        $str = $this->$db->quote($str);

        return $str;
    }

}
