1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
183.
184.
185.
186.
187.
188.
189.
190.
191.
192.
193.
194.
195.
196.
197.
198.
199.
200.
201.
202.
203.
204.
205.
206.
207.
208.
209.
210.
211.
212.
213.
214.
215.
216.
217.
218.
219.
220.
221.
222.
223.
224.
225.
226.
227.
228.
229.
230.
231.
232.
233.
234.
235.
236.
237.
238.
239.
240.
241.
242.
243.
244.
245.
246.
247.
248.
249.
250.
251.
252.
253.
254.
255.
256.
257.
258.
259.
260.
261.
262.
263.
264.
265.
266.
267.
268.
269.
270.
271.
272.
273.
274.
275.
276.
277.
278.
279.
280.
281.
282.
283.
284.
285.
286.
287.
288.
289.
290.
291.
292.
293.
294.
295.
296.
297.
298.
299.
300.
301.
302.
303.
304.
305.
306.
307.
308.
309.
310.
311.
312.
313.
314.
315.
316.
317.
318.
319.
320.
321.
322.
323.
324.
325.
326.
327.
328.
329.
330.
331.
332.
333.
334.
335.
336.
337.
338.
339.
340.
341.
342.
343.
344.
345.
346.
347.
348.
349.
350.
351.
352.
353.
354.
355.
356.
357.
358.
359.
360.
361.
362.
363.
364.
365.
366.
367.
368.
369.
370.
371.
372.
373.
374.
375.
376.
377.
378.
379.
380.
381.
382.
383.
384.
385.
386.
387.
388.
389.
390.
391.
392.
393.
394.
395.
396.
397.
398.
399.
400.
401.
402.
403.
404.
405.
406.
407.
408.
409.
410.
411.
412.
413.
414.
415.
416.
417.
418.
419.
420.
421.
422.
423.
424.
425.
426.
427.
428.
429.
430.
431.
432.
433.
434.
435.
436.
437.
438.
439.
440.
441.
442.
443.
444.
445.
446.
447.
448.
449.
450.
451.
452.
453.
454.
455.
456.
457.
458.
459.
460.
461.
462.
463.
464.
465.
466.
467.
468.
469.
470.
471.
472.
473.
474.
475.
476.
477.
478.
479.
480.
481.
482.
483.
484.
485.
486.
487.
488.
489.
490.
491.
492.
493.
494.
495.
496.
497.
498.
499.
500.
501.
502.
503.
504.
505.
506.
507.
508.
509.
510.
511.
512.
513.
514.
515.
516.
517.
518.
519.
520.
521.
522.
523.
524.
525.
526.
527.
528.
529.
530.
531.
532.
533.
534.
535.
536.
537.
538.
539.
540.
541.
542.
543.
544.
545.
546.
547.
548.
549.
550.
551.
552.
553.
554.
555.
556.
557.
558.
559.
560.
561.
562.
563.
564.
565.
566.
567.
568.
569.
570.
571.
572.
573.
574.
575.
576.
577.
578.
579.
580.
581.
582.
583.
584.
585.
586.
587.
588.
589.
590.
591.
592.
593.
594.
595.
596.
597.
598.
599.
600.
601.
602.
603.
604.
605.
606.
607.
608.
609.
610.
611.
612.
613.
614.
615.
616.
617.
618.
619.
620.
621.
622.
623.
624.
625.
626.
627.
628.
629.
630.
631.
632.
633.
634.
635.
636.
637.
638.
639.
640.
641.
642.
643.
644.
645.
646.
647.
648.
649.
650.
651.
652.
653.
654.
655.
656.
657.
658.
659.
660.
661.
662.
663.
664.
665.
666.
667.
668.
669.
670.
671.
672.
673.
674.
675.
676.
677.
678.
679.
680.
681.
682.
683.
684.
685.
686.
687.
688.
689.
690.
691.
692.
693.
694.
695.
696.
697.
698.
699.
700.
701.
702.
703.
704.
705.
706.
707.
708.
709.
710.
711.
712.
713.
714.
715.
716.
717.
718.
719.
720.
721.
722.
723.
724.
725.
726.
727.
728.
729.
730.
731.
732.
733.
734.
735.
736.
737.
738.
739.
740.
741.
742.
743.
744.
745.
746.
747.
748.
749.
750.
751.
752.
753.
754.
755.
756.
757.
758.
759.
760.
761.
762.
763.
764.
765.
766.
767.
768.
769.
770.
771.
772.
773.
774.
775.
776.
777.
<?php
/**
* Класс отвечает за загрузку скриптов и вывод инфромации пользователю
* @author undef
* @date undef
* @last-modified undef
*/
class View
{
public $LayoutName = 'page';
private static $instance = null;
private static $cache = null;
/** @var $Uri Uri */
public $Uri;
/** @var $User User */
public $User;
/** @var $Db Db */
public $Db;
public $kcaptcha;
public $Adv;
public $content;
private $before;
private $auto_blocks = '';
public static $debug = false;
private $language = false;
private $defaultLanguage = 'ru';
private $values = array();
private $toRender = array();
private $params = array(
'doctype' => null,
'html' => null,
'head' => null,
'maintitle' => null,
'title' => array(),
'maintitlesep' => null,
'titlesep' => null,
'charset' => null,
'description' => null,
'keywords' => null,
'favicon' => null,
'css' => null,
'csscode' => null,
'js' => null,
'default_lang' => null,
'langs' => null,
'jscode' => null
);
public $page;
public $onpage;
public $maxElements;
public $content_type = 'text/html';
public static $compact_mode = false;
/**
* @desc Конструктор класса, проверяет параметры и инициализирует переменные
* @global object $E_URI
* @global object $E_DB
* @global object $E_USER
*/
public function __construct()
{
global $E_URI, $E_DB, $E_USER;
$this->kcaptcha = new Kcaptcha();
$this->Uri = $E_URI;
$this->User = $E_USER;
$this->Db = $E_DB;
$this->Adv = new Adv();
$config = array();
include PAGERPATH.'default/config.php';
$this->params = $config;
if(is_dir(PAGERPATH.$this->Uri->site_group)) {
include PAGERPATH.$this->Uri->site_group.'/config.php';
$this->params = $config;
}
// если это старый сайт
if(isset($this->params['flag']['old'])) {
$this->Uri->setUri(array('index'));
}
// а вдруг компактный режим?
if(isset($this->params['compact'])) {
self::$compact_mode = true;
}
if(((isset($_SESSION['flag']['debug']) and $_SESSION['flag']['debug'] == 1) or isset($_GET['debug']))
and System::isSandbox()
) {
self::$debug = true;
}
$this->defineLang();
}
/**
* @desc получаем параметр для подстановки в шаблон по ключу
* @param $key ключ
* @return mixed|bool значение
*/
public function getParam($key)
{
///XXX можно не использовать конструкцию if-else
// так как если условие не выполнится, возвращать false
if(isset($this->params[$key])) {
return $this->params[$key];
}else {
return false;
}
}
/**
* @desc устанавливаем параметр для установки в шаблон
* @param $key ключ
* @param $value значение
* @param bool $replace заменить?
*/
public function setParam($key, $value, $replace=false)
{
$separator = (($key=='css' or $key=='js')?PHP_EOL:'');
if($key == 'title') {
$this->params['title'][] = $value;
}elseif($replace == false and isset($this->params[$key]) and !empty($this->params[$key])) {
$this->params[$key] .= $separator.$value;
}else {
$this->params[$key] = $value;
}
}
/**
* @desc функция возвращает заголовок страницы для вывода в шаблон
* @param bool $without_main без общего заголовка
* @return string сформированный тайтл
*/
public function createTitle($without_main = false)
{
if(!is_array($this->params['title']) or empty($this->params['title'])) {
$this->params['title'] = array();
}
$titles = implode($this->params['titlesep'], $this->params['title']);
if($without_main == false) {
return $this->params['maintitle']. $this->params['maintitlesep'] . $titles;
} else {
return $titles;
}
}
/**
* получаем экземпляр класса
* @return View экземпляр класса
*/
public static function getInstance()
{
if(is_null(self::$instance)) {
global $E_VIEW;
self::$instance = $E_VIEW;
//self::$instance = new self();
}
return self::$instance;
}
public static function get($class) {
switch(strtolower($class)) {
case 'db':
return View::getInstance()->Db;
break;
case 'uri':
return View::getInstance()->Uri;
break;
case 'user':
return View::getInstance()->User;
break;
case 'cache':
return System::get('cache');
break;
default:
return null;
}
}
/**
* Получаем данные о кэше
* @return Memcache
*/
public static function getCache()
{
if(is_null(self::$cache)) {
self::$cache = new Memcache();
self::$cache->connect('127.0.0.1', 11211);
}
return self::$cache;
}
/**
* Свойству класса устанавливаем значение
* @param type $name
* @param type $value
*/
//FIXME название метода, возможно, должно быть set
public function __set($name, $value)
{
/*if(isset($this->values[$name])) $this->values[$name] = $value;
else $this->values[$name] = $value;*/
$this->{$name} = $value;
}
/*public function __get($name)
{
if(isset($this->values[$name])) return $this->values[$name];
return false;
}*/
/**
* Проверяем, есть ли такой файл для экшен-скриптов
* @param type $path
* @return boolean
*/
//FIXME название метода, возможно, должно быть actionPath
private function action_path($path)
{
$uri = array_slice($this->Uri->uri,1,4);
while(count($uri)>0) {
$tempath = $path . implode('-',$uri) . '.php';
Monitoring_php::$action_path = $tempath;
if($this->check_path($tempath, true)) {
return true;
}else {
unset($uri[count($uri)-1]);
}
}
return false;
}
/**
* Проверяем, есть ли такой файл
* @param string $path
* @param type $include включить в сценарий?(по умолч. false)
* @return boolean|string
*/
//FIXME название метода, возможно, должно быть checkPath
public function check_path($path, $include=false)
{
if(file_exists(PAGERPATH.$this->Uri->site_group.$path)) {
$site = $this->Uri->site_group;
}elseif(file_exists(PAGERPATH.'default'.$path)) {
$site = 'default';
}else {
return false;
}
$path = PAGERPATH.$site.$path;
Monitoring_php::$check_path = PAGERPATH.$site;
if($include === false) {
return $path;
} else {
include $path;
return true;
}
}
/**
* Загружает скрипт(контролер)
* @param bool $not_init true если вызывается не из init файла
* @param bool $default для рекурсивного вызова если не найден нужный сайт
* @return bool найден или нет
*/
//FIXME переменна $default не используется
public function content($not_init = false, $default = false)
{
$script_time_start = microtime(true);
$path = '/content/'.$this->Uri->s(0).'/';
//Ищем файл
if($not_init == false and $this->check_path($path.'_Init.php', true)) {
{Monitoring_php::addToLogScr(Monitoring_php::$check_path.$path.'_Init.php', microtime(true)-$script_time_start);}
} elseif($this->Uri->s(0) == 'actions' && $this->action_path($path)) {
{Monitoring_php::addToLogScr(Monitoring_php::$check_path.Monitoring_php::$action_path, microtime(true)-$script_time_start);}
} elseif($this->check_path($path.$this->Uri->s(1).'.php', true)) {
{Monitoring_php::addToLogScr(Monitoring_php::$check_path.$path.$this->Uri->s(1).'.php', microtime(true)-$script_time_start);}
} elseif($this->Uri->s(1)!='index' and $this->check_path($path.'index.php', true)) {
{Monitoring_php::addToLogScr(Monitoring_php::$check_path.$path.'index.php', microtime(true)-$script_time_start);}
}else {
return false;
}
return true;
}
/**
* Загружает скрипт блока, общий шаблон и его собственный
* @param string $name
* @return string
*/
public function block($name)
{
$script_time_start = microtime(true);
$script = '';
$block = '';
$name = strtolower($name);
$path = $this->check_path('/blocks/'.$name.'.php');
if($path != false) {
ob_start();
include $path;
$script = ob_get_clean();
}
Monitoring_php::addToLogScr($path, microtime(true)-$script_time_start);
$path = $this->check_path('/templates/_blocks/'.$name.'.tpl.php');
if($path != false) {
ob_start();
include $path;
$block = ob_get_clean();
}
$path = $this->check_path('/templates/_blocks/block.tpl.php');
if($path != false) {
ob_start();
include $path;
$block = ob_get_clean();
}
return $script.$block;
}
/**
* Проверяет наличие макета и шаблонов
* @param array $path массив сегментов uri для редиректа
*/
public function router($path = null)
{
$request_time_start = microtime(true);
$this->toRender = array();
if($path != null and is_array($path) and count($path) > 0) {
$this->params['title'] = null;
$this->Uri->setUri($path);
}
if($this->params['site under construction at this moment'] === true) {
$this->Uri->setUri(array('systemerror','construction'));
}
if($this->Uri->s(0) != 'actions' and isset($this->params['blocks'])) {
foreach($this->params['blocks'] as $block) {
$this->auto_blocks .= $this->block($block);
}
}
$this->content();
$path = '/templates/'. $this->Uri->s(0) .'/';
$second = false;
if($this->Uri->s(2) !== false) {
$check = $this->check_path($path . $this->Uri->s(1) .'-'. $this->Uri->s(2) .'.tpl.php');
if($check != false) {
$second = true;$this->toRender['template-2'] = $check;
}
}
$check = $this->check_path($path . $this->Uri->s(1) .'.tpl.php');
if($check != false and $second != true) {
$this->toRender['template-1'] = $check;
} elseif(($check = $this->check_path($path . 'index.tpl.php')) != false and $second != true) {
$this->toRender['template-1'] = $check;
}
$check = $this->check_path($path . 'Template.tpl.php');
if($check != false) {
$this->toRender['main_temlate'] = $check;
}
//если не найдены шаблоны то логируем 404 и на index
if(count($this->toRender) == 0 and $this->Uri->s(0) != 'actions') {
System::error('404');
r('/index');
}
$check = $this->check_path('/layouts/' . $this->LayoutName . '.tpl.php');
if($check != false) {
$this->toRender['layout'] = $check;
}
Monitoring_php::addToLogReq('router', microtime(true)-$request_time_start);
}
/**
* Подгрузка шаблонов, макета
*/
public function render()
{
$request_time_start = microtime(true);
$this->before = ob_get_clean();
foreach ($this->toRender as $key => $value) {
if($key == 'layout' and !empty($this->before)) {
$this->content = $this->before.$this->content;
}
ob_start();
include $value;
$this->content = ob_get_clean();
}
Monitoring_php::addToLogReq('render', microtime(true)-$request_time_start);
}
/**
* возвращает заголовки и результат работы сайта (контент)
*/
public function output()
{
$request_time_start = microtime(true);
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Content-type: {$this->content_type}; charset=utf-8");
echo $this->content.$this->auto_blocks;
Monitoring_php::addToLogReq('output', microtime(true)-$request_time_start);
}
/**
* @desc Производит быстрый (при режиме compact)
*/
//FIXME название метода возможно, должно быть fastRender
public function fast_render()
{
$path = PAGERPATH.$this->Uri->site_group.'/compact/';
$uri = $this->Uri->uri;
$found = false;
$file_path = '';
while(count($uri)>0) {
$file_path = $path.implode('-',$uri).'.php';
if(file_exists($file_path)) {
$found = true; break;
}else {
unset($uri[count($uri)-1]);
}
}
// если страница не найдена, логируем ошибку и генерим 404
if(!$found){
System::error('404');
header('HTTP/1.1 404 Not Found');
return;
}
$error = false;
if(file_exists($path.'_Init.php')) {
$error = include $path.'_Init.php';
}
if($error) {
$this->content = ob_get_clean();
return;
}
include $file_path;
$this->content = ob_get_clean();
}
/**
* задает контент-тип сайта
* @param string $type ContentType
*/
//FIXME название метода с большой букв
public function ContentType($type)
{
if(self::$debug) {
return;
}
$this->content_type = 'text/html';
if($type=='xml') {
$this->content_type = 'text/xml';
} elseif($type=='js') {
$this->content_type = 'application/x-javascript';
} elseif($type=='json') {
$this->content_type = 'application/json';
}
}
/**
* Генерит таблицу
* @param string $title
* @param string $elem
* @param string $lvl
* @return string таблица
*/
public function getTable($title, $elem, $lvl = 1)
{
$return = '<h'.$lvl.' style="color:#6b6a3c;">'.$title.'</h'.$lvl.'>'.PHP_EOL.
'<table border="1" style="color:black;border:1px solid black;width:100%;font-size:11;">';
foreach ($elem as $key => $val) {
$return .= '<tr>';
$return .='<td style="width:20px;"> </td>';
if(is_array($val) == false) {
$return .='<td style="width:30%;text-align:right;font-weight:bold;">'.$key.'  </td>';
}
if(is_array($val)) {
$val = $this->getTable($key, $val, $lvl+1);
} elseif(empty($val)) {
$val = ' ';
}
$return .= '<td><div style="word-wrap: break-word;">'.$val.'</div></td>';
$return .= '</tr>';
}
$return .= '</table>';
return $return;
}
/**
* выводит подробную инфу массивов POST, GET, SESSION, COOKIE и др. в красивой форме
* @return string данные
*/
public function debugOutput()
{
$time = System::difference('всего', null);
System::debug('debugOutput', 'total time execution', $time);
$return = '
<script type="text/javascript">
if (typeof jQuery != "undefined") {
$(document).ready(function(){
$("#the_debug_button").click(function(){
$("#the_debug_info").slideToggle("fast", function() {
if($(this).is(":hidden")) {
$(this).parent().css("position", "fixed");
} else {
$(this).parent().css("position", "absolute");
}
});
});
});
}
</script>
<div style="border: 3px double #99AAAA; display: block; font-size: 11px; margin-top: 10px; padding: 10px; position: absolute; z-index:100000;">
<div id="the_debug_button" style="cursor: pointer;">debug</div>
<pre id="the_debug_info" style="width: 100%; color: black; background-color: white;">';
$to_debug = array(
'debug' =>System::$debug_info,
'POST' =>$_POST,
'GET' =>$_GET,
'SESSION' =>$_SESSION,
'COOKIE' =>$_COOKIE,
'time differences' =>System::$differences,
'view' => array(
'site' =>$this->Uri->site,
'site_group' =>System::getSiteParam('sysname'),
'uri_clean' =>$this->Uri->uri_clean_string,
'uri' =>$this->Uri->uri_string
),
'toRender' =>$this->toRender,
'queries' =>$this->Db->history,
'SERVER' =>$_SERVER
);
foreach($to_debug as $title => $elem) {
$return .= $this->getTable($title, $elem);
}
$return .= '
</pre>
</div>';
return $return;
}
/**
*Сохраняет запросы в сессии
*/
public function saveQueries()
{
$url = $this->Uri->site.'/'.$this->Uri->uri_string;
$dt = date("H:i:s d.m.Y");
$queries = $this->Db->history;
if(!empty($queries)) {
$_SESSION['saveQueries'][] = array('url' => $url, 'dt' => $dt, 'queries' => $queries);
}
}
/**
* @desc По сути обьявляет о начале пагинации (определяет переменные)
* @param int $page текущий номер страницы
* @param int $onpage кол-во записей, которые нужно выводить на странице
* @param int $max кол-во всех элементов
*/
//FIXME название функции с большой буквы
function Navigation($page,$onpage,$max)
{
$this->page = intval($page);
if ($this->page==0) {
$this->page = 1;
}
$this->page = abs($this->page);
$this->onpage = $onpage;
$this->maxElements = $max;
}
/**
* Выводит массив со страницами
* @param string $link начальная ссылка (т.е. http://site.ru/news/ .= 1,2,3..)
* @param type $split
* @param type $active
* @return array массив страниц
*/
function buildLinks($link, $split = true, $active = ' style="font-size: 11px;"')
{
$pageArray = array();
$links = array();
if(strpos($link, '%d') === false) {
$link = $link . '%d';
}
$pages = ceil($this->maxElements/$this->onpage);
if ($pages<=11) {
for ($i=1;$i<=$pages;$i++) {
$pageArray[$i] = $i;
}
} else {
$b = $this->page-floor(11/2);
if (11%2==0) {
$b++;
}
if ($b<1) {
$b = 1;
}
if ($b+11>$pages) {
$b = $pages-11+1;
}
for ($i=1;$i<=11;$i++) {
$pageArray[$i] = $b++;
}
if ($pageArray[1]<>1) {
$pageArray[1] = 1;
$pageArray[2] = '...';
}
if ($pageArray[11]<>$pages) {
$pageArray[11-1] = '...';
$pageArray[11] = $pages;
}
}
foreach($pageArray as $output) {
if ($output<>$this->page) {
if ($output<>'...') {
$links[] = '<a href="' . sprintf($link, $output) . '">'.$output.'</a> ';
if ($split and $output<>$pages)
$links[] = " | ";
} else {
$links[] = ' <span' . $active . '>'.$output.'</span> ';
if ($split and $output<>$pages)
$links[] = " | ";
}
} else {
$links[] = ' <span' . $active . '>'.$output.'</span> ';
if ($split and $output<>$pages) {
$links[] = " | ";
}
}
}
return $links;
}
/**
* @desc Делает лимит для запроса
* @return string LIMIT ... OFFSET ...
*/
function buildLimit()
{
$limit_start = ($this->page-1)*$this->onpage;
return 'LIMIT '.$this->onpage.' OFFSET '.$limit_start;
}
/**
* @desc Попытка возродить старую функцию t :)
* @param string $file файл, который нужно показать
* @param string $folder имя папки, где лежит файл
* @param string $vars переменные, передаваемые в функцию (пока нахер их)
* @return string содержимое шаблона
*/
function t($file, $folder, $vars=null)
{
if(!$file || !$folder) {
die("Fatal error");
}
$path = $this->check_path('/templates/'.$folder.'/'.$file.'.tpl.php');
$result = '';
if($path != false) {
if($vars != null and is_array($vars)) {
//extract - импортирует переменные из массива в текущую символьную таблицу.
extract($vars, EXTR_PREFIX_SAME, "var");
}
ob_start();
include $path;
$result = ob_get_clean();
}
return $result;
}
/**
* @desc формирует меню на основе полученного массива
* @param array $links
* @return string
*/
function menu($links)
{
if(empty($links) || !is_array($links)) {
return false;
}
$return = array();
foreach ($links as $link) {
$class = 'lnk';
if(isset($link[2]) && $link[2] == true) { //if external link
$href = $link[0];
} else { //if internal link
if(!is_array($link[0]) && is_string($link[0])) { //string to array
$link[0] = explode('/', $link[0]);
if($link[0][0] == '') {
array_shift($link[0]);
}
}
if(isset($link[0][0]) and $this->Uri->s(0) == $link[0][0]) { //adding class 'activ'
if(isset($link[0][1]) and $this->Uri->s(1) == $link[0][1]) {
$class .= ' activ';
}elseif(!isset($link[0][1])) {
$class .= ' activ';
}
}
$href = '/'.implode('/', $link[0]);
}
$return[] = "<span class=\"".$class."\"><a href=\"".$href."\">".$link[1]."</a></span>";
}
return implode('|', $return).PHP_EOL;
}
/**
* Определяет язык
*/
private function defineLang()
{
//определяем, какой язык текущий по флагу либо в сессии, либо в куках
if(isset($_SESSION['flag']['lang'])) {
$this->language = $_SESSION['flag']['lang'];
} elseif(isset($_COOKIE['7572559ca86e781ba8fe8073a0b725c6'])) {//0eb7c72e1b567be46408c7a4bfea6048
$this->language = $_COOKIE['7572559ca86e781ba8fe8073a0b725c6'];
$_SESSION['flag']['lang'] = $this->language;
} elseif(isset($_SESSION['user']['id'])) {
$lang = $this->Db->select("SELECT lang FROM {{users}} WHERE id=".$_SESSION['user']['id']." LIMIT 1");
if(!empty($lang[0])) {
$this->language = $lang[0]['lang'];
$_SESSION['flag']['lang'] = $this->language;
Cookie('7572559ca86e781ba8fe8073a0b725c6', $this->language);
}
}
//если мы всё-таки не смогли определить язык
if($this->language == false) {
if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
$match = preg_match('/^([a-z]{2,3})/', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $lang);
//пробуем выцепить язык регуляркой
if($match > 0 and isset($this->params['langs']) and in_array($lang[1], $this->params['langs'])) {
$this->language = $lang[1];
} else {
$this->language = $this->getParam('default_lang');//$this->defaultLanguage;
}
} else {
//если ничего не получилось, устанавливаем дефолтный язык
$this->language = $this->getParam('default_lang');//$this->defaultLanguage;
}
$_SESSION['flag']['lang'] = $this->language;
Cookie('7572559ca86e781ba8fe8073a0b725c6', $this->language);
if(isset($_SESSION['user']['id'])) {
$this->Db->update('users', "lang='".$this->language."'", 'id='.$_SESSION['user']['id']);
}
}
}
}