common.php 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +---------------------------------------------------------------------
  9. // | Author: Dean <zxxjjforever@163.com>
  10. // +----------------------------------------------------------------------
  11. use think\Db;
  12. use think\facade\Env;
  13. use think\facade\Url;
  14. use dir\Dir;
  15. use think\facade\Route;
  16. use think\Loader;
  17. use cmf\lib\Storage;
  18. use think\facade\Hook;
  19. // 应用公共文件
  20. if (PHP_SAPI == 'cli') {
  21. $apps = cmf_scan_dir(APP_PATH . '*', GLOB_ONLYDIR);
  22. foreach ($apps as $app) {
  23. $commandFile = APP_PATH . $app . '/command.php';
  24. if (file_exists($commandFile)) {
  25. $commands = include $commandFile;
  26. // 注册命令行指令
  27. \think\Console::addDefaultCommands($commands);
  28. }
  29. }
  30. }
  31. /**
  32. * 获取当前登录的管理员ID
  33. * @return int
  34. */
  35. function cmf_get_current_admin_id()
  36. {
  37. return session('ADMIN_ID');
  38. }
  39. /**
  40. * 判断前台用户是否登录
  41. * @return boolean
  42. */
  43. function cmf_is_user_login()
  44. {
  45. $sessionUser = session('user');
  46. return !empty($sessionUser);
  47. }
  48. /**
  49. * 获取当前登录的前台用户的信息,未登录时,返回false
  50. * @return array|boolean
  51. */
  52. function cmf_get_current_user()
  53. {
  54. $sessionUser = session('user');
  55. if (!empty($sessionUser)) {
  56. unset($sessionUser['user_pass']); // 销毁敏感数据
  57. return $sessionUser;
  58. } else {
  59. return false;
  60. }
  61. }
  62. /**
  63. * 更新当前登录前台用户的信息
  64. * @param array $user 前台用户的信息
  65. */
  66. function cmf_update_current_user($user)
  67. {
  68. session('user', $user);
  69. }
  70. /**
  71. * 获取当前登录前台用户id
  72. * @return int
  73. */
  74. function cmf_get_current_user_id()
  75. {
  76. $sessionUserId = session('user.id');
  77. if (empty($sessionUserId)) {
  78. return 0;
  79. }
  80. return $sessionUserId;
  81. }
  82. /**
  83. * 返回带协议的域名
  84. */
  85. function cmf_get_domain()
  86. {
  87. return request()->domain();
  88. }
  89. /**
  90. * 获取网站根目录
  91. * @return string 网站根目录
  92. */
  93. function cmf_get_root()
  94. {
  95. $root = request()->root();
  96. $root = str_replace("//", '/', $root);
  97. $root = str_replace('/index.php', '', $root);
  98. if (defined('APP_NAMESPACE') && APP_NAMESPACE == 'api') {
  99. $root = preg_replace('/\/api$/', '', $root);
  100. }
  101. $root = rtrim($root, '/');
  102. return $root;
  103. }
  104. /**
  105. * 获取当前主题名
  106. * @return string
  107. */
  108. function cmf_get_current_theme()
  109. {
  110. if (PHP_SAPI != 'cli') {
  111. static $_currentTheme;
  112. if (!empty($_currentTheme)) {
  113. return $_currentTheme;
  114. }
  115. }
  116. $t = 't';
  117. // $theme = config('template.cmf_default_theme');
  118. if(cmf_is_mobile()){
  119. $theme = config('template.cmf_mobile_default_theme');
  120. }else{
  121. $theme = config('template.cmf_default_theme');
  122. }
  123. $cmfDetectTheme = config('template.cmf_detect_theme');
  124. if ($cmfDetectTheme) {
  125. if (isset($_GET[$t])) {
  126. $theme = $_GET[$t];
  127. cookie('cmf_template', $theme, 864000);
  128. } elseif (cookie('cmf_template')) {
  129. $theme = cookie('cmf_template');
  130. }
  131. }
  132. $hookTheme = hook_one('switch_theme');
  133. if ($hookTheme) {
  134. $theme = $hookTheme;
  135. }
  136. $designT = '_design_theme';
  137. if (isset($_GET[$designT])) {
  138. $theme = $_GET[$designT];
  139. cookie('cmf_design_theme', $theme, 4);
  140. } elseif (cookie('cmf_design_theme')) {
  141. $theme = cookie('cmf_design_theme');
  142. }
  143. $_currentTheme = $theme;
  144. return $theme;
  145. }
  146. /**
  147. * 获取当前后台主题名
  148. * @return string
  149. */
  150. function cmf_get_current_admin_theme()
  151. {
  152. if (PHP_SAPI != 'cli') {
  153. static $_currentAdminTheme;
  154. if (!empty($_currentAdminTheme)) {
  155. return $_currentAdminTheme;
  156. }
  157. }
  158. $t = '_at';
  159. $theme = config('template.cmf_admin_default_theme');
  160. $cmfDetectTheme = true;
  161. if ($cmfDetectTheme) {
  162. if (isset($_GET[$t])) {
  163. $theme = $_GET[$t];
  164. cookie('cmf_admin_theme', $theme, 864000);
  165. } elseif (cookie('cmf_admin_theme')) {
  166. $theme = cookie('cmf_admin_theme');
  167. }
  168. }
  169. $hookTheme = hook_one('switch_admin_theme');
  170. if ($hookTheme) {
  171. $theme = $hookTheme;
  172. }
  173. $_currentAdminTheme = $theme;
  174. return $theme;
  175. }
  176. /**
  177. * 获取前台模板根目录
  178. * @param string $theme
  179. * @return string 前台模板根目录
  180. */
  181. function cmf_get_theme_path($theme = null)
  182. {
  183. $themePath = config('template.cmf_theme_path');
  184. if ($theme === null) {
  185. // 获取当前主题名称
  186. $theme = cmf_get_current_theme();
  187. }
  188. return WEB_ROOT . $themePath . $theme;
  189. }
  190. /**
  191. * 获取用户头像地址
  192. * @param $avatar 用户头像文件路径,相对于 upload 目录
  193. * @return string
  194. */
  195. function cmf_get_user_avatar_url($avatar)
  196. {
  197. if (!empty($avatar)) {
  198. if (strpos($avatar, "http") === 0) {
  199. return $avatar;
  200. } else {
  201. return cmf_get_image_url($avatar, 'avatar');
  202. }
  203. } else {
  204. return $avatar;
  205. }
  206. }
  207. /**
  208. * CMF密码加密方法
  209. * @param string $pw 要加密的原始密码
  210. * @param string $authCode 加密字符串
  211. * @return string
  212. */
  213. function cmf_password($pw, $authCode = '')
  214. {
  215. if (empty($authCode)) {
  216. $authCode = config('database.authcode');
  217. }
  218. $result = "###" . md5(md5($authCode . $pw));
  219. return $result;
  220. }
  221. /**
  222. * CMF密码加密方法 (X2.0.0以前的方法)
  223. * @param string $pw 要加密的原始密码
  224. * @return string
  225. */
  226. function cmf_password_old($pw)
  227. {
  228. $decor = md5(config('database.prefix'));
  229. $mi = md5($pw);
  230. return substr($decor, 0, 12) . $mi . substr($decor, -4, 4);
  231. }
  232. /**
  233. * CMF密码比较方法,所有涉及密码比较的地方都用这个方法
  234. * @param string $password 要比较的密码
  235. * @param string $passwordInDb 数据库保存的已经加密过的密码
  236. * @return boolean 密码相同,返回true
  237. */
  238. function cmf_compare_password($password, $passwordInDb)
  239. {
  240. if (strpos($passwordInDb, "###") === 0) {
  241. return cmf_password($password) == $passwordInDb;
  242. } else {
  243. return cmf_password_old($password) == $passwordInDb;
  244. }
  245. }
  246. /**
  247. * 文件日志
  248. * @param $content 要写入的内容
  249. * @param string $file 日志文件,在web 入口目录
  250. */
  251. function cmf_log($content, $file = "log.txt")
  252. {
  253. file_put_contents($file, $content, FILE_APPEND);
  254. }
  255. /**
  256. * 随机字符串生成
  257. * @param int $len 生成的字符串长度
  258. * @return string
  259. */
  260. function cmf_random_string($len = 6)
  261. {
  262. $chars = [
  263. "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
  264. "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
  265. "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
  266. "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
  267. "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
  268. "3", "4", "5", "6", "7", "8", "9"
  269. ];
  270. $charsLen = count($chars) - 1;
  271. shuffle($chars); // 将数组打乱
  272. $output = "";
  273. for ($i = 0; $i < $len; $i++) {
  274. $output .= $chars[mt_rand(0, $charsLen)];
  275. }
  276. return $output;
  277. }
  278. /**
  279. * 清空系统缓存
  280. */
  281. function cmf_clear_cache()
  282. {
  283. // 清除 opcache缓存
  284. if (function_exists("opcache_reset")) {
  285. opcache_reset();
  286. }
  287. // 清楚Redis缓存
  288. app\index\service\RedisService::delByKeys('cache:*');
  289. // end
  290. // 静态化清除缓存
  291. @unlink(CMF_ROOT.'public/index.html');
  292. $dirs = [];
  293. $rootDirs = cmf_scan_dir(Env::get('runtime_path') . "*");
  294. //$noNeedClear=array(".","..","Data");
  295. $noNeedClear = ['.', '..', 'log'];
  296. $rootDirs = array_diff($rootDirs, $noNeedClear);
  297. foreach ($rootDirs as $dir) {
  298. if ($dir != "." && $dir != "..") {
  299. $dir = Env::get('runtime_path') . $dir;
  300. if (is_dir($dir)) {
  301. //array_push ( $dirs, $dir );
  302. $tmpRootDirs = cmf_scan_dir($dir . "/*");
  303. foreach ($tmpRootDirs as $tDir) {
  304. if ($tDir != "." && $tDir != "..") {
  305. $tDir = $dir . '/' . $tDir;
  306. if (is_dir($tDir)) {
  307. array_push($dirs, $tDir);
  308. } else {
  309. // @unlink($tDir);
  310. }
  311. }
  312. }
  313. } else {
  314. // @unlink($dir);
  315. }
  316. }
  317. }
  318. $dirTool = new Dir("");
  319. foreach ($dirs as $dir) {
  320. $dirTool->delDir($dir);
  321. }
  322. }
  323. /**
  324. * 保存数组变量到php文件
  325. * @param string $path 保存路径
  326. * @param mixed $var 要保存的变量
  327. * @return boolean 保存成功返回true,否则false
  328. */
  329. function cmf_save_var($path, $var)
  330. {
  331. $result = file_put_contents($path, "<?php\treturn " . var_export($var, true) . ";?>");
  332. return $result;
  333. }
  334. /**
  335. * 设置动态配置
  336. * @param array $data <br>如:['template' => ['cmf_default_theme' => 'default']];
  337. * @return boolean
  338. */
  339. function cmf_set_dynamic_config($data)
  340. {
  341. if (!is_array($data)) {
  342. return false;
  343. }
  344. foreach ($data as $key => $value) {
  345. if (is_array($value)) {
  346. $configFile = CMF_ROOT . "data/config/{$key}.php";
  347. if (file_exists($configFile)) {
  348. $configs = include $configFile;
  349. } else {
  350. $configs = [];
  351. }
  352. $configs = array_merge($configs, $value);
  353. try {
  354. file_put_contents($configFile, "<?php\treturn " . var_export($configs, true) . ";");
  355. } catch (\Exception $e) {
  356. return false;
  357. }
  358. }
  359. }
  360. cmf_clear_cache();
  361. return true;
  362. }
  363. /**
  364. * 转化格式化的字符串为数组
  365. * @param string $tag 要转化的字符串,格式如:"id:2;cid:1;order:post_date desc;"
  366. * @return array 转化后字符串<pre>
  367. * array(
  368. * 'id'=>'2',
  369. * 'cid'=>'1',
  370. * 'order'=>'post_date desc'
  371. * )
  372. */
  373. function cmf_param_lable($tag = '')
  374. {
  375. $param = [];
  376. $array = explode(';', $tag);
  377. foreach ($array as $v) {
  378. $v = trim($v);
  379. if (!empty($v)) {
  380. list($key, $val) = explode(':', $v);
  381. $param[trim($key)] = trim($val);
  382. }
  383. }
  384. return $param;
  385. }
  386. /**
  387. * 获取后台管理设置的网站信息,此类信息一般用于前台
  388. * @return array
  389. */
  390. function cmf_get_site_info()
  391. {
  392. $siteInfo = cmf_get_option('site_info');
  393. if (isset($siteInfo['site_analytics'])) {
  394. $siteInfo['site_analytics'] = htmlspecialchars_decode($siteInfo['site_analytics']);
  395. }
  396. return $siteInfo;
  397. }
  398. /**
  399. * 获取CMF系统的设置,此类设置用于全局
  400. * @return array
  401. */
  402. function cmf_get_cmf_setting()
  403. {
  404. return cmf_get_option('cmf_setting');
  405. }
  406. /**
  407. * 更新CMF系统的设置,此类设置用于全局
  408. * @param $data
  409. * @return bool
  410. * @throws \think\Exception
  411. * @throws \think\db\exception\DataNotFoundException
  412. * @throws \think\db\exception\ModelNotFoundException
  413. * @throws \think\exception\DbException
  414. * @throws \think\exception\PDOException
  415. */
  416. function cmf_set_cmf_setting($data)
  417. {
  418. if (!is_array($data) || empty($data)) {
  419. return false;
  420. }
  421. return cmf_set_option('cmf_setting', $data);
  422. }
  423. /**
  424. * 设置系统配置,通用
  425. * @param string $key 配置键值,都小写
  426. * @param array $data 配置值,数组
  427. * @param bool $replace 是否完全替换
  428. * @return bool 是否成功
  429. * @throws \think\Exception
  430. * @throws \think\db\exception\DataNotFoundException
  431. * @throws \think\db\exception\ModelNotFoundException
  432. * @throws \think\exception\DbException
  433. * @throws \think\exception\PDOException
  434. */
  435. function cmf_set_option($key, $data, $replace = false)
  436. {
  437. if (!is_array($data) || empty($data) || !is_string($key) || empty($key)) {
  438. return false;
  439. }
  440. $key = strtolower($key);
  441. $option = [];
  442. $findOption = Db::name('option')->where('option_name', $key)->find();
  443. if ($findOption) {
  444. if (!$replace) {
  445. $oldOptionValue = json_decode($findOption['option_value'], true);
  446. if (!empty($oldOptionValue)) {
  447. $data = array_merge($oldOptionValue, $data);
  448. }
  449. }
  450. $option['option_value'] = json_encode($data);
  451. Db::name('option')->where('option_name', $key)->update($option);
  452. // echo Db::name('option')->getLastSql() . "\n";
  453. } else {
  454. $option['option_name'] = $key;
  455. $option['option_value'] = json_encode($data);
  456. Db::name('option')->insert($option);
  457. }
  458. cache('cmf_options_' . $key, null);//删除缓存
  459. return true;
  460. }
  461. /**
  462. * 获取系统配置,通用
  463. * @param string $key 配置键值,都小写
  464. * @return array
  465. */
  466. function cmf_get_option($key)
  467. {
  468. if (!is_string($key) || empty($key)) {
  469. return [];
  470. }
  471. if (PHP_SAPI != 'cli') {
  472. static $cmfGetOption;
  473. if (empty($cmfGetOption)) {
  474. $cmfGetOption = [];
  475. } else {
  476. if (!empty($cmfGetOption[$key])) {
  477. return $cmfGetOption[$key];
  478. }
  479. }
  480. }
  481. $optionValue = cache('cmf_options_' . $key);
  482. if (empty($optionValue)) {
  483. $optionValue = Db::name('option')->where('option_name', $key)->value('option_value');
  484. if (!empty($optionValue)) {
  485. $optionValue = json_decode($optionValue, true);
  486. cache('cmf_options_' . $key, $optionValue);
  487. }
  488. }
  489. $cmfGetOption[$key] = $optionValue;
  490. return $optionValue;
  491. }
  492. /**
  493. * 获取CMF上传配置
  494. */
  495. function cmf_get_upload_setting()
  496. {
  497. $uploadSetting = cmf_get_option('upload_setting');
  498. if (empty($uploadSetting) || empty($uploadSetting['file_types'])) {
  499. $uploadSetting = [
  500. 'file_types' => [
  501. 'image' => [
  502. 'upload_max_filesize' => '10240',//单位KB
  503. 'extensions' => 'jpg,jpeg,png,gif,bmp4'
  504. ],
  505. 'video' => [
  506. 'upload_max_filesize' => '10240',
  507. 'extensions' => 'mp4,avi,wmv,rm,rmvb,mkv'
  508. ],
  509. 'audio' => [
  510. 'upload_max_filesize' => '10240',
  511. 'extensions' => 'mp3,wma,wav'
  512. ],
  513. 'file' => [
  514. 'upload_max_filesize' => '10240',
  515. 'extensions' => 'txt,pdf,doc,docx,xls,xlsx,ppt,pptx,zip,rar'
  516. ]
  517. ],
  518. 'chunk_size' => 512,//单位KB
  519. 'max_files' => 20 //最大同时上传文件数
  520. ];
  521. }
  522. if (empty($uploadSetting['upload_max_filesize'])) {
  523. $uploadMaxFileSizeSetting = [];
  524. foreach ($uploadSetting['file_types'] as $setting) {
  525. $extensions = explode(',', trim($setting['extensions']));
  526. if (!empty($extensions)) {
  527. $uploadMaxFileSize = intval($setting['upload_max_filesize']) * 1024;//转化成B
  528. foreach ($extensions as $ext) {
  529. if (!isset($uploadMaxFileSizeSetting[$ext]) || $uploadMaxFileSize > $uploadMaxFileSizeSetting[$ext]) {
  530. $uploadMaxFileSizeSetting[$ext] = $uploadMaxFileSize;
  531. }
  532. }
  533. }
  534. }
  535. $uploadSetting['upload_max_filesize'] = $uploadMaxFileSizeSetting;
  536. }
  537. return $uploadSetting;
  538. }
  539. /**
  540. * 获取html文本里的img
  541. * @param string $content html 内容
  542. * @return array 图片列表 数组item格式<pre>
  543. * [
  544. * "src"=>'图片链接',
  545. * "title"=>'图片标签的 title 属性',
  546. * "alt"=>'图片标签的 alt 属性'
  547. * ]
  548. * </pre>
  549. */
  550. function cmf_get_content_images($content)
  551. {
  552. //import('phpQuery.phpQuery', EXTEND_PATH);
  553. \phpQuery::newDocumentHTML($content);
  554. $pq = pq(null);
  555. $images = $pq->find("img");
  556. $imagesData = [];
  557. if ($images->length) {
  558. foreach ($images as $img) {
  559. $img = pq($img);
  560. $image = [];
  561. $image['src'] = $img->attr("src");
  562. $image['title'] = $img->attr("title");
  563. $image['alt'] = $img->attr("alt");
  564. array_push($imagesData, $image);
  565. }
  566. }
  567. \phpQuery::$documents = null;
  568. return $imagesData;
  569. }
  570. /**
  571. * 去除字符串中的指定字符
  572. * @param string $str 待处理字符串
  573. * @param string $chars 需去掉的特殊字符
  574. * @return string
  575. */
  576. function cmf_strip_chars($str, $chars = '?<*.>\'\"')
  577. {
  578. return preg_replace('/[' . $chars . ']/is', '', $str);
  579. }
  580. /**
  581. * 发送邮件
  582. * @param string $address 收件人邮箱
  583. * @param string $subject 邮件标题
  584. * @param string $message 邮件内容
  585. * @return array<br>
  586. * 返回格式:<br>
  587. * array(<br>
  588. * "error"=>0|1,//0代表出错<br>
  589. * "message"=> "出错信息"<br>
  590. * );
  591. * @throws phpmailerException
  592. */
  593. function cmf_send_email($address, $subject, $message)
  594. {
  595. $smtpSetting = cmf_get_option('smtp_setting');
  596. $mail = new \PHPMailer\PHPMailer\PHPMailer();
  597. // 设置PHPMailer使用SMTP服务器发送Email
  598. $mail->IsSMTP();
  599. $mail->IsHTML(true);
  600. //$mail->SMTPDebug = 3;
  601. // 设置邮件的字符编码,若不指定,则为'UTF-8'
  602. $mail->CharSet = 'UTF-8';
  603. // 添加收件人地址,可以多次使用来添加多个收件人
  604. $mail->AddAddress($address);
  605. // 设置邮件正文
  606. $mail->Body = $message;
  607. // 设置邮件头的From字段。
  608. $mail->From = $smtpSetting['from'];
  609. // 设置发件人名字
  610. $mail->FromName = $smtpSetting['from_name'];
  611. // 设置邮件标题
  612. $mail->Subject = $subject;
  613. // 设置SMTP服务器。
  614. $mail->Host = $smtpSetting['host'];
  615. //by Rainfer
  616. // 设置SMTPSecure。
  617. $Secure = $smtpSetting['smtp_secure'];
  618. $mail->SMTPSecure = empty($Secure) ? '' : $Secure;
  619. // 设置SMTP服务器端口。
  620. $port = $smtpSetting['port'];
  621. $mail->Port = empty($port) ? "25" : $port;
  622. // 设置为"需要验证"
  623. $mail->SMTPAuth = true;
  624. $mail->SMTPAutoTLS = false;
  625. $mail->Timeout = 10;
  626. // 设置用户名和密码。
  627. $mail->Username = $smtpSetting['username'];
  628. $mail->Password = $smtpSetting['password'];
  629. // 发送邮件。
  630. if (!$mail->Send()) {
  631. $mailError = $mail->ErrorInfo;
  632. return ["error" => 1, "message" => $mailError];
  633. } else {
  634. return ["error" => 0, "message" => "success"];
  635. }
  636. }
  637. /**
  638. * 转化数据库保存的文件路径,为可以访问的url
  639. * @param string $file
  640. * @param mixed $style 图片样式,支持各大云存储
  641. * @return string
  642. */
  643. function cmf_get_asset_url($file, $style = '')
  644. {
  645. if (strpos($file, "http") === 0) {
  646. return $file;
  647. } else if (strpos($file, "/") === 0) {
  648. return $file;
  649. } else {
  650. // $storage = cmf_get_option('storage');
  651. // if (empty($storage['type'])) {
  652. // $storage['type'] = 'Local';
  653. // }
  654. // if ($storage['type'] != 'Local') {
  655. // $watermark = cmf_get_plugin_config($storage['type']);
  656. // $style = empty($style) ? $watermark['styles_watermark'] : $style;
  657. // }
  658. $storage = Storage::instance();
  659. return $storage->getUrl($file, $style);
  660. }
  661. }
  662. /**
  663. * 转化数据库保存图片的文件路径,为可以访问的url
  664. * @param string $file 文件路径,数据存储的文件相对路径
  665. * @param string $style 图片样式,支持各大云存储
  666. * @return string 图片链接
  667. */
  668. function cmf_get_image_url($file, $style = 'watermark')
  669. {
  670. if (empty($file)) {
  671. return '';
  672. }
  673. if (strpos($file, "http") === 0) {
  674. return $file;
  675. } else if (strpos($file, "/") === 0) {
  676. return cmf_get_domain() . $file;
  677. } else {
  678. // $storage = cmf_get_option('storage');
  679. // if (empty($storage['type'])) {
  680. // $storage['type'] = 'Local';
  681. // }
  682. // if ($storage['type'] != 'Local') {
  683. // $watermark = cmf_get_plugin_config($storage['type']);
  684. // $style = empty($style) ? $watermark['styles_watermark'] : $style;
  685. // }
  686. $storage = Storage::instance();
  687. return $storage->getImageUrl($file, $style);
  688. }
  689. }
  690. /**
  691. * 获取图片预览链接
  692. * @param string $file 文件路径,相对于upload
  693. * @param string $style 图片样式,支持各大云存储
  694. * @return string
  695. */
  696. function cmf_get_image_preview_url($file, $style = 'watermark')
  697. {
  698. if (empty($file)) {
  699. return '';
  700. }
  701. if (strpos($file, "http") === 0) {
  702. return $file;
  703. } else if (strpos($file, "/") === 0) {
  704. return $file;
  705. } else {
  706. // $storage = cmf_get_option('storage');
  707. // if (empty($storage['type'])) {
  708. // $storage['type'] = 'Local';
  709. // }
  710. // if ($storage['type'] != 'Local') {
  711. // $watermark = cmf_get_plugin_config($storage['type']);
  712. // $style = empty($style) ? $watermark['styles_watermark'] : $style;
  713. // }
  714. $storage = Storage::instance();
  715. return $storage->getPreviewUrl($file, $style);
  716. }
  717. }
  718. /**
  719. * 获取文件下载链接
  720. * @param string $file 文件路径,数据库里保存的相对路径
  721. * @param int $expires 过期时间,单位 s
  722. * @return string 文件链接
  723. */
  724. function cmf_get_file_download_url($file, $expires = 3600)
  725. {
  726. if (empty($file)) {
  727. return '';
  728. }
  729. if (strpos($file, "http") === 0) {
  730. return $file;
  731. } else if (strpos($file, "/") === 0) {
  732. return $file;
  733. } else {
  734. $storage = Storage::instance();
  735. return $storage->getFileDownloadUrl($file, $expires);
  736. }
  737. }
  738. /**
  739. * 解密用cmf_str_encode加密的字符串
  740. * @param $string 要解密的字符串
  741. * @param string $key 加密时salt
  742. * @param int $expiry 多少秒后过期
  743. * @param string $operation 操作,默认为DECODE
  744. * @return bool|string
  745. */
  746. function cmf_str_decode($string, $key = '', $expiry = 0, $operation = 'DECODE')
  747. {
  748. $ckey_length = 4;
  749. $key = md5($key ? $key : config("database.authcode"));
  750. $keya = md5(substr($key, 0, 16));
  751. $keyb = md5(substr($key, 16, 16));
  752. $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';
  753. $cryptkey = $keya . md5($keya . $keyc);
  754. $key_length = strlen($cryptkey);
  755. $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
  756. $string_length = strlen($string);
  757. $result = '';
  758. $box = range(0, 255);
  759. $rndkey = [];
  760. for ($i = 0; $i <= 255; $i++) {
  761. $rndkey[$i] = ord($cryptkey[$i % $key_length]);
  762. }
  763. for ($j = $i = 0; $i < 256; $i++) {
  764. $j = ($j + $box[$i] + $rndkey[$i]) % 256;
  765. $tmp = $box[$i];
  766. $box[$i] = $box[$j];
  767. $box[$j] = $tmp;
  768. }
  769. for ($a = $j = $i = 0; $i < $string_length; $i++) {
  770. $a = ($a + 1) % 256;
  771. $j = ($j + $box[$a]) % 256;
  772. $tmp = $box[$a];
  773. $box[$a] = $box[$j];
  774. $box[$j] = $tmp;
  775. $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
  776. }
  777. if ($operation == 'DECODE') {
  778. if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
  779. return substr($result, 26);
  780. } else {
  781. return '';
  782. }
  783. } else {
  784. return $keyc . str_replace('=', '', base64_encode($result));
  785. }
  786. }
  787. /**
  788. * 加密字符串
  789. * @param $string 要加密的字符串
  790. * @param string $key salt
  791. * @param int $expiry 多少秒后过期
  792. * @return bool|string
  793. */
  794. function cmf_str_encode($string, $key = '', $expiry = 0)
  795. {
  796. return cmf_str_decode($string, $key, $expiry, "ENCODE");
  797. }
  798. /**
  799. * 获取文件相对路径
  800. * @param string $assetUrl 文件的URL
  801. * @return string
  802. */
  803. function cmf_asset_relative_url($assetUrl)
  804. {
  805. if (strpos($assetUrl, "http") === 0) {
  806. return $assetUrl;
  807. } else {
  808. return str_replace('/upload/', '', $assetUrl);
  809. }
  810. }
  811. /**
  812. * 检查用户对某个url内容的可访问性,用于记录如是否赞过,是否访问过等等;开发者可以自由控制,对于没有必要做的检查可以不做,以减少服务器压力
  813. * @param string $object 访问对象的id,格式:不带前缀的表名+id;如post1表示xx_post表里id为1的记录;如果object为空,表示只检查对某个url访问的合法性
  814. * @param int $countLimit 访问次数限制,如1,表示只能访问一次
  815. * @param boolean $ipLimit ip限制,false为不限制,true为限制
  816. * @param int $expire 距离上次访问的最小时间单位s,0表示不限制,大于0表示最后访问$expire秒后才可以访问
  817. * @return true 可访问,false不可访问
  818. * @throws \think\Exception
  819. * @throws \think\db\exception\DataNotFoundException
  820. * @throws \think\db\exception\ModelNotFoundException
  821. * @throws \think\exception\DbException
  822. * @throws \think\exception\PDOException
  823. */
  824. function cmf_check_user_action($object = "", $countLimit = 1, $ipLimit = false, $expire = 0)
  825. {
  826. $request = request();
  827. $action = $request->module() . "/" . $request->controller() . "/" . $request->action();
  828. if (is_array($object)) {
  829. $userId = $object['user_id'];
  830. $object = $object['object'];
  831. } else {
  832. $userId = cmf_get_current_user_id();
  833. }
  834. $ip = get_client_ip(0, true);//修复ip获取
  835. $where = ["user_id" => $userId, "action" => $action, "object" => $object];
  836. if ($ipLimit) {
  837. $where['ip'] = $ip;
  838. }
  839. $findLog = Db::name('user_action_log')->where($where)->find();
  840. $time = time();
  841. if ($findLog) {
  842. Db::name('user_action_log')->where($where)->update([
  843. "count" => Db::raw("count+1"),
  844. "last_visit_time" => $time,
  845. "ip" => $ip
  846. ]);
  847. if ($findLog['count'] >= $countLimit) {
  848. return false;
  849. }
  850. if ($expire > 0 && ($time - $findLog['last_visit_time']) < $expire) {
  851. return false;
  852. }
  853. } else {
  854. Db::name('user_action_log')->insert([
  855. "user_id" => $userId,
  856. "action" => $action,
  857. "object" => $object,
  858. "count" => Db::raw("count+1"),
  859. "last_visit_time" => $time, "ip" => $ip
  860. ]);
  861. }
  862. return true;
  863. }
  864. /**
  865. * 判断是否为手机访问
  866. * @return boolean
  867. */
  868. function cmf_is_mobile()
  869. {
  870. if (PHP_SAPI != 'cli') {
  871. static $cmf_is_mobile;
  872. if (isset($cmf_is_mobile))
  873. return $cmf_is_mobile;
  874. }
  875. $cmf_is_mobile = request()->isMobile();
  876. return $cmf_is_mobile;
  877. }
  878. /**
  879. * 判断是否为微信访问
  880. * @return boolean
  881. */
  882. function cmf_is_wechat()
  883. {
  884. if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
  885. return true;
  886. }
  887. return false;
  888. }
  889. /**
  890. * 判断是否为Android访问
  891. * @return boolean
  892. */
  893. function cmf_is_android()
  894. {
  895. if (strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false) {
  896. return true;
  897. }
  898. return false;
  899. }
  900. /**
  901. * 判断是否为ios访问
  902. * @return boolean
  903. */
  904. function cmf_is_ios()
  905. {
  906. if (strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone') || strpos($_SERVER['HTTP_USER_AGENT'], 'iPad')) {
  907. {
  908. return true;
  909. }
  910. return false;
  911. }
  912. }
  913. /**
  914. * 判断是否为iPhone访问
  915. * @return boolean
  916. */
  917. function cmf_is_iphone()
  918. {
  919. if (strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone')) {
  920. {
  921. return true;
  922. }
  923. return false;
  924. }
  925. }
  926. /**
  927. * 判断是否为iPad访问
  928. * @return boolean
  929. */
  930. function cmf_is_ipad()
  931. {
  932. if (strpos($_SERVER['HTTP_USER_AGENT'], 'iPad')) {
  933. {
  934. return true;
  935. }
  936. return false;
  937. }
  938. }
  939. /**
  940. * 添加钩子
  941. * @param string $hook 钩子名称
  942. * @param mixed $params 传入参数
  943. * @return void
  944. */
  945. function hook($hook, $params = null)
  946. {
  947. return Hook::listen($hook, $params);
  948. }
  949. /**
  950. * 添加钩子,只执行一个
  951. * @param string $hook 钩子名称
  952. * @param mixed $params 传入参数
  953. * @return mixed
  954. */
  955. function hook_one($hook, $params = null)
  956. {
  957. return Hook::listen($hook, $params, true);
  958. }
  959. /**
  960. * 获取插件类名
  961. * @param string $name 插件名
  962. * @return string
  963. */
  964. function cmf_get_plugin_class($name)
  965. {
  966. $name = ucwords($name);
  967. $pluginDir = cmf_parse_name($name);
  968. $class = "plugins\\{$pluginDir}\\{$name}Plugin";
  969. return $class;
  970. }
  971. /**
  972. * 获取插件配置
  973. * @param string $name 插件名,大驼峰格式
  974. * @return array
  975. */
  976. function cmf_get_plugin_config($name)
  977. {
  978. $class = cmf_get_plugin_class($name);
  979. if (class_exists($class)) {
  980. $plugin = new $class();
  981. return $plugin->getConfig();
  982. } else {
  983. return [];
  984. }
  985. }
  986. /**
  987. * 替代scan_dir的方法
  988. * @param string $pattern 检索模式 搜索模式 *.txt,*.doc; (同glog方法)
  989. * @param int $flags
  990. * @param $pattern
  991. * @return array
  992. */
  993. function cmf_scan_dir($pattern, $flags = null)
  994. {
  995. $files = glob($pattern, $flags);
  996. if (empty($files)) {
  997. $files = [];
  998. } else {
  999. $files = array_map('basename', $files);
  1000. }
  1001. return $files;
  1002. }
  1003. /**
  1004. * 获取某个目录下所有子目录
  1005. * @param $dir
  1006. * @return array
  1007. */
  1008. function cmf_sub_dirs($dir)
  1009. {
  1010. $dir = ltrim($dir, "/");
  1011. $dirs = [];
  1012. $subDirs = cmf_scan_dir("$dir/*", GLOB_ONLYDIR);
  1013. if (!empty($subDirs)) {
  1014. foreach ($subDirs as $subDir) {
  1015. $subDir = "$dir/$subDir";
  1016. array_push($dirs, $subDir);
  1017. $subDirSubDirs = cmf_sub_dirs($subDir);
  1018. if (!empty($subDirSubDirs)) {
  1019. $dirs = array_merge($dirs, $subDirSubDirs);
  1020. }
  1021. }
  1022. }
  1023. return $dirs;
  1024. }
  1025. /**
  1026. * 生成访问插件的url
  1027. * @param string $url url格式:插件名://控制器名/方法
  1028. * @param array $param 参数
  1029. * @param bool $domain 是否显示域名 或者直接传入域名
  1030. * @return string
  1031. */
  1032. function cmf_plugin_url($url, $param = [], $domain = false)
  1033. {
  1034. $url = parse_url($url);
  1035. $case_insensitive = true;
  1036. $plugin = $case_insensitive ? Loader::parseName($url['scheme']) : $url['scheme'];
  1037. $controller = $case_insensitive ? Loader::parseName($url['host']) : $url['host'];
  1038. $action = trim($case_insensitive ? strtolower($url['path']) : $url['path'], '/');
  1039. /* 解析URL带的参数 */
  1040. if (isset($url['query'])) {
  1041. parse_str($url['query'], $query);
  1042. $param = array_merge($query, $param);
  1043. }
  1044. /* 基础参数 */
  1045. $params = [
  1046. '_plugin' => $plugin,
  1047. '_controller' => $controller,
  1048. '_action' => $action,
  1049. ];
  1050. $params = array_merge($params, $param); //添加额外参数
  1051. return url('\\cmf\\controller\\PluginController@index', $params, true, $domain);
  1052. }
  1053. /**
  1054. * 检查权限
  1055. * @param $userId int 要检查权限的用户 ID
  1056. * @param $name string|array 需要验证的规则列表,支持逗号分隔的权限规则或索引数组
  1057. * @param $relation string 如果为 'or' 表示满足任一条规则即通过验证;如果为 'and'则表示需满足所有规则才能通过验证
  1058. * @return boolean 通过验证返回true;失败返回false
  1059. */
  1060. function cmf_auth_check($userId, $name = null, $relation = 'or')
  1061. {
  1062. if (empty($userId)) {
  1063. return false;
  1064. }
  1065. if ($userId == 1) {
  1066. return true;
  1067. }
  1068. $authObj = new \cmf\lib\Auth();
  1069. if (empty($name)) {
  1070. $request = request();
  1071. $module = $request->module();
  1072. $controller = $request->controller();
  1073. $action = $request->action();
  1074. $name = strtolower($module . "/" . $controller . "/" . $action);
  1075. }
  1076. return $authObj->check($userId, $name, $relation);
  1077. }
  1078. function cmf_alpha_id($in, $to_num = false, $pad_up = 4, $passKey = null)
  1079. {
  1080. $index = "aBcDeFgHiJkLmNoPqRsTuVwXyZAbCdEfGhIjKlMnOpQrStUvWxYz0123456789";
  1081. if ($passKey !== null) {
  1082. // Although this function's purpose is to just make the
  1083. // ID short - and not so much secure,
  1084. // with this patch by Simon Franz (http://blog.snaky.org/)
  1085. // you can optionally supply a password to make it harder
  1086. // to calculate the corresponding numeric ID
  1087. for ($n = 0; $n < strlen($index); $n++) $i[] = substr($index, $n, 1);
  1088. $passhash = hash('sha256', $passKey);
  1089. $passhash = (strlen($passhash) < strlen($index)) ? hash('sha512', $passKey) : $passhash;
  1090. for ($n = 0; $n < strlen($index); $n++) $p[] = substr($passhash, $n, 1);
  1091. array_multisort($p, SORT_DESC, $i);
  1092. $index = implode($i);
  1093. }
  1094. $base = strlen($index);
  1095. if ($to_num) {
  1096. // Digital number <<-- alphabet letter code
  1097. $in = strrev($in);
  1098. $out = 0;
  1099. $len = strlen($in) - 1;
  1100. for ($t = 0; $t <= $len; $t++) {
  1101. $bcpow = pow($base, $len - $t);
  1102. $out = $out + strpos($index, substr($in, $t, 1)) * $bcpow;
  1103. }
  1104. if (is_numeric($pad_up)) {
  1105. $pad_up--;
  1106. if ($pad_up > 0) $out -= pow($base, $pad_up);
  1107. }
  1108. $out = sprintf('%F', $out);
  1109. $out = substr($out, 0, strpos($out, '.'));
  1110. } else {
  1111. // Digital number -->> alphabet letter code
  1112. if (is_numeric($pad_up)) {
  1113. $pad_up--;
  1114. if ($pad_up > 0) $in += pow($base, $pad_up);
  1115. }
  1116. $out = "";
  1117. for ($t = floor(log($in, $base)); $t >= 0; $t--) {
  1118. $bcp = pow($base, $t);
  1119. $a = floor($in / $bcp) % $base;
  1120. $out = $out . substr($index, $a, 1);
  1121. $in = $in - ($a * $bcp);
  1122. }
  1123. $out = strrev($out); // reverse
  1124. }
  1125. return $out;
  1126. }
  1127. /**
  1128. * 验证码检查,验证完后销毁验证码
  1129. * @param string $value 要验证的字符串
  1130. * @param string $id 验证码的ID
  1131. * @param bool $reset 验证成功后是否重置
  1132. * @return bool
  1133. */
  1134. function cmf_captcha_check($value, $id = "", $reset = true)
  1135. {
  1136. $captcha = new \think\captcha\Captcha();
  1137. $captcha->reset = $reset;
  1138. return $captcha->check($value, $id);
  1139. }
  1140. /**
  1141. * 切分SQL文件成多个可以单独执行的sql语句
  1142. * @param $file string sql文件路径
  1143. * @param $tablePre string 表前缀
  1144. * @param string $charset 字符集
  1145. * @param string $defaultTablePre 默认表前缀
  1146. * @param string $defaultCharset 默认字符集
  1147. * @return array
  1148. */
  1149. function cmf_split_sql($file, $tablePre, $charset = 'utf8mb4', $defaultTablePre = 'cmf_', $defaultCharset = 'utf8mb4')
  1150. {
  1151. if (file_exists($file)) {
  1152. //读取SQL文件
  1153. $sql = file_get_contents($file);
  1154. $sql = str_replace("\r", "\n", $sql);
  1155. $sql = str_replace("BEGIN;\n", '', $sql);//兼容 navicat 导出的 insert 语句
  1156. $sql = str_replace("COMMIT;\n", '', $sql);//兼容 navicat 导出的 insert 语句
  1157. $sql = str_replace($defaultCharset, $charset, $sql);
  1158. $sql = trim($sql);
  1159. //替换表前缀
  1160. $sql = str_replace(" `{$defaultTablePre}", " `{$tablePre}", $sql);
  1161. $sqls = explode(";\n", $sql);
  1162. return $sqls;
  1163. }
  1164. return [];
  1165. }
  1166. /**
  1167. * 判断当前的语言包,并返回语言包名
  1168. * @return string 语言包名
  1169. */
  1170. function cmf_current_lang()
  1171. {
  1172. return request()->langset();
  1173. }
  1174. /**
  1175. * 获取惟一订单号
  1176. * @return string
  1177. */
  1178. function cmf_get_order_sn()
  1179. {
  1180. return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
  1181. }
  1182. /**
  1183. * 获取文件扩展名
  1184. * @param string $filename 文件名
  1185. * @return string 文件扩展名
  1186. */
  1187. function cmf_get_file_extension($filename)
  1188. {
  1189. $pathinfo = pathinfo($filename);
  1190. return strtolower($pathinfo['extension']);
  1191. }
  1192. /**
  1193. * 检查手机或邮箱是否还可以发送验证码,并返回生成的验证码
  1194. * @param string $account 手机或邮箱
  1195. * @param integer $length 验证码位数,支持4,6,8
  1196. * @return string 数字验证码
  1197. * @throws \think\db\exception\DataNotFoundException
  1198. * @throws \think\db\exception\ModelNotFoundException
  1199. * @throws \think\exception\DbException
  1200. */
  1201. function cmf_get_verification_code($account, $length = 6)
  1202. {
  1203. if (empty($account)) return false;
  1204. $verificationCodeQuery = Db::name('verification_code');
  1205. $currentTime = time();
  1206. $maxCount = 5;
  1207. $findVerificationCode = $verificationCodeQuery->where('account', $account)->find();
  1208. $result = false;
  1209. if (empty($findVerificationCode)) {
  1210. $result = true;
  1211. } else {
  1212. $sendTime = $findVerificationCode['send_time'];
  1213. $todayStartTime = strtotime(date('Y-m-d', $currentTime));
  1214. if ($sendTime < $todayStartTime) {
  1215. $result = true;
  1216. } else if ($findVerificationCode['count'] < $maxCount) {
  1217. $result = true;
  1218. }
  1219. }
  1220. if ($result) {
  1221. switch ($length) {
  1222. case 4:
  1223. $result = rand(1000, 9999);
  1224. break;
  1225. case 6:
  1226. $result = rand(100000, 999999);
  1227. break;
  1228. case 8:
  1229. $result = rand(10000000, 99999999);
  1230. break;
  1231. default:
  1232. $result = rand(100000, 999999);
  1233. }
  1234. }
  1235. return $result;
  1236. }
  1237. /**
  1238. * 更新手机或邮箱验证码发送日志
  1239. * @param string $account 手机或邮箱
  1240. * @param string $code 验证码
  1241. * @param int $expireTime 过期时间
  1242. * @return int|string
  1243. * @throws \think\Exception
  1244. * @throws \think\db\exception\DataNotFoundException
  1245. * @throws \think\db\exception\ModelNotFoundException
  1246. * @throws \think\exception\DbException
  1247. * @throws \think\exception\PDOException
  1248. */
  1249. function cmf_verification_code_log($account, $code, $expireTime = 0)
  1250. {
  1251. $currentTime = time();
  1252. $expireTime = $expireTime > $currentTime ? $expireTime : $currentTime + 30 * 60;
  1253. $findVerificationCode = Db::name('verification_code')->where('account', $account)->find();
  1254. if ($findVerificationCode) {
  1255. $todayStartTime = strtotime(date("Y-m-d"));//当天0点
  1256. if ($findVerificationCode['send_time'] <= $todayStartTime) {
  1257. $count = 1;
  1258. } else {
  1259. $count = Db::raw('count+1');
  1260. }
  1261. $result = Db::name('verification_code')
  1262. ->where('account', $account)
  1263. ->update([
  1264. 'send_time' => $currentTime,
  1265. 'expire_time' => $expireTime,
  1266. 'code' => $code,
  1267. 'count' => $count
  1268. ]);
  1269. } else {
  1270. $result = Db::name('verification_code')
  1271. ->insert([
  1272. 'account' => $account,
  1273. 'send_time' => $currentTime,
  1274. 'code' => $code,
  1275. 'count' => 1,
  1276. 'expire_time' => $expireTime
  1277. ]);
  1278. }
  1279. return $result;
  1280. }
  1281. /**
  1282. * 手机或邮箱验证码检查,验证完后销毁验证码增加安全性,返回true验证码正确,false验证码错误
  1283. * @param string $account 手机或邮箱
  1284. * @param string $code 验证码
  1285. * @param boolean $clear 是否验证后销毁验证码
  1286. * @return string 错误消息,空字符串代码验证码正确
  1287. * @return string
  1288. * @throws \think\Exception
  1289. * @throws \think\db\exception\DataNotFoundException
  1290. * @throws \think\db\exception\ModelNotFoundException
  1291. * @throws \think\exception\DbException
  1292. * @throws \think\exception\PDOException
  1293. */
  1294. function cmf_check_verification_code($account, $code, $clear = false)
  1295. {
  1296. $findVerificationCode = Db::name('verification_code')->where('account', $account)->find();
  1297. if ($findVerificationCode) {
  1298. if ($findVerificationCode['expire_time'] > time()) {
  1299. if ($code == $findVerificationCode['code']) {
  1300. if ($clear) {
  1301. Db::name('verification_code')->where('account', $account)->update(['code' => '']);
  1302. }
  1303. } else {
  1304. return "验证码不正确!";
  1305. }
  1306. } else {
  1307. return "验证码已经过期,请先获取验证码!";
  1308. }
  1309. } else {
  1310. return "请先获取验证码!";
  1311. }
  1312. return "";
  1313. }
  1314. /**
  1315. * 清除某个手机或邮箱的数字验证码,一般在验证码验证正确完成后
  1316. * @param string $account 手机或邮箱
  1317. * @return boolean true:手机验证码正确,false:手机验证码错误
  1318. * @throws \think\Exception
  1319. * @throws \think\exception\PDOException
  1320. */
  1321. function cmf_clear_verification_code($account)
  1322. {
  1323. $verificationCodeQuery = Db::name('verification_code');
  1324. $result = $verificationCodeQuery->where('account', $account)->update(['code' => '']);
  1325. return $result;
  1326. }
  1327. /**
  1328. * 区分大小写的文件存在判断
  1329. * @param string $filename 文件地址
  1330. * @return boolean
  1331. */
  1332. function file_exists_case($filename)
  1333. {
  1334. if (is_file($filename)) {
  1335. if (APP_DEBUG) {
  1336. if (basename(realpath($filename)) != basename($filename))
  1337. return false;
  1338. }
  1339. return true;
  1340. }
  1341. return false;
  1342. }
  1343. /**
  1344. * 生成用户 token
  1345. * @param $userId
  1346. * @param $deviceType
  1347. * @return string 用户 token
  1348. * @throws \think\Exception
  1349. * @throws \think\db\exception\DataNotFoundException
  1350. * @throws \think\db\exception\ModelNotFoundException
  1351. * @throws \think\exception\DbException
  1352. * @throws \think\exception\PDOException
  1353. */
  1354. function cmf_generate_user_token($userId, $deviceType)
  1355. {
  1356. $userTokenQuery = Db::name("user_token")
  1357. ->where('user_id', $userId)
  1358. ->where('device_type', $deviceType);
  1359. $findUserToken = $userTokenQuery->find();
  1360. $currentTime = time();
  1361. $expireTime = $currentTime + 24 * 3600 * 180;
  1362. $token = md5(uniqid()) . md5(uniqid());
  1363. if (empty($findUserToken)) {
  1364. Db::name("user_token")->insert([
  1365. 'token' => $token,
  1366. 'user_id' => $userId,
  1367. 'expire_time' => $expireTime,
  1368. 'create_time' => $currentTime,
  1369. 'device_type' => $deviceType
  1370. ]);
  1371. } else {
  1372. if ($findUserToken['expire_time'] > time() && !empty($findUserToken['token'])) {
  1373. $token = $findUserToken['token'];
  1374. } else {
  1375. Db::name("user_token")
  1376. ->where('user_id', $userId)
  1377. ->where('device_type', $deviceType)
  1378. ->update([
  1379. 'token' => $token,
  1380. 'expire_time' => $expireTime,
  1381. 'create_time' => $currentTime
  1382. ]);
  1383. }
  1384. }
  1385. return $token;
  1386. }
  1387. /**
  1388. * 字符串命名风格转换
  1389. * type 0 将Java风格转换为C的风格 1 将C风格转换为Java的风格
  1390. * @param string $name 字符串
  1391. * @param integer $type 转换类型
  1392. * @param bool $ucfirst 首字母是否大写(驼峰规则)
  1393. * @return string
  1394. */
  1395. function cmf_parse_name($name, $type = 0, $ucfirst = true)
  1396. {
  1397. return Loader::parseName($name, $type, $ucfirst);
  1398. }
  1399. /**
  1400. * 判断字符串是否为已经序列化过
  1401. * @param $str
  1402. * @return bool
  1403. */
  1404. function cmf_is_serialized($str)
  1405. {
  1406. return ($str == serialize(false) || @unserialize($str) !== false);
  1407. }
  1408. /**
  1409. * 判断是否SSL协议
  1410. * @return boolean
  1411. */
  1412. function cmf_is_ssl()
  1413. {
  1414. if (isset($_SERVER['HTTPS']) && ('1' == $_SERVER['HTTPS'] || 'on' == strtolower($_SERVER['HTTPS']))) {
  1415. return true;
  1416. } elseif (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'])) {
  1417. return true;
  1418. }
  1419. return false;
  1420. }
  1421. /**
  1422. * 获取CMF系统的设置,此类设置用于全局
  1423. * @param string $key 设置key,为空时返回所有配置信息
  1424. * @return array|bool|mixed
  1425. * @throws \think\db\exception\DataNotFoundException
  1426. * @throws \think\db\exception\ModelNotFoundException
  1427. * @throws \think\exception\DbException
  1428. */
  1429. function cmf_get_cmf_settings($key = "")
  1430. {
  1431. $cmfSettings = cache("cmf_settings");
  1432. if (empty($cmfSettings)) {
  1433. $objOptions = new \app\admin\model\OptionModel();
  1434. $objResult = $objOptions->where("option_name", 'cmf_settings')->find();
  1435. $arrOption = $objResult ? $objResult->toArray() : [];
  1436. if ($arrOption) {
  1437. $cmfSettings = json_decode($arrOption['option_value'], true);
  1438. } else {
  1439. $cmfSettings = [];
  1440. }
  1441. cache("cmf_settings", $cmfSettings);
  1442. }
  1443. if (!empty($key)) {
  1444. if (isset($cmfSettings[$key])) {
  1445. return $cmfSettings[$key];
  1446. } else {
  1447. return false;
  1448. }
  1449. }
  1450. return $cmfSettings;
  1451. }
  1452. /**
  1453. * @deprecated
  1454. * 判读是否sae环境
  1455. * @return bool
  1456. */
  1457. function cmf_is_sae()
  1458. {
  1459. if (function_exists('saeAutoLoader')) {
  1460. return true;
  1461. } else {
  1462. return false;
  1463. }
  1464. }
  1465. /**
  1466. * 获取客户端IP地址
  1467. * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
  1468. * @param boolean $adv 是否进行高级模式获取(有可能被伪装)
  1469. * @return string
  1470. */
  1471. function get_client_ip($type = 0, $adv = true)
  1472. {
  1473. return request()->ip($type, $adv);
  1474. }
  1475. /**
  1476. * 生成base64的url,用于数据库存放 url
  1477. * @param $url 路由地址,如 控制器/方法名,应用/控制器/方法名
  1478. * @param $params url参数
  1479. * @return string
  1480. */
  1481. function cmf_url_encode($url, $params)
  1482. {
  1483. // 解析参数
  1484. if (is_string($params)) {
  1485. // aaa=1&bbb=2 转换成数组
  1486. parse_str($params, $params);
  1487. }
  1488. return base64_encode(json_encode(['action' => $url, 'param' => $params]));
  1489. }
  1490. /**
  1491. * CMF Url生成
  1492. * @param string $url 路由地址
  1493. * @param string|array $vars 变量
  1494. * @param bool|string $suffix 生成的URL后缀
  1495. * @param bool|string $domain 域名
  1496. * @return string
  1497. * @throws \think\db\exception\DataNotFoundException
  1498. * @throws \think\db\exception\ModelNotFoundException
  1499. * @throws \think\exception\DbException
  1500. */
  1501. function cmf_url($url = '', $vars = '', $suffix = true, $domain = false)
  1502. {
  1503. global $CMF_GV_routes;
  1504. if (empty($CMF_GV_routes)) {
  1505. $routeModel = new \app\admin\model\RouteModel();
  1506. $CMF_GV_routes = $routeModel->getRoutes();
  1507. }
  1508. if (false === strpos($url, '://') && 0 !== strpos($url, '/')) {
  1509. $info = parse_url($url);
  1510. $url = !empty($info['path']) ? $info['path'] : '';
  1511. if (isset($info['fragment'])) {
  1512. // 解析锚点
  1513. $anchor = $info['fragment'];
  1514. if (false !== strpos($anchor, '?')) {
  1515. // 解析参数
  1516. list($anchor, $info['query']) = explode('?', $anchor, 2);
  1517. }
  1518. if (false !== strpos($anchor, '@')) {
  1519. // 解析域名
  1520. list($anchor, $domain) = explode('@', $anchor, 2);
  1521. }
  1522. } elseif (strpos($url, '@') && false === strpos($url, '\\')) {
  1523. // 解析域名
  1524. list($url, $domain) = explode('@', $url, 2);
  1525. }
  1526. }
  1527. // 解析参数
  1528. if (is_string($vars)) {
  1529. // aaa=1&bbb=2 转换成数组
  1530. parse_str($vars, $vars);
  1531. }
  1532. if (isset($info['query'])) {
  1533. // 解析地址里面参数 合并到vars
  1534. parse_str($info['query'], $params);
  1535. $vars = array_merge($params, $vars);
  1536. }
  1537. if (!empty($vars) && !empty($CMF_GV_routes[$url])) {
  1538. foreach ($CMF_GV_routes[$url] as $actionRoute) {
  1539. $sameVars = array_intersect_assoc($vars, $actionRoute['vars']);
  1540. if (count($sameVars) == count($actionRoute['vars'])) {
  1541. ksort($sameVars);
  1542. $url = $url . '?' . http_build_query($sameVars);
  1543. $vars = array_diff_assoc($vars, $sameVars);
  1544. break;
  1545. }
  1546. }
  1547. }
  1548. if (!empty($anchor)) {
  1549. $url = $url . '#' . $anchor;
  1550. }
  1551. // if (!empty($domain)) {
  1552. // $url = $url . '@' . $domain;
  1553. // }
  1554. return Url::build($url, $vars, $suffix, $domain);
  1555. }
  1556. /**
  1557. * 判断 cmf 核心是否安装
  1558. * @return bool
  1559. */
  1560. function cmf_is_installed()
  1561. {
  1562. static $cmfIsInstalled;
  1563. if (empty($cmfIsInstalled)) {
  1564. $cmfIsInstalled = file_exists(CMF_ROOT . 'data/install.lock');
  1565. }
  1566. return $cmfIsInstalled;
  1567. }
  1568. /**
  1569. * 替换编辑器内容中的文件地址
  1570. * @param string $content 编辑器内容
  1571. * @param boolean $isForDbSave true:表示把绝对地址换成相对地址,用于数据库保存,false:表示把相对地址换成绝对地址用于界面显示
  1572. * @return string
  1573. */
  1574. function cmf_replace_content_file_url($content, $isForDbSave = false)
  1575. {
  1576. //import('phpQuery.phpQuery', EXTEND_PATH);
  1577. \phpQuery::newDocumentHTML($content);
  1578. $pq = pq(null);
  1579. $storage = Storage::instance();
  1580. $localStorage = new cmf\lib\storage\Local([]);
  1581. $storageDomain = $storage->getDomain();
  1582. $domain = request()->host();
  1583. $images = $pq->find("img");
  1584. if ($images->length) {
  1585. foreach ($images as $img) {
  1586. $img = pq($img);
  1587. $imgSrc = $img->attr("src");
  1588. if ($isForDbSave) {
  1589. if (preg_match("/^\/upload\//", $imgSrc)) {
  1590. $img->attr("src", preg_replace("/^\/upload\//", '', $imgSrc));
  1591. } elseif (preg_match("/^http(s)?:\/\/$domain\/upload\//", $imgSrc)) {
  1592. $img->attr("src", $localStorage->getFilePath($imgSrc));
  1593. } elseif (preg_match("/^http(s)?:\/\/$storageDomain\//", $imgSrc)) {
  1594. $img->attr("src", $storage->getFilePath($imgSrc));
  1595. }
  1596. } else {
  1597. $img->attr("src", cmf_get_image_url($imgSrc));
  1598. }
  1599. }
  1600. }
  1601. $links = $pq->find("a");
  1602. if ($links->length) {
  1603. foreach ($links as $link) {
  1604. $link = pq($link);
  1605. $href = $link->attr("href");
  1606. if ($isForDbSave) {
  1607. if (preg_match("/^\/upload\//", $href)) {
  1608. $link->attr("href", preg_replace("/^\/upload\//", '', $href));
  1609. } elseif (preg_match("/^http(s)?:\/\/$domain\/upload\//", $href)) {
  1610. $link->attr("href", $localStorage->getFilePath($href));
  1611. } elseif (preg_match("/^http(s)?:\/\/$storageDomain\//", $href)) {
  1612. $link->attr("href", $storage->getFilePath($href));
  1613. }
  1614. } else {
  1615. if (!(preg_match("/^\//", $href) || preg_match("/^http/", $href))) {
  1616. $link->attr("href", cmf_get_file_download_url($href));
  1617. }
  1618. }
  1619. }
  1620. }
  1621. $content = $pq->html();
  1622. \phpQuery::$documents = null;
  1623. return $content;
  1624. }
  1625. /**
  1626. * 获取后台风格名称
  1627. * @return string
  1628. */
  1629. function cmf_get_admin_style()
  1630. {
  1631. $adminSettings = cmf_get_option('admin_settings');
  1632. return empty($adminSettings['admin_style']) ? 'simpleadmin' : $adminSettings['admin_style'];
  1633. }
  1634. /**
  1635. * curl get 请求
  1636. * @param $url
  1637. * @return mixed
  1638. */
  1639. function cmf_curl_get($url)
  1640. {
  1641. $ch = curl_init();
  1642. curl_setopt($ch, CURLOPT_URL, $url);
  1643. curl_setopt($ch, CURLOPT_FAILONERROR, true);
  1644. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  1645. curl_setopt($ch, CURLOPT_AUTOREFERER, true);
  1646. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  1647. curl_setopt($ch, CURLOPT_TIMEOUT, 5);
  1648. $SSL = substr($url, 0, 8) == "https://" ? true : false;
  1649. if ($SSL) {
  1650. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
  1651. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 检查证书中是否设置域名
  1652. }
  1653. $content = curl_exec($ch);
  1654. curl_close($ch);
  1655. return $content;
  1656. }
  1657. /**
  1658. * 用户操作记录
  1659. * @param string $action 用户操作
  1660. * @throws \think\Exception
  1661. * @throws \think\db\exception\DataNotFoundException
  1662. * @throws \think\db\exception\ModelNotFoundException
  1663. * @throws \think\exception\DbException
  1664. * @throws \think\exception\PDOException
  1665. */
  1666. function cmf_user_action($action)
  1667. {
  1668. $userId = cmf_get_current_user_id();
  1669. if (empty($userId)) {
  1670. return;
  1671. }
  1672. $findUserAction = Db::name('user_action')->where('action', $action)->find();
  1673. if (empty($findUserAction)) {
  1674. return;
  1675. }
  1676. $changeScore = false;
  1677. if ($findUserAction['cycle_type'] == 0) {
  1678. $changeScore = true;
  1679. } elseif ($findUserAction['reward_number'] > 0) {
  1680. $findUserScoreLog = Db::name('user_score_log')->order('create_time DESC')->find();
  1681. if (!empty($findUserScoreLog)) {
  1682. $cycleType = intval($findUserAction['cycle_type']);
  1683. $cycleTime = intval($findUserAction['cycle_time']);
  1684. switch ($cycleType) {//1:按天;2:按小时;3:永久
  1685. case 1:
  1686. $firstDayStartTime = strtotime(date('Y-m-d', $findUserScoreLog['create_time']));
  1687. $endDayEndTime = strtotime(date('Y-m-d', strtotime("+{$cycleTime} day", $firstDayStartTime)));
  1688. // $todayStartTime = strtotime(date('Y-m-d'));
  1689. // $todayEndTime = strtotime(date('Y-m-d', strtotime('+1 day')));
  1690. $findUserScoreLogCount = Db::name('user_score_log')->where([
  1691. 'user_id' => $userId,
  1692. 'create_time' => [['gt', $firstDayStartTime], ['lt', $endDayEndTime]]
  1693. ])->count();
  1694. if ($findUserScoreLogCount < $findUserAction['reward_number']) {
  1695. $changeScore = true;
  1696. }
  1697. break;
  1698. case 2:
  1699. if (($findUserScoreLog['create_time'] + $cycleTime * 3600) < time()) {
  1700. $changeScore = true;
  1701. }
  1702. break;
  1703. case 3:
  1704. break;
  1705. }
  1706. } else {
  1707. $changeScore = true;
  1708. }
  1709. }
  1710. if ($changeScore) {
  1711. Db::name('user_score_log')->insert([
  1712. 'user_id' => $userId,
  1713. 'create_time' => time(),
  1714. 'action' => $action,
  1715. 'score' => $findUserAction['score'],
  1716. 'coin' => $findUserAction['coin'],
  1717. ]);
  1718. $data = [];
  1719. if ($findUserAction['score'] > 0) {
  1720. $data['score'] = Db::raw('score+' . $findUserAction['score']);
  1721. }
  1722. if ($findUserAction['score'] < 0) {
  1723. $data['score'] = Db::raw('score-' . abs($findUserAction['score']));
  1724. }
  1725. if ($findUserAction['coin'] > 0) {
  1726. $data['coin'] = Db::raw('coin+' . $findUserAction['coin']);
  1727. }
  1728. if ($findUserAction['coin'] < 0) {
  1729. $data['coin'] = Db::raw('coin-' . abs($findUserAction['coin']));
  1730. }
  1731. Db::name('user')->where('id', $userId)->update($data);
  1732. }
  1733. }
  1734. function cmf_api_request($url, $params = [])
  1735. {
  1736. //初始化
  1737. $curl = curl_init();
  1738. //设置抓取的url
  1739. curl_setopt($curl, CURLOPT_URL, 'http://127.0.0.1:1314/api/' . $url);
  1740. //设置头文件的信息作为数据流输出
  1741. curl_setopt($curl, CURLOPT_HEADER, 0);
  1742. //设置获取的信息以文件流的形式返回,而不是直接输出。
  1743. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  1744. //设置post方式提交
  1745. curl_setopt($curl, CURLOPT_POST, 1);
  1746. $token = session('token');
  1747. curl_setopt($curl, CURLOPT_HTTPHEADER, ["XX-Token: $token"]);
  1748. //设置post数据
  1749. curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
  1750. //执行命令
  1751. $data = curl_exec($curl);
  1752. //关闭URL请求
  1753. curl_close($curl);
  1754. //显示获得的数据
  1755. return json_decode($data, true);
  1756. }
  1757. /**
  1758. * 判断是否允许开放注册
  1759. */
  1760. function cmf_is_open_registration()
  1761. {
  1762. $cmfSettings = cmf_get_option('cmf_settings');
  1763. return empty($cmfSettings['open_registration']) ? false : true;
  1764. }
  1765. /**
  1766. * XML编码
  1767. * @param mixed $data 数据
  1768. * @param string $root 根节点名
  1769. * @param string $item 数字索引的子节点名
  1770. * @param string $attr 根节点属性
  1771. * @param string $id 数字索引子节点key转换的属性名
  1772. * @param string $encoding 数据编码
  1773. * @return string
  1774. */
  1775. function cmf_xml_encode($data, $root = 'think', $item = 'item', $attr = '', $id = 'id', $encoding = 'utf-8')
  1776. {
  1777. if (is_array($attr)) {
  1778. $_attr = [];
  1779. foreach ($attr as $key => $value) {
  1780. $_attr[] = "{$key}=\"{$value}\"";
  1781. }
  1782. $attr = implode(' ', $_attr);
  1783. }
  1784. $attr = trim($attr);
  1785. $attr = empty($attr) ? '' : " {$attr}";
  1786. $xml = "<?xml version=\"1.0\" encoding=\"{$encoding}\"?>";
  1787. $xml .= "<{$root}{$attr}>";
  1788. $xml .= cmf_data_to_xml($data, $item, $id);
  1789. $xml .= "</{$root}>";
  1790. return $xml;
  1791. }
  1792. /**
  1793. * 数据XML编码
  1794. * @param mixed $data 数据
  1795. * @param string $item 数字索引时的节点名称
  1796. * @param string $id 数字索引key转换为的属性名
  1797. * @return string
  1798. */
  1799. function cmf_data_to_xml($data, $item = 'item', $id = 'id')
  1800. {
  1801. $xml = $attr = '';
  1802. foreach ($data as $key => $val) {
  1803. if (is_numeric($key)) {
  1804. $id && $attr = " {$id}=\"{$key}\"";
  1805. $key = $item;
  1806. }
  1807. $xml .= "<{$key}{$attr}>";
  1808. $xml .= (is_array($val) || is_object($val)) ? cmf_data_to_xml($val, $item, $id) : $val;
  1809. $xml .= "</{$key}>";
  1810. }
  1811. return $xml;
  1812. }
  1813. /**
  1814. * 检查手机格式,中国手机不带国家代码,国际手机号格式为:国家代码-手机号
  1815. * @param $mobile
  1816. * @return bool
  1817. */
  1818. function cmf_check_mobile($mobile)
  1819. {
  1820. if (preg_match('/(^(13\d|14\d|15\d|16\d|17\d|18\d|19\d)\d{8})$/', $mobile)) {
  1821. return true;
  1822. } else {
  1823. if (preg_match('/^\d{1,4}-\d{5,11}$/', $mobile)) {
  1824. if (preg_match('/^\d{1,4}-0+/', $mobile)) {
  1825. //不能以0开头
  1826. return false;
  1827. }
  1828. return true;
  1829. }
  1830. return false;
  1831. }
  1832. }
  1833. /**
  1834. * 文件大小格式化
  1835. * @param $bytes 文件大小(字节 Byte)
  1836. * @return string
  1837. */
  1838. function cmf_file_size_format($bytes)
  1839. {
  1840. $type = ['B', 'KB', 'MB', 'GB', 'TB'];
  1841. for ($i = 0; $bytes >= 1024; $i++)//单位每增大1024,则单位数组向后移动一位表示相应的单位
  1842. {
  1843. $bytes /= 1024;
  1844. }
  1845. return (floor($bytes * 100) / 100) . $type[$i];//floor是取整函数,为了防止出现一串的小数,这里取了两位小数
  1846. }
  1847. /**
  1848. * 计数器增加
  1849. * @param $name 计数器英文标识
  1850. * @param int $min 计数器最小值
  1851. * @param int $step 增加步长
  1852. * @return mixed
  1853. */
  1854. function cmf_counter_inc($name, $min = 1, $step = 1)
  1855. {
  1856. $id = cache('core_counter_' . $name);
  1857. if (empty($id)) {
  1858. $id = Db::name('core_counter')->where('name', $name)->value('id');
  1859. if (empty($id)) {
  1860. $id = Db::name('core_counter')->insertGetId([
  1861. 'name' => $name,
  1862. 'value' => 0
  1863. ]);
  1864. }
  1865. cache('core_counter_' . $name, $id);
  1866. }
  1867. Db::startTrans();
  1868. try {
  1869. $value = Db::name('core_counter')->where('id', $id)->lock(true)->value('value');
  1870. if ($min > $value) {
  1871. $value = $min;
  1872. } else {
  1873. $value += $step;
  1874. }
  1875. Db::name('core_counter')->where('id', $id)->update(['value' => $value]);
  1876. Db::commit();
  1877. } catch (\Exception $e) {
  1878. Db::rollback();
  1879. $value = false;
  1880. }
  1881. return $value;
  1882. }
  1883. /**
  1884. * 获取ThinkPHP版本
  1885. * @return string
  1886. */
  1887. function cmf_thinkphp_version()
  1888. {
  1889. return \think\facade\App::version();
  1890. }
  1891. /**
  1892. * 获取ThinkCMF版本
  1893. * @return string
  1894. */
  1895. function cmf_version()
  1896. {
  1897. try {
  1898. $version = trim(file_get_contents(CMF_ROOT . 'version'));
  1899. } catch (\Exception $e) {
  1900. $version = '0.0.0';
  1901. }
  1902. return $version;
  1903. }
  1904. /**
  1905. * 获取ThinkCMF核心包目录
  1906. */
  1907. function cmf_core_path()
  1908. {
  1909. return __DIR__ . DIRECTORY_SEPARATOR;
  1910. }
  1911. /**
  1912. * 获取模块配置文件路径
  1913. * @param $app 应用
  1914. * @param $file 文件名不带后缀
  1915. */
  1916. function cmf_get_app_config_file($app, $file)
  1917. {
  1918. switch ($app) {
  1919. case 'cmf':
  1920. $configFile = cmf_core_path() . "{$file}.php";
  1921. break;
  1922. case 'swoole':
  1923. $configFile = Env::get('root_path') . "vendor/thinkcmf/cmf-swoole/src/{$file}.php";
  1924. break;
  1925. default:
  1926. $configFile = APP_PATH . $app . "/{$file}.php";
  1927. if (!file_exists($configFile)) {
  1928. $configFile = Env::get('root_path') . "vendor/thinkcmf/cmf-app/src/{$app}/{$file}.php";
  1929. }
  1930. }
  1931. return $configFile;
  1932. }
  1933. /**
  1934. * 转换+-为desc和asc
  1935. * @deprecated
  1936. * @param $order array 转换对象
  1937. * @return array
  1938. */
  1939. function order_shift($order)
  1940. {
  1941. $orderArr = [];
  1942. foreach ($order as $key => $value) {
  1943. $upDwn = substr($value, 0, 1);
  1944. $orderType = $upDwn == '-' ? 'desc' : 'asc';
  1945. $orderField = substr($value, 1);
  1946. if (!empty($whiteParams)) {
  1947. if (in_array($orderField, $whiteParams)) {
  1948. $orderArr[$orderField] = $orderType;
  1949. }
  1950. } else {
  1951. $orderArr[$orderField] = $orderType;
  1952. }
  1953. }
  1954. return $orderArr;
  1955. }
  1956. /**
  1957. * 模型检查
  1958. * @deprecated
  1959. * @param $relationFilter array 检查的字段
  1960. * @param $relations string 被检查的字段
  1961. * @return array|bool
  1962. */
  1963. function allowed_relations($relationFilter, $relations)
  1964. {
  1965. if (is_string($relations)) {
  1966. $relations = explode(',', $relations);
  1967. }
  1968. if (!is_array($relations)) {
  1969. return false;
  1970. }
  1971. return array_intersect($relationFilter, $relations);
  1972. }
  1973. /**
  1974. * 字符串转数组
  1975. * @deprecated
  1976. * @param string $string 字符串
  1977. * @return array
  1978. */
  1979. function str_to_arr($string)
  1980. {
  1981. $result = is_string($string) ? explode(',', $string) : $string;
  1982. return $result;
  1983. }
  1984. /**
  1985. * @param $str
  1986. * @return string
  1987. */
  1988. function formatName($str){
  1989. return mb_substr($str, 0, 1, 'utf-8').'**';
  1990. }
  1991. /**
  1992. * HTTP请求
  1993. * @param $url 链接
  1994. * @param $data 提交数据
  1995. * @param string $type 请求类型:get post
  1996. * @param string $dataType 返回数据类型 array json
  1997. * @param int $timeout
  1998. * @return mixed
  1999. */
  2000. function httpRequest($url, $data=[], $type='post', $dataType='array', $timeout=60){
  2001. $data = $data && is_array($data)? http_build_query($data) : $data;
  2002. $url = strtolower($type) == 'get'? $url.(strpos($url, '?') === false ? '?' : ''). $data : $url;
  2003. $ch = curl_init($url);
  2004. curl_setopt($ch, CURLOPT_HTTPHEADER, ["User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36"]);
  2005. curl_setopt($ch, CURLOPT_HEADER,0 );
  2006. curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
  2007. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  2008. curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
  2009. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查,0-规避ssl的证书检查
  2010. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  2011. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  2012. if($type == 'post'){
  2013. curl_setopt($ch, CURLOPT_POST, 1);
  2014. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  2015. }
  2016. $ret = curl_exec($ch);
  2017. curl_close($ch);
  2018. if(strtolower($dataType) == 'array' && !is_array($ret)){
  2019. $ret = json_decode(trim($ret), true);
  2020. }
  2021. return $ret;
  2022. }
  2023. /**
  2024. * HTTP请求
  2025. * @param $url 链接
  2026. * @param $data 提交数据
  2027. * @param string $type 请求类型:get post
  2028. * @param string $dataType 返回数据类型 array json
  2029. * @param int $timeout
  2030. * @return mixed
  2031. */
  2032. function httpGet($url, $dataType='array', $timeout=60){
  2033. $ch = curl_init($url);
  2034. curl_setopt($ch, CURLOPT_HTTPHEADER, ["User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36"]);
  2035. curl_setopt($ch, CURLOPT_HEADER,0);
  2036. curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
  2037. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  2038. curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
  2039. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查,0-规避ssl的证书检查
  2040. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  2041. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  2042. $ret = curl_exec($ch);
  2043. $ret = trim($ret);
  2044. curl_close($ch);
  2045. if(strtolower($dataType) == 'array' && !is_array($ret)){
  2046. $retArr = json_decode($ret, true);
  2047. if(empty($retArr)){
  2048. $ret = iconv('gb2312','utf-8', $ret);
  2049. $retArr = json_decode($ret, true);
  2050. }
  2051. $ret = $retArr;
  2052. }
  2053. return $ret;
  2054. }
  2055. /**
  2056. * 过滤字符串
  2057. * @param $str
  2058. * @return string
  2059. */
  2060. function strFilter($str){
  2061. $str = str_replace('`', '', $str);
  2062. $str = str_replace('·', '', $str);
  2063. $str = str_replace('~', '', $str);
  2064. $str = str_replace('!', '', $str);
  2065. $str = str_replace('!', '', $str);
  2066. $str = str_replace('@', '', $str);
  2067. $str = str_replace('#', '', $str);
  2068. $str = str_replace('$', '', $str);
  2069. $str = str_replace('¥', '', $str);
  2070. $str = str_replace('%', '', $str);
  2071. $str = str_replace('^', '', $str);
  2072. $str = str_replace('……', '', $str);
  2073. $str = str_replace('&', '', $str);
  2074. $str = str_replace('*', '', $str);
  2075. $str = str_replace('(', '', $str);
  2076. $str = str_replace(')', '', $str);
  2077. $str = str_replace('(', '', $str);
  2078. $str = str_replace(')', '', $str);
  2079. $str = str_replace('-', '', $str);
  2080. $str = str_replace('_', '', $str);
  2081. $str = str_replace('——', '', $str);
  2082. $str = str_replace('+', '', $str);
  2083. $str = str_replace('=', '', $str);
  2084. $str = str_replace('|', '', $str);
  2085. $str = str_replace('\\', '', $str);
  2086. $str = str_replace('[', '', $str);
  2087. $str = str_replace(']', '', $str);
  2088. $str = str_replace('【', '', $str);
  2089. $str = str_replace('】', '', $str);
  2090. $str = str_replace('{', '', $str);
  2091. $str = str_replace('}', '', $str);
  2092. $str = str_replace(';', '', $str);
  2093. $str = str_replace(';', '', $str);
  2094. $str = str_replace(':', '', $str);
  2095. $str = str_replace(':', '', $str);
  2096. $str = str_replace('\'', '', $str);
  2097. $str = str_replace('"', '', $str);
  2098. $str = str_replace('“', '', $str);
  2099. $str = str_replace('”', '', $str);
  2100. $str = str_replace(',', '', $str);
  2101. $str = str_replace(',', '', $str);
  2102. $str = str_replace('<', '', $str);
  2103. $str = str_replace('>', '', $str);
  2104. $str = str_replace('《', '', $str);
  2105. $str = str_replace('》', '', $str);
  2106. $str = str_replace('.', '', $str);
  2107. $str = str_replace('。', '', $str);
  2108. $str = str_replace('/', '', $str);
  2109. $str = str_replace('、', '', $str);
  2110. $str = str_replace('?', '', $str);
  2111. $str = str_replace('?', '', $str);
  2112. return trim($str);
  2113. }
  2114. /**
  2115. * 格式化页面 内容
  2116. * @param $html
  2117. * @return mixed|null|string|string[]
  2118. */
  2119. function filterHtmlUrl($html){
  2120. $ip = request()->domain();
  2121. $html = str_replace("http://{$ip}:443", '', $html);
  2122. $html = str_replace("http://{$ip}", '', $html);
  2123. $html = str_replace(["http://","https://"],["//","//"], $html);
  2124. return $html;
  2125. }