common.php 66 KB

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