| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575 |
- <?php
- // +----------------------------------------------------------------------
- // | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
- // +----------------------------------------------------------------------
- // | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
- // +----------------------------------------------------------------------
- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
- // +---------------------------------------------------------------------
- // | Author: Dean <zxxjjforever@163.com>
- // +----------------------------------------------------------------------
- use think\Db;
- use think\facade\Env;
- use think\facade\Url;
- use dir\Dir;
- use think\facade\Route;
- use think\Loader;
- use cmf\lib\Storage;
- use think\facade\Hook;
- // 应用公共文件
- if (PHP_SAPI == 'cli') {
- $apps = cmf_scan_dir(APP_PATH . '*', GLOB_ONLYDIR);
- foreach ($apps as $app) {
- $commandFile = APP_PATH . $app . '/command.php';
- if (file_exists($commandFile)) {
- $commands = include $commandFile;
- // 注册命令行指令
- \think\Console::addDefaultCommands($commands);
- }
- }
- }
- /**
- * 获取当前登录的管理员ID
- * @return int
- */
- function cmf_get_current_admin_id()
- {
- return session('ADMIN_ID');
- }
- /**
- * 判断前台用户是否登录
- * @return boolean
- */
- function cmf_is_user_login()
- {
- $sessionUser = session('user');
- return !empty($sessionUser);
- }
- /**
- * 获取当前登录的前台用户的信息,未登录时,返回false
- * @return array|boolean
- */
- function cmf_get_current_user()
- {
- $sessionUser = session('user');
- if (!empty($sessionUser)) {
- unset($sessionUser['user_pass']); // 销毁敏感数据
- return $sessionUser;
- } else {
- return false;
- }
- }
- /**
- * 更新当前登录前台用户的信息
- * @param array $user 前台用户的信息
- */
- function cmf_update_current_user($user)
- {
- session('user', $user);
- }
- /**
- * 获取当前登录前台用户id
- * @return int
- */
- function cmf_get_current_user_id()
- {
- $sessionUserId = session('user.id');
- if (empty($sessionUserId)) {
- return 0;
- }
- return $sessionUserId;
- }
- /**
- * 返回带协议的域名
- */
- function cmf_get_domain()
- {
- return request()->domain();
- }
- /**
- * 获取网站根目录
- * @return string 网站根目录
- */
- function cmf_get_root()
- {
- $root = request()->root();
- $root = str_replace("//", '/', $root);
- $root = str_replace('/index.php', '', $root);
- if (defined('APP_NAMESPACE') && APP_NAMESPACE == 'api') {
- $root = preg_replace('/\/api(.php)$/', '', $root);
- }
- $root = rtrim($root, '/');
- return $root;
- }
- /**
- * 获取当前主题名
- * @return string
- */
- function cmf_get_current_theme()
- {
- if (PHP_SAPI != 'cli') {
- static $_currentTheme;
- if (!empty($_currentTheme)) {
- return $_currentTheme;
- }
- }
- $t = 't';
- $theme = config('template.cmf_default_theme');
- $cmfDetectTheme = config('template.cmf_detect_theme');
- if ($cmfDetectTheme) {
- if (isset($_GET[$t])) {
- $theme = $_GET[$t];
- cookie('cmf_template', $theme, 864000);
- } elseif (cookie('cmf_template')) {
- $theme = cookie('cmf_template');
- }
- }
- $hookTheme = hook_one('switch_theme');
- if ($hookTheme) {
- $theme = $hookTheme;
- }
- $designT = '_design_theme';
- if (isset($_GET[$designT])) {
- $theme = $_GET[$designT];
- cookie('cmf_design_theme', $theme, 4);
- } elseif (cookie('cmf_design_theme')) {
- $theme = cookie('cmf_design_theme');
- }
- $_currentTheme = $theme;
- return $theme;
- }
- /**
- * 获取当前后台主题名
- * @return string
- */
- function cmf_get_current_admin_theme()
- {
- if (PHP_SAPI != 'cli') {
- static $_currentAdminTheme;
- if (!empty($_currentAdminTheme)) {
- return $_currentAdminTheme;
- }
- }
- $t = '_at';
- $theme = config('template.cmf_admin_default_theme');
- $cmfDetectTheme = true;
- if ($cmfDetectTheme) {
- if (isset($_GET[$t])) {
- $theme = $_GET[$t];
- cookie('cmf_admin_theme', $theme, 864000);
- } elseif (cookie('cmf_admin_theme')) {
- $theme = cookie('cmf_admin_theme');
- }
- }
- $hookTheme = hook_one('switch_admin_theme');
- if ($hookTheme) {
- $theme = $hookTheme;
- }
- $_currentAdminTheme = $theme;
- return $theme;
- }
- /**
- * 获取前台模板根目录
- * @param string $theme
- * @return string 前台模板根目录
- */
- function cmf_get_theme_path($theme = null)
- {
- $themePath = config('template.cmf_theme_path');
- if ($theme === null) {
- // 获取当前主题名称
- $theme = cmf_get_current_theme();
- }
- return WEB_ROOT . $themePath . $theme;
- }
- /**
- * 获取用户头像地址
- * @param $avatar 用户头像文件路径,相对于 upload 目录
- * @return string
- */
- function cmf_get_user_avatar_url($avatar)
- {
- if (!empty($avatar)) {
- if (strpos($avatar, "http") === 0) {
- return $avatar;
- } else {
- return cmf_get_image_url($avatar, 'avatar');
- }
- } else {
- return $avatar;
- }
- }
- /**
- * CMF密码加密方法
- * @param string $pw 要加密的原始密码
- * @param string $authCode 加密字符串
- * @return string
- */
- function cmf_password($pw, $authCode = '')
- {
- if (empty($authCode)) {
- $authCode = config('database.authcode');
- }
- $result = "###" . md5(md5($authCode . $pw));
- return $result;
- }
- /**
- * CMF密码加密方法 (X2.0.0以前的方法)
- * @param string $pw 要加密的原始密码
- * @return string
- */
- function cmf_password_old($pw)
- {
- $decor = md5(config('database.prefix'));
- $mi = md5($pw);
- return substr($decor, 0, 12) . $mi . substr($decor, -4, 4);
- }
- /**
- * CMF密码比较方法,所有涉及密码比较的地方都用这个方法
- * @param string $password 要比较的密码
- * @param string $passwordInDb 数据库保存的已经加密过的密码
- * @return boolean 密码相同,返回true
- */
- function cmf_compare_password($password, $passwordInDb)
- {
- if (strpos($passwordInDb, "###") === 0) {
- return cmf_password($password) == $passwordInDb;
- } else {
- return cmf_password_old($password) == $passwordInDb;
- }
- }
- /**
- * 文件日志
- * @param $content 要写入的内容
- * @param string $file 日志文件,在web 入口目录
- */
- function cmf_log($content, $file = "log.txt")
- {
- file_put_contents($file, $content, FILE_APPEND);
- }
- /**
- * 随机字符串生成
- * @param int $len 生成的字符串长度
- * @return string
- */
- function cmf_random_string($len = 6)
- {
- $chars = [
- "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
- "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
- "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
- "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
- "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
- "3", "4", "5", "6", "7", "8", "9"
- ];
- $charsLen = count($chars) - 1;
- shuffle($chars); // 将数组打乱
- $output = "";
- for ($i = 0; $i < $len; $i++) {
- $output .= $chars[mt_rand(0, $charsLen)];
- }
- return $output;
- }
- /**
- * 清空系统缓存
- */
- function cmf_clear_cache()
- {
- // 清除 opcache缓存
- if (function_exists("opcache_reset")) {
- opcache_reset();
- }
- $dirs = [];
- $rootDirs = cmf_scan_dir(Env::get('runtime_path') . "*");
- //$noNeedClear=array(".","..","Data");
- $noNeedClear = ['.', '..', 'log'];
- $rootDirs = array_diff($rootDirs, $noNeedClear);
- foreach ($rootDirs as $dir) {
- if ($dir != "." && $dir != "..") {
- $dir = Env::get('runtime_path') . $dir;
- if (is_dir($dir)) {
- //array_push ( $dirs, $dir );
- $tmpRootDirs = cmf_scan_dir($dir . "/*");
- foreach ($tmpRootDirs as $tDir) {
- if ($tDir != "." && $tDir != "..") {
- $tDir = $dir . '/' . $tDir;
- if (is_dir($tDir)) {
- array_push($dirs, $tDir);
- } else {
- // @unlink($tDir);
- }
- }
- }
- } else {
- // @unlink($dir);
- }
- }
- }
- $dirTool = new Dir("");
- foreach ($dirs as $dir) {
- $dirTool->delDir($dir);
- }
- }
- /**
- * 保存数组变量到php文件
- * @param string $path 保存路径
- * @param mixed $var 要保存的变量
- * @return boolean 保存成功返回true,否则false
- */
- function cmf_save_var($path, $var)
- {
- $result = file_put_contents($path, "<?php\treturn " . var_export($var, true) . ";?>");
- return $result;
- }
- /**
- * 设置动态配置
- * @param array $data <br>如:['template' => ['cmf_default_theme' => 'default']];
- * @return boolean
- */
- function cmf_set_dynamic_config($data)
- {
- if (!is_array($data)) {
- return false;
- }
- foreach ($data as $key => $value) {
- if (is_array($value)) {
- $configFile = CMF_DATA . "config/{$key}.php";
- if (file_exists($configFile)) {
- $configs = include $configFile;
- } else {
- $configs = [];
- }
- $configs = array_merge($configs, $value);
- try {
- file_put_contents($configFile, "<?php\treturn " . var_export($configs, true) . ";");
- } catch (\Exception $e) {
- return false;
- }
- }
- }
- cmf_clear_cache();
- return true;
- }
- /**
- * 转化格式化的字符串为数组
- * @param string $tag 要转化的字符串,格式如:"id:2;cid:1;order:post_date desc;"
- * @return array 转化后字符串<pre>
- * array(
- * 'id'=>'2',
- * 'cid'=>'1',
- * 'order'=>'post_date desc'
- * )
- */
- function cmf_param_lable($tag = '')
- {
- $param = [];
- $array = explode(';', $tag);
- foreach ($array as $v) {
- $v = trim($v);
- if (!empty($v)) {
- list($key, $val) = explode(':', $v);
- $param[trim($key)] = trim($val);
- }
- }
- return $param;
- }
- /**
- * 获取后台管理设置的网站信息,此类信息一般用于前台
- * @return array
- */
- function cmf_get_site_info()
- {
- $siteInfo = cmf_get_option('site_info');
- if (isset($siteInfo['site_analytics'])) {
- $siteInfo['site_analytics'] = htmlspecialchars_decode($siteInfo['site_analytics']);
- }
- return $siteInfo;
- }
- /**
- * 获取CMF系统的设置,此类设置用于全局
- * @return array
- */
- function cmf_get_cmf_setting()
- {
- return cmf_get_option('cmf_setting');
- }
- /**
- * 更新CMF系统的设置,此类设置用于全局
- * @param $data
- * @return bool
- * @throws \think\Exception
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\ModelNotFoundException
- * @throws \think\exception\DbException
- * @throws \think\exception\PDOException
- */
- function cmf_set_cmf_setting($data)
- {
- if (!is_array($data) || empty($data)) {
- return false;
- }
- return cmf_set_option('cmf_setting', $data);
- }
- /**
- * 设置系统配置,通用
- * @param string $key 配置键值,都小写
- * @param array $data 配置值,数组
- * @param bool $replace 是否完全替换
- * @return bool 是否成功
- * @throws \think\Exception
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\ModelNotFoundException
- * @throws \think\exception\DbException
- * @throws \think\exception\PDOException
- */
- function cmf_set_option($key, $data, $replace = false)
- {
- if (!is_array($data) || empty($data) || !is_string($key) || empty($key)) {
- return false;
- }
- $key = strtolower($key);
- $option = [];
- $findOption = Db::name('option')->where('option_name', $key)->find();
- if ($findOption) {
- if (!$replace) {
- $oldOptionValue = json_decode($findOption['option_value'], true);
- if (!empty($oldOptionValue)) {
- $data = array_merge($oldOptionValue, $data);
- }
- }
- $option['option_value'] = json_encode($data);
- Db::name('option')->where('option_name', $key)->update($option);
- // echo Db::name('option')->getLastSql() . "\n";
- } else {
- $option['option_name'] = $key;
- $option['option_value'] = json_encode($data);
- Db::name('option')->insert($option);
- }
- cache('cmf_options_' . $key, null);//删除缓存
- return true;
- }
- /**
- * 获取系统配置,通用
- * @param string $key 配置键值,都小写
- * @return array
- */
- function cmf_get_option($key)
- {
- if (!is_string($key) || empty($key)) {
- return [];
- }
- if (PHP_SAPI != 'cli') {
- static $cmfGetOption;
- if (empty($cmfGetOption)) {
- $cmfGetOption = [];
- } else {
- if (!empty($cmfGetOption[$key])) {
- return $cmfGetOption[$key];
- }
- }
- }
- $optionValue = cache('cmf_options_' . $key);
- if (empty($optionValue)) {
- $optionValue = Db::name('option')->where('option_name', $key)->value('option_value');
- if (!empty($optionValue)) {
- $optionValue = json_decode($optionValue, true);
- cache('cmf_options_' . $key, $optionValue);
- }
- }
- $cmfGetOption[$key] = $optionValue;
- return $optionValue;
- }
- /**
- * 获取CMF上传配置
- */
- function cmf_get_upload_setting()
- {
- $uploadSetting = cmf_get_option('upload_setting');
- if (empty($uploadSetting) || empty($uploadSetting['file_types'])) {
- $uploadSetting = [
- 'file_types' => [
- 'image' => [
- 'upload_max_filesize' => '10240',//单位KB
- 'extensions' => 'jpg,jpeg,png,gif,bmp4'
- ],
- 'video' => [
- 'upload_max_filesize' => '10240',
- 'extensions' => 'mp4,avi,wmv,rm,rmvb,mkv'
- ],
- 'audio' => [
- 'upload_max_filesize' => '10240',
- 'extensions' => 'mp3,wma,wav'
- ],
- 'file' => [
- 'upload_max_filesize' => '10240',
- 'extensions' => 'txt,pdf,doc,docx,xls,xlsx,ppt,pptx,zip,rar'
- ]
- ],
- 'chunk_size' => 512,//单位KB
- 'max_files' => 20 //最大同时上传文件数
- ];
- }
- if (empty($uploadSetting['upload_max_filesize'])) {
- $uploadMaxFileSizeSetting = [];
- foreach ($uploadSetting['file_types'] as $setting) {
- $extensions = explode(',', trim($setting['extensions']));
- if (!empty($extensions)) {
- $uploadMaxFileSize = intval($setting['upload_max_filesize']) * 1024;//转化成B
- foreach ($extensions as $ext) {
- if (!isset($uploadMaxFileSizeSetting[$ext]) || $uploadMaxFileSize > $uploadMaxFileSizeSetting[$ext]) {
- $uploadMaxFileSizeSetting[$ext] = $uploadMaxFileSize;
- }
- }
- }
- }
- $uploadSetting['upload_max_filesize'] = $uploadMaxFileSizeSetting;
- }
- return $uploadSetting;
- }
- /**
- * 获取html文本里的img
- * @param string $content html 内容
- * @return array 图片列表 数组item格式<pre>
- * [
- * "src"=>'图片链接',
- * "title"=>'图片标签的 title 属性',
- * "alt"=>'图片标签的 alt 属性'
- * ]
- * </pre>
- */
- function cmf_get_content_images($content)
- {
- //import('phpQuery.phpQuery', EXTEND_PATH);
- \phpQuery::newDocumentHTML($content);
- $pq = pq(null);
- $images = $pq->find("img");
- $imagesData = [];
- if ($images->length) {
- foreach ($images as $img) {
- $img = pq($img);
- $image = [];
- $image['src'] = $img->attr("src");
- $image['title'] = $img->attr("title");
- $image['alt'] = $img->attr("alt");
- array_push($imagesData, $image);
- }
- }
- \phpQuery::$documents = null;
- return $imagesData;
- }
- /**
- * 去除字符串中的指定字符
- * @param string $str 待处理字符串
- * @param string $chars 需去掉的特殊字符
- * @return string
- */
- function cmf_strip_chars($str, $chars = '?<*.>\'\"')
- {
- return preg_replace('/[' . $chars . ']/is', '', $str);
- }
- /**
- * 发送邮件
- * @param string $address 收件人邮箱
- * @param string $subject 邮件标题
- * @param string $message 邮件内容
- * @return array<br>
- * 返回格式:<br>
- * array(<br>
- * "error"=>0|1,//0代表出错<br>
- * "message"=> "出错信息"<br>
- * );
- * @throws phpmailerException
- */
- function cmf_send_email($address, $subject, $message)
- {
- $smtpSetting = cmf_get_option('smtp_setting');
- $mail = new \PHPMailer\PHPMailer\PHPMailer();
- // 设置PHPMailer使用SMTP服务器发送Email
- $mail->IsSMTP();
- $mail->IsHTML(true);
- //$mail->SMTPDebug = 3;
- // 设置邮件的字符编码,若不指定,则为'UTF-8'
- $mail->CharSet = 'UTF-8';
- // 添加收件人地址,可以多次使用来添加多个收件人
- $mail->AddAddress($address);
- // 设置邮件正文
- $mail->Body = $message;
- // 设置邮件头的From字段。
- $mail->From = $smtpSetting['from'];
- // 设置发件人名字
- $mail->FromName = $smtpSetting['from_name'];
- // 设置邮件标题
- $mail->Subject = $subject;
- // 设置SMTP服务器。
- $mail->Host = $smtpSetting['host'];
- //by Rainfer
- // 设置SMTPSecure。
- $Secure = $smtpSetting['smtp_secure'];
- $mail->SMTPSecure = empty($Secure) ? '' : $Secure;
- // 设置SMTP服务器端口。
- $port = $smtpSetting['port'];
- $mail->Port = empty($port) ? "25" : $port;
- // 设置为"需要验证"
- $mail->SMTPAuth = true;
- $mail->SMTPAutoTLS = false;
- $mail->Timeout = 10;
- // 设置用户名和密码。
- $mail->Username = $smtpSetting['username'];
- $mail->Password = $smtpSetting['password'];
- // 发送邮件。
- if (!$mail->Send()) {
- $mailError = $mail->ErrorInfo;
- return ["error" => 1, "message" => $mailError];
- } else {
- return ["error" => 0, "message" => "success"];
- }
- }
- /**
- * 转化数据库保存的文件路径,为可以访问的url
- * @param string $file
- * @param mixed $style 图片样式,支持各大云存储
- * @return string
- */
- function cmf_get_asset_url($file, $style = '')
- {
- if (strpos($file, "http") === 0) {
- return $file;
- } else if (strpos($file, "/") === 0) {
- return $file;
- } else {
- // $storage = cmf_get_option('storage');
- // if (empty($storage['type'])) {
- // $storage['type'] = 'Local';
- // }
- // if ($storage['type'] != 'Local') {
- // $watermark = cmf_get_plugin_config($storage['type']);
- // $style = empty($style) ? $watermark['styles_watermark'] : $style;
- // }
- $storage = Storage::instance();
- return $storage->getUrl($file, $style);
- }
- }
- /**
- * 转化数据库保存图片的文件路径,为可以访问的url
- * @param string $file 文件路径,数据存储的文件相对路径
- * @param string $style 图片样式,支持各大云存储
- * @return string 图片链接
- */
- function cmf_get_image_url($file, $style = 'watermark')
- {
- if (empty($file)) {
- return '';
- }
- if (strpos($file, "http") === 0) {
- return $file;
- } else if (strpos($file, "/") === 0) {
- return cmf_get_domain() . $file;
- } else {
- // $storage = cmf_get_option('storage');
- // if (empty($storage['type'])) {
- // $storage['type'] = 'Local';
- // }
- // if ($storage['type'] != 'Local') {
- // $watermark = cmf_get_plugin_config($storage['type']);
- // $style = empty($style) ? $watermark['styles_watermark'] : $style;
- // }
- $storage = Storage::instance();
- return $storage->getImageUrl($file, $style);
- }
- }
- /**
- * 获取图片预览链接
- * @param string $file 文件路径,相对于upload
- * @param string $style 图片样式,支持各大云存储
- * @return string
- */
- function cmf_get_image_preview_url($file, $style = 'watermark')
- {
- if (empty($file)) {
- return '';
- }
- if (strpos($file, "http") === 0) {
- return $file;
- } else if (strpos($file, "/") === 0) {
- return $file;
- } else {
- // $storage = cmf_get_option('storage');
- // if (empty($storage['type'])) {
- // $storage['type'] = 'Local';
- // }
- // if ($storage['type'] != 'Local') {
- // $watermark = cmf_get_plugin_config($storage['type']);
- // $style = empty($style) ? $watermark['styles_watermark'] : $style;
- // }
- $storage = Storage::instance();
- return $storage->getPreviewUrl($file, $style);
- }
- }
- /**
- * 获取文件下载链接
- * @param string $file 文件路径,数据库里保存的相对路径
- * @param int $expires 过期时间,单位 s
- * @return string 文件链接
- */
- function cmf_get_file_download_url($file, $expires = 3600)
- {
- if (empty($file)) {
- return '';
- }
- if (strpos($file, "http") === 0) {
- return $file;
- } else if (strpos($file, "/") === 0) {
- return $file;
- } else if(strpos($file, "#") === 0) {
- return $file;
- } else {
- $storage = Storage::instance();
- return $storage->getFileDownloadUrl($file, $expires);
- }
- }
- /**
- * 解密用cmf_str_encode加密的字符串
- * @param $string 要解密的字符串
- * @param string $key 加密时salt
- * @param int $expiry 多少秒后过期
- * @param string $operation 操作,默认为DECODE
- * @return bool|string
- */
- function cmf_str_decode($string, $key = '', $expiry = 0, $operation = 'DECODE')
- {
- $ckey_length = 4;
- $key = md5($key ? $key : config("database.authcode"));
- $keya = md5(substr($key, 0, 16));
- $keyb = md5(substr($key, 16, 16));
- $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';
- $cryptkey = $keya . md5($keya . $keyc);
- $key_length = strlen($cryptkey);
- $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
- $string_length = strlen($string);
- $result = '';
- $box = range(0, 255);
- $rndkey = [];
- for ($i = 0; $i <= 255; $i++) {
- $rndkey[$i] = ord($cryptkey[$i % $key_length]);
- }
- for ($j = $i = 0; $i < 256; $i++) {
- $j = ($j + $box[$i] + $rndkey[$i]) % 256;
- $tmp = $box[$i];
- $box[$i] = $box[$j];
- $box[$j] = $tmp;
- }
- for ($a = $j = $i = 0; $i < $string_length; $i++) {
- $a = ($a + 1) % 256;
- $j = ($j + $box[$a]) % 256;
- $tmp = $box[$a];
- $box[$a] = $box[$j];
- $box[$j] = $tmp;
- $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
- }
- if ($operation == 'DECODE') {
- if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
- return substr($result, 26);
- } else {
- return '';
- }
- } else {
- return $keyc . str_replace('=', '', base64_encode($result));
- }
- }
- /**
- * 加密字符串
- * @param $string 要加密的字符串
- * @param string $key salt
- * @param int $expiry 多少秒后过期
- * @return bool|string
- */
- function cmf_str_encode($string, $key = '', $expiry = 0)
- {
- return cmf_str_decode($string, $key, $expiry, "ENCODE");
- }
- /**
- * 获取文件相对路径
- * @param string $assetUrl 文件的URL
- * @return string
- */
- function cmf_asset_relative_url($assetUrl)
- {
- if (strpos($assetUrl, "http") === 0) {
- return $assetUrl;
- } else {
- return str_replace('/upload/', '', $assetUrl);
- }
- }
- /**
- * 检查用户对某个url内容的可访问性,用于记录如是否赞过,是否访问过等等;开发者可以自由控制,对于没有必要做的检查可以不做,以减少服务器压力
- * @param string $object 访问对象的id,格式:不带前缀的表名+id;如post1表示xx_post表里id为1的记录;如果object为空,表示只检查对某个url访问的合法性
- * @param int $countLimit 访问次数限制,如1,表示只能访问一次
- * @param boolean $ipLimit ip限制,false为不限制,true为限制
- * @param int $expire 距离上次访问的最小时间单位s,0表示不限制,大于0表示最后访问$expire秒后才可以访问
- * @return true 可访问,false不可访问
- * @throws \think\Exception
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\ModelNotFoundException
- * @throws \think\exception\DbException
- * @throws \think\exception\PDOException
- */
- function cmf_check_user_action($object = "", $countLimit = 1, $ipLimit = false, $expire = 0)
- {
- $request = request();
- $action = $request->module() . "/" . $request->controller() . "/" . $request->action();
- if (is_array($object)) {
- $userId = $object['user_id'];
- $object = $object['object'];
- } else {
- $userId = cmf_get_current_user_id();
- }
- $ip = get_client_ip(0, true);//修复ip获取
- $where = ["user_id" => $userId, "action" => $action, "object" => $object];
- if ($ipLimit) {
- $where['ip'] = $ip;
- }
- $findLog = Db::name('user_action_log')->where($where)->find();
- $time = time();
- if ($findLog) {
- Db::name('user_action_log')->where($where)->update([
- "count" => Db::raw("count+1"),
- "last_visit_time" => $time,
- "ip" => $ip
- ]);
- if ($findLog['count'] >= $countLimit) {
- return false;
- }
- if ($expire > 0 && ($time - $findLog['last_visit_time']) < $expire) {
- return false;
- }
- } else {
- Db::name('user_action_log')->insert([
- "user_id" => $userId,
- "action" => $action,
- "object" => $object,
- "count" => Db::raw("count+1"),
- "last_visit_time" => $time, "ip" => $ip
- ]);
- }
- return true;
- }
- /**
- * 判断是否为手机访问
- * @return boolean
- */
- function cmf_is_mobile()
- {
- if (PHP_SAPI != 'cli') {
- static $cmf_is_mobile;
- if (isset($cmf_is_mobile))
- return $cmf_is_mobile;
- }
- $cmf_is_mobile = request()->isMobile();
- return $cmf_is_mobile;
- }
- /**
- * 判断是否为微信访问
- * @return boolean
- */
- function cmf_is_wechat()
- {
- if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
- return true;
- }
- return false;
- }
- /**
- * 判断是否为Android访问
- * @return boolean
- */
- function cmf_is_android()
- {
- if (strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false) {
- return true;
- }
- return false;
- }
- /**
- * 判断是否为ios访问
- * @return boolean
- */
- function cmf_is_ios()
- {
- if (strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone') || strpos($_SERVER['HTTP_USER_AGENT'], 'iPad')) {
- return true;
- }
- return false;
- }
- /**
- * 判断是否为iPhone访问
- * @return boolean
- */
- function cmf_is_iphone()
- {
- if (strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone')) {
- return true;
- }
- return false;
- }
- /**
- * 判断是否为iPad访问
- * @return boolean
- */
- function cmf_is_ipad()
- {
- if (strpos($_SERVER['HTTP_USER_AGENT'], 'iPad')) {
- return true;
- }
- return false;
- }
- /**
- * 添加钩子
- * @param string $hook 钩子名称
- * @param mixed $params 传入参数
- * @return void
- */
- function hook($hook, $params = null)
- {
- return Hook::listen($hook, $params);
- }
- /**
- * 添加钩子,只执行一个
- * @param string $hook 钩子名称
- * @param mixed $params 传入参数
- * @return mixed
- */
- function hook_one($hook, $params = null)
- {
- return Hook::listen($hook, $params, true);
- }
- /**
- * 获取插件类名
- * @param string $name 插件名
- * @return string
- */
- function cmf_get_plugin_class($name)
- {
- $name = ucwords($name);
- $pluginDir = cmf_parse_name($name);
- $class = "plugins\\{$pluginDir}\\{$name}Plugin";
- return $class;
- }
- /**
- * 获取插件配置
- * @param string $name 插件名,大驼峰格式
- * @return array
- */
- function cmf_get_plugin_config($name)
- {
- $class = cmf_get_plugin_class($name);
- if (class_exists($class)) {
- $plugin = new $class();
- return $plugin->getConfig();
- } else {
- return [];
- }
- }
- /**
- * 替代scan_dir的方法
- * @param string $pattern 检索模式 搜索模式 *.txt,*.doc; (同glog方法)
- * @param int $flags
- * @param $pattern
- * @return array
- */
- function cmf_scan_dir($pattern, $flags = null)
- {
- $files = glob($pattern, $flags);
- if (empty($files)) {
- $files = [];
- } else {
- $files = array_map('basename', $files);
- }
- return $files;
- }
- /**
- * 获取某个目录下所有子目录
- * @param $dir
- * @return array
- */
- function cmf_sub_dirs($dir)
- {
- $dir = ltrim($dir, "/");
- $dirs = [];
- $subDirs = cmf_scan_dir("$dir/*", GLOB_ONLYDIR);
- if (!empty($subDirs)) {
- foreach ($subDirs as $subDir) {
- $subDir = "$dir/$subDir";
- array_push($dirs, $subDir);
- $subDirSubDirs = cmf_sub_dirs($subDir);
- if (!empty($subDirSubDirs)) {
- $dirs = array_merge($dirs, $subDirSubDirs);
- }
- }
- }
- return $dirs;
- }
- /**
- * 生成访问插件的url
- * @param string $url url格式:插件名://控制器名/方法
- * @param array $vars 参数
- * @param bool $domain 是否显示域名 或者直接传入域名
- * @return string
- */
- function cmf_plugin_url($url, $vars = [], $domain = false)
- {
- global $CMF_GV_routes;
- if (empty($CMF_GV_routes)) {
- $routeModel = new \app\admin\model\RouteModel();
- $CMF_GV_routes = $routeModel->getRoutes();
- }
- $url = parse_url($url);
- $case_insensitive = true;
- $plugin = $case_insensitive ? Loader::parseName($url['scheme']) : $url['scheme'];
- $controller = $case_insensitive ? Loader::parseName($url['host']) : $url['host'];
- $action = trim($case_insensitive ? strtolower($url['path']) : $url['path'], '/');
- /* 解析URL带的参数 */
- if (isset($url['query'])) {
- parse_str($url['query'], $query);
- $vars = array_merge($query, $vars);
- }
- /* 基础参数 */
- $params = [
- '_plugin' => $plugin,
- '_controller' => $controller,
- '_action' => $action,
- ];
- $pluginUrl = '\\cmf\\controller\\PluginController@index?' . http_build_query($params);
- if (!empty($vars) && !empty($CMF_GV_routes[$pluginUrl])) {
- foreach ($CMF_GV_routes[$pluginUrl] as $actionRoute) {
- $sameVars = array_intersect_assoc($vars, $actionRoute['vars']);
- if (count($sameVars) == count($actionRoute['vars'])) {
- ksort($sameVars);
- $pluginUrl = $pluginUrl . '&' . http_build_query($sameVars);
- $vars = array_diff_assoc($vars, $sameVars);
- break;
- }
- }
- }
- return url($pluginUrl, $vars, true, $domain);
- }
- /**
- * 检查权限
- * @param $userId int 要检查权限的用户 ID
- * @param $name string|array 需要验证的规则列表,支持逗号分隔的权限规则或索引数组
- * @param $relation string 如果为 'or' 表示满足任一条规则即通过验证;如果为 'and'则表示需满足所有规则才能通过验证
- * @return boolean 通过验证返回true;失败返回false
- */
- function cmf_auth_check($userId, $name = null, $relation = 'or')
- {
- if (empty($userId)) {
- return false;
- }
- if ($userId == 1) {
- return true;
- }
- $authObj = new \cmf\lib\Auth();
- if (empty($name)) {
- $request = request();
- $module = $request->module();
- $controller = $request->controller();
- $action = $request->action();
- $name = strtolower($module . "/" . $controller . "/" . $action);
- }
- return $authObj->check($userId, $name, $relation);
- }
- function cmf_alpha_id($in, $to_num = false, $pad_up = 4, $passKey = null)
- {
- $index = "aBcDeFgHiJkLmNoPqRsTuVwXyZAbCdEfGhIjKlMnOpQrStUvWxYz0123456789";
- if ($passKey !== null) {
- // Although this function's purpose is to just make the
- // ID short - and not so much secure,
- // with this patch by Simon Franz (http://blog.snaky.org/)
- // you can optionally supply a password to make it harder
- // to calculate the corresponding numeric ID
- for ($n = 0; $n < strlen($index); $n++) $i[] = substr($index, $n, 1);
- $passhash = hash('sha256', $passKey);
- $passhash = (strlen($passhash) < strlen($index)) ? hash('sha512', $passKey) : $passhash;
- for ($n = 0; $n < strlen($index); $n++) $p[] = substr($passhash, $n, 1);
- array_multisort($p, SORT_DESC, $i);
- $index = implode($i);
- }
- $base = strlen($index);
- if ($to_num) {
- // Digital number <<-- alphabet letter code
- $in = strrev($in);
- $out = 0;
- $len = strlen($in) - 1;
- for ($t = 0; $t <= $len; $t++) {
- $bcpow = pow($base, $len - $t);
- $out = $out + strpos($index, substr($in, $t, 1)) * $bcpow;
- }
- if (is_numeric($pad_up)) {
- $pad_up--;
- if ($pad_up > 0) $out -= pow($base, $pad_up);
- }
- $out = sprintf('%F', $out);
- $out = substr($out, 0, strpos($out, '.'));
- } else {
- // Digital number -->> alphabet letter code
- if (is_numeric($pad_up)) {
- $pad_up--;
- if ($pad_up > 0) $in += pow($base, $pad_up);
- }
- $out = "";
- for ($t = floor(log($in, $base)); $t >= 0; $t--) {
- $bcp = pow($base, $t);
- $a = floor($in / $bcp) % $base;
- $out = $out . substr($index, $a, 1);
- $in = $in - ($a * $bcp);
- }
- $out = strrev($out); // reverse
- }
- return $out;
- }
- /**
- * 验证码检查,验证完后销毁验证码
- * @param string $value 要验证的字符串
- * @param string $id 验证码的ID
- * @param bool $reset 验证成功后是否重置
- * @return bool
- */
- function cmf_captcha_check($value, $id = "", $reset = true)
- {
- $captcha = new \think\captcha\Captcha();
- $captcha->reset = $reset;
- return $captcha->check($value, $id);
- }
- /**
- * 切分SQL文件成多个可以单独执行的sql语句
- * @param $file string sql文件路径
- * @param $tablePre string 表前缀
- * @param string $charset 字符集
- * @param string $defaultTablePre 默认表前缀
- * @param string $defaultCharset 默认字符集
- * @return array
- */
- function cmf_split_sql($file, $tablePre, $charset = 'utf8mb4', $defaultTablePre = 'cmf_', $defaultCharset = 'utf8mb4')
- {
- if (file_exists($file)) {
- //读取SQL文件
- $sql = file_get_contents($file);
- $sql = str_replace("\r", "\n", $sql);
- $sql = str_replace("BEGIN;\n", '', $sql);//兼容 navicat 导出的 insert 语句
- $sql = str_replace("COMMIT;\n", '', $sql);//兼容 navicat 导出的 insert 语句
- $sql = str_replace($defaultCharset, $charset, $sql);
- $sql = trim($sql);
- //替换表前缀
- $sql = str_replace(" `{$defaultTablePre}", " `{$tablePre}", $sql);
- $sqls = explode(";\n", $sql);
- return $sqls;
- }
- return [];
- }
- /**
- * 判断当前的语言包,并返回语言包名
- * @return string 语言包名
- */
- function cmf_current_lang()
- {
- return request()->langset();
- }
- /**
- * 获取惟一订单号
- * @return string
- */
- function cmf_get_order_sn()
- {
- return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
- }
- /**
- * 获取文件扩展名
- * @param string $filename 文件名
- * @return string 文件扩展名
- */
- function cmf_get_file_extension($filename)
- {
- $pathinfo = pathinfo($filename);
- return strtolower($pathinfo['extension']);
- }
- /**
- * 检查手机或邮箱是否还可以发送验证码,并返回生成的验证码
- * @param string $account 手机或邮箱
- * @param integer $length 验证码位数,支持4,6,8
- * @return string 数字验证码
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\ModelNotFoundException
- * @throws \think\exception\DbException
- */
- function cmf_get_verification_code($account, $length = 6)
- {
- if (empty($account)) return false;
- $verificationCodeQuery = Db::name('verification_code');
- $currentTime = time();
- $maxCount = 5;
- $findVerificationCode = $verificationCodeQuery->where('account', $account)->find();
- $result = false;
- if (empty($findVerificationCode)) {
- $result = true;
- } else {
- $sendTime = $findVerificationCode['send_time'];
- $todayStartTime = strtotime(date('Y-m-d', $currentTime));
- if ($sendTime < $todayStartTime) {
- $result = true;
- } else if ($findVerificationCode['count'] < $maxCount) {
- $result = true;
- }
- }
- if ($result) {
- switch ($length) {
- case 4:
- $result = rand(1000, 9999);
- break;
- case 6:
- $result = rand(100000, 999999);
- break;
- case 8:
- $result = rand(10000000, 99999999);
- break;
- default:
- $result = rand(100000, 999999);
- }
- }
- return $result;
- }
- /**
- * 更新手机或邮箱验证码发送日志
- * @param string $account 手机或邮箱
- * @param string $code 验证码
- * @param int $expireTime 过期时间
- * @return int|string
- * @throws \think\Exception
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\ModelNotFoundException
- * @throws \think\exception\DbException
- * @throws \think\exception\PDOException
- */
- function cmf_verification_code_log($account, $code, $expireTime = 0)
- {
- $currentTime = time();
- $expireTime = $expireTime > $currentTime ? $expireTime : $currentTime + 30 * 60;
- $findVerificationCode = Db::name('verification_code')->where('account', $account)->find();
- if ($findVerificationCode) {
- $todayStartTime = strtotime(date("Y-m-d"));//当天0点
- if ($findVerificationCode['send_time'] <= $todayStartTime) {
- $count = 1;
- } else {
- $count = Db::raw('count+1');
- }
- $result = Db::name('verification_code')
- ->where('account', $account)
- ->update([
- 'send_time' => $currentTime,
- 'expire_time' => $expireTime,
- 'code' => $code,
- 'count' => $count
- ]);
- } else {
- $result = Db::name('verification_code')
- ->insert([
- 'account' => $account,
- 'send_time' => $currentTime,
- 'code' => $code,
- 'count' => 1,
- 'expire_time' => $expireTime
- ]);
- }
- return $result;
- }
- /**
- * 手机或邮箱验证码检查,验证完后销毁验证码增加安全性,返回true验证码正确,false验证码错误
- * @param string $account 手机或邮箱
- * @param string $code 验证码
- * @param boolean $clear 是否验证后销毁验证码
- * @return string 错误消息,空字符串代码验证码正确
- * @return string
- * @throws \think\Exception
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\ModelNotFoundException
- * @throws \think\exception\DbException
- * @throws \think\exception\PDOException
- */
- function cmf_check_verification_code($account, $code, $clear = false)
- {
- $findVerificationCode = Db::name('verification_code')->where('account', $account)->find();
- if ($findVerificationCode) {
- if ($findVerificationCode['expire_time'] > time()) {
- if ($code == $findVerificationCode['code']) {
- if ($clear) {
- Db::name('verification_code')->where('account', $account)->update(['code' => '']);
- }
- } else {
- return "验证码不正确!";
- }
- } else {
- return "验证码已经过期,请先获取验证码!";
- }
- } else {
- return "请先获取验证码!";
- }
- return "";
- }
- /**
- * 清除某个手机或邮箱的数字验证码,一般在验证码验证正确完成后
- * @param string $account 手机或邮箱
- * @return boolean true:手机验证码正确,false:手机验证码错误
- * @throws \think\Exception
- * @throws \think\exception\PDOException
- */
- function cmf_clear_verification_code($account)
- {
- $verificationCodeQuery = Db::name('verification_code');
- $result = $verificationCodeQuery->where('account', $account)->update(['code' => '']);
- return $result;
- }
- /**
- * 区分大小写的文件存在判断
- * @param string $filename 文件地址
- * @return boolean
- */
- function file_exists_case($filename)
- {
- if (is_file($filename)) {
- if (APP_DEBUG) {
- if (basename(realpath($filename)) != basename($filename))
- return false;
- }
- return true;
- }
- return false;
- }
- /**
- * 生成用户 token
- * @param $userId
- * @param $deviceType
- * @return string 用户 token
- * @throws \think\Exception
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\ModelNotFoundException
- * @throws \think\exception\DbException
- * @throws \think\exception\PDOException
- */
- function cmf_generate_user_token($userId, $deviceType)
- {
- $userTokenQuery = Db::name("user_token")
- ->where('user_id', $userId)
- ->where('device_type', $deviceType);
- $findUserToken = $userTokenQuery->find();
- $currentTime = time();
- $expireTime = $currentTime + 24 * 3600 * 180;
- $token = md5(uniqid()) . md5(uniqid());
- if (empty($findUserToken)) {
- Db::name("user_token")->insert([
- 'token' => $token,
- 'user_id' => $userId,
- 'expire_time' => $expireTime,
- 'create_time' => $currentTime,
- 'device_type' => $deviceType
- ]);
- } else {
- if ($findUserToken['expire_time'] > time() && !empty($findUserToken['token'])) {
- $token = $findUserToken['token'];
- } else {
- Db::name("user_token")
- ->where('user_id', $userId)
- ->where('device_type', $deviceType)
- ->update([
- 'token' => $token,
- 'expire_time' => $expireTime,
- 'create_time' => $currentTime
- ]);
- }
- }
- return $token;
- }
- /**
- * 字符串命名风格转换
- * type 0 将Java风格转换为C的风格 1 将C风格转换为Java的风格
- * @param string $name 字符串
- * @param integer $type 转换类型
- * @param bool $ucfirst 首字母是否大写(驼峰规则)
- * @return string
- */
- function cmf_parse_name($name, $type = 0, $ucfirst = true)
- {
- return Loader::parseName($name, $type, $ucfirst);
- }
- /**
- * 判断字符串是否为已经序列化过
- * @param $str
- * @return bool
- */
- function cmf_is_serialized($str)
- {
- return ($str == serialize(false) || @unserialize($str) !== false);
- }
- /**
- * 判断是否SSL协议
- * @return boolean
- */
- function cmf_is_ssl()
- {
- if (isset($_SERVER['HTTPS']) && ('1' == $_SERVER['HTTPS'] || 'on' == strtolower($_SERVER['HTTPS']))) {
- return true;
- } elseif (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'])) {
- return true;
- }
- return false;
- }
- /**
- * 获取CMF系统的设置,此类设置用于全局
- * @param string $key 设置key,为空时返回所有配置信息
- * @return array|bool|mixed
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\ModelNotFoundException
- * @throws \think\exception\DbException
- */
- function cmf_get_cmf_settings($key = "")
- {
- $cmfSettings = cache("cmf_settings");
- if (empty($cmfSettings)) {
- $objOptions = new \app\admin\model\OptionModel();
- $objResult = $objOptions->where("option_name", 'cmf_settings')->find();
- $arrOption = $objResult ? $objResult->toArray() : [];
- if ($arrOption) {
- $cmfSettings = json_decode($arrOption['option_value'], true);
- } else {
- $cmfSettings = [];
- }
- cache("cmf_settings", $cmfSettings);
- }
- if (!empty($key)) {
- if (isset($cmfSettings[$key])) {
- return $cmfSettings[$key];
- } else {
- return false;
- }
- }
- return $cmfSettings;
- }
- /**
- * @deprecated
- * 判读是否sae环境
- * @return bool
- */
- function cmf_is_sae()
- {
- if (function_exists('saeAutoLoader')) {
- return true;
- } else {
- return false;
- }
- }
- /**
- * 获取客户端IP地址
- * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
- * @param boolean $adv 是否进行高级模式获取(有可能被伪装)
- * @return string
- */
- function get_client_ip($type = 0, $adv = true)
- {
- return request()->ip($type, $adv);
- }
- /**
- * 生成base64的url,用于数据库存放 url
- * @param $url 路由地址,如 控制器/方法名,应用/控制器/方法名
- * @param $params url参数
- * @return string
- */
- function cmf_url_encode($url, $params)
- {
- // 解析参数
- if (is_string($params)) {
- // aaa=1&bbb=2 转换成数组
- parse_str($params, $params);
- }
- return base64_encode(json_encode(['action' => $url, 'param' => $params]));
- }
- /**
- * CMF Url生成
- * @param string $url 路由地址
- * @param string|array $vars 变量
- * @param bool|string $suffix 生成的URL后缀
- * @param bool|string $domain 域名
- * @return string
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\ModelNotFoundException
- * @throws \think\exception\DbException
- */
- function cmf_url($url = '', $vars = '', $suffix = true, $domain = false)
- {
- global $CMF_GV_routes;
- if (empty($CMF_GV_routes)) {
- $routeModel = new \app\admin\model\RouteModel();
- $CMF_GV_routes = $routeModel->getRoutes();
- }
- if (false === strpos($url, '://') && 0 !== strpos($url, '/')) {
- $info = parse_url($url);
- $url = !empty($info['path']) ? $info['path'] : '';
- if (isset($info['fragment'])) {
- // 解析锚点
- $anchor = $info['fragment'];
- if (false !== strpos($anchor, '?')) {
- // 解析参数
- list($anchor, $info['query']) = explode('?', $anchor, 2);
- }
- if (false !== strpos($anchor, '@')) {
- // 解析域名
- list($anchor, $domain) = explode('@', $anchor, 2);
- }
- } elseif (strpos($url, '@') && false === strpos($url, '\\')) {
- // 解析域名
- list($url, $domain) = explode('@', $url, 2);
- }
- }
- // 解析参数
- if (is_string($vars)) {
- // aaa=1&bbb=2 转换成数组
- parse_str($vars, $vars);
- }
- if (isset($info['query'])) {
- // 解析地址里面参数 合并到vars
- parse_str($info['query'], $params);
- $vars = array_merge($params, $vars);
- }
- if (!empty($vars) && !empty($CMF_GV_routes[$url])) {
- foreach ($CMF_GV_routes[$url] as $actionRoute) {
- $sameVars = array_intersect_assoc($vars, $actionRoute['vars']);
- if (count($sameVars) == count($actionRoute['vars'])) {
- ksort($sameVars);
- $url = $url . '?' . http_build_query($sameVars);
- $vars = array_diff_assoc($vars, $sameVars);
- break;
- }
- }
- }
- if (!empty($anchor)) {
- $url = $url . '#' . $anchor;
- }
- // if (!empty($domain)) {
- // $url = $url . '@' . $domain;
- // }
- return Url::build($url, $vars, $suffix, $domain);
- }
- /**
- * 判断 cmf 核心是否安装
- * @return bool
- */
- function cmf_is_installed()
- {
- static $cmfIsInstalled;
- if (empty($cmfIsInstalled)) {
- $cmfIsInstalled = file_exists(CMF_DATA . 'install.lock');
- }
- return $cmfIsInstalled;
- }
- /**
- * 替换编辑器内容中的文件地址
- * @param string $content 编辑器内容
- * @param boolean $isForDbSave true:表示把绝对地址换成相对地址,用于数据库保存,false:表示把相对地址换成绝对地址用于界面显示
- * @return string
- */
- function cmf_replace_content_file_url($content, $isForDbSave = false)
- {
- //import('phpQuery.phpQuery', EXTEND_PATH);
- \phpQuery::newDocumentHTML($content);
- $pq = pq(null);
- $storage = Storage::instance();
- $localStorage = new cmf\lib\storage\Local([]);
- $storageDomain = $storage->getDomain();
- $domain = request()->host();
- $images = $pq->find("img");
- if ($images->length) {
- foreach ($images as $img) {
- $img = pq($img);
- $imgSrc = $img->attr("src");
- if ($isForDbSave) {
- if (preg_match("/^\/upload\//", $imgSrc)) {
- $img->attr("src", preg_replace("/^\/upload\//", '', $imgSrc));
- } elseif (preg_match("/^http(s)?:\/\/$domain\/upload\//", $imgSrc)) {
- $img->attr("src", $localStorage->getFilePath($imgSrc));
- } elseif (preg_match("/^http(s)?:\/\/$storageDomain\//", $imgSrc)) {
- $img->attr("src", $storage->getFilePath($imgSrc));
- }
- } else {
- $img->attr("src", cmf_get_image_url($imgSrc));
- }
- }
- }
- $links = $pq->find("a");
- if ($links->length) {
- foreach ($links as $link) {
- $link = pq($link);
- $href = $link->attr("href");
- if ($isForDbSave) {
- if (preg_match("/^\/upload\//", $href)) {
- $link->attr("href", preg_replace("/^\/upload\//", '', $href));
- } elseif (preg_match("/^http(s)?:\/\/$domain\/upload\//", $href)) {
- $link->attr("href", $localStorage->getFilePath($href));
- } elseif (preg_match("/^http(s)?:\/\/$storageDomain\//", $href)) {
- $link->attr("href", $storage->getFilePath($href));
- }
- } else {
- if (!(preg_match("/^\//", $href) || preg_match("/^http/", $href))) {
- $link->attr("href", cmf_get_file_download_url($href));
- }
- }
- }
- }
- $content = $pq->html();
- \phpQuery::$documents = null;
- return $content;
- }
- /**
- * 获取后台风格名称
- * @return string
- */
- function cmf_get_admin_style()
- {
- $adminSettings = cmf_get_option('admin_settings');
- return empty($adminSettings['admin_style']) ? 'simpleadmin' : $adminSettings['admin_style'];
- }
- /**
- * curl get 请求
- * @param $url
- * @return mixed
- */
- function cmf_curl_get($url)
- {
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_FAILONERROR, true);
- curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
- curl_setopt($ch, CURLOPT_AUTOREFERER, true);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_TIMEOUT, 5);
- $SSL = substr($url, 0, 8) == "https://" ? true : false;
- // if ($SSL) {
- // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
- // curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 检查证书中是否设置域名
- // }
- $content = curl_exec($ch);
- curl_close($ch);
- return $content;
- }
- /**
- * 用户操作记录
- * @param string $action 用户操作
- * @throws \think\Exception
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\ModelNotFoundException
- * @throws \think\exception\DbException
- * @throws \think\exception\PDOException
- */
- function cmf_user_action($action)
- {
- $userId = cmf_get_current_user_id();
- if (empty($userId)) {
- return;
- }
- $findUserAction = Db::name('user_action')->where('action', $action)->find();
- if (empty($findUserAction)) {
- return;
- }
- $changeScore = false;
- if ($findUserAction['cycle_type'] == 0) {
- $changeScore = true;
- } elseif ($findUserAction['reward_number'] > 0) {
- $findUserScoreLog = Db::name('user_score_log')->order('create_time DESC')->find();
- if (!empty($findUserScoreLog)) {
- $cycleType = intval($findUserAction['cycle_type']);
- $cycleTime = intval($findUserAction['cycle_time']);
- switch ($cycleType) {//1:按天;2:按小时;3:永久
- case 1:
- $firstDayStartTime = strtotime(date('Y-m-d', $findUserScoreLog['create_time']));
- $endDayEndTime = strtotime(date('Y-m-d', strtotime("+{$cycleTime} day", $firstDayStartTime)));
- // $todayStartTime = strtotime(date('Y-m-d'));
- // $todayEndTime = strtotime(date('Y-m-d', strtotime('+1 day')));
- $findUserScoreLogCount = Db::name('user_score_log')->where([
- 'user_id' => $userId,
- 'create_time' => [['gt', $firstDayStartTime], ['lt', $endDayEndTime]]
- ])->count();
- if ($findUserScoreLogCount < $findUserAction['reward_number']) {
- $changeScore = true;
- }
- break;
- case 2:
- if (($findUserScoreLog['create_time'] + $cycleTime * 3600) < time()) {
- $changeScore = true;
- }
- break;
- case 3:
- break;
- }
- } else {
- $changeScore = true;
- }
- }
- if ($changeScore) {
- Db::name('user_score_log')->insert([
- 'user_id' => $userId,
- 'create_time' => time(),
- 'action' => $action,
- 'score' => $findUserAction['score'],
- 'coin' => $findUserAction['coin'],
- ]);
- $data = [];
- if ($findUserAction['score'] > 0) {
- $data['score'] = Db::raw('score+' . $findUserAction['score']);
- }
- if ($findUserAction['score'] < 0) {
- $data['score'] = Db::raw('score-' . abs($findUserAction['score']));
- }
- if ($findUserAction['coin'] > 0) {
- $data['coin'] = Db::raw('coin+' . $findUserAction['coin']);
- }
- if ($findUserAction['coin'] < 0) {
- $data['coin'] = Db::raw('coin-' . abs($findUserAction['coin']));
- }
- Db::name('user')->where('id', $userId)->update($data);
- }
- }
- function cmf_api_request($url, $params = [])
- {
- //初始化
- $curl = curl_init();
- //设置抓取的url
- curl_setopt($curl, CURLOPT_URL, 'http://127.0.0.1:1314/api/' . $url);
- //设置头文件的信息作为数据流输出
- curl_setopt($curl, CURLOPT_HEADER, 0);
- //设置获取的信息以文件流的形式返回,而不是直接输出。
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
- //设置post方式提交
- curl_setopt($curl, CURLOPT_POST, 1);
- $token = session('token');
- curl_setopt($curl, CURLOPT_HTTPHEADER, ["XX-Token: $token"]);
- //设置post数据
- curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
- //执行命令
- $data = curl_exec($curl);
- //关闭URL请求
- curl_close($curl);
- //显示获得的数据
- return json_decode($data, true);
- }
- /**
- * 判断是否允许开放注册
- */
- function cmf_is_open_registration()
- {
- $cmfSettings = cmf_get_option('cmf_settings');
- return empty($cmfSettings['open_registration']) ? false : true;
- }
- /**
- * XML编码
- * @param mixed $data 数据
- * @param string $root 根节点名
- * @param string $item 数字索引的子节点名
- * @param string $attr 根节点属性
- * @param string $id 数字索引子节点key转换的属性名
- * @param string $encoding 数据编码
- * @return string
- */
- function cmf_xml_encode($data, $root = 'think', $item = 'item', $attr = '', $id = 'id', $encoding = 'utf-8')
- {
- if (is_array($attr)) {
- $_attr = [];
- foreach ($attr as $key => $value) {
- $_attr[] = "{$key}=\"{$value}\"";
- }
- $attr = implode(' ', $_attr);
- }
- $attr = trim($attr);
- $attr = empty($attr) ? '' : " {$attr}";
- $xml = "<?xml version=\"1.0\" encoding=\"{$encoding}\"?>";
- $xml .= "<{$root}{$attr}>";
- $xml .= cmf_data_to_xml($data, $item, $id);
- $xml .= "</{$root}>";
- return $xml;
- }
- /**
- * 数据XML编码
- * @param mixed $data 数据
- * @param string $item 数字索引时的节点名称
- * @param string $id 数字索引key转换为的属性名
- * @return string
- */
- function cmf_data_to_xml($data, $item = 'item', $id = 'id')
- {
- $xml = $attr = '';
- foreach ($data as $key => $val) {
- if (is_numeric($key)) {
- $id && $attr = " {$id}=\"{$key}\"";
- $key = $item;
- }
- $xml .= "<{$key}{$attr}>";
- $xml .= (is_array($val) || is_object($val)) ? cmf_data_to_xml($val, $item, $id) : $val;
- $xml .= "</{$key}>";
- }
- return $xml;
- }
- /**
- * 检查手机格式,中国手机不带国家代码,国际手机号格式为:国家代码-手机号
- * @param $mobile
- * @return bool
- */
- function cmf_check_mobile($mobile)
- {
- if (preg_match('/(^(13\d|14\d|15\d|16\d|17\d|18\d|19\d)\d{8})$/', $mobile)) {
- return true;
- } else {
- if (preg_match('/^\d{1,4}-\d{5,11}$/', $mobile)) {
- if (preg_match('/^\d{1,4}-0+/', $mobile)) {
- //不能以0开头
- return false;
- }
- return true;
- }
- return false;
- }
- }
- /**
- * 文件大小格式化
- * @param $bytes 文件大小(字节 Byte)
- * @return string
- */
- function cmf_file_size_format($bytes)
- {
- $type = ['B', 'KB', 'MB', 'GB', 'TB'];
- for ($i = 0; $bytes >= 1024; $i++)//单位每增大1024,则单位数组向后移动一位表示相应的单位
- {
- $bytes /= 1024;
- }
- return (floor($bytes * 100) / 100) . $type[$i];//floor是取整函数,为了防止出现一串的小数,这里取了两位小数
- }
- /**
- * 计数器增加
- * @param $name 计数器英文标识
- * @param int $min 计数器最小值
- * @param int $step 增加步长
- * @return mixed
- */
- function cmf_counter_inc($name, $min = 1, $step = 1)
- {
- $id = cache('core_counter_' . $name);
- if (empty($id)) {
- $id = Db::name('core_counter')->where('name', $name)->value('id');
- if (empty($id)) {
- $id = Db::name('core_counter')->insertGetId([
- 'name' => $name,
- 'value' => 0
- ]);
- }
- cache('core_counter_' . $name, $id);
- }
- Db::startTrans();
- try {
- $value = Db::name('core_counter')->where('id', $id)->lock(true)->value('value');
- if ($min > $value) {
- $value = $min;
- } else {
- $value += $step;
- }
- Db::name('core_counter')->where('id', $id)->update(['value' => $value]);
- Db::commit();
- } catch (\Exception $e) {
- Db::rollback();
- $value = false;
- }
- return $value;
- }
- /**
- * 获取ThinkPHP版本
- * @return string
- */
- function cmf_thinkphp_version()
- {
- return \think\facade\App::version();
- }
- /**
- * 获取ThinkCMF版本
- * @return string
- */
- function cmf_version()
- {
- try {
- $version = trim(file_get_contents(CMF_ROOT . 'version'));
- } catch (\Exception $e) {
- $version = '0.0.0';
- }
- return $version;
- }
- /**
- * 获取ThinkCMF核心包目录
- */
- function cmf_core_path()
- {
- return __DIR__ . DIRECTORY_SEPARATOR;
- }
- /**
- * 获取模块配置文件路径
- * @param $app 应用
- * @param $file 文件名不带后缀
- */
- function cmf_get_app_config_file($app, $file)
- {
- switch ($app) {
- case 'cmf':
- $configFile = cmf_core_path() . "{$file}.php";
- break;
- case 'swoole':
- $configFile = Env::get('root_path') . "vendor/thinkcmf/cmf-swoole/src/{$file}.php";
- break;
- default:
- $configFile = APP_PATH . $app . "/{$file}.php";
- if (!file_exists($configFile)) {
- $configFile = Env::get('root_path') . "vendor/thinkcmf/cmf-app/src/{$app}/{$file}.php";
- }
- }
- return $configFile;
- }
- /**
- * 转换+-为desc和asc
- * @deprecated
- * @param $order array 转换对象
- * @return array
- */
- function order_shift($order)
- {
- $orderArr = [];
- foreach ($order as $key => $value) {
- $upDwn = substr($value, 0, 1);
- $orderType = $upDwn == '-' ? 'desc' : 'asc';
- $orderField = substr($value, 1);
- if (!empty($whiteParams)) {
- if (in_array($orderField, $whiteParams)) {
- $orderArr[$orderField] = $orderType;
- }
- } else {
- $orderArr[$orderField] = $orderType;
- }
- }
- return $orderArr;
- }
- /**
- * 模型检查
- * @deprecated
- * @param $relationFilter array 检查的字段
- * @param $relations string 被检查的字段
- * @return array|bool
- */
- function allowed_relations($relationFilter, $relations)
- {
- if (is_string($relations)) {
- $relations = explode(',', $relations);
- }
- if (!is_array($relations)) {
- return false;
- }
- return array_intersect($relationFilter, $relations);
- }
- /**
- * 字符串转数组
- * @deprecated
- * @param string $string 字符串
- * @return array
- */
- function str_to_arr($string)
- {
- $result = is_string($string) ? explode(',', $string) : $string;
- return $result;
- }
- ///////////// 新增函数 /////////////
- /**
- * 返回JSON数据
- * @param $params 状态码:success-成功,error-失败或返回所有参数数组如:['code'=>'success','messgae'=>'message','data'=>[]]
- * @param string $message 错误消息
- * @param array $data 返回数据
- */
- function showJson($params, $message='', $data=null, $end=''){
- if($params && is_array($params)){
- $message = isset($params['message'])? trim($params['message']) : 'message';
- $data = isset($params['data'])? $params['data'] : null;
- $code = isset($params['code'])? $params['code'] : 'error';
- }else{
- $code = $params;
- }
- $code = is_numeric($code)? lang($code) : $code;
- $message = is_numeric($message)? lang($message) : $message;
- $jsonData = [
- 'code' => in_array($code, ['error', 'success','login','exception']) ? $code : 'error',
- 'message' => $message ? $message : 'message',
- ];
- if ($data !== null) {
- $jsonData['data'] = $data;
- }
- header("Content:application/json;chartset=uft-8");
- echo json_encode($jsonData, 256).$end;
- exit;
- }
- /**
- * HTTP请求
- * @param $url 链接
- * @param $data 提交数据
- * @param string $type 请求类型:get post
- * @param string $dataType 返回数据类型 array json
- * @param int $timeout
- * @return mixed
- */
- function httpRequest($url, $data=[], $type='post', $dataType='array', $timeout=60){
- $data = $data && is_array($data)? http_build_query($data) : $data;
- $url = strtolower($type) == 'get'? $url.(strpos($url, '?') === false ? '?' : ''). $data : $url;
- $ch = curl_init($url);
- echo $url;
- var_dump($data);
- curl_setopt($ch, CURLOPT_POST, 1);
- curl_setopt($ch, CURLOPT_HEADER,0 );
- curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查,0-规避ssl的证书检查
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
- curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
- $ret = curl_exec($ch);
- curl_close($ch);
- echo $ret;
- if(strtolower($dataType) == 'array' && !is_array($ret)){
- $ret = json_decode($ret, true);
- }
- return $ret;
- }
- /**
- * HTTP请求
- * @param $url 链接
- * @param $data 提交数据
- * @param string $type 请求类型:get post
- * @param string $dataType 返回数据类型 array json
- * @param int $timeout
- * @return mixed
- */
- function grabRequest($url, $header=[], $data=[], $type='get', $dataType='array', $cookieType='', $timeout=60){
- $getData = $data && is_array($data)? http_build_query($data) : '';
- $url = strtolower($type) == 'get'? $url.(strpos($url, '?') === false && $getData? '?' : ''). $getData : $url;
- $ch = curl_init($url);
- if($header){
- curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
- }else{
- curl_setopt($ch, CURLOPT_HEADER, 0);
- }
-
- if (!empty($cookieType)) {
- $cookie = file_get_contents('./logs/cookie_{$cookieType}.txt');
- if($cookie){
- curl_setopt($ch, CURLOPT_COOKIE, $cookie);
- }
- }
- curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
- curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查,0-规避ssl的证书检查
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
- if($type == 'post'){
- curl_setopt($ch, CURLOPT_POST, 1);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
- }
- curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
- $ret = curl_exec($ch);
- curl_close($ch);
- if(strtolower($dataType) == 'array' && !is_array($ret)){
- $ret = json_decode($ret, true);
- }
- return $ret;
- }
- /**
- * HTTP请求
- * @param $url 链接
- * @param $data 提交数据
- * @param string $type 请求类型:get post
- * @param string $dataType 返回数据类型 array json
- * @param int $timeout
- * @return mixed
- */
- function postRequest($url, $data=[], $header=[], $dataType='array', $cookieType='', $timeout=60){
- $ch = curl_init($url);
- if($header){
- var_dump($header);
- curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
- }else{
- curl_setopt($ch, CURLOPT_HEADER, 0);
- }
- if (!empty($cookieType)) {
- $cookie = file_get_contents("./logs/cookie_{$cookieType}.txt");
- if($cookie){
- echo $cookie."\n";
- curl_setopt($ch, CURLOPT_COOKIE, $cookie);
- }
- }
- echo $data;
- curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
- curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
- curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'post');
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查,0-规避ssl的证书检查
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
- curl_setopt($ch, CURLOPT_POST, 1);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
- curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
- $ret = curl_exec($ch);
- echo $ret;
- curl_close($ch);
- if(strtolower($dataType) == 'array' && !is_array($ret)){
- $ret = json_decode($ret, true);
- }
- return $ret;
- }
- /**
- *
- * 接口请求
- * @author wesmiler
- * @param $url 接口地址
- * @param $data
- * @param $type
- * @param int $timeout
- * @return mixed
- */
- function requestCookies($url, $data='', $cookie='', $type='auth', $timeout=5)
- {
- $ch = curl_init($url);
- if($cookie){
- curl_setopt($ch, CURLOPT_COOKIE, $cookie);
- }
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //禁止 cURL 验证对等证书
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //是否检测服务器的域名与证书上的是否一致
- curl_setopt($ch, CURLOPT_HEADER, 1);
- curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
- curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
- if($data){
- curl_setopt($ch, CURLOPT_POST, 1);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
- }
- $ret = curl_exec($ch);
- curl_close($ch);
- $cookie = '';
- $time = microtime(true);
- // file_put_contents("./logs/page_".date('YmdHis').".html", $url."\n".$ret);
- file_put_contents("./logs/cookies_ret_".date('YmdHis').'_'.$time.".txt", $url."\n".$ret);
- $preg_cookie = '/(Set-Cookie|set-cookie): (.*?);/m';
- if ($ret && preg_match_all($preg_cookie, $ret, $cookies)) {
- if(isset($cookies[2])){
- array_filter($cookies[2]);
- $cookie = implode(';', $cookies[2]);
- }
- }
- file_put_contents("./logs/cookies_".date('YmdHis').'_'.$time.".txt", $cookie);
- return $cookie;
- }
- /**
- * 解析COOKIE
- * @param $cookies
- * @return array
- */
- function getCookieArr($cookies){
- $cookieArr = [];
- $cookies = explode(';', $cookies);
- foreach ($cookies as $cookie){
- $data = explode('=', $cookie);
- $key = isset($data[0])? trim($data[0]) : '';
- $val = preg_replace("/^{$key}/",'', $cookie);
- if($key){
- $cookieArr[$key] = trim($val);
- }
- }
- return $cookieArr;
- }
- /**
- * 生成用户名
- * @author wesmiler
- * @date 2018年9月25日
- * @param string $userCode ID,可为空
- * @return string
- */
- function makeUserName($userCode='',$prefix='U'){
- $charset = 'utf-8';
- $codeLength = 8;
- $length = 10;
- $userCode = $userCode? $userCode : db('user')->max('id')+1;
- $length = $length>10? $length : 10;
- $userCodeLength = mb_strlen($userCode, $charset);
- $prefixLength = mb_strlen($prefix, $charset);
- if($userCodeLength>$codeLength){
- $code = md5(date('is').uniqid($prefix).rand(10, 999).$userCode);
- $code = $prefix.'00'.mb_substr($code, -8, 6, $charset);
- }else{
- $time = microtime(true);
- $code = $prefix.str_repeat('0', $length-$userCodeLength-$prefixLength-1).($time%9).$userCode;
- }
- $code = strtoupper($code);
- return $code;
- }
- /**
- * @param $str
- * @return string
- */
- function formatName($str){
- return mb_substr($str, 0, 3, 'utf-8').'*****'.mb_substr($str, -3, 3, 'utf-8');
- }
- /**
- * 解码
- * @param $str
- * @return string
- */
- function phpescape($str)
- {
- $sublen=strlen($str);
- $retrunString="";
- for ($i=0;$i<$sublen;$i++)
- {
- if(ord($str[$i])>=127)
- {
- $tmpString=bin2hex(iconv("gb2312","ucs-2",substr($str,$i,2)));
- $retrunString.="%u".$tmpString;
- $i++;
- } else
- {
- $retrunString.="%".dechex(ord($str[$i]));
- }
- }
- return $retrunString;
- }
- /**
- * 解析前端JSON字符串
- * @param $data
- * @return bool|mixed
- */
- function jsonParse($data){
- if(empty($data)){
- return false;
- }
- $data = html_entity_decode($data);
- return json_decode($data, true);
- }
- /**
- * 生成UUID
- * @return bool|mixed
- */
- function makeRandomUid(){
- $v8js = new V8Js();
- $jsStr = <<< ETO
- function r() {
- function t() {
- return n ? 15 & n[e++] : 16 * Math.random() | 0
- }
- var n = null,
- e = 0,
- r = window.crypto || window.msCrypto;
- r && r.getRandomValues && (n = r.getRandomValues(new Uint8Array(31)));
- for (var o, i = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx", a = "", s = 0; s < i.length; s++) o = i[s], "x" === o ? a += t().toString(16) : "y" === o ? (o = 3 & t() | 8, a += o.toString(16)) : a += o;
- return a
- }
- ETO;
- try {
- $uuid = $v8js->executeString($jsStr, 'uuid.js');
- echo $uuid;
- return $uuid;
- } catch (\V8JsScriptException $e){
- return false;
- }
-
- }
|