审查视图

application/common.php 11.6 KB
Karson authored
1 2 3 4
<?php

// 公共助手函数
Karson authored
5 6
use Symfony\Component\VarExporter\VarExporter;
7
if (!function_exists('__')) {
Karson authored
8 9 10

    /**
     * 获取语言变量值
11
     * @param string $name 语言变量名
12
     * @param array  $vars 动态变量值
13
     * @param string $lang 语言
Karson authored
14 15 16 17
     * @return mixed
     */
    function __($name, $vars = [], $lang = '')
    {
18
        if (is_numeric($name) || !$name) {
Karson authored
19
            return $name;
20
        }
21
        if (!is_array($vars)) {
Karson authored
22 23 24 25
            $vars = func_get_args();
            array_shift($vars);
            $lang = '';
        }
26
        return \think\Lang::get($name, $vars, $lang);
Karson authored
27 28 29
    }
}
30
if (!function_exists('format_bytes')) {
Karson authored
31 32 33

    /**
     * 将字节转换为可读文本
34
     * @param int    $size      大小
Karson authored
35 36 37 38 39 40
     * @param string $delimiter 分隔符
     * @return string
     */
    function format_bytes($size, $delimiter = '')
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
41
        for ($i = 0; $size >= 1024 && $i < 6; $i++) {
Karson authored
42
            $size /= 1024;
43
        }
Karson authored
44 45 46 47
        return round($size, 2) . $delimiter . $units[$i];
    }
}
48
if (!function_exists('datetime')) {
Karson authored
49 50 51

    /**
     * 将时间戳转换为日期时间
52
     * @param int    $time   时间戳
Karson authored
53 54 55 56 57 58 59 60 61 62
     * @param string $format 日期时间格式
     * @return string
     */
    function datetime($time, $format = 'Y-m-d H:i:s')
    {
        $time = is_numeric($time) ? $time : strtotime($time);
        return date($format, $time);
    }
}
63
if (!function_exists('human_date')) {
Karson authored
64 65 66

    /**
     * 获取语义化时间
67
     * @param int $time  时间
Karson authored
68 69 70 71 72 73 74 75 76
     * @param int $local 本地时间
     * @return string
     */
    function human_date($time, $local = null)
    {
        return \fast\Date::human($time, $local);
    }
}
77
if (!function_exists('cdnurl')) {
Karson authored
78 79 80

    /**
     * 获取上传资源的CDN的地址
81
     * @param string  $url    资源相对地址
82
     * @param boolean $domain 是否显示域名 或者直接传入域名
Karson authored
83 84
     * @return string
     */
85
    function cdnurl($url, $domain = false)
Karson authored
86
    {
87 88 89
        $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
        $url = preg_match($regex, $url) ? $url : \think\Config::get('upload.cdnurl') . $url;
        if ($domain && !preg_match($regex, $url)) {
90 91
            $domain = is_bool($domain) ? request()->domain() : $domain;
            $url = $domain . $url;
92 93
        }
        return $url;
Karson authored
94 95 96 97
    }
}

98
if (!function_exists('is_really_writable')) {
Karson authored
99 100 101

    /**
     * 判断文件或文件夹是否可写
Karson authored
102
     * @param string $file 文件或目录
103
     * @return    bool
Karson authored
104 105 106
     */
    function is_really_writable($file)
    {
107
        if (DIRECTORY_SEPARATOR === '/') {
Karson authored
108 109
            return is_writable($file);
        }
110
        if (is_dir($file)) {
Karson authored
111
            $file = rtrim($file, '/') . '/' . md5(mt_rand());
112 113
            if (($fp = @fopen($file, 'ab')) === false) {
                return false;
Karson authored
114 115 116 117
            }
            fclose($fp);
            @chmod($file, 0777);
            @unlink($file);
118 119 120
            return true;
        } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
            return false;
Karson authored
121 122
        }
        fclose($fp);
123
        return true;
Karson authored
124 125 126
    }
}
127
if (!function_exists('rmdirs')) {
Karson authored
128 129 130

    /**
     * 删除文件夹
131 132
     * @param string $dirname  目录
     * @param bool   $withself 是否删除自身
Karson authored
133 134 135 136
     * @return boolean
     */
    function rmdirs($dirname, $withself = true)
    {
137
        if (!is_dir($dirname)) {
Karson authored
138
            return false;
139
        }
Karson authored
140
        $files = new RecursiveIteratorIterator(
141 142
            new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
Karson authored
143 144
        );
145
        foreach ($files as $fileinfo) {
Karson authored
146 147 148
            $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
            $todo($fileinfo->getRealPath());
        }
149
        if ($withself) {
Karson authored
150 151 152 153 154 155
            @rmdir($dirname);
        }
        return true;
    }
}
156
if (!function_exists('copydirs')) {
Karson authored
157 158 159 160

    /**
     * 复制文件夹
     * @param string $source 源文件夹
161
     * @param string $dest   目标文件夹
Karson authored
162 163 164
     */
    function copydirs($source, $dest)
    {
165 166
        if (!is_dir($dest)) {
            mkdir($dest, 0755, true);
Karson authored
167 168
        }
        foreach (
169
            $iterator = new RecursiveIteratorIterator(
170 171 172
                new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::SELF_FIRST
            ) as $item
173 174
        ) {
            if ($item->isDir()) {
Karson authored
175
                $sontDir = $dest . DS . $iterator->getSubPathName();
176 177
                if (!is_dir($sontDir)) {
                    mkdir($sontDir, 0755, true);
Karson authored
178
                }
179
            } else {
Karson authored
180 181 182 183 184 185
                copy($item, $dest . DS . $iterator->getSubPathName());
            }
        }
    }
}
186
if (!function_exists('mb_ucfirst')) {
Karson authored
187 188 189 190 191 192
    function mb_ucfirst($string)
    {
        return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
    }
}
193
if (!function_exists('addtion')) {
Karson authored
194 195 196

    /**
     * 附加关联字段数据
197
     * @param array $items  数据列表
Karson authored
198 199 200 201 202
     * @param mixed $fields 渲染的来源字段
     * @return array
     */
    function addtion($items, $fields)
    {
203
        if (!$items || !$fields) {
Karson authored
204
            return $items;
205
        }
Karson authored
206
        $fieldsArr = [];
207
        if (!is_array($fields)) {
Karson authored
208
            $arr = explode(',', $fields);
209
            foreach ($arr as $k => $v) {
Karson authored
210 211
                $fieldsArr[$v] = ['field' => $v];
            }
212 213 214
        } else {
            foreach ($fields as $k => $v) {
                if (is_array($v)) {
Karson authored
215
                    $v['field'] = isset($v['field']) ? $v['field'] : $k;
216
                } else {
Karson authored
217 218 219 220 221
                    $v = ['field' => $v];
                }
                $fieldsArr[$v['field']] = $v;
            }
        }
222
        foreach ($fieldsArr as $k => &$v) {
Karson authored
223 224 225 226 227 228 229 230 231 232 233
            $v = is_array($v) ? $v : ['field' => $v];
            $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
            $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
            $v['column'] = isset($v['column']) ? $v['column'] : 'name';
            $v['model'] = isset($v['model']) ? $v['model'] : '';
            $v['table'] = isset($v['table']) ? $v['table'] : '';
            $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
        }
        unset($v);
        $ids = [];
        $fields = array_keys($fieldsArr);
234 235 236
        foreach ($items as $k => $v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
Karson authored
237 238 239 240 241
                    $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
                }
            }
        }
        $result = [];
242 243
        foreach ($fieldsArr as $k => $v) {
            if ($v['model']) {
Karson authored
244
                $model = new $v['model'];
245
            } else {
Karson authored
246 247 248 249 250 251
                $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
            }
            $primary = $v['primary'] ? $v['primary'] : $model->getPk();
            $result[$v['field']] = $model->where($primary, 'in', $ids[$v['field']])->column("{$primary},{$v['column']}");
        }
252 253 254
        foreach ($items as $k => &$v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
Karson authored
255 256 257 258 259 260 261 262 263
                    $curr = array_flip(explode(',', $v[$n]));

                    $v[$fieldsArr[$n]['display']] = implode(',', array_intersect_key($result[$n], $curr));
                }
            }
        }
        return $items;
    }
}
264
265
if (!function_exists('var_export_short')) {
266 267 268

    /**
     * 返回打印数组结构
Karson authored
269
     * @param string $var 数组
270 271
     * @return string
     */
Karson authored
272
    function var_export_short($var)
273
    {
Karson authored
274
        return VarExporter::export($var);
275
    }
276
}
277
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
if (!function_exists('letter_avatar')) {
    /**
     * 首字母头像
     * @param $text
     * @return string
     */
    function letter_avatar($text)
    {
        $total = unpack('L', hash('adler32', $text, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

        $bg = "rgb({$r},{$g},{$b})";
        $color = "#ffffff";
        $first = mb_strtoupper(mb_substr($text, 0, 1));
Karson authored
293
        $src = base64_encode('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" width="100" height="100"></rect><text x="50" y="50" font-size="50" text-copy="fast" fill="' . $color . '" text-anchor="middle" text-rights="admin" alignment-baseline="central">' . $first . '</text></svg>');
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
        $value = 'data:image/svg+xml;base64,' . $src;
        return $value;
    }
}

if (!function_exists('hsv2rgb')) {
    function hsv2rgb($h, $s, $v)
    {
        $r = $g = $b = 0;

        $i = floor($h * 6);
        $f = $h * 6 - $i;
        $p = $v * (1 - $s);
        $q = $v * (1 - $f * $s);
        $t = $v * (1 - (1 - $f) * $s);

        switch ($i % 6) {
            case 0:
                $r = $v;
                $g = $t;
                $b = $p;
                break;
            case 1:
                $r = $q;
                $g = $v;
                $b = $p;
                break;
            case 2:
                $r = $p;
                $g = $v;
                $b = $t;
                break;
            case 3:
                $r = $p;
                $g = $q;
                $b = $v;
                break;
            case 4:
                $r = $t;
                $g = $p;
                $b = $v;
                break;
            case 5:
                $r = $v;
                $g = $p;
                $b = $q;
                break;
        }

        return [
            floor($r * 255),
            floor($g * 255),
            floor($b * 255)
        ];
    }
}
Karson authored
350
351
if (!function_exists('check_nav_active')) {
Karson authored
352
    /**
353
     * 检测会员中心导航是否高亮
Karson authored
354
     */
355 356 357 358 359 360 361 362 363 364 365 366 367 368
    function check_nav_active($url, $classname = 'active')
    {
        $auth = \app\common\library\Auth::instance();
        $requestUrl = $auth->getRequestUri();
        $url = ltrim($url, '/');
        return $requestUrl === str_replace(".", "/", $url) ? $classname : '';
    }
}

if (!function_exists('check_cors_request')) {
    /**
     * 跨域检测
     */
    function check_cors_request()
Karson authored
369 370 371 372
    {
        if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN']) {
            $info = parse_url($_SERVER['HTTP_ORIGIN']);
            $domainArr = explode(',', config('fastadmin.cors_request_domain'));
373
            $domainArr[] = request()->host(true);
Karson authored
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
            if (in_array("*", $domainArr) || in_array($_SERVER['HTTP_ORIGIN'], $domainArr) || (isset($info['host']) && in_array($info['host'], $domainArr))) {
                header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
            } else {
                header('HTTP/1.1 403 Forbidden');
                exit;
            }

            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Max-Age: 86400');

            if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
                if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
                    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
                }
                if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
                    header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
                }
                exit;
            }
        }
    }
}
Karson authored
396 397 398 399 400 401 402 403 404 405

if (!function_exists('xss_clean')) {
    /**
     * 清理XSS
     */
    function xss_clean($content, $is_image = false)
    {
        return \app\common\library\Security::instance()->xss_clean($content, $is_image);
    }
}