<?php

/**
 * EasyAdmin for Giglance
 *
 * @package Functions
 * @version 2.6.9
 * @author CoTEMPLATE
 * @copyright Copyright (c) CoTEMPLATE.com
 */
defined('COT_CODE') or die('Wrong URL.');

function ea_generate_menu($tpl = '', $tpl_sub, $menu, $level, $accordion = 'accordion') {

    if (empty($menu))
        return '';

    $tpl_mod = !empty($tpl) ? $tpl : $tpl_sub;

    $t = new XTemplate(cot_tplfile($tpl_mod, 'core'));

    foreach ($menu as $key => $item) {
        $item['active'] = !empty($item['active']) ? 1 : 0;
        $item['url'] = (isset($item['url']) && $item['url'] != '') ? $item['url'] : '#';
        $t->assign(array(
            'MENU_LEVEL' => $level,
            'MENU_URL' => $item['url'],
            'MENU_DESC' => isset($item['desc']) ? htmlspecialchars($item['desc']) : '',
            'MENU_CLASS' => isset($item['class']) ? $item['class'] : '',
            'MENU_ICON_CLASS' => isset($item['icon_class']) ? $item['icon_class'] : '',
            'MENU_ICON' => $item['icon'],
            'MENU_TITLE' => htmlspecialchars($item['title']),
            'MENU_ID' => $key,
            'MENU_ACCARDION' => $accordion,
            'MENU_ACTIVE' => (isset($item['active']) && $item['active']) ? 1 : 0,
        ));
        if (!empty($item['items'])) {
            $t->assign(array(
                'MENU_SUBMENU' => ea_generate_menu('', $tpl_sub, $item['items'], $level + 1, $accordion)
            ));
        } else {
            $t->assign(array(
                'MENU_SUBMENU' => '',
            ));
        }
        if (!empty($item['subitems'])) {
            $t->assign(array(
                'MENU_SUBITEMS' => ea_generate_menu($tpl, $tpl_sub, $item['subitems'], 1, 'accordion_'.$key)
            ));
        } else {
            $t->assign(array(
                'MENU_SUBITEMS' => '',
            ));
        }
        if (!empty($item['title'])) {
            $t->parse('MAIN.ITEM');
        }
    }
    $t->parse('MAIN');
    return $t->text('MAIN');
}

function ea_translit($var, $lower = true, $punkt = true) {
    global $langtranslit;

    if (is_array($var))
        return "";

    $var = str_replace(chr(0), '', $var);

    if (!is_array($langtranslit) OR ! count($langtranslit)) {
        $var = trim(strip_tags($var));

        if ($punkt)
            $var = preg_replace("/[^a-z0-9\_\-.]+/mi", "", $var);
        else
            $var = preg_replace("/[^a-z0-9\_\-]+/mi", "", $var);

        $var = preg_replace('#[.]+#i', '.', $var);
        $var = str_ireplace(".php", ".ppp", $var);

        if ($lower)
            $var = strtolower($var);

        return $var;
    }

    $var = trim(strip_tags($var));
    $var = preg_replace("/\s+/ms", "-", $var);
    $var = str_replace("/", "-", $var);

    $var = strtr($var, $langtranslit);

    if ($punkt)
        $var = preg_replace("/[^a-z0-9\_\-.]+/mi", "", $var);
    else
        $var = preg_replace("/[^a-z0-9\_\-]+/mi", "", $var);

    $var = preg_replace('#[\-]+#i', '-', $var);
    $var = preg_replace('#[.]+#i', '.', $var);

    if ($lower)
        $var = strtolower($var);

    $var = str_ireplace(".php", "", $var);
    $var = str_ireplace(".php", ".ppp", $var);

    if (strlen($var) > 200) {

        $var = substr($var, 0, 200);

        if (($temp_max = strrpos($var, '-')))
            $var = substr($var, 0, $temp_max);
    }

    return $var;
}

function convert_unicode($eat, $to = 'utf-8') {

    $to = strtolower($to);

    if ($to == 'utf-8') {

        return $eat;
    } else {

        if (function_exists('mb_convert_encoding')) {

            $eat = mb_convert_encoding($eat, $to, "UTF-8");
        } elseif (function_exists('iconv')) {

            $eat = iconv("UTF-8", $to . "//IGNORE", $eat);
        } else
            $eat = "The library iconv is not supported by your server";
    }

    return $eat;
}

function cot_build_ea_user($id, $user, $extra_attrs = '') {
    if (!$id) {
        return empty($user) ? '' : $user;
    } else {
        return empty($user) ? '?' : cot_rc_link(cot_url('users', 'm=details&id=' . $id . '&u=' . $user), $user, $extra_attrs);
    }
}

function cot_generate_ea_usertags($user_data, $tag_prefix = '', $emptyname = '', $allgroups = false, $cacheitem = true) {
    global $db, $cot_extrafields, $cot_groups, $cfg, $L, $user_cache, $db_users;

    static $extp_first = null, $extp_main = null;

    $return_array = array();

    if (is_null($extp_first)) {
        $extp_first = cot_getextplugins('usertags.first');
        $extp_main = cot_getextplugins('usertags.main');
    }

    /* === Hook === */
    foreach ($extp_first as $pl) {
        include $pl;
    }
    /* ===== */

    $user_id = is_array($user_data) ? (int) $user_data['user_id'] : (is_numeric($user_data) ? (int) $user_data : 0);
    if (isset($user_cache[$user_id])) {
        $temp_array = $user_cache[$user_id];
    } else {
        if (!is_array($user_data) && $user_id > 0) {
            $sql = $db->query("SELECT * FROM $db_users WHERE user_id = $user_id LIMIT 1");
            $user_data = $sql->fetch();
        }

        if (is_array($user_data) && $user_data['user_id'] > 0 && !empty($user_data['user_name'])) {
            $user_data['user_birthdate'] = cot_date2stamp($user_data['user_birthdate']);
            $user_data['user_text'] = cot_parse($user_data['user_text'], $cfg['users']['usertextimg']);

            $temp_array = array(
                'ID' => $user_data['user_id'],
                'NAME' => cot_build_ea_user($user_data['user_id'], htmlspecialchars($user_data['user_name'])),
                'NICKNAME' => htmlspecialchars($user_data['user_name']),
                'TITLE' => $cot_groups[$user_data['user_maingrp']]['title'],
                'MAINGRPID' => $user_data['user_maingrp'],
                'MAINGRPNAME' => $cot_groups[$user_data['user_maingrp']]['name'],
                'MAINGRPSTARS' => cot_build_stars($cot_groups[$user_data['user_maingrp']]['level']),
                'MAINGRPICON' => cot_build_groupicon($cot_groups[$user_data['user_maingrp']]['icon']),
                'TEXT' => $user_data['user_text'],
                'EMAIL' => cot_build_email($user_data['user_email'], false),
                'THEME' => $user_data['user_theme'],
                'SCHEME' => $user_data['user_scheme'],
                'GENDER' => ($user_data['user_gender'] == '' || $user_data['user_gender'] == 'U') ? '' : $L['Gender_' . $user_data['user_gender']],
                'BIRTHDATE' => (is_null($user_data['user_birthdate'])) ? '' : cot_date('date_full', $user_data['user_birthdate']),
                'BIRTHDATE_STAMP' => (is_null($user_data['user_birthdate'])) ? '' : $user_data['user_birthdate'],
                'AGE' => (is_null($user_data['user_birthdate'])) ? '' : cot_build_age($user_data['user_birthdate']),
                'TIMEZONE' => cot_build_timezone(cot_timezone_offset($user_data['user_timezone'], false, false)) . ' ' . str_replace('_', ' ', $user_data['user_timezone']),
                'REGDATE' => cot_date('datetime_medium', $user_data['user_regdate']),
                'REGDATE_STAMP' => $user_data['user_regdate'],
                'LASTLOG' => cot_date('datetime_medium', $user_data['user_lastlog']),
                'LASTLOG_STAMP' => $user_data['user_lastlog'],
                'LOGCOUNT' => $user_data['user_logcount'],
                'POSTCOUNT' => $user_data['user_postcount'],
                'LASTIP' => $user_data['user_lastip']
            );

            if ($allgroups) {
                $temp_array['GROUPS'] = cot_build_groupsms($user_data['user_id'], FALSE, $user_data['user_maingrp']);
            }
            // Extra fields
            if (isset($cot_extrafields[$db_users])) {
                foreach ($cot_extrafields[$db_users] as $exfld) {
                    $temp_array[strtoupper($exfld['field_name'])] = cot_build_extrafields_data('user', $exfld, $user_data['user_' . $exfld['field_name']]);
                    $temp_array[strtoupper($exfld['field_name']) . '_TITLE'] = isset($L['user_' . $exfld['field_name'] . '_title']) ? $L['user_' . $exfld['field_name'] . '_title'] : $exfld['field_description'];
                    $temp_array[strtoupper($exfld['field_name']) . '_VALUE'] = $user_data['user_' . $exfld['field_name']];
                }
            }
        } else {
            $temp_array = array(
                'ID' => 0,
                'NAME' => (!empty($emptyname)) ? $emptyname : $L['um_deleted'],
                'NICKNAME' => (!empty($emptyname)) ? $emptyname : $L['um_deleted'],
                'MAINGRP' => cot_build_group(1),
                'MAINGRPID' => 1,
                'MAINGRPSTARS' => '',
                'MAINGRPICON' => cot_build_groupicon($cot_groups[1]['icon']),
                'TEXT' => '',
                'EMAIL' => '',
                'GENDER' => '',
                'BIRTHDATE' => '',
                'BIRTHDATE_STAMP' => '',
                'AGE' => '',
                'REGDATE' => '',
                'REGDATE_STAMP' => '',
                'POSTCOUNT' => '',
                'LASTIP' => ''
            );
        }

        /* === Hook === */
        foreach ($extp_main as $pl) {
            include $pl;
        }
        /* ===== */

        $cacheitem && $user_cache[$user_data['user_id']] = $temp_array;
    }
    foreach ($temp_array as $key => $val) {
        $return_array[$tag_prefix . $key] = $val;
    }
    return $return_array;
}

function ea_get_extensionparams($code, $is_module = false) {
    global $cfg, $cot_modules, $cot_plugins_enabled;
    $dir = $is_module ? $cfg['modules_dir'] : $cfg['plugins_dir'];

    if ($is_module) {
        $name = $cot_modules[$code]['title'];
    } else {
        $name = $cot_plugins_enabled[$code]['title'];
    }

    if (empty($name)) {
        $ext_info = $dir . '/' . $code . '/' . $code . '.setup.php';
        $exists = file_exists($ext_info);
        if ($exists) {
            $info = cot_infoget($ext_info, 'COT_EXT');
            if (!$info && cot_plugin_active('genoa')) {
                // Try to load old format info
                $info = cot_infoget($ext_info, 'SED_EXTPLUGIN');
            }
            $name = $info['Name'];
            $desc = $info['Desc'];
        } else {
            $info = array(
                'Name' => $code
            );
        }
        $name = $info['Name'];
    }
    $icofile = $dir . '/' . $code . '/' . $code . '.png';
    $icon = file_exists($icofile) ? $icofile : '';

    $langfile = cot_langfile($code, $is_module ? 'module' : 'plug');
    if (file_exists($langfile)) {
        include $langfile;
        if (!empty($L['info_name']))
            $name = $L['info_name'];
        if (!empty($L['info_desc']))
            $desc = $L['info_desc'];
    }

    return array(
        'name' => htmlspecialchars($name),
        'desc' => $desc,
        'icon' => $icon
    );
}