<?php

ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

$ip = getenv("REMOTE_ADDR");

require __DIR__ . '/settings.php';

$me = 0;
if (!empty($_COOKIE['kuka']) && $_COOKIE['kuka']==$kuka)
{
 $user = '[Я]';
 $me = 1;
}
//else if ($ip==file_get_contents("../mixlinks.ru/ip.php")) $user = '[Я]';
else $user = $ip;

if($me && 0)
{
 foreach ($_GET as $key => $value)
 {
  echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$key => $value<br>";
 }
}
//exit;


$time_start = microtime(1);
$os = getenv("HTTP_USER_AGENT"); $os_low = strtolower($os);

$alert = ''; 
$all_errs = '';
$use_skidka = 0;
$tov_na_str = 17; 

$err_get = '-';
$N="\n";
$l_1=0; $l_2=0;

$spage='index'; 
$desk_null = false; 
$head_loc='-';
$html = '';


set_error_handler('errors'); 
function errors($errno, $errmsg, $filename, $linenum)
{
 global $all_errs, $main_url;
 $errors = array(E_NOTICE, E_STRICT, E_WARNING);

 $all_errs .= "L-$linenum. №$errno: $errmsg<br><a href=https://$main_url".getenv("REQUEST_URI")." target=_blank>".getenv("REQUEST_URI")."</a><br><br>\r\n";
}




// получить ссылку оплаты товара
function getBuyLink($buy_id, $agent_id, $main_url, $lang)
{
 if (empty($agent_id))
 {
  $agent_id = 203028;
 }

 $location = "https://www.oplata.info/asp/pay_wm.asp?id_d=".$buy_id.
 "&id_po=0".
 "&cart_uid=".
 "&ai=".$agent_id.
 "&ae=".
 "&curr=ATM".
 "&failpage=https://".$main_url."/".$lang."/opisanie/".$buy_id."/".$agent_id.".shtml";

 return $location;
}


// генерация SEO URL (с авто-fallback)
function makeUrl($str)
{
 global $buf_name_default_eng;

 // убираем пробелы
 $str = trim((string)$str);

 // если пусто — берём дефолт
 if ($str === '')
 {
  $str = $buf_name_default_eng ?: 'product';
 }

 // нижний регистр
 $str = mb_strtolower($str, 'UTF-8');

 // всё лишнее → _
 $str = preg_replace('/[^a-z0-9]+/u', '_', $str);

 // схлопываем ___
 $str = preg_replace('/_+/', '_', $str);

 // обрезаем _
 $str = trim($str, '_');

 // на всякий
 if ($str === '')
 {
  $str = $buf_name_default_eng ?: 'product';
 }

 return $str;
}



// получить 0 или 1
function getBool($key, $default = 0)
{
 if (isset($_GET[$key]))
 {
  return ($_GET[$key] == 1) ? 1 : 0;
 }

 if (isset($_COOKIE[$key]))
 {
  return ($_COOKIE[$key] == 1) ? 1 : 0;
 }

 return $default;
}



// функция генерации ссылки с учётом поиска
function getPageUrl($page, $place, $tovar_type, $site, $q = '')
{
 // базовая ссылка
 $url = $place.'_'.$tovar_type.'_'.$site.'_'.$page.".shtml";  

 if (!empty($q))
 {
  // защита от пробелов и спецсимволов
  $q_encoded = urlencode($q);

  // если есть поисковый запрос — добавляем GET
  $url .= "?q=".$q_encoded;
 }

 return $url;
}



if ($use_koef)
{
 if (isset($_GET['koef'])) 
 { 
  $koef_on = $_GET['koef'];
  setcookie('koef', $koef_on, time() + 60*60*24*30*12*20, "/");
  //if ($me) echo "<center><font color=#666666>#1 isset(_GET['koef'] koef=$koef_on</font>";
  //exit;
 }
 else 
 {
  if (isset($_COOKIE['koef'])) 
  {
   $koef_on = $_COOKIE['koef'];
   //if ($me) echo "<center><font color=#666666>#2 isset(_COOKIE['koef'] koef=$koef_on</font>";
   //exit;
  }
  else 
  {
   $koef_on = 1;
   setcookie('koef', $koef_on, time() + 60*60*24*30*12*20, "/");
   //if ($me) echo "<center><font color=#666666>#3 задаём тут =1 koef=$koef_on</font>";
   //exit;
  }
 }
}
else
{
 $koef_on = 0;
}

if ($koef_on) { $place = 'vygodnye'; $alt_place = 'deshyovye'; } 
else          { $place = 'deshyovye'; $alt_place = 'vygodnye'; }














// доступные языки
$allowed_langs = ['rus','eng','ukr','deu','chi'];

// нормализация языка
function normalizeLang($lang, $allowed_langs)
{
 if (in_array($lang, $allowed_langs))
 {
  return $lang;
 }

 return 'rus';
}

// 1. приоритет: GET
if (isset($_GET['lang']))
{
 $lang = normalizeLang($_GET['lang'], $allowed_langs);
 setcookie('lang', $lang, time() + 60*60*24*365*20, "/");
}

// 2. потом COOKIE
else if (isset($_COOKIE['lang']))
{
 $lang = normalizeLang($_COOKIE['lang'], $allowed_langs);
}

// 3. автоопределение
else
{
 $map = [
  'ru' => 'rus',
  'en' => 'eng',
  'de' => 'deu',
  'uk' => 'ukr',
  'zh' => 'chi'
 ];

 $user_lang = 'ru'; // дефолт

 if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE']))
 {
  $user_lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
 }

 $lang = $map[$user_lang] ?? 'eng';

 setcookie('lang', $lang, time() + 60*60*24*365*20, "/");
}






// ВАЛЮТА, ЯЗЫК И СИМВОЛ

$lang_config = [
 'rus' => ['currency' => 'rur', 'symbol' => '&#8381;'], // ₽
 'ukr' => ['currency' => 'uah', 'symbol' => '&#8372;'], // ₴
 'eng' => ['currency' => 'usd', 'symbol' => '$'],
 'chi' => ['currency' => 'usd', 'symbol' => '$'],
 'deu' => ['currency' => 'eur', 'symbol' => '&euro;']   // €
];

$sel_valuta = $lang_config[$lang]['currency'] ?? 'rur';
$val_z      = $lang_config[$lang]['symbol']   ?? '&#8381;';

// поле для запроса в БД
$price_field = 'price_' . $sel_valuta;










 


// получаем параметры (сразу чистим)
$buy_id      = isset($_GET['buy'])      ? (int)$_GET['buy']      : 0;
$agent_id    = isset($_GET['agent_id']) ? (int)$_GET['agent_id'] : 203028;
$opisanie_id = isset($_GET['opisanie']) ? (int)$_GET['opisanie'] : 0;


// ПОКУПКА
if ($buy_id > 0)
{
 // --- защита от ботов ---
 if (strpos($os_low, "bot") === false && strpos($os_low, "megaindex") === false)
 {
  $location = getBuyLink($buy_id, $agent_id, $main_url, $lang);

  header('Referrer-Policy: no-referrer');
  header('Location: ' . $location, true, 302);
  exit;
 }

 $head_loc = "buy";
 $spage = "buy";
}


// ОПИСАНИЕ
else if ($opisanie_id > 0)
{
 $spage = "opisanie";
}


// старые ссылки ?opisanie= → редирект
if (isset($_GET['opisanie']) && (int)$_GET['opisanie'] > 0 && strpos($_SERVER['REQUEST_URI'], '/opisanie/') === false)
{
    $url = 'https://'.$main_url.'/rus/'.$place.'_'.$tovar_type.'_'.$site.'_'.$select_page.'.shtml';

    $all_errs .= 'c описания перекидываем ('.(int)$_GET['opisanie'].')<br>';

    file_put_contents('opisanie_redirect.log',
        date('c').' '.$_SERVER['REQUEST_URI']." -> ".$url."\n",
        FILE_APPEND
         );

    header('Location: '.$url, true, 301);
    exit;
}

 






 


// определяем мобильность
$user_agent = strtolower($_SERVER['HTTP_USER_AGENT'] ?? '');

function isMobile($ua)
{
 return preg_match('/mobile|android|iphone|ipad|ipod|touch/i', $ua);
}

// приоритет: GET
$mesto = $_GET['m'] ?? '';

if ($mesto === 'mobile' || isMobile($user_agent))
{
 $mesto = 'mobile';

 $kol1 = '10%';
 $kol2 = '80%';
 $kol3 = '10%';
 $w_price = '9%';

 $mesto_mail = 'mobile';
}
else
{
 $kol1 = '20%';
 $kol2 = '60%';
 $kol3 = '20%';
 $w_price = '*';

 $mesto_mail = $mesto;
}

$is_mobile = ($mesto === 'mobile') || isMobile($user_agent);
 
 





//  ОТОБРАЖАТЬ ЛИ СПИСОК ПРОИЗВОЛЬНЫХ
$use_proizv = getBool('pr');

// всегда синхронизируем cookie
setcookie('pr', $use_proizv, time() + 60*60*24*365*20, "/");
 
 





 
//  УСТАНОВКА last_modified

$ts = floor(time() / 3600) * 3600;

header("Last-Modified: " . gmdate("D, d M Y H:i:s", $ts) . " GMT");

if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']))
{
 if (strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $ts)
 {
  header("HTTP/1.1 304 Not Modified");
  exit;
 }
}




 
// no cache
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Cache-Control: post-check=0,pre-check=0", false);
header("Cache-Control: max-age=0", false);
header("Pragma: no-cache");
//
 
 
 
 
if (!headers_sent()) {header('Content-Type: text/html; charset=utf-8');}

 
/*
if (!isset($_COOKIE['ref']))
{
 setcookie('ref', 'ref', time() + 60*60*24*30*3, "/");
 $ref=true;
}
else $ref=false;
*/
 
/*if(isset($_GET['fr'])) $from=$_GET['fr']; else $from="";
if ($from=='ml' or $from=='sk' or $from=='vv' or $from=='pm' or $from=='iz'
    or $from=='gl' or $from=='fe' or $from=='f4' or $from=='tl') $ref=false;
*/
 





include '../mixlinks.ru/counter/counter.php';

include "langs/$lang.php";









//  О П Р Е Д Е Л Е Н И Е   С Т Р А Н И Ц Ы 
 
// --------------------------------------------------
// поиск
// --------------------------------------------------
$search = trim($_GET['q'] ?? '');
$search_key = mb_strtolower($search);


if(isset($_GET['page']) && $search == '')
{
 $select_page = $_GET['page'];
 if ($select_page == 0)
 {
  if (!isset($_COOKIE['page']))
  {
   $select_page = 1;
   setcookie("page", 1, time() + 60*60*24*30*12*20, "/");
  }
  else
  {
  $select_page = $_COOKIE['page'];
  }
 }
 if (headers_sent()) $all_errs .= "L-". __LINE__ .": Заголовки уже ушли<br>";
 if ($search == '') setcookie("page", $select_page, time() + 60*60*24*30*12*20, "/");
}
else
{
 if (!isset($_COOKIE['page']))
 {
  $select_page = 1;
 setcookie("page", 1, time() + 60*60*24*30*12*20, "/");
 }
 else
 {
  $select_page = $_COOKIE['page'];
 }
}

if(isset($_POST['input_page']))
{
 $select_page = $_POST['input_page'];
}






// --------------------------------------------------
// безопасно читаем cookie search_pages
// --------------------------------------------------
$search_pages = [];

if (!empty($_COOKIE['search_pages']))
{
 $decoded = json_decode($_COOKIE['search_pages'], true);
 if (is_array($decoded))
 {
  $search_pages = $decoded;
 }
}

// --------------------------------------------------
// ВАЖНЫЙ ФЛАГ:
// true = пришли из каталога (или новый поиск)
// false = обычная пагинация поиска
// --------------------------------------------------
$is_new_search = ($search !== '' && $_GET['page']==0);

/*
if ($is_new_search)
{
 echo '### is_new_search ###';
}
else
{
 echo "$search - ".$_GET['page'].'<br>';
}
*/

// --------------------------------------------------
// определяем страницу
// --------------------------------------------------
if ($search !== '')
{
 // если это новый поиск — берём куку (если есть)
 if ($is_new_search && isset($search_pages[$search_key]))
 {
  $select_page = (int)$search_pages[$search_key];
 }
 else
 {
  // иначе берём page как есть (пагинация)
  $select_page = (int)($_GET['page'] ?? 1);
 }
}

// защита
if ($select_page < 1)
{
 $select_page = 1;
}

// --------------------------------------------------
// сохраняем ТОЛЬКО если это не обычная пагинация
// --------------------------------------------------
if ($search !== '')
{
 $search_pages[$search_key] = $select_page;

 setcookie(
  'search_pages',
  json_encode($search_pages, JSON_UNESCAPED_UNICODE),
  time() + 60*60*24*365,
  "/"
 );
}

// --------------------------------------------------
// параметры пагинации
// --------------------------------------------------
$page  = $select_page;
$limit = (int)$tov_na_str;
$offset = ($page - 1) * $limit;








if (strpos(getenv("REQUEST_URI"), 'shtml')===false) // если в ссылке нет shtml
{
 //if ($koef_on) $place = 'vygodnye'; else $place = 'deshyovye';
 header('Location: https://'.$main_url.'/'.$lang.'/'.$place.'_'.$tovar_type.'_'.$site.'_'.$select_page.'.shtml');
}
else // если не выбран язык
{
 //if ($koef_on) $place = 'vygodnye'; else $place = 'deshyovye';
 if (strpos(getenv("REQUEST_URI"), 'rus')===false
 and strpos(getenv("REQUEST_URI"), 'eng')===false
 and strpos(getenv("REQUEST_URI"), 'deu')===false
 and strpos(getenv("REQUEST_URI"), 'chi')===false
 and strpos(getenv("REQUEST_URI"), 'ukr')===false)
  header('Location: '.'https://'.$main_url.'/rus/'.$place.'_'.$tovar_type.'_'.$site.'_1.shtml'); 
}










//setcookie('koef', '', time() - 3600, '/');
//setcookie('page_before_search', '', time() - 3600, '/');
//setcookie('pr', '', time() - 3600, '/');

// СМОТРИМ ВСЕ КУКИ
if ($me && FALSE)
{
 foreach ($_COOKIE as $key => $value)
 {
  echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$key => $value<br>";
 }
}




// --------------------------------------------------
// подключение к SQLite
// --------------------------------------------------
$db = new SQLite3(__DIR__ . '/products.db');




if ($spage == 'index')
{
 // базовый WHERE (динамический)
 $where = "WHERE is_active = 1";

 // фильтр по цене (только если > 0)
 if ($filter_min_price > 0)
 {
  $where .= " AND price_rur >= :min_price";
 }

 // фильтр по комиссии (только если > 0)
 if ($filter_min_comis > 0)
 {
  $where .= " AND max_commiss >= :min_comis";
 }

 // поиск
 if ($search !== '')
 {
  $where .= " AND (
   name LIKE :search COLLATE NOCASE
   OR
   name_eng LIKE :search COLLATE NOCASE
  )";
 }

 // 1. быстрый COUNT (использует индекс)
 $count_sql = "
  SELECT COUNT(*)
  FROM products
  $where
 ";

 $stmt_count = $db->prepare($count_sql);

 if ($stmt_count === false)
 {
    die("SQL ERROR COUNT: ".$db->lastErrorMsg()."<br><pre>".$count_sql."</pre>");
 }

 // бинды
 if ($filter_min_price > 0)
 {
  $stmt_count->bindValue(':min_price', $filter_min_price, SQLITE3_INTEGER);
 }

 if ($filter_min_comis > 0)
 {
  $stmt_count->bindValue(':min_comis', $filter_min_comis, SQLITE3_INTEGER);
 }

 if ($search !== '')
 {
  $stmt_count->bindValue(':search', '%'.$search.'%', SQLITE3_TEXT);
 }

 $res = $stmt_count->execute();

 if ($res === false)
 {
    die("EXECUTE ERROR COUNT: ".$db->lastErrorMsg());
 }

 $total_items = (int)$res->fetchArray(SQLITE3_NUM)[0];

 // страницы
 $total_pages = max(1, ceil($total_items / $limit));

 // 2. получаем данные (БЕЗ COUNT OVER)

 switch ($lang)
 {
  case 'rus':
  case 'ukr':
   $name_field = 'name';
  break;

  default:
   $name_field = 'name_eng';
 }

 $data_sql = "
  SELECT 
   id,
   $name_field AS name,
   name_eng AS name_url,
   section_id,
   seller_name,
   max_commiss,
   $price_field AS price,
   partner_commiss_agent_id AS agent_id
  FROM products
  $where
  ORDER BY max_commiss DESC, id DESC
  LIMIT :limit OFFSET :offset
 ";

 $stmt = $db->prepare($data_sql);

 // бинды
 if ($filter_min_price > 0)
 {
  $stmt->bindValue(':min_price', $filter_min_price, SQLITE3_INTEGER);
 }

 if ($filter_min_comis > 0)
 {
  $stmt->bindValue(':min_comis', $filter_min_comis, SQLITE3_INTEGER);
 }

 if ($search !== '')
 {
  $stmt->bindValue(':search', '%'.$search.'%', SQLITE3_TEXT);
 }

 // пагинация
 $stmt->bindValue(':limit', $limit, SQLITE3_INTEGER);
 $stmt->bindValue(':offset', $offset, SQLITE3_INTEGER);

 // выполнение
 $result = $stmt->execute();

 // --------------------------------------------------
 // собираем строки
 // --------------------------------------------------
 $rows = [];

 while ($row = $result->fetchArray(SQLITE3_ASSOC))
 {
  $rows[] = $row;
 }

}


if ($head_loc=="-")
{
 $lang_iso = [
  'rus' => 'ru',
  'ukr' => 'uk',
  'eng' => 'en',
  'deu' => 'de',
  'chi' => 'zh'
 ][$lang] ?? 'en';

 $html = 
 "<meta NAME='Keywords' CONTENT='".$meta_keys."'>
  <meta charset='utf-8'>
  <meta name='language' content='".$lang_iso."'>
  <meta name='format-detection' content='telephone=no'>
  <meta name='yandex-verification' content='".$yandex_verification."'>

  <link rel='SHORTCUT ICON' href='https://$main_url/img/favicon.ico' type='image/png'>
 
 <!--script type='text/javascript'>
 document.ondragstart = noselect; ". // запрет на перетаскивание 
 "document.onselectstart = noselect; ". // запрет на выделение элементов страницы 
 "document.oncontextmenu = noselect; ". // запрет на выведение контекстного меню 
 "function noselect() {return false;} 
 </script-->
 ";
 $html .= file_get_contents("style.php");
 $html .= "
 </head>

 <body>
 <!--div class='noselect'-->
 ";
}

 
/*if ($user!="[Я]") $html .= '<!-- Yandex.Metrika counter --><script type="text/javascript">(function (d, w, c) { (w[c] = w[c] || []).push(function() { try { w.yaCounter'.$metrika_id.' = new Ya.Metrika({id:'.$metrika_id.', webvisor:true, clickmap:true, trackLinks:true, accurateTrackBounce:true}); } catch(e) { } }); var n = d.getElementsByTagName("script")[0], s = d.createElement("script"), f = function () { n.parentNode.insertBefore(s, n); }; s.type = "text/javascript"; s.async = true; s.src = (d.location.protocol == "https:" ? "https:" : "http:") + "//mc.yandex.ru/metrika/watch.js"; if (w.opera == "[object Opera]") { d.addEventListener("DOMContentLoaded", f, false); } else { f(); } })(document, window, "yandex_metrika_callbacks");</script><noscript><div><img src="//mc.yandex.ru/watch/'.$metrika_id.'" style="position:absolute; left:-9999px;" alt="" /></div></noscript><!-- /Yandex.Metrika counter -->';*/

if ($user!="[Я]") $html .= '
<!-- Yandex.Metrika counter -->
<script type="text/javascript">
    (function(m,e,t,r,i,k,a){
        m[i]=m[i]||function(){(m[i].a=m[i].a||[]).push(arguments)};
        m[i].l=1*new Date();
        for (var j = 0; j < document.scripts.length; j++) {if (document.scripts[j].src === r) { return; }}
        k=e.createElement(t),a=e.getElementsByTagName(t)[0],k.async=1,k.src=r,a.parentNode.insertBefore(k,a)
    })(window, document,\'script\',\'https://mc.yandex.ru/metrika/tag.js?id='.$metrika_id.'\', \'ym\');

    ym('.$metrika_id.', \'init\', {ssr:true, clickmap:true, referrer: document.referrer, url: location.href, accurateTrackBounce:true, trackLinks:true});
</script>
<noscript><div><img src="https://mc.yandex.ru/watch/'.$metrika_id.'" style="position:absolute; left:-9999px;" alt="" /></div></noscript>
<!-- /Yandex.Metrika counter -->


';





if ($mesto!="mobile") 
{
 $html .= "
 <table width='100%' height='100%' border='0' bordercolor='blue' cellspacing='5' cellpadding='0'>
 <tr height='82'>
 <td width='".$kol1."' valign='center' align='center' style='background:url(st_img/bg_sh_mix.png) repeat-x;'>".$title_left."
 </td>
 <td width='".$kol2."' align='CENTER' style='background:url(st_img/bg_sh_mix.png) repeat-x;' NOWRAP>";
 if (!$is_bot) $html .= "<a rel='nofollow' href='https://".$main_url."/$lang/".$place."_".$tovar_type."_".$site."_1.shtml'>";
 $html .= "<h1>$title_header</h1>";
 if (!$is_bot) $html .= "</a>";


 $html .= "</td>
 <td width='".$kol3."' valign='top' align='right' style='background:url(st_img/bg_sh_mix.png) repeat-x;padding:4;'>\r\n";
 
 $html .= '
 <noscript>
 <a href="'.str_replace($lang,'rus',getenv("REQUEST_URI")).'"><img width="29" height="16" src="st_img/russia.gif"></a>&nbsp;&nbsp;<a href="'.str_replace($lang,'ukr',getenv("REQUEST_URI")).'"><img width="29" height="16" src="st_img/ukraina.gif"></a>&nbsp;&nbsp;<a href="'.str_replace($lang,'eng',getenv("REQUEST_URI")).'"><img width="29" height="16" src="st_img/usa.gif"></a>&nbsp;&nbsp;<a href="'.str_replace($lang,'deu',getenv("REQUEST_URI")).'"><img width="29" height="16" src="st_img/germany.gif"></a>
 </noscript>';

 $request = getenv("REQUEST_URI");

 // режем только первый сегмент /lang/
 $parts = explode('/', trim($request, '/'));

 if (isset($parts[1]))
 {
  $lang_url = '';

  if (count($parts) > 1)
  {
   // берём всё кроме первого элемента (языка)
   $tail = array_slice($parts, 1);

   // защита от повторного языка внутри URL
   if (in_array($tail[0], ['rus','eng','ukr','deu','chi']))
   {
    array_shift($tail);
   }

   $lang_url = '/' . implode('/', $tail);
  }
 }
 else
 {
  $lang_url = '';
 }

 $html .= "
 <script>
 document.write('<select id=lang><option>Language</option><option value=rus>Русский</option><option value=ukr>Український</option><option value=eng>English</option><option value=deu>Deutsch</option><option value=chi>中文</option></select>');
 </script>

 <script type=text/javascript>
 var lang = document.getElementById('lang');
 lang.onchange = function()
 { 
  //window.location = 'https://$main_url/' + lang.options[lang.options.selectedIndex].value + '$lang_url';
  window.location = 'https://$main_url/' + lang.value + '$lang_url';
 }
 </script>
 
  </td>
 </tr>
 <tr height='*' style='background:white;' valign='top'>";
}
else
{
 $html .= "
 <table width='100%' height='100%' border='0' bordercolor='blue' cellspacing='5' cellpadding='0'>
 <tr height='82'>
 <td colspan='3' width='98%' align='CENTER' style='background:url(st_img/bg_sh_mix.png) repeat-x;' NOWRAP>";
 if (!$is_bot) $html .= "<a rel='nofollow' href='https://".$main_url."/$lang/".$place."_".$tovar_type."_".$site."_1.shtml'>";
 $html .= "<h1>$title_header</h1>";
 if (!$is_bot) $html .= "</a>";
 $html .= "</td>
 </tr>
 <tr height='*' style='background:white;' valign='top'>\r\n";
}
 
/*style='background: #fff url(st_img/main_bg.gif) repeat-x;'*/
 
 
 
if ($mesto!="mobile") 
{
 $html .= "  <td width='".$kol1."' valign='top' style='padding-left:15px;padding-right:15px;padding-top:15px;text-align: justify;font-weight:600;'><font class='info'>".$info_left."</font></td>\r\n\r\n";
}
else
{ 
 $html .= "  <td colspan='3' width='".$kol2."' align='CENTER'>";
}

if ($mesto!="mobile") 
{
 $html .= "   <td width='".$kol2."' align='CENTER' valign='top' style='padding-left:15px;padding-right:15px;padding-top:6px;text-align:justify;'>\r\n\r\n";
}



//if ($user=="[Я]") $html .= "valuta=".$sel_valuta;



if ($spage == 'index')
{
 require __DIR__ . '/includes/page_index.php';
}
 
 


if ($spage == 'opisanie')
{
 require __DIR__ . '/includes/page_opisanie.php';
}

echo '</td>';




$time_load = round(microtime(1)-$time_start,4);

if ($all_errs!='' or $alert!='')
{
 if (!function_exists('send_mail')) include ('../mixlinks.ru/php/mail.php');

 if ($alert!='')
 {
  send_mail('', "Уведомление с сайта $site", $user." ".$os."<br>".$alert."<br>time_load: $time_load<br>lang_str_alert: $lang_str_alert", 'Лиза', 'Лиза', 0);
 }

 if ($all_errs!='')
 {
  send_mail('', "Ошибка на сайте $site", "<table><tr><td style='border: 1px solid #b3b3b3;'>IP-адрес:</td><td colspan=3 style='border: 1px solid #b3b3b3;'>".$user."</td></tr><tr><td style='border: 1px solid #b3b3b3;'>User-agent:</td><td colspan=3 style='border: 1px solid #b3b3b3;'>".$os."</td></tr><tr><td style='border: 0px solid #b3b3b3;' colspan=4>&nbsp;</td></tr>".$all_errs.'</table>'."<br>time_load: $time_load<br>lang_str_alert: $lang_str_alert", 'Лиза', 'Лиза', 0);
 }

}





if ($mesto!="mobile")
{
 echo "  <td width='".$kol3."' valign='top' style='padding-left:15px;padding-right:15px;padding-top:15px;text-align: justify;font-weight:600;'><font class='info'>".$info_rightside."</font></td>";
}

$time_load = round(microtime(1)-$time_start,4);

?>

 </tr>
  
 <!-- // СТРОКА ПОДВАЛА -->
 
 <tr height='30'>
  <td colspan='3' width='100%' style='padding-left:0px;padding-right:0px;padding-top:0px;text-align: left;font-weight:600;'>
   <table width='100%' height='100%' border='0' bordercolor='red' cellspacing='0' cellpadding='0'>
    <tr height='30'>
     <td width='50%' style='padding-left:15px;padding-right:15px;padding-top:0px;text-align: left;font-weight:600;'><font class='copyr'></font></td>
     <td width='50%' style='padding-left:15px;padding-right:15px;padding-top:0px;text-align: right;font-weight:600;'><font class='copyr'><!--noindex--><font color=#bfbfbf>[<?php if (isset($com_tovars)) echo $com_tovars; echo " ".$time_load; echo " ".$sel_valuta; ?>]</font>&nbsp;&nbsp;&nbsp;<!--/noindex-->@ <?=$main_url?> 2009–<?=date("Y",time());?></font></td>
    </tr>
   </table>
  </td>
 </tr>

 
</table>
</div>
</body>
</html>
