<?php

function sql_update($arr)
{
    $a = array();
    foreach ($arr as $k => $v)
    {
        $a[] = $k . '=\'' . addslashes($v) . '\'';
    }
    return implode(',', $a);
}
function sql_insert($arr)
{
    $karr = $varr = $varr2 = array();
    foreach ($arr as $key => $val)
    {
        if (is_array($val))
        {
            foreach ($val as $k => $v)
            {
                empty($karr) && $karr = array_keys($val);
                $varr[$key][] = '\'' . addslashes($v) . '\'';
            }
        } else
        {
            $karr[] = $key;
            $varr[0][] = '\'' . addslashes($val) . '\'';
        }
    }
    $kstr = ' (' . implode(',', $karr) . ')';
    foreach ($varr as $v)
    {
        $varr2[] = '(' . implode(',', $v) . ')';
    }
    return $kstr . ' value' . implode(',', $varr2);
}
function timer_start()
{
    global $timestart;
    return $timestart = microtime(true);
}
function postlangdatas($key, $key2 = null)
{
    global $conf;
    $arr = array();
    if (isset($key))
    {
        foreach ($conf['sys_elangs'] as $k => $v)
        {
            $arr[$k] = trim($_POST[$key][$k]);
        }
    } else
    {
        foreach ($conf['sys_elangs'] as $k => $v)
        {
            $arr[$k] = trim($_POST[$key][$key2][$k]);
        }
    }
    return $arr;
}
function modname($mod)
{
    global $conf;
    if (in_array($mod, $conf['main_modules']))
    {
        return mlang($conf['sys_modules'][$mod]['name'], $mod);
    } else
    {
        foreach ($conf['sys_modules'] as $k => $v)
        {
            if (is_array($v['sub']))
            {
                if (isset($v['sub'][$mod]))
                {
                    return mlang($v['sub'][$mod]['name'], $mod);
                }
            }
        }
    }
    return '<none>';
}
function xlang($arr, $lang = LANG)
{
    if (is_string($arr))
    {
        return ($arr === '' ? '<none>' : $arr);
    }
    return (isset($arr[$lang]) && $arr[$lang] !== '') ? $arr[$lang] : '<none>';
}
function htmlxlang($arr, $lang = LANG)
{
    return html(xlang($arr, $lang));
}
function mlang($key, $mod = MOD)
{
    global $conf;
    return empty($conf['langs'][$mod][$key]) ? ($mod . ':' . $key) : $conf['langs'][$mod][$key];
}
function htmlmlang($key, $mod = MOD)
{
    return htmlspecialchars(mlang($key, $mod));
}
function tlang($key)
{
    global $conf;
    return empty($conf['langs']['-tpl'][$key]) ? (LANG . ':' . $key) : $conf['langs']['-tpl'][$key];
}
function htmltlang($key)
{
    return htmlspecialchars(tlang($key));
}
function html($str)
{
    return htmlspecialchars($str);
}
function cache_exists($key)
{
    global $cache, $conf;
    if (!IS_CACHE)
        return false;
    return isset($cache[$key]);
}
function set_cache($key, $value, $flush = 10)
{
    global $db, $cache;
    IS_CACHE or $flush = 0;
    $flush = TIME + $flush;
    $_value = is_string($value) ? $value : serialize($value);
    $row = $db->query("select * from " . PF . "val where name='" . $key .
        "' && iscache=1 limit 0,1");
    if ($db->num_rows($row) > 0)
    {
        $db->query("update " . PF . "val set value='" . addslashes($_value) .
            "',flush='" . $flush . "' where name='" . $key . "' && iscache=1");
    } else
    {
        $db->query("insert into " . PF .
            "val (name,value,iscache,flush,serialize) values('" . $key . "','" . addslashes
            ($_value) . "','1','" . $flush . "','" . (is_string($value) ? 0 : 1) . "')");
    }
    $cache[$key] = $value;
}
function set_conf($key, $value)
{
    global $db, $conf;
    $_value = is_string($value) ? $value : serialize($value);
    if ($row = $db->fetch_first("select * from " . PF . "val where name='" . $key .
        "' && iscache='0' limit 0,1"))
    {
        $db->query("update " . PF . "val set value='" . addslashes($_value) .
            "',serialize='" . (is_string($value) ? 0 : 1) . "' where id='" . $row['id'] .
            "'");
    } else
    {
        $db->query("insert into " . PF .
            "val (name,value,iscache,flush,serialize) values('" . $key . "','" . addslashes
            ($_value) . "','0','0','" . (is_string($value) ? 0 : 1) . "')");
    }
}
function get_val()
{
    global $db, $cache, $conf;
    $result = $db->query("select * from " . PF . "val");
    while ($row = $db->fetch_array($result))
    {
        if ($row['iscache'] > 0 && $row['flush'] < TIME)
        {
            $db->query("delete from " . PF . "val where id='$row[id]'");
            continue;
        }
        ${$row['iscache'] > 0 ? 'cache' : 'conf'}[$row['name']] = $row['serialize'] > 0 ?
            unserialize($row['value']) : $row['value'];
    }
}
function getval($key)
{
    return $GLOBALS['__sys__'][$key];
}
function setval($key, $val)
{
    $GLOBALS['__sys__'][$key] = $val;
}
function yun_model()
{
    $action = ACTION;
    $_mod = CMOD === false ? MOD : CMOD;
    if ($t = is_submodule($_mod))
    {
        $modpath = $t . '/' . $_mod;
        $mod = $t . '_' . $_mod;
    } else
    {
        $modpath = $mod = $_mod;
    }
    $file = ABSPATH . 'modules/' . $modpath . '/' . $action . '.php';
    $file2 = THEMEDIR . 'modules/' . $modpath . '/' . $action . '.php';
    $a_func = '_' . $mod . '_' . $action . '_func';
    if (file_exists($file2))
    {
        $code = 'require(\'' . $file2 . '\');';
    } else
        if (file_exists($file))
        {
            $code = 'require(\'' . $file . '\');';
        } else
            $code = ';';
    eval('function ' . $a_func .
        '(){global $db,$conf,$user,$mpv,$bpv,$cache;return ' . $code . '}');
    $a_func();
    $arr = getval('actiontplfile');
    if (!empty($arr))
    {
        $mod = $arr[0];
        $action = $arr[1];
    }
    $file = ABSPATH . 'modules/' . $modpath . '/' . $action . '_tpl.php';
    $file2 = THEMEDIR . 'modules/' . $modpath . '/' . $action . '_tpl.php';
    $t_func = '_' . $mod . '_' . $action . '_tpl_func';
    if (file_exists($file2))
    {
        $code = 'require(\'' . $file2 . '\');';
    } else
        if (file_exists($file))
        {
            $code = 'require(\'' . $file . '\');';
        } else
            $code = ';';
    eval('function ' . $t_func .
        '(){global $db,$conf,$user,$mpv,$bpv;$cache;$args=func_get_args();for($k=0;$k<count($args);$k++) ${\'arg_\'.$k}=&$args[$k];' .
        $code . '}');
    $argstr = '';
    $args = get_arg($a_func);
    while (list($key, $val) = @each($args))
    {
        $argstr .= ',$args[' . $key . ']';
    }
    eval('apply(\'content\',$t_func.\'()\',0' . $argstr . ');');
}
function template()
{
    $tplarr = array_pop(do_apply('tplfile'));
    $arr = $tplarr[isset($tplarr[ACTION]) ? ACTION : 0];
    $tplfile = $arr[0];
    $tplfile2 = $arr[0] . $arr[1];
    $arr = getval('tplfile');
    if (!empty($arr))
    {
        $tplfile = $arr[0];
        $tplfile2 = $arr[0] . $arr[1];
    }
    if (IS_WIN)
    {
        $tplfile = $tplfile2 = 'win';
    }
    if (file_exists($sourfile = THEMEDIR . $tplfile2 . '.php'))
    {
        $cachefile = ABSPATH . 'cache/' . THEMENAME . '_' . $tplfile2 . '.php';
    } else
        if (file_exists($sourfile = THEMEDIR . $tplfile . '.php'))
        {
            $cachefile = ABSPATH . 'cache/' . THEMENAME . '_' . $tplfile . '.php';
        } else
        {
            $sourfile = THEMEDIR . 'default.php';
            $cachefile = ABSPATH . 'cache/' . THEMENAME . '_default.php';
        }
        if (!IS_CACHE || !file_exists($cachefile) || filemtime($cachefile) < filemtime($sourfile))
        {
            $data = file_get_contents($sourfile);
            $data = str_replace(array('href="css/', 'src="images/', 'src="img/', 'src="js/',
                'src="others/'), array('href="' . THEMEPATH . 'css/', 'src="' . THEMEPATH .
                'images/', 'src="' . THEMEPATH . 'img/', 'src="' . THEMEPATH . 'js/', 'src="' .
                THEMEPATH . 'others/'), $data);
            write_file($cachefile, $data) or yun_error('./cache/' . mlang('-3', '无法写入',
                'system'));
        }
    return $cachefile;
}
function module_exists($mod)
{
    global $conf;
    if (in_array($mod, $conf['main_modules']))
    {
        return true;
    } else
    {
        foreach ($conf['sys_modules'] as $k => $v)
        {
            if (is_array($v['sub']))
            {
                if (isset($v['sub'][$mod]))
                {
                    return true;
                }
            }
        }
    }
    return false;
}
function is_submodule($mod)
{
    global $conf;
    if (in_array($mod, $conf['main_modules']))
    {
        return false;
    } else
    {
        foreach ($conf['sys_modules'] as $k => $v)
        {
            if (is_array($v['sub']))
            {
                if (isset($v['sub'][$mod]))
                {
                    return $k;
                }
            }
        }
    }
    return false;
}
function __autoload($class_name)
{
    if ($class_name == 'mysql')
    {
        require_once (ABSPATH . 'includes/class_mysql.php');
    } else
    {
        $arr = explode('_', $class_name);
        if (module_exists($arr[0]))
        {
            if (file_exists($file = ABSPATH . 'modules/' . $arr[0] . '/__class.php'))
                require_once ($file);
        }
    }
}
function hook_exists($action)
{
    global $yun_hooks;
    return is_array($yun_hooks[$action]);
}
function do_apply($action, $type = 'array')
{
    global $yun_hooks;
    $arr = array();
    if (hook_exists($action))
    {
        krsort($yun_hooks[$action]);
        foreach ($yun_hooks[$action] as $funcs)
        {
            foreach ($funcs as $func)
            {
                if (!is_string($func[0]) || substr($func[0], -2) != '()')
                {
                    $arr[] = $func[0];
                    continue;
                }
                $func[0] = str_replace('()', '', $func[0]);
                $argarr_1 = is_array($func[1]) ? $func[1] : array();
                $argarr_2 = (func_num_args() > 2) ? array_splice(func_get_args(), 2) : array();
                $argarr = $argarr_1 + $argarr_2;
                $arg = array();
                while (list($key, ) = @each($argarr))
                {
                    $arg[] = '$argarr[' . $key . ']';
                }
                eval('$_t=' . $func[0] . '(' . implode(',', $arg) .
                    ');empty($_t) or $arr[]=$_t;');
            }
        }
    }
    switch ($type)
    {
        case 'string':
            return implode('', $arr);
            break;
        case 'array+':
            $_arr = array();
            for ($i = 0; $i < count($arr); $_arr += $arr[$i], $i++)
                ;
            return $_arr;
            break;
        case 'array_merge':
            $_arr = array();
            for ($i = 0; $i < count($arr); $_arr = array_merge($_arr, $arr[$i]), $i++)
                ;
            return $_arr;
            break;
        case 'array':
            return $arr;
            break;
        default:
            return;
    }
}
function action_exists($action)
{
    global $yun_hooks;
    return is_array($yun_hooks[$action]) ? true : false;
}
function apply($action, $func, $level = 0)
{
    global $yun_hooks;
    if ($level === true)
    {
        unset($yun_hooks[$action]);
        $level = 0;
    }
    $args = (func_num_args() > 3) ? array_splice(func_get_args(), 3) : null;
    $yun_hooks[$action][$level][] = array($func, $args);
}
function str_is_int($str)
{
    return ereg("^[0-9]+$", $str);
}
function encrypt($txt, $key = 'yun')
{
    $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.";
    $ikey = "-x6g6ZWm2G9g_vr0Bo.pOq3kRIxsZ6rm";
    $nh1 = rand(0, 64);
    $nh2 = rand(0, 64);
    $nh3 = rand(0, 64);
    $ch1 = $chars{$nh1};
    $ch2 = $chars{$nh2};
    $ch3 = $chars{$nh3};
    $nhnum = $nh1 + $nh2 + $nh3;
    $knum = 0;
    $i = 0;
    while (isset($key{$i}))
        $knum += ord($key{$i++});
    $mdKey = substr(md5(md5(md5($key . $ch1) . $ch2 . $ikey) . $ch3), $nhnum % 8, $knum %
        8 + 16);
    $txt = base64_encode($txt);
    $txt = str_replace(array('+', '/', '='), array('-', '_', '.'), $txt);
    $tmp = '';
    $j = 0;
    $k = 0;
    $tlen = strlen($txt);
    $klen = strlen($mdKey);
    for ($i = 0; $i < $tlen; $i++)
    {
        $k = $k == $klen ? 0 : $k;
        $j = ($nhnum + strpos($chars, $txt{$i}) + ord($mdKey{$k++})) % 64;
        $tmp .= $chars{$j};
    }
    $tmplen = strlen($tmp);
    $tmp = substr_replace($tmp, $ch3, $nh2 % ++$tmplen, 0);
    $tmp = substr_replace($tmp, $ch2, $nh1 % ++$tmplen, 0);
    $tmp = substr_replace($tmp, $ch1, $knum % ++$tmplen, 0);
    return $tmp;
}
function decrypt($txt, $key = 'yun')
{
    $tlen = strlen($txt);
    if ($tlen < 1)
        return;
    $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.";
    $ikey = "-x6g6ZWm2G9g_vr0Bo.pOq3kRIxsZ6rm";
    $knum = 0;
    $i = 0;
    while (isset($key{$i}))
        $knum += ord($key{$i++});
    $ch1 = $txt{$knum % $tlen};
    $nh1 = strpos($chars, $ch1);
    $txt = substr_replace($txt, '', $knum % $tlen--, 1);
    $ch2 = $txt{$nh1 % $tlen};
    $nh2 = strpos($chars, $ch2);
    $txt = substr_replace($txt, '', $nh1 % $tlen--, 1);
    $ch3 = $txt{$nh2 % $tlen};
    $nh3 = strpos($chars, $ch3);
    $txt = substr_replace($txt, '', $nh2 % $tlen--, 1);
    $nhnum = $nh1 + $nh2 + $nh3;
    $mdKey = substr(md5(md5(md5($key . $ch1) . $ch2 . $ikey) . $ch3), $nhnum % 8, $knum %
        8 + 16);
    $tmp = '';
    $j = 0;
    $k = 0;
    $tlen = strlen($txt);
    $klen = strlen($mdKey);
    for ($i = 0; $i < $tlen; $i++)
    {
        $k = $k == $klen ? 0 : $k;
        $j = strpos($chars, $txt{$i}) - $nhnum - ord($mdKey{$k++});
        while ($j < 0)
            $j += 64;
        $tmp .= $chars{$j};
    }
    $tmp = str_replace(array('-', '_', '.'), array('+', '/', '='), $tmp);
    return trim(base64_decode($tmp));
}
function stripslashe($string)
{
    if (is_array($string))
    {
        foreach ($string as $key => $val)
        {
            $string[$key] = stripslashe($val);
        }
    } else
    {
        $string = stripslashes($string);
    }
    return $string;
}
function arg()
{
    $arr = debug_backtrace();
    $args = func_get_args();
    setval('_arg_' . $arr[2]['function'], $args);
}
function get_arg($key)
{
    $arr = getval('_arg_' . $key);
    return is_array($arr) ? $arr : array();
}
function read_file($file)
{
    if (!file_exists($file))
    {
        return false;
    }
    if (function_exists('file_get_contents'))
    {
        return file_get_contents($file);
    }
    if (!$fp = @fopen($file, FOPEN_READ))
    {
        return false;
    }
    flock($fp, LOCK_SH);
    $data = '';
    if (filesize($file) > 0)
    {
        $data = &fread($fp, filesize($file));
    }
    flock($fp, LOCK_UN);
    fclose($fp);
    return $data;
}
function write_file($root, $data, $mode = 'wb')
{
    if (!$fp = @fopen($root, $mode))
    {
        return false;
    }
    flock($fp, LOCK_EX);
    fwrite($fp, $data);
    flock($fp, LOCK_UN);
    fclose($fp);
    return true;
}
function mkdirs($pathname, $mode = 0755)
{
    is_dir(dirname($pathname)) || mkdirs(dirname($pathname), $mode);
    return is_dir($pathname) || @mkdir($pathname, $mode);
}
function showtime($time, $w = 0)
{
    global $conf;
    return @date($conf['format_date'][$w], $time);
}
function urlex($lang)
{
    global $conf;
    if ($lang == LANG)
        return 'javascript:void(0)';
    if ($_SERVER['REQUEST_URI'] == ROOTPATH)
    {
        return ROOTPATH . (IS_REWRITE ? ($lang . '/') : ('?lang=' . $lang));
    }
    static $u = true;
    if ($u === true)
    {
        if (IS_REWRITE)
        {
            preg_replace("/^" . preg_quote(ROOTPATH, '/') . "[a-z]{2}([\-A-Z]{3})*\/(.*)$/ies",
                "\$u='\\2'", $_SERVER['REQUEST_URI']);
        } else
        {
            preg_replace("/^" . preg_quote(ROOTPATH, '/') . "\?(lang=[a-z]{2}([\-A-Z]{3})*)*\&*(.*)$/ies",
                "\$u='\\3'", $_SERVER['REQUEST_URI']);
        }
    }
    $is_show = !($lang == $conf['sys_lang']);
    if (IS_REWRITE)
    {
        return ROOTPATH . ($is_show ? ($lang . '/') : '') . $u;
    } else
    {
        if ($is_show)
        {
            return ROOTPATH . '?lang=' . $lang . ($u <> '' ? '&' : '') . $u;
        } else
        {
            return ROOTPATH . ($u <> '' ? '?' : '') . $u;
        }
    }
}
function url($url)
{
    if (IS_REWRITE)
        return $url;
    if (preg_match("/^" . preg_quote(ROOTPATH, '/') . "(([a-z]{2}(\-[A-Z]{2})*)\/)*(((\w+)\-)*(\w+)\/(([a-zA-Z_]+\d*(.[a-zA-Z_]+\d*)*)\/)*((\d+)\/((\d+)\/((\d+)\/)*)*)*)*\?*(.*)$/",
        $url, $s))
    {
        $url = '?lang=' . $s[2] . '&gid=' . $s[6] . '&mod=' . $s[7] . '&action=' . $s[9] .
            '&a=' . $s[12] . '&b=' . $s[14] . '&c=' . $s[16] . '&' . $s[17];
    }
    $url = preg_replace(array("/\?(\w+)=&/", "/\?(\w+)=&/", "/&(\w+)=&/", "/&(\w+)=&/",
        "/&(\w+)=&/", "/&$/"), array("?", "?", "&", "&", "&", ""), $url);
    return ROOTPATH . $url;
}
function tag($mod, $name)
{
    global $db, $user, $bpv, $mpv, $conf, $cache;
    if (!module_exists($mod))
        return;
    $pmod = is_submodule($mod);
    if ($pmod === false)
    {
        if (!file_exists($file = THEMEDIR . 'modules/' . $mod . '/tags/' . $name .
            '.php') && !file_exists($file = ABSPATH . 'modules/' . $mod . '/tags/' . $name .
            '.php'))
            return;
    } else
    {
        if (!file_exists($file = THEMEDIR . 'modules/' . $pmod . '/' . $mod . '/tags/' .
            $name . '.php') && !file_exists($file = ABSPATH . 'modules/' . $pmod . '/' . $mod .
            '/tags/' . $name . '.php'))
            return;
    }
    $argarr = (func_num_args() > 2) ? array_splice(func_get_args(), 2) : array();
    while (list($key, ) = @each($argarr))
    {
        eval('$' . chr(97 + $key) . '=&$argarr[' . $key . '];');
    }
    return require ($file);
}
function bpv($team)
{
    global $conf;
    $team = isset($conf['sys_teams'][$team]) ? $team : 0;
    return $conf['sys_teams'][$team]['pvs'];
}
function get_user($u)
{
    static $user = array();
    global $db;
    if (!isset($user[$u]))
    {
        if (!str_is_int($u))
        {
            $ur = $db->fetch_first('select * from ' . PF . 'user where name="' . addslashes
                ($u) . '"');
        } else
        {
            if ($u > 0)
            {
                $ur = $db->fetch_first('select * from ' . PF . 'user where id="' . $u . '"');
            } else
                $ur = false;
        }
        if (empty($ur))
        {
            $ur = array('id' => 0, 'name' => 'NONAME', 'team' => -1);
        }
        $user[$u] = $ur;
    }
    return $user[$u];
}
function msgrefresh()
{
    if (MOD != 'system' || ACTION != 'message')
        return;
    $sid = substr(md5($_SERVER['REQUEST_URI']), 0, 5);
    $reurl = urldecode($_GET['url']);
    if (empty($reurl))
    {
        header('Location: ' . url(RP));
        exit;
    }
    $cookie = array();
    if (!empty($_COOKIE[PF . 'yun_reurl']))
    {
        @$cookie = unserialize($_COOKIE[PF . 'yun_reurl']);
        if (!is_array($cookie))
        {
            header('Location: ' . url(RP));
            exit;
        }
    }
    if (empty($cookie[$sid]))
    {
        if (count($cookie) > 5)
            array_shift($cookie);
        $cookie[$sid] = $reurl;
        setcookie(PF . 'yun_reurl', serialize($cookie), 0, ROOTPATH);
    } else
    {
        header('HTTP/1.1 301 Moved Permanently');
        header('Location: ' . $cookie[$sid]);
        exit;
    }
}
function arraysort($arr, $sarr)
{
    $a = $b = array();
    foreach ($arr as $k => $v)
    {
        $kv = array_shift($sarr);
        empty($kv) && $kv = 0;
        $a[$kv][] = $k;
    }
    ksort($a);
    foreach ($a as $v)
    {
        foreach ($v as $v2)
        {
            $b[$v2] = $arr[$v2];
        }
    }
    return $b;
}
function randstr($length = 5)
{
    $hash = '';
    $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
    $max = strlen($chars) - 1;

    for ($i = 0; $i < $length; $i++)
    {
        $hash .= $chars[mt_rand(0, $max)];
    }
    return $hash;
}
function runcode($code)
{
    eval('?>' . stripslashes($code) . '<?php ');
}
function nocache()
{
    header("Expires: Mon, 26 Jul 1997 00:00:00 GMT");
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header("Cache-Control: no-cache, must-revalidate");
    header("Pragma: no-cache");
}

?>