<?php
// +----------------------------------------------------------------------
// | Wendasns [ 开源问答社区系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020~2021 http://wendasns.com All rights reserved.
// +----------------------------------------------------------------------	
namespace wendasns;

class Filter
{

    /**
     * 解析登录账号
     *
     * @param string $name cookie名称
     * @param string $pre  cookie前缀,默认为null即没有前缀
     *
     * @return bool
     */
	public function safeAccount($account){
    	if(preg_match("/^1[345768]{1}\d{9}$/", $account)){
    		return ['mobile',$account];
    	}elseif(filter_var($account, FILTER_VALIDATE_EMAIL)){
    		return ['email',$account];
    	}else{
    		return ['username',$account];
    	}
    }

    /**
     * 过滤提问/回答/文章html标签
     *
     * @param string $content 过滤内容
     *
     * @return string
     */
	public function htmlToUbb($content){
		$pattern = [
			'/<p>(.*?)<\/p>/',
			'/<p.*style="(.*?)".*?>(.*?)<\/p>/',
			'/<b>(.*?)<\/b>/',//加粗
			'/<i>(.*?)<\/i>/',//斜体
			'/<img.*src="(.*?)".*?>/',
			'/<a.*href="(.*?)".*?>(.*?)<\/a>/',
			'/<br>/',
		];
		$replace = [
			'[p]${1}[/p]',
			'[p=${1}]${2}[/p]',
			'[b]${1}[/b]',
			'[i]${1}[/i]',
			'[img]${1}[/img]',
			'[url=${1}]${2}[/url]',
			'[br]',
		];
		$content = preg_replace($pattern, $replace, $content);
    	//$content = htmlspecialchars($content);//把预定义的字符 "<" （小于）和 ">" （大于）转换为 HTML 实体：
    	$content = strip_tags($content);//剥去字符串中的 HTML 标签
    	$content = $this->ubbToHtml($content);
    	//$content = addslashes($content);//在每个双引号（"）前添加反斜杠：
    	return $content;
    }

    /**
     * 过滤提问/回答/文章html标签
     *
     * @param string $content 过滤内容
     *
     * @return string
     */
	public function ubbToHtml($content){
		$pattern = [
			'/\[p\](.*?)\[\/p\]/',
			'/\[p=(.*?)\](.*?)\[\/p\]/',
			'/\[b\](.*?)\[\/b\]/',
			'/\[i\](.*?)\[\/i\]/',
			'/\[img\](.*?)\[\/img\]/',
			'/\[url=(.*?)\](.*?)\[\/url\]/',
			'/\[br\]/',
		];
		$replace = [
			'<p>${1}</p>',
			'<p style="${1}">${2}</p>',
			'<b>${1}</b>',
			'<i>${1}</i>',
			'<img src="${1}" alt=""/>',
			'<a href="${1}" target="_blank">${2}</a>',
			'<br>',
		];
		$content = preg_replace($pattern, $replace, $content);
    	return $content;
    }
    
    /**
     * 过滤html标签，sql注入，返回纯文本
     *
     * @param string $content 内容
     *
     * @return string
     */
    public function cleanHtml($content){
    	$content = htmlspecialchars($content);
    	$content = addslashes($content);
    	return $content;
    }
    
    //表单空值过滤
    public function emptyFilter($vars, $default)
    {
    	return $vars ? $vars : $default;
    }
}