<?php
// +----------------------------------------------------------------------
// | A3Mall
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.a3-mall.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xzncit <158373108@qq.com>
// +----------------------------------------------------------------------

namespace app\common\library\utils;

use app\common\library\utils\Image;
use app\common\library\file\File;

/**
 * @package app\common\library\utils
 * @class CString
 * @author xzncit 2023-08-25
 */
class CString {

    /**
     * 截取UTF-8编码下字符串的函数
     * @param   string      $str        被截取的字符串
     * @param   int         $length     截取的长度
     * @param   bool        $append     是否附加省略号
     * @return  string
     */
    public static function msubstr($str, $length = 0, $append = true) {
        $str = trim($str);
        $strlength = strlen($str);

        if ($length == 0 || $length >= $strlength) {
            return $str;
        } elseif ($length < 0) {
            $length = $strlength + $length;
            if ($length < 0) {
                $length = $strlength;
            }
        }

        if (function_exists('mb_substr')) {
            $newstr = mb_substr($str, 0, $length);
        } elseif (function_exists('iconv_substr')) {
            $newstr = iconv_substr($str, 0, $length);
        } else {
            $newstr = substr($str, 0, $length);
        }

        if ($append && $str != $newstr) {
            $newstr .= '...';
        }

        return self::removeEmojiChar($newstr);
    }

    /**
     * 过滤文本XSS
     * @param $string
     * @return string
     */
    public static function filter($string){
        if(empty($string)) return $string;
        $path = File::getPath() . 'runtime/cache/htmlpurifier';
        if(!file_exists($path)){
            mkdir($path,0777,true);
        }

        $config = \HTMLPurifier_Config::createDefault();
        $config->set('Cache.SerializerPath',$path);
        $config->set('HTML.SafeEmbed',true);
        $config->set('HTML.SafeObject',true);
        $config->set('HTML.SafeIframe',true);
        $config->set('Output.FlashCompat',true);
        $config->set('Attr.EnableID',true);
        $config->set('Core.Encoding','UTF-8');
        $def = $config->getHTMLDefinition(true);
        $def->addAttribute('a', 'target', 'Enum#_blank,_self,_target,_top');
        $def->addAttribute('iframe', 'src',"URI");
        return (new \HTMLPurifier($config))->purify($string);
    }

    /**
     * 删除多余空白字符
     * @param string $string
     * @return string
     */
    public static function trim($string) {
        $value = str_replace(["&nbsp;", "　"], [' ', ' '], $string);
        return trim(preg_replace("/[\r\n\t ]{1,}/", '', $value));
    }

}