<?php
defined('EMLOG_ROOT') || exit('access denied!');


if (!function_exists('get_client_browser')) {
    /**
     * 获取客户端浏览器以及版本号
     * @param $agent //$_SERVER['HTTP_USER_AGENT']
     * @return array
     */
    function get_client_browser($agent = '')
    {
        $browser = '';
        $browser_ver = '';
        if (preg_match('/OmniWeb\/(v*)([^\s|;]+)/i', $agent, $regs)) {
            $browser = 'OmniWeb';
            $browser_ver = $regs[2];
        }
        if (preg_match('/Netscape([\d]*)\/([^\s]+)/i', $agent, $regs)) {
            $browser = 'Netscape';
            $browser_ver = $regs[2];
        }
        if (preg_match('/safari\/([^\s]+)/i', $agent, $regs)) {
            $browser = 'Safari';
            $browser_ver = $regs[1];
        }
        if (preg_match('/MSIE\s([^\s|;]+)/i', $agent, $regs)) {
            $browser = 'Internet Explorer';
            $browser_ver = $regs[1];
        }
        if (preg_match('/Opera[\s|\/]([^\s]+)/i', $agent, $regs)) {
            $browser = 'Opera';
            $browser_ver = $regs[1];
        }
        if (preg_match('/NetCaptor\s([^\s|;]+)/i', $agent, $regs)) {
            $browser = '(Internet Explorer ' . $browser_ver . ') NetCaptor';
            $browser_ver = $regs[1];
        }
        if (preg_match('/Maxthon/i', $agent, $regs)) {
            $browser = '(Internet Explorer ' . $browser_ver . ') Maxthon';
            $browser_ver = '';
        }
        if (preg_match('/360SE/i', $agent, $regs)) {
            $browser = '(Internet Explorer ' . $browser_ver . ') 360SE';
            $browser_ver = '';
        }
        if (preg_match('/SE 2.x/i', $agent, $regs)) {
            $browser = '(Internet Explorer ' . $browser_ver . ') Sougou Browser';
            $browser_ver = '';
        }
        if (preg_match('/FireFox\/([^\s]+)/i', $agent, $regs)) {
            $browser = 'FireFox';
            $browser_ver = $regs[1];
        }
        if (preg_match('/Lynx\/([^\s]+)/i', $agent, $regs)) {
            $browser = 'Lynx';
            $browser_ver = $regs[1];
        }
        if (preg_match('/Chrome\/([^\s]+)/i', $agent, $regs)) {
            $browser = 'Chrome';
            $browser_ver = $regs[1];
        }
        if (preg_match('/MicroMessenger\/([^\s]+)/i', $agent, $regs)) {
            $browser = 'Wechat Browser';
            $browser_ver = $regs[1];
        }
        if ($browser != '') {
            return $browser;
        } else {
            return 'Unknown Browser';
        }
    }
}

if (!function_exists('get_client_os')) {
    /**
     * 获取客户端操作系统
     * @param $agent //$_SERVER['HTTP_USER_AGENT']
     * @return array[os]            操作系统名称
     * @return array[os_ver]        操作系统版本号
     * @return array[equipment]     终端设备类型
     */
    function get_client_os($agent = '')
    {
        //window系统
        if (stripos($agent, 'window')) {
            $os = 'Windows';
            if (preg_match('/nt 6.0/i', $agent)) {
                $os_ver = 'Vista';
            } elseif (preg_match('/nt 10.0/i', $agent)) {
                $os_ver = '10';
            } elseif (preg_match('/nt 6.3/i', $agent)) {
                $os_ver = '8.1';
            } elseif (preg_match('/nt 6.2/i', $agent)) {
                $os_ver = '8.0';
            } elseif (preg_match('/nt 6.1/i', $agent)) {
                $os_ver = '7';
            } elseif (preg_match('/nt 5.1/i', $agent)) {
                $os_ver = 'XP';
            } elseif (preg_match('/nt 5/i', $agent)) {
                $os_ver = '2000';
            } elseif (preg_match('/nt 98/i', $agent)) {
                $os_ver = '98';
            } elseif (preg_match('/nt/i', $agent)) {
                $os_ver = 'nt';
            } else {
                $os_ver = '';
            }
            // if (preg_match('/x64/i', $agent)) {
            //     $os .= '(x64)';
            // }elseif(preg_match('/x32/i', $agent)){
            //     $os .= '(x32)';
            // }
        } elseif (stripos($agent, 'linux')) {
            if (stripos($agent, 'android')) {
                preg_match('/android\s([\d\.]+)/i', $agent, $match);
                $os = 'Android';
                // $os_ver = $match[1];
            } else {
                $os = 'Linux';
            }
        } elseif (stripos($agent, 'unix')) {
            $os = 'Unix';
        } elseif (preg_match('/iPhone|iPad|iPod/i', $agent)) {
            preg_match('/OS\s([0-9_\.]+)/i', $agent, $match);
            $os = '';
            $os_ver = str_replace('_', '.', $match[1]);
            if (preg_match('/iPhone/i', $agent)) {
                $os = 'iPhone';
            } elseif (preg_match('/iPad/i', $agent)) {
                $os = 'iPad';
            } elseif (preg_match('/iPod/i', $agent)) {
                $os = 'iPod';
            }
        } elseif (stripos($agent, 'mac os')) {
            preg_match('/Mac OS X\s([0-9_\.]+)/i', $agent, $match);
            $os = 'Mac';
            $os_ver = str_replace('_', '.', $match[1]);
        } else {
            $os = 'Other';
            $os_ver = '';
        }
        return $os . ' ' . $os_ver;
    }
}

if (!function_exists('calculate_reading_time')) {
    function calculate_reading_time($str, $readingSpeed = 200)
    {
        /**
         * 根据文本长度获取阅读时间
         * @param string $str
         * @param int $length
         * @return array|string|string[]|null
         */
        $textLength = mb_strlen(strip_html_tags($str, 99999));
        $seconds = $textLength / $readingSpeed;
        if ($seconds < 1)
            return "本文约<span class=\"value\">{$textLength}</span>字，阅读需<span class=\"unit\">1</span>分钟";
        $intervals = array(
            60 => '小时',
            1  => '分钟'
        );
        foreach ($intervals as $second => $unit) {
            $value = $seconds / $second;
            if ($value >= 1) {
                return "本文约<span class=\"value\">{$textLength}</span>字，阅读需<span class=\"unit\">" . round($value) . "</span>{$unit}";
            }
        };
    }
}

if (!function_exists('str_to_timestamp')) {
    /**
     * 时间戳或时间转为标准时间戳
     * @param string $str
     * @return string|false
     */
    function str_to_timestamp($str)
    {
        if (is_numeric($str) && date('Y-m-d H:i:s', substr((string)$str, 0, 10)) !== false) {
            return substr((string)$str, 0, 10);
        } elseif (strtotime($str) !== false) {
            return strtotime($str);
        } else {
            return false;
        }
    }
}

if (!function_exists('sub_string')) {
    /**
     * 字符串截断
     * @param string $str
     * @param int $length
     * @param string $ending
     * @return string
     */
    function sub_string($str, $length, $ending = '…')
    {
        $ending = mb_strlen($str) > $length ? $ending : '';
        return mb_substr($str, 0, $length, "utf-8") . $ending;
    }
}


if (!function_exists('strip_html_tags')) {
    /**
     * 去除HTML标签、图像等 仅保留文本
     * @param string $str
     * @param int $length
     * @return array|string|string[]|null
     */
    function strip_html_tags($str)
    {
        // HTML实体转换为字符
        $str = htmlspecialchars_decode($str);
        // 去除空格
        $str = str_replace(" ", "", $str);
        // 去除字符串中的 HTML、XML 以及 PHP 的标签，获取纯文本内容
        $str = strip_tags($str);
        // 去除换行
        $str = str_replace(array("\n", "\r\n", "\r"), '', $str);
        // 去除Script
        $preg = '/<script[\s\S]*?<\/script>/i';
        // 剥离JS代码
        $str = preg_replace($preg, "", $str, -1);
        return $str;
    }
}

if (!function_exists('get_data_log')) {
    /**
     * 获取文章详情
     * @param int $gid
     * @return array
     */
    function get_data_log($gid)
    {
        $db = Database::getInstance();
        $query = $db->query("SELECT * FROM " . DB_PREFIX . "blog WHERE gid=$gid");
        return $db->fetch_array($query);
    }
}

if (!function_exists('studio_string_to_array')) {
    /**
     * 文本配置解析为数组
     * @param string $field
     * @param int $start
     * @param int $length
     * @return array|string
     */
    function studio_string_to_array($field, $start, $length = 2)
    {
        $str = _g($field);
        if (empty($str))
            return $str;
        $arr = explode("\n", $str);
        $res = [];
        foreach ($arr as $index => $item) {
            $items = explode("||", $item);
            array_push($res, $items);
        }
        return array_slice($res, $start, $length);
    }
}

if (!function_exists('blogger_aggregates')) {
    /**
     * 获取博客统计信息
     * @return array
     */
    function blogger_aggregates()
    {
        $CACHE = Cache::getInstance();
        $sta_cache = $CACHE->readCache('sta');
        $user_cache = $CACHE->readCache('user');
        return [
            '文章数' => $sta_cache['lognum'],
            '评论数' => $sta_cache['comnum_all'],
            '用户数' => count($user_cache),
        ];
    }
}

if (!function_exists('time_ago')) {
    /**
     * 返回指定时间戳为当前时间戳的几秒前、几分钟前、几小时前…
     * @param int $timestamp
     * @return string || null
     */
    function time_ago($time)
    {
        $timestamp = str_to_timestamp($time);
        if (!$timestamp)
            return;
        $difference = time() - $timestamp;
        if ($difference < 10)
            return '刚刚';
        $intervals = array(
            12 * 30 * 24 * 60 * 60 => '年前',
            30 * 24 * 60 * 60      => '个月前',
            7 * 24 * 60 * 60       => '周前',
            24 * 60 * 60           => '天前',
            60 * 60                => '小时前',
            60                     => '分钟前',
            1                      => '秒前',
        );
        foreach ($intervals as $second => $unit) {
            $value = $difference / $second;
            if ($value >= 1) {
                return round($value) . $unit;
            }
        };
    }
}
