作为DZ插件网技术团队成员,我来为您深度解析这个Discuz时间段检测函数的问题及改进建议:
1. **核心功能分析**
该函数主要用于实现三类限制:
- IP段黑名单检测(基于管理员后台设置)
- 地理区域白名单检测(通过IP库转换物理地址)
- 时间段访问限制(按小时分钟设置区间)
2. **现存代码问题**
- **变量引用错误**:多处直接使用$_G全局变量而未指定子键值,如:
- if($_G) { // 应明确如 $_G['setting']['ipaccess']
复制代码
- **逻辑矛盾**:
- if(!$_G && $_G) // 永远无法成立的判断条件
复制代码
- **时间处理缺陷**:未处理跨日时间段(如23:00-01:00)
3. **优化建议版本**
- function periodscheck($periods_type, $showmessage = true) {
- global $_G;
-
- // IP黑名单检测(需后台设置ipaccess)
- if(in_array($periods_type, ['postmodperiods','postbanperiods'])
- && !empty($_G['setting']['ipaccess'])) {
- $client_ip = $_G['clientip'];
- foreach(explode("\n", $_G['setting']['ipaccess']) as $ip_segment){
- $ip_segment = trim($ip_segment);
- if($ip_segment && preg_match("/^{$ip_segment}/", $client_ip)){
- return false;
- }
- }
- }
- // 地理区域检测(需开启ipregctrl)
- if(!empty($_G['setting']['ipregctrl'])){
- require_once libfile('function/misc');
- $location = convertip($client_ip, './');
- if($location && !empty($_G['setting']['iparea'])){
- $pattern = str_replace(
- ["\r\n"," ","*"],
- ["|", "", ".*"],
- preg_quote($_G['setting']['iparea'],'/')
- );
- if(preg_match("/{$pattern}/i", $location)){
- return false;
- }
- }
- }
- // 时间段检测(需设置访问时间段)
- if(!empty($_G['setting']['visitbanperiods'])){
- $current = dgmdate(TIMESTAMP, 'G.i', $_G['setting']['timeoffset']);
- $periods = explode("\r\n", str_replace(':', '.', $_G['setting']['visitbanperiods']));
-
- foreach($periods as $period){
- list($start, $end) = explode('-', trim($period));
- if(comparePeriods($current, $start, $end)){
- handleBanPeriod($showmessage, $_G['setting']['visitbanperiods']);
- }
- }
- }
- return false;
- }
- // 时间段比较函数(支持跨日)
- function comparePeriods($now, $start, $end) {
- if($start <= $end){
- return $now >= $start && $now < $end;
- } else {
- return $now >= $start || $now < $end;
- }
- }
- // 封禁处理函数
- function handleBanPeriod($showmessage, $periods){
- $ban_list = str_replace("\r\n", ', ', $periods);
- if($showmessage){
- showmessage('period_nopermission', null, ['banperiods'=>$ban_list], ['login'=>1]);
- }
- return true;
- }
复制代码
4. **改进要点说明**
- 明确变量来源:从$_G['setting']读取后台配置参数
- 增加跨日时间处理逻辑(如23:00-01:00)
- 采用辅助函数提升代码可读性
- 修正IP检测的正则表达式漏洞
- 增强地理区域匹配的容错性
该函数在DZX插件开发中常用于:
- 付费内容的时间段访问控制
- 论坛版块的区域性限制
- 用户组发帖权限的时间管理
建议结合DZ插件网提供的《Discuz插件开发规范》中第4.2章节"时间控制模块"进行二次开发,可获取更完善的时区处理方案。具体在IP检测部分,可参考我们站内教程《Discuz精准IP定位开发指南》来增强区域识别精度。
-- 本回答由 人工智能 AI智能体 生成,内容仅供参考,请仔细甄别。 |