helper.php 12.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 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 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
<?php

use App\Models\File\Image;
use App\Services\CosService;
use App\Utils\LogUtils;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Carbon;
use App\Models\UpdateNotify;

define('HTTP_OPENAI_URL', 'http://openai.waimaoq.com/');
/**
 * 生成路由标识
 * @param $string
 * @return string
 * @author zbj
 * @date 2023/4/15
 */

if (!function_exists('generateRoute')) {
    function generateRoute($string)
    {
        return trim(strtolower(preg_replace('/[\W]+/', '-', trim($string))), '-');
    }
}


/**
 * 手动记录错误日志
 * @param $title
 * @param $params
 * @param Throwable $exception
 * @author zbj
 * @date 2023/4/27
 */
function errorLog($title, $params, Throwable $exception)
{
    $exceptionMessage = "错误CODE:" . $exception->getCode() .
        "-----错误message:" . $exception->getMessage() .
        '------错误文件:' . $exception->getFile() .
        '-------错误行数:' . $exception->getLine();

    LogUtils::error($title, $params, $exceptionMessage);
}

if (!function_exists('http_post')) {
    /**
     * 发送http post请求
     * @param type $url
     * @param type $post_data
     */
    function http_post($url, $post_data, $header = [])
    {
        if (empty($header)) {
            $header = array(
                "Accept: application/json",
                "Content-Type:application/json;charset=utf-8",
            );
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $res = curl_exec($ch);
        if (curl_errno($ch)) {
            @file_put_contents(storage_path('logs/lyh_error.log'), var_export($res, true) . PHP_EOL, FILE_APPEND);
        }
        curl_close($ch);
        return json_decode($res, true);
    }
}


if (!function_exists('http_get')) {
    /**
     * 发送http get请求
     * @param type $url
     * @return type
     */
    function http_get($url, $header = [])
    {
        if (empty($header)) {
            $header[] = "content-type: application/json;
            charset = UTF-8";
        }
        $ch1     = curl_init();
        $timeout = 5;
        curl_setopt($ch1, CURLOPT_URL, $url);
        curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch1, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch1, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, false);
        $access_txt = curl_exec($ch1);
        \Illuminate\Support\Facades\Log::info($access_txt);
        curl_close($ch1);
        return json_decode($access_txt, true);
    }
}


if (!function_exists('_get_child')) {
    /**
     * 菜单权限->得到子级数组
     * @param int
     * @return array
     */
    function _get_child($my_id, $arr)
    {
        $new_arr = array();
        foreach ($arr as $k => $v) {
            $v = (array)$v;
            if ($v['pid'] == $my_id) {
                $v['sub']  = _get_child($v['id'], $arr);
                $new_arr[] = $v;
            }
        }
        return $new_arr ? $new_arr : false;
    }
}


if (!function_exists('checkDomain')) {
    /**
     * 检查并补全域名协议
     * @return false|string
     * @author zbj
     * @date 2023/5/5
     */
    function checkDomain($value)
    {
        $urlParts = parse_url(strtolower($value));
        if (empty($urlParts['host'])) {
            $urlParts = parse_url('https://' . $value);
        }
        $host   = $urlParts['host'] ?? '';
        $scheme = $urlParts['scheme'] ?? 'https';
        if (!in_array($scheme, ['http', 'https'])) {
            return false;
        }
        if (preg_match('/^(?:[-A-Za-z0-9]+\.)+[A-Za-z]{2,6}$/', $host)) {
            return $scheme . '://' . $host . '/';
        } else {
            return false;
        }
    }
}


/**
 * 把返回的数据集转换成Tree
 * @param $list array 数据列表
 * @param string|int $pk 主键|root
 * @param string $pid 父id
 * @param string $child 子键
 * @param int $root 获取哪个id下面
 * @param bool $empty_child 当子数据不存在,是否要返回空子数据
 * @return array
 */
function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0, $empty_child = true)
{
    // 如果是数字,则是root
    if (is_numeric($pk)) {
        $root = $pk;
        $pk   = 'id';
    }
    // 创建Tree
    $tree = array();
    if (is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            if ($empty_child) {
                $list[$key][$child] = [];
            }
            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $refer[$parentId][$child][] =   &$list[$key];
                }
            }
        }
    }
    return $tree;
}

/**
 * tree数据转list
 * @param $tree
 * @param string $child
 * @return array
 * @author:dc
 * @time 2022/1/11 10:13
 */
function tree_to_list($tree, $child = '_child')
{
    $lists = [];
    foreach ($tree as $item) {
        $c = $item[$child] ?? [];
        unset($item[$child]);
        $lists[] = $item;
        if ($c) {
            $lists = array_merge($lists, tree_to_list($c, $child));
        }
    }
    return $lists;
}

if (!function_exists('getThisWeekStarDate')) {
    /**
     * 获取本周一的日期
     * @return mixed
     * @author zbj
     * @date 2023/5/11
     */
    function getThisWeekStarDate()
    {
        return Carbon::now()->startOfWeek()->toDateString();
    }
}

if (!function_exists('object_to_array')) {
    /**
     * 获取本周一的日期
     * @return mixed
     * @author zbj
     * @date 2023/5/11
     */
    function object_to_array($data)
    {
        if (is_object($data)) {
            $data = (array)$data;
        } else {
            foreach ($data as $k => $v) {
                $data[$k] = object_to_array($v);
            }
        }
        return $data;
    }
}

if (!function_exists('getPreviousDaysDate')) {
    /**
     * 获取当前指定前几天日期,默认获取前三天日期
     * @param int $day
     * @return array
     */
    function getPreviousDaysDate(int $day = 3)
    {
        $days = [];
        while ($day > 0) {
            $days[] = date("Y-m-d", strtotime("-{$day} days"));
            $day    -= 1;
        }
        return $days;
    }
}

if (!function_exists('getPreviousMonthsDate')) {
    /**
     * 获取当前指定前几天日期,默认获取前三天日期
     * @param int $month
     * @return array
     */
    function getPreviousMonthsDate(int $month = 3)
    {
        $months = [];
        while ($month > 0) {
            $months[] = date("Y-m", strtotime("-{$month} months"));
            $month    -= 1;
        }
        return $months;
    }
}

if (!function_exists('getInquiryInformation')) {
    /**
     * 获取第三方询盘信息
     * @return array|string
     * @throws GuzzleException
     */
    function getInquiryInformation($domain, $sta_date)
    {
        $token  = md5($domain . date("Y-m-d"));
        $source = '1,3';
        $url    = "https://form.globalso.com/api/external-interface/country_con/15243d63ed5a5738?domain={$domain}&token={$token}&source={$source}&sta_date={$sta_date}";
        $client = new Client(['verify' => false]);
        $http   = $client->get($url);
        $data   = [];
        if ($http->getStatusCode() != 200) {
            return $data;
        }
        $content = $http->getBody()->getContents();
        $json    = json_decode($content, true);
        if ($json['status'] != 200) {
            return $content;
        }
        $data['count'] = $json['data']['count'];
        $data['lists'] = $json['data']['data'];
        return $data;
    }
}

if (!function_exists('stringUnderlineLowercase')) {
    /**
     * 正则 - 名字转为小写并将空格转为下划线
     * @param $name
     * @return string
     */
    function stringUnderlineLowercase($name)
    {
        return trim(strtolower(preg_replace('/[^a-zA-Z0-9]/', '_', $name)));
    }
}

if (!function_exists('checkIsGreaterMonth')) {
    /**
     * 判断传入日期是否大于当月
     * @param $date
     * @return bool
     */
    function checkIsGreaterMonth($date)
    {
        // 传入日期的时间戳
        $timestamp = strtotime($date);
        // 当前月份的时间戳
        $nowMonth = strtotime(date('Y-m'));
        // 判断传入日期是否大于当前月份
        return $timestamp > $nowMonth;
    }
}

if (!function_exists('checkIsMonth')) {
    /**
     * 判断传入日期是否是当月
     * @param $date
     * @return bool
     */
    function checkIsMonth($date)
    {
        // 获取当前时间戳
        $now = time();
        // 获取当月的起始时间戳和结束时间戳
        $firstDay = strtotime(date('Y-m-01', $now));
        $lastDay  = strtotime(date('Y-m-t', $now));
        // 传入日期的时间戳
        $timestamp = strtotime($date);
        // 判断传入日期是否在当月范围内
        return $timestamp >= $firstDay && $timestamp <= $lastDay;
    }
}

if (!function_exists('getDateDays')) {
    /**
     * 返回当月到今天的天数
     * @param string|null $date 日期,格式:Y-m
     * @return array
     */
    function getDateDays(string $date = null)
    {
        list($year, $month, $day) = explode('-', date('Y-m-d'));
        // 获取当前月的第一天
        $first_day_of_month = "{$year}-{$month}-01";
        // 获取今天的日期
        $today = "{$year}-{$month}-{$day}";
        if (!is_null($date)) {
            $dd = explode('-', $date);
            if (!checkIsGreaterMonth($date) && !checkIsMonth($date)) {
                $year               = $dd[0];
                $month              = $dd[1];
                $first_day_of_month = "{$year}-{$month}-01";
                return getDateArray("{$year}-{$month}-" . date("t", strtotime($first_day_of_month)));
            }
        }
        $day_timestamp = strtotime($today) - strtotime($first_day_of_month);
        return getDateArray("{$year}-{$month}-" . date('d', $day_timestamp));
    }
}

if (!function_exists('getDateArray')) {
    /**
     * 获取当月获取日期
     * @param string $date 日期,格式:Y-m-d
     * @return array
     */
    function getDateArray(string $date)
    {
        list($year, $month, $day) = explode('-', date($date));
        $i    = 1;
        $days = [];
        while ($i <= $day) {
            $days[] = "{$year}-{$month}-" . str_pad($i, 2, "0", STR_PAD_LEFT);
            $i++;
        }
        return $days;
    }
}

if (!function_exists('getImageUrl')) {
    /**
     * @remark :获取图片链接
     * @name   :getImageUrl
     * @author :lyh
     * @method :post
     * @time   :2023/7/20 16:46
     */
    function getImageUrl($hash){
        if(is_array($hash)){
            foreach ($hash as $v){
                $url[] = getImageUrl($v);
            }
        }else{
            $imageModel = new Image();
            $info = $imageModel->read(['hash'=>$hash]);
            if(!empty($info)){
                if($info['is_cos'] == 1){
                    $cos = new CosService();
                    $url = $cos->getImageUrl($info['path']);
                }else{
                    $url = url('a/image/'.$info['hash']);
                }
            }else{
                $url = $hash;
            }
        }
        return $url;
    }
}

/**
 * @remark :字符串截取
 * @name   :characterTruncation
 * @author :lyh
 * @method :post
 * @time   :2023/6/28 17:39
 */
function characterTruncation($string,$pattern){
    preg_match($pattern, $string, $matches);
    if (isset($matches[0])) {
        $result = $matches[0];
        return $result; // 输出:这是footer标签的内容
    } else {
        return '';
    }
}