<?php

#получаем данные пользователя и уровень прав (+ кеширование)

function get_user($user_id = 0) {
    $user_id = (int) $user_id;

    global $users, $set;

    $db = new db;

    if ($set['id_system'] != null) {
        $set['id_system'] = 0;
    }

    if (!empty($users[$user_id])) {
        return $users[$user_id];
    } else
    if ($user_id == 0) {
        return array(
            'id' => (int) $set['id_system'],
            'nick' => '  ' . $set['nick_system'] . '  ',
            'level' => 999,
            'sex' => 1,
            'group_name' => lang('Системный робот'),
            'group_access' => 2,
            'ncolor' => '#FF0000',
            'ncolor2' => '#FF0000',
            'date_last' => time(),
            'date_reg' => (int) $set['data_install'],
            'browser' => 'web',
            'ank_o_sebe' => lang('Для уведомлений'));
    } else {
        $file = H . 'sys/cache/users/' . $user_id . '.json';

        if ($set['cache_get_user'] != null)
            $set['cache_get_user'] = 5;

        if (file_exists($file) and ( time() - filemtime($file) < $set['cache_get_user']))
            $cache = false;
        else
            $cache = true;

        if ($cache) {
            $u = $db->get_row($db->query("SELECT * FROM user WHERE id = '" . $user_id . "' LIMIT 1"));
            $tmp_us = $db->get_row($db->query("SELECT level, name AS group_name FROM user_group WHERE id = '" . $u['group_access'] . "' LIMIT 1"));
            if (!$tmp_us['group_name']) {
                $u['level'] = (string) 0;
                $u['group_name'] = lang('Пользователь');
            } else {
                $u['level'] = (string) $tmp_us['level'];
                $u['group_name'] = $tmp_us['group_name'];
            }
            file_put_contents($file, json_encode($u));
        }
        $users[$user_id] = empty($temp_us) ? json_decode(file_get_contents($file), true) : $temp_us;
        return $users[$user_id];
    }
}
