Base.php 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413
  1. <?php
  2. namespace App\Module;
  3. use App\Model\DBCache;
  4. use Cache;
  5. use DB;
  6. use Exception;
  7. use Illuminate\Contracts\Pagination\LengthAwarePaginator;
  8. use Redirect;
  9. use Request;
  10. use Storage;
  11. class Base
  12. {
  13. const version = "1.4.6";
  14. /**
  15. * 获取数组或对象值
  16. * @param $obj
  17. * @param string $key
  18. * @param string $default
  19. * @return string
  20. */
  21. public static function val($obj, $key = '', $default = '')
  22. {
  23. if (is_object($obj)) $obj = Base::object2array($obj);
  24. if (is_int($key)) {
  25. if (isset($obj[$key])){
  26. $obj = $obj[$key];
  27. }else{
  28. $obj = "";
  29. }
  30. }elseif (!empty($key)){
  31. $arr = explode(".", str_replace("|", ".", $key));
  32. foreach ($arr as $val){
  33. if (isset($obj[$val])){
  34. $obj = $obj[$val];
  35. }else{
  36. $obj = ""; break;
  37. }
  38. }
  39. }
  40. if ($default && empty($obj)) $obj = $default;
  41. return $obj;
  42. }
  43. /**
  44. * 获取当前uri
  45. * @return string
  46. */
  47. public static function getUrl()
  48. {
  49. return Request::getRequestUri();
  50. }
  51. /**
  52. * 跳转
  53. * @param null $url
  54. * @return mixed
  55. */
  56. public static function goUrl($url = null)
  57. {
  58. if (empty($url)) {
  59. $url = Base::getUrl();
  60. }
  61. return Redirect::to($url, 301);
  62. }
  63. /**
  64. * 默认显示
  65. * @param $str
  66. * @param $val
  67. * @param $default
  68. * @return mixed
  69. */
  70. public static function nullShow($str, $val, $default = '')
  71. {
  72. return $str ? ($default ? $default : $str) : $val;
  73. }
  74. /**
  75. * 补零
  76. * @param $str
  77. * @param int $length 长度
  78. * @param bool $before 是否补在前面
  79. * @return string
  80. */
  81. public static function zeroFill($str, $length = 0, $before = true)
  82. {
  83. if (strlen($str) >= $length) {
  84. return $str;
  85. }
  86. $_str = '';
  87. for ($i = 0; $i < $length; $i++) {
  88. $_str .= '0';
  89. }
  90. if ($before) {
  91. $_ret = substr($_str . $str, $length * -1);
  92. } else {
  93. $_ret = substr($str . $_str, 0, $length);
  94. }
  95. return $_ret;
  96. }
  97. /**
  98. * 新建目录
  99. * @param $path
  100. * @return mixed
  101. */
  102. public static function makeDir($path)
  103. {
  104. try{
  105. Storage::makeDirectory($path);
  106. } catch (Exception $e) {}
  107. if (!file_exists($path)){
  108. self::makeDir(dirname($path));
  109. @mkdir($path, 0777);
  110. @chmod($path, 0777);
  111. }
  112. return $path;
  113. }
  114. /**
  115. * 删除目录
  116. * @param $path
  117. */
  118. public static function deleteDir($path)
  119. {
  120. Storage::deleteDirectory($path);
  121. }
  122. /**
  123. * 删除目录及目录下所有的文件
  124. * @param $dirName
  125. * @param bool $undeleteDir 不删除目录(只删除文件)
  126. */
  127. public static function deleteDirAndFile($dirName, $undeleteDir = false)
  128. {
  129. if ($handle = opendir($dirName)) {
  130. while (false !== ($item = readdir($handle))) {
  131. if ($item != "." && $item != "..") {
  132. if (is_dir($dirName . "/" . $item)) {
  133. self::deleteDirAndFile($dirName . "/" . $item);
  134. } else {
  135. @unlink($dirName . "/" . $item);
  136. }
  137. }
  138. }
  139. closedir($handle);
  140. if ($undeleteDir === false) {
  141. rmdir($dirName);
  142. }
  143. }
  144. }
  145. /**
  146. * 去除html
  147. * @param $text
  148. * @param int $length
  149. * @return mixed|string
  150. */
  151. public static function getHtml($text, $length = 255)
  152. {
  153. $text = Base::cutStr(strip_tags($text), $length, 0, "...");
  154. return $text;
  155. }
  156. /**
  157. *
  158. * 截取字符串
  159. * @param string $string 字符串
  160. * @param int $length 截取长度
  161. * @param int $start 何处开始
  162. * @param string $dot 超出尾部添加
  163. * @param string $charset 默认编码
  164. * @return mixed|string
  165. */
  166. public static function cutStr($string, $length, $start = 0, $dot = '', $charset = 'utf-8')
  167. {
  168. if (strtolower($charset) == 'utf-8') {
  169. if (Base::getStrlen($string) <= $length) return $string;
  170. $strcut = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $string);
  171. $strcut = Base::utf8Substr($strcut, $length, $start);
  172. $strcut = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);
  173. return $strcut . $dot;
  174. } else {
  175. $length = $length * 2;
  176. if (strlen($string) <= $length) return $string;
  177. $string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $string);
  178. $strcut = '';
  179. for ($i = 0; $i < $length; $i++) {
  180. $strcut .= ord($string[$i]) > 127 ? $string[$i] . $string[++$i] : $string[$i];
  181. }
  182. $strcut = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);
  183. }
  184. return $strcut . $dot;
  185. }
  186. /**
  187. * PHP获取字符串中英文混合长度
  188. * @param string $str 字符串
  189. * @param string $charset 编码
  190. * @return float 返回长度,1中文=1位,2英文=1位
  191. */
  192. public static function getStrlen($str, $charset = 'utf-8')
  193. {
  194. if (strtolower($charset) == 'utf-8') {
  195. $str = iconv('utf-8', 'GBK//IGNORE', $str);
  196. }
  197. $num = strlen($str);
  198. $cnNum = 0;
  199. for ($i = 0; $i < $num; $i++) {
  200. if (ord(substr($str, $i + 1, 1)) > 127) {
  201. $cnNum++;
  202. $i++;
  203. }
  204. }
  205. $enNum = $num - ($cnNum * 2);
  206. $number = ($enNum / 2) + $cnNum;
  207. return ceil($number);
  208. }
  209. /**
  210. * PHP截取UTF-8字符串,解决半字符问题。
  211. * @param string $str 源字符串
  212. * @param int $len 左边的子串的长度
  213. * @param int $start 何处开始
  214. * @return string 取出的字符串, 当$len小于等于0时, 会返回整个字符串
  215. */
  216. public static function utf8Substr($str, $len, $start = 0)
  217. {
  218. $len = $len * 2;
  219. $new_str = [];
  220. for ($i = 0; $i < $len; $i++) {
  221. $temp_str = substr($str, 0, 1);
  222. if (ord($temp_str) > 127) {
  223. $i++;
  224. if ($i < $len) {
  225. $new_str[] = substr($str, 0, 3);
  226. $str = substr($str, 3);
  227. }
  228. } else {
  229. $new_str[] = substr($str, 0, 1);
  230. $str = substr($str, 1);
  231. }
  232. }
  233. return join(array_slice($new_str, $start));
  234. }
  235. /**
  236. * 将字符串转换为数组
  237. * @param string $data 字符串
  238. * @param array $default 为空时返回的默认数组
  239. * @return array 返回数组格式,如果,data为空,则返回$default
  240. */
  241. public static function string2array($data, $default = [])
  242. {
  243. if (is_array($data)) {
  244. return $data ? $data : $default;
  245. }
  246. $data = trim($data);
  247. if ($data == '') return $default;
  248. if (strpos(strtolower($data), 'array') === 0 && strtolower($data) !== 'array') {
  249. @ini_set('display_errors', 'on');
  250. @eval("\$array = $data;");
  251. @ini_set('display_errors', 'off');
  252. } else {
  253. if (strpos($data, '{\\') === 0) {
  254. $data = stripslashes($data);
  255. }
  256. $array = json_decode($data, true);
  257. }
  258. return isset($array) && is_array($array) && $data ? $array : $default;
  259. }
  260. /**
  261. * 将数组转换为字符串
  262. * @param array $data 数组
  263. * @param int $isformdata 如果为0,则不使用new_stripslashes处理,可选参数,默认为1
  264. * @return string 返回字符串,如果,data为空,则返回空
  265. */
  266. public static function array2string($data, $isformdata = 1)
  267. {
  268. if ($data == '' || empty($data)) return '';
  269. if ($isformdata) $data = Base::newStripslashes($data);
  270. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  271. return Base::newAddslashes(json_encode($data));
  272. } else {
  273. return Base::newAddslashes(json_encode($data, JSON_FORCE_OBJECT));
  274. }
  275. }
  276. /**
  277. * 将数组转换为字符串 (格式化)
  278. * @param array $data 数组
  279. * @param int $isformdata 如果为0,则不使用new_stripslashes处理,可选参数,默认为1
  280. * @return string 返回字符串,如果,data为空,则返回空
  281. */
  282. public static function array2string_discard($data, $isformdata = 1)
  283. {
  284. if ($data == '' || empty($data)) return '';
  285. if ($isformdata) $data = Base::newStripslashes($data);
  286. return var_export($data, TRUE);
  287. }
  288. /**
  289. * json字符串转换成array
  290. * @param $string
  291. * @return array|mixed
  292. */
  293. public static function json2array($string)
  294. {
  295. if (is_array($string)) {
  296. return $string;
  297. }
  298. try {
  299. return json_decode($string, true);
  300. } catch (Exception $e) {
  301. return [];
  302. }
  303. }
  304. /**
  305. * array转换成功json字符串
  306. * @param $array
  307. * @return string
  308. */
  309. public static function array2json($array)
  310. {
  311. if (!is_array($array)) {
  312. return $array;
  313. }
  314. try {
  315. return json_encode($array);
  316. } catch (Exception $e) {
  317. return '';
  318. }
  319. }
  320. /**
  321. * 叠加数组或对象
  322. * @param object|array $array
  323. * @param array $over
  324. * @return object|array
  325. */
  326. public static function array_over(&$array, $over = [])
  327. {
  328. if (is_array($over)) {
  329. foreach ($over AS $key=>$val) {
  330. if (is_array($array)) {
  331. $array[$key] = $val;
  332. }
  333. if (is_object($array)) {
  334. $array->$key = $val;
  335. }
  336. }
  337. }
  338. return $array;
  339. }
  340. /**
  341. * 获取数组第一个值
  342. * @param $array
  343. * @return mixed
  344. */
  345. public static function arrayFirst($array)
  346. {
  347. $val = '';
  348. if (is_array($array)) {
  349. foreach ($array AS $item) {
  350. $val = $item;
  351. break;
  352. }
  353. }
  354. return $val;
  355. }
  356. /**
  357. * 获取数组最后一个值
  358. * @param $array
  359. * @return mixed
  360. */
  361. public static function arrayLast($array)
  362. {
  363. $val = '';
  364. if (is_array($array)) {
  365. foreach (array_reverse($array) AS $item) {
  366. $val = $item;
  367. break;
  368. }
  369. }
  370. return $val;
  371. }
  372. /**
  373. * 数组指定值作为数组键
  374. * @param $array
  375. * @param $valkey
  376. * @return array
  377. */
  378. public static function arrayValkey($array, $valkey)
  379. {
  380. self::coll2array($array);
  381. if (is_array($array)) {
  382. $items = [];
  383. foreach ($array AS $item) {
  384. $items[$item[$valkey]] = $item;
  385. }
  386. $array = $items;
  387. }
  388. return $array;
  389. }
  390. /**
  391. * 对象转数组
  392. * @param $array
  393. * @return array
  394. */
  395. public static function object2array(&$array)
  396. {
  397. if (is_object($array)) {
  398. $array = (array)$array;
  399. }
  400. if (is_array($array)) {
  401. foreach ($array as $key => $value) {
  402. $array[$key] = Base::object2array($value);
  403. }
  404. }
  405. return $array;
  406. }
  407. /**
  408. * 数据库返回对象转数组
  409. * @param $array
  410. * @return array
  411. */
  412. public static function coll2array(&$array)
  413. {
  414. if (is_object($array) && $array) {
  415. $obj = $array;
  416. $array = [];
  417. foreach ($obj AS $key=>$item) {
  418. $array[$key] = $item;
  419. }
  420. Base::object2array($array);
  421. }
  422. return $array;
  423. }
  424. /**
  425. * 数据库返回对象转数组
  426. * @param $array
  427. * @return array
  428. */
  429. public static function DBC2A($array)
  430. {
  431. return Base::coll2array($array);
  432. }
  433. /**
  434. * 数据库自更新数组
  435. * @param $array
  436. * @return array|\Illuminate\Database\Query\Expression
  437. */
  438. public static function DBUP($array) {
  439. if (is_array($array)) {
  440. foreach ($array AS $key => $val) {
  441. $array[$key] = DB::raw(Base::DBRAW($key . ($val < 0 ? '-' : '+') . abs($val)));
  442. }
  443. } else {
  444. $array = DB::raw(Base::DBRAW($array));
  445. }
  446. return $array;
  447. }
  448. /**
  449. * 数据库更新或插入
  450. * @param $builder
  451. * @param $where
  452. * @param $update
  453. * @param array $insert
  454. * @return bool
  455. */
  456. public static function DBUPIN($builder, $where, $update, $insert = [])
  457. {
  458. if (is_string($builder)) {
  459. $builder = DB::table($builder);
  460. }
  461. if (!$builder->where($where)->exists()) {
  462. return $builder->insert(array_merge($where, $insert));
  463. }
  464. return (bool)$builder->take(1)->update($update);
  465. }
  466. /**
  467. * 处理数据库原生符号
  468. * @param string $value
  469. * @return mixed
  470. */
  471. public static function DBRAW($value = '')
  472. {
  473. if (env('DB_CONNECTION') === 'pgsql') {
  474. $value = str_replace("`", "\"", $value);
  475. }
  476. return $value;
  477. }
  478. /**
  479. * array转xml
  480. * @param $data
  481. * @param string $root 根节点
  482. * @return string
  483. */
  484. public static function array2xml($data, $root = '<xml>'){
  485. $str = "";
  486. if ($root) $str .= $root;
  487. foreach ($data as $key => $val) {
  488. if (is_array($val)) {
  489. $child = self::array2xml($val, false);
  490. $str .= "<$key>$child</$key>";
  491. } else {
  492. $str .= "<$key><![CDATA[$val]]></$key>";
  493. }
  494. }
  495. if ($root) $str .= '</xml>';
  496. return $str;
  497. }
  498. /**
  499. * xml转json
  500. * @param string $source 传的是文件,还是xml的string的判断
  501. * @return string
  502. */
  503. public static function xml2json($source)
  504. {
  505. if (is_file($source)) {
  506. $xml_array = @simplexml_load_file($source);
  507. } else {
  508. $xml_array = @simplexml_load_string($source, NULL, LIBXML_NOCDATA);
  509. }
  510. return json_encode($xml_array);
  511. }
  512. /**
  513. * 返回经stripslashes处理过的字符串或数组
  514. * @param array|string $string 需要处理的字符串或数组
  515. * @return mixed
  516. */
  517. public static function newStripslashes($string)
  518. {
  519. if (is_numeric($string)) {
  520. return $string;
  521. }elseif (!is_array($string)) {
  522. return stripslashes($string);
  523. }
  524. foreach ($string as $key => $val) $string[$key] = Base::newStripslashes($val);
  525. return $string;
  526. }
  527. /**
  528. * 返回经addslashes处理过的字符串或数组
  529. * @param array|string $string 需要处理的字符串或数组
  530. * @return mixed
  531. */
  532. public static function newAddslashes($string)
  533. {
  534. if (is_numeric($string)) {
  535. return $string;
  536. }elseif (!is_array($string)) {
  537. return addslashes($string);
  538. }
  539. foreach ($string as $key => $val) $string[$key] = Base::newAddslashes($val);
  540. return $string;
  541. }
  542. /**
  543. * 返回经trim处理过的字符串或数组
  544. * @param $string
  545. * @return array|string
  546. */
  547. public static function newTrim($string)
  548. {
  549. if (!is_array($string)) return trim($string);
  550. foreach ($string as $key => $val) $string[$key] = Base::newTrim($val);
  551. return $string;
  552. }
  553. /**
  554. * 返回经intval处理过的字符串或数组
  555. * @param $string
  556. * @return array|string
  557. */
  558. public static function newIntval($string)
  559. {
  560. if (!is_array($string)) return intval($string);
  561. foreach ($string as $key => $val) $string[$key] = Base::newIntval($val);
  562. return $string;
  563. }
  564. /**
  565. * 重MD5加密
  566. * @param $text
  567. * @param string $pass
  568. * @return string
  569. */
  570. public static function md52($text, $pass = '')
  571. {
  572. $_text = md5($text) . $pass;
  573. return md5($_text);
  574. }
  575. /**
  576. * 随机字符串
  577. * @param int $length 随机字符长度
  578. * @param string $type
  579. * @return string 1数字、2大小写字母、21小写字母、22大写字母、默认全部;
  580. */
  581. public static function generatePassword($length = 8, $type = '')
  582. {
  583. // 密码字符集,可任意添加你需要的字符
  584. switch ($type) {
  585. case '1':
  586. $chars = '0123456789';
  587. break;
  588. case '2':
  589. $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  590. break;
  591. case '21':
  592. $chars = 'abcdefghijklmnopqrstuvwxyz';
  593. break;
  594. case '22':
  595. $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  596. break;
  597. default:
  598. $chars = $type ? $type : 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  599. break;
  600. }
  601. $passwordstr = '';
  602. $max = strlen($chars) - 1;
  603. for ($i = 0; $i < $length; $i++) {
  604. $passwordstr .= $chars[mt_rand(0, $max)];
  605. }
  606. return $passwordstr;
  607. }
  608. /**
  609. * 同 generate_password 默认获取纯数字
  610. * @param $length
  611. * @param string $chars
  612. * @return string
  613. */
  614. public static function strRandom($length, $chars = '0123456789')
  615. {
  616. return Base::generatePassword($length, $chars);
  617. }
  618. /**
  619. * 判断两个地址域名是否相同
  620. * @param string $var1
  621. * @param string $var2
  622. * @return bool
  623. */
  624. public static function hostContrast($var1, $var2)
  625. {
  626. $arr1 = parse_url($var1);
  627. $arr2 = parse_url($var2);
  628. //
  629. $host1 = $var1;
  630. if (isset($arr1['host'])) {
  631. $host1 = $arr1['host'];
  632. }
  633. //
  634. $host2 = $var2;
  635. if (isset($arr2['host'])) {
  636. $host2 = $arr2['host'];
  637. }
  638. return $host1== $host2;
  639. }
  640. /**
  641. * 获取url域名
  642. * @param string $var
  643. * @return mixed
  644. */
  645. public static function getHost($var = '')
  646. {
  647. if (empty($var)) {
  648. $var = url("/");
  649. }
  650. $arr = parse_url($var);
  651. return $arr['host'];
  652. }
  653. /**
  654. * 相对路径补全
  655. * @param string|array $str
  656. * @return string
  657. */
  658. public static function fillUrl($str = '')
  659. {
  660. if (is_array($str)) {
  661. foreach ($str AS $key=>$item) {
  662. $str[$key] = Base::fillUrl($item);
  663. }
  664. return $str;
  665. }
  666. if (empty($str)) {
  667. return $str;
  668. }
  669. if (substr($str, 0, 2) == "//" ||
  670. substr($str, 0, 7) == "http://" ||
  671. substr($str, 0, 8) == "https://" ||
  672. substr($str, 0, 6) == "ftp://" ||
  673. substr($str, 0, 1) == "/" ||
  674. substr(str_replace(' ', '', $str), 0, 11) == "data:image/"
  675. ) {
  676. return $str;
  677. } else {
  678. return url($str);
  679. }
  680. }
  681. /**
  682. * 反 fillUrl
  683. * @param string $str
  684. * @return array|string
  685. */
  686. public static function unFillUrl($str = '')
  687. {
  688. if (is_array($str)) {
  689. foreach ($str AS $key=>$item) {
  690. $str[$key] = Base::unFillUrl($item);
  691. }
  692. return $str;
  693. }
  694. return Base::leftDelete($str, url('') . '/');
  695. }
  696. /**
  697. * 格式化内容图片地址
  698. * @param $content
  699. * @return mixed
  700. */
  701. public static function formatContentImg($content)
  702. {
  703. $pattern = '/<img(.*?)src=("|\')(.*?)\2/is';
  704. if (preg_match($pattern, $content)) {
  705. preg_match_all($pattern, $content, $matchs);
  706. foreach ($matchs[3] AS $index => $value) {
  707. if (!(substr($value, 0, 7) == "http://" ||
  708. substr($value, 0, 8) == "https://" ||
  709. substr($value, 0, 6) == "ftp://" ||
  710. substr(str_replace(' ', '', $value), 0, 11) == "data:image/"
  711. )) {
  712. if (substr($value, 0, 2) == "//") {
  713. $value = "http:" . $value;
  714. }elseif (substr($value, 0, 1) == "/") {
  715. $value = substr($value, 1);
  716. }
  717. $newValue = "<img" . $matchs[1][$index] . "src=" . $matchs[2][$index] . self::fillUrl($value) . $matchs[2][$index];
  718. $content = str_replace($matchs[0][$index], $newValue, $content);
  719. }
  720. }
  721. }
  722. return $content;
  723. }
  724. /**
  725. * 打散字符串,只留为数字的项
  726. * @param $delimiter
  727. * @param $string
  728. * @return array
  729. */
  730. public static function explodeInt($delimiter, $string)
  731. {
  732. $array = is_array($string) ? $string : explode($delimiter, $string);
  733. foreach ($array AS $k => $v) {
  734. if (!is_numeric($v)) {
  735. unset($array[$k]);
  736. }
  737. }
  738. return $array;
  739. }
  740. /**
  741. * 检测日期格式
  742. * @param string $str 需要检测的字符串
  743. * @return bool
  744. */
  745. public static function isDate($str)
  746. {
  747. $strArr = explode('-', $str);
  748. if (empty($strArr) || count($strArr) != 3) {
  749. return false;
  750. } else {
  751. list($year, $month, $day) = $strArr;
  752. if (checkdate($month, $day, $year)) {
  753. return true;
  754. } else {
  755. return false;
  756. }
  757. }
  758. }
  759. /**
  760. * 检测时间格式
  761. * @param string $str 需要检测的字符串
  762. * @return bool
  763. */
  764. public static function isTime($str)
  765. {
  766. $strArr = explode(':', $str);
  767. if (empty($strArr) || count($strArr) != 2) {
  768. return false;
  769. } else {
  770. list($hour, $minute) = $strArr;
  771. if (intval($hour) > 23 || intval($minute) > 59) {
  772. return false;
  773. } else {
  774. return true;
  775. }
  776. }
  777. }
  778. /**
  779. * 检测手机号码格式
  780. * @param string $str 需要检测的字符串
  781. * @return bool
  782. */
  783. public static function isMobile($str)
  784. {
  785. if (preg_match("/^1([3456789])\d{9}$/", $str)) {
  786. return true;
  787. }else{
  788. return false;
  789. }
  790. }
  791. /**
  792. * 检测邮箱格式
  793. * @param string $str 需要检测的字符串
  794. * @return int
  795. */
  796. public static function isMail($str)
  797. {
  798. $RegExp = '/^[a-z0-9][a-z\.0-9-_]+@[a-z0-9_-]+(?:\.[a-z]{0,3}\.[a-z]{0,2}|\.[a-z]{0,3}|\.[a-z]{0,2})$/i';
  799. return preg_match($RegExp, $str);
  800. }
  801. /**
  802. * 正则判断是否纯数字
  803. * @param $str
  804. * @return bool
  805. */
  806. public static function isNumber($str)
  807. {
  808. if (preg_match("/^\d*$/", $str)) {
  809. return true;
  810. } else {
  811. return false;
  812. }
  813. }
  814. /**
  815. * 判断身份证是否正确
  816. * @param $id
  817. * @return bool
  818. */
  819. public static function isIdcard($id)
  820. {
  821. $id = strtoupper($id);
  822. $regx = "/(^\d{15}$)|(^\d{17}([0-9]|X)$)/";
  823. $arr_split = array();
  824. if(!preg_match($regx, $id)) {
  825. return FALSE;
  826. }
  827. if(15==strlen($id)) {
  828. //检查15位
  829. $regx = "/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/";
  830. @preg_match($regx, $id, $arr_split);
  831. //检查生日日期是否正确
  832. $dtm_birth = "19".$arr_split[2] . '/' . $arr_split[3]. '/' .$arr_split[4];
  833. if(!strtotime($dtm_birth)) {
  834. return FALSE;
  835. } else {
  836. return TRUE;
  837. }
  838. } else {
  839. //检查18位
  840. $regx = "/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/";
  841. @preg_match($regx, $id, $arr_split);
  842. $dtm_birth = $arr_split[2] . '/' . $arr_split[3]. '/' .$arr_split[4];
  843. //检查生日日期是否正确
  844. if(!strtotime($dtm_birth)) {
  845. return FALSE;
  846. } else {
  847. //检验18位身份证的校验码是否正确。
  848. //校验位按照ISO 7064:1983.MOD 11-2的规定生成,X可以认为是数字10。
  849. $arr_int = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
  850. $arr_ch = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
  851. $sign = 0;
  852. for ( $i = 0; $i < 17; $i++ ) {
  853. $b = (int) $id[$i];
  854. $w = $arr_int[$i];
  855. $sign += $b * $w;
  856. }
  857. $n = $sign % 11;
  858. $val_num = $arr_ch[$n];
  859. if ($val_num != substr($id,17, 1)) {
  860. return FALSE;
  861. } else {
  862. return TRUE;
  863. }
  864. }
  865. }
  866. }
  867. /**
  868. * 阵列数组
  869. * @param $keys
  870. * @param $src
  871. * @param bool $default
  872. * @return array
  873. */
  874. public static function arrayElements($keys, $src, $default = FALSE)
  875. {
  876. $return = [];
  877. if (!is_array($keys)) {
  878. $keys = array($keys);
  879. }
  880. foreach ($keys as $key) {
  881. if (isset($src[$key])) {
  882. $return[$key] = $src[$key];
  883. } else {
  884. $return[$key] = $default;
  885. }
  886. }
  887. return $return;
  888. }
  889. /**
  890. * 判断字符串存在(包含)
  891. * @param string $string
  892. * @param string $find
  893. * @return bool
  894. */
  895. public static function strExists($string, $find)
  896. {
  897. if (!is_string($string) || !is_string($find)) {
  898. return false;
  899. }
  900. return !(strpos($string, $find) === FALSE);
  901. }
  902. /**
  903. * 判断字符串开头包含
  904. * @param string $string //原字符串
  905. * @param string $find //判断字符串
  906. * @param bool|false $lower //是否不区分大小写
  907. * @return int
  908. */
  909. public static function leftExists($string, $find, $lower = false)
  910. {
  911. if (!is_string($string) || !is_string($find)) {
  912. return false;
  913. }
  914. if ($lower) {
  915. $string = strtolower($string);
  916. $find = strtolower($find);
  917. }
  918. return (substr($string, 0, strlen($find)) == $find);
  919. }
  920. /**
  921. * 判断字符串结尾包含
  922. * @param string $string //原字符串
  923. * @param string $find //判断字符串
  924. * @param bool|false $lower //是否不区分大小写
  925. * @return int
  926. */
  927. public static function rightExists($string, $find, $lower = false)
  928. {
  929. if (!is_string($string) || !is_string($find)) {
  930. return false;
  931. }
  932. if ($lower) {
  933. $string = strtolower($string);
  934. $find = strtolower($find);
  935. }
  936. return (substr($string, strlen($find) * -1) == $find);
  937. }
  938. /**
  939. * 删除开头指定字符串
  940. * @param $string
  941. * @param $find
  942. * @param bool $lower
  943. * @return string
  944. */
  945. public static function leftDelete($string, $find, $lower = false)
  946. {
  947. if (Base::leftExists($string, $find, $lower)) {
  948. $string = substr($string, strlen($find));
  949. }
  950. return $string ? $string : '';
  951. }
  952. /**
  953. * 删除结尾指定字符串
  954. * @param $string
  955. * @param $find
  956. * @param bool $lower
  957. * @return string
  958. */
  959. public static function rightDelete($string, $find, $lower = false)
  960. {
  961. if (Base::rightExists($string, $find, $lower)) {
  962. $string = substr($string, 0, strlen($find) * -1);
  963. }
  964. return $string;
  965. }
  966. /**
  967. * 截取指定字符串
  968. * @param $str
  969. * @param string $ta
  970. * @param string $tb
  971. * @return string
  972. */
  973. public static function getMiddle($str, $ta = '', $tb = ''){
  974. if ($ta && strpos($str, $ta) !== false){
  975. $str = substr($str, strpos($str, $ta) + strlen($ta));
  976. }
  977. if ($tb && strpos($str, $tb) !== false){
  978. $str = substr($str, 0, strpos($str, $tb));
  979. }
  980. return $str;
  981. }
  982. /**
  983. * 自定义替换次数
  984. * @param $search
  985. * @param $replace
  986. * @param $subject
  987. * @param int $limit
  988. * @return string|string[]|null
  989. */
  990. public static function strReplaceLimit($search, $replace, $subject, $limit = -1)
  991. {
  992. if (is_array($search)) {
  993. foreach ($search as $k => $v) {
  994. $search[$k] = '`' . preg_quote($search[$k], '`') . '`';
  995. }
  996. } else {
  997. $search = '`' . preg_quote($search, '`') . '`';
  998. }
  999. return preg_replace($search, $replace, $subject, $limit);
  1000. }
  1001. /**
  1002. * 获取或设置
  1003. * @param $setname //配置名称
  1004. * @param bool $array //保存内容
  1005. * @param bool $isCache //读取缓存
  1006. * @return array
  1007. */
  1008. public static function setting($setname, $array = false, $isCache = false)
  1009. {
  1010. global $_A;
  1011. if (empty($setname)) {
  1012. return [];
  1013. }
  1014. if ($array === false && isset($_A["__static_setting_" . $setname])) {
  1015. return $_A["__static_setting_" . $setname];
  1016. }
  1017. $setting = [];
  1018. $setrow = DBCache::table('setting')->where('title', $setname)->cache($isCache)->first();
  1019. if (!empty($setrow)) {
  1020. $setting = Base::string2array($setrow['setting']);
  1021. } else {
  1022. DB::table('setting')->insert(['title' => $setname]);
  1023. }
  1024. if ($array !== false) {
  1025. $setting = $array;
  1026. DB::table('setting')->where('title', $setname)->update(['setting' => (is_array($array) ? Base::array2string($array) : $array)]);
  1027. DBCache::table('setting')->where('title', $setname)->removeCache()->first();
  1028. }
  1029. $_A["__static_setting_" . $setname] = $setting;
  1030. return $setting;
  1031. }
  1032. /**
  1033. * 获取设置值
  1034. * @param $setname
  1035. * @param $keyname
  1036. * @param $defaultVal
  1037. * @return mixed
  1038. */
  1039. public static function settingFind($setname, $keyname, $defaultVal = '')
  1040. {
  1041. $array = Base::setting($setname);
  1042. return isset($array[$keyname]) ? $array[$keyname] : $defaultVal;
  1043. }
  1044. /**
  1045. * 秒 (转) 年、天、时、分、秒
  1046. * @param $time
  1047. * @return array|bool
  1048. */
  1049. public static function sec2time($time)
  1050. {
  1051. if (is_numeric($time)) {
  1052. $value = array(
  1053. "years" => 0, "days" => 0, "hours" => 0,
  1054. "minutes" => 0, "seconds" => 0,
  1055. );
  1056. /*
  1057. if($time >= 31536000){
  1058. $value["years"] = floor($time/31536000);
  1059. $time = ($time%31536000);
  1060. }
  1061. */
  1062. if ($time >= 86400) {
  1063. $value["days"] = floor($time / 86400);
  1064. $time = ($time % 86400);
  1065. }
  1066. if ($time >= 3600) {
  1067. $value["hours"] = floor($time / 3600);
  1068. $time = ($time % 3600);
  1069. }
  1070. if ($time >= 60) {
  1071. $value["minutes"] = floor($time / 60);
  1072. $time = ($time % 60);
  1073. }
  1074. $value["seconds"] = floor($time);
  1075. return (array)$value;
  1076. } else {
  1077. return (bool)FALSE;
  1078. }
  1079. }
  1080. /**
  1081. * 年、天、时、分、秒 (转) 秒
  1082. * @param $value
  1083. * @return int
  1084. */
  1085. public static function time2sec($value)
  1086. {
  1087. $time = intval($value["seconds"]);
  1088. $time += intval($value["minutes"] * 60);
  1089. $time += intval($value["hours"] * 3600);
  1090. $time += intval($value["days"] * 86400);
  1091. $time += intval($value["years"] * 31536000);
  1092. return $time;
  1093. }
  1094. /**
  1095. * 阿拉伯数字转化为中文
  1096. * @param $num
  1097. * @return string
  1098. */
  1099. public static function chinaNum($num)
  1100. {
  1101. $china = array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九');
  1102. $arr = str_split($num);
  1103. $txt = '';
  1104. for ($i = 0; $i < count($arr); $i++) {
  1105. $txt .= $china[$arr[$i]];
  1106. }
  1107. return $txt;
  1108. }
  1109. /**
  1110. * 阿拉伯数字转化为中文(用于星期,七改成日)
  1111. * @param $num
  1112. * @return string
  1113. */
  1114. public static function chinaNumZ($num)
  1115. {
  1116. return str_replace("七", "日", Base::chinaNum($num));
  1117. }
  1118. /**
  1119. * 获取(时间戳转)今天是星期几,只返回(几)
  1120. * @param string|number $unixTime
  1121. * @return string
  1122. */
  1123. public static function getTimeWeek($unixTime = '')
  1124. {
  1125. $unixTime = is_numeric($unixTime) ? $unixTime : Base::time();
  1126. $weekarray = ['日', '一', '二', '三', '四', '五', '六'];
  1127. return $weekarray[date('w', $unixTime)];
  1128. }
  1129. /**
  1130. * 获取(时间戳转)现在时间段:深夜、凌晨、早晨、上午.....
  1131. * @param string|number $unixTime
  1132. * @return string
  1133. */
  1134. public static function getTimeDayeSegment($unixTime = '')
  1135. {
  1136. $unixTime = is_numeric($unixTime) ? $unixTime : Base::time();
  1137. $H = date('H', $unixTime);
  1138. if ($H >= 19) {
  1139. return '晚上';
  1140. } elseif ($H >= 18) {
  1141. return '傍晚';
  1142. } elseif ($H >= 13) {
  1143. return '下午';
  1144. } elseif ($H >= 12) {
  1145. return '中午';
  1146. } elseif ($H >= 8) {
  1147. return '上午';
  1148. } elseif ($H >= 5) {
  1149. return '早晨';
  1150. } elseif ($H >= 1) {
  1151. return '凌晨';
  1152. } elseif ($H >= 0) {
  1153. return '深夜';
  1154. } else {
  1155. return '';
  1156. }
  1157. }
  1158. /**
  1159. * 国际化(替换国际语言)
  1160. * @param $val
  1161. * @return mixed
  1162. */
  1163. public static function Lang($val)
  1164. {
  1165. $repArray = [];
  1166. if (is_array($val)) {
  1167. if (self::strExists($val[0], '%') && count($val) > 1) {
  1168. $repArray = array_slice($val, 1);
  1169. }
  1170. $val = $val[0];
  1171. }
  1172. $data = self::langData();
  1173. if (isset($data[$val]) && $data[$val] !== null) {
  1174. $val = $data[$val];
  1175. }
  1176. if ($repArray) {
  1177. foreach ($repArray AS $item) {
  1178. $val = self::strReplaceLimit('%', $item, $val, 1);
  1179. }
  1180. }
  1181. return $val;
  1182. }
  1183. /**
  1184. * 加载语言数据
  1185. * @param bool $refresh
  1186. * @return array|mixed
  1187. */
  1188. public static function langData($refresh = false)
  1189. {
  1190. global $_A;
  1191. if (!isset($_A["__static_langdata"]) || $refresh === true) {
  1192. $_A["__static_langdata"] = [];
  1193. $language = trim(Request::header('language'));
  1194. $langpath = resource_path('lang/' . $language . '/general.php');
  1195. if (file_exists($langpath)) {
  1196. $data = include $langpath;
  1197. if (is_array($data)) {
  1198. $_A["__static_langdata"] = $data;
  1199. }
  1200. }
  1201. }
  1202. return $_A["__static_langdata"];
  1203. }
  1204. /**
  1205. * JSON返回
  1206. * @param $param
  1207. * @return string
  1208. */
  1209. public static function jsonEcho($param)
  1210. {
  1211. global $_GPC;
  1212. //
  1213. $json = json_encode($param);
  1214. $callback = $_GPC['callback'];
  1215. if ($callback) {
  1216. return $callback . '(' . $json . ')';
  1217. } else {
  1218. return $json;
  1219. }
  1220. }
  1221. /**
  1222. * 数组返回 正确
  1223. * @param $msg
  1224. * @param array $data
  1225. * @param int $ret
  1226. * @return array
  1227. */
  1228. public static function retSuccess($msg, $data = [], $ret = 1)
  1229. {
  1230. return array(
  1231. 'ret' => $ret,
  1232. 'msg' => self::Lang($msg),
  1233. 'data' => $data
  1234. );
  1235. }
  1236. /**
  1237. * 数组返回 错误
  1238. * @param $msg
  1239. * @param array $data
  1240. * @param int $ret
  1241. * @return array
  1242. */
  1243. public static function retError($msg, $data = [], $ret = 0)
  1244. {
  1245. return array(
  1246. 'ret' => $ret,
  1247. 'msg' => self::Lang($msg),
  1248. 'data' => $data
  1249. );
  1250. }
  1251. /**
  1252. * Ajax 错误返回
  1253. * @param $msg
  1254. * @param array $data
  1255. * @param int $ret
  1256. * @return array|void
  1257. */
  1258. public static function ajaxError($msg, $data = [], $ret = 0)
  1259. {
  1260. if (Request::input('__Access-Control-Allow-Origin') || Request::header('Content-Type') === 'application/json') {
  1261. return Base::retError($msg, $data, $ret);
  1262. }else{
  1263. return abort(404);
  1264. }
  1265. }
  1266. /**
  1267. * JSON返回 正确
  1268. * @param $msg
  1269. * @param array $data
  1270. * @param int $ret
  1271. * @return string
  1272. */
  1273. public static function jsonSuccess($msg, $data = [], $ret = 1)
  1274. {
  1275. return Base::jsonEcho(Base::retSuccess($msg, $data, $ret));
  1276. }
  1277. /**
  1278. * JSON返回 错误
  1279. * @param $msg
  1280. * @param array $data
  1281. * @param int $ret
  1282. * @return string
  1283. */
  1284. public static function jsonError($msg, $data = [], $ret = 0)
  1285. {
  1286. return Base::jsonEcho(Base::retError($msg, $data, $ret));
  1287. }
  1288. /**
  1289. * 是否错误
  1290. * @param $param
  1291. * @return bool
  1292. */
  1293. public static function isError($param)
  1294. {
  1295. return intval($param['ret']) <= 0;
  1296. }
  1297. /**
  1298. * 异常模板
  1299. * @param $msg
  1300. * @param bool $catch
  1301. * @return bool
  1302. */
  1303. public static function Exce($msg, $catch = false)
  1304. {
  1305. if ($catch === false) {
  1306. return "{{ExceMsg:".$msg.":ExceMsg}}";
  1307. }else{
  1308. if (Base::strExists($msg . "", "{{ExceMsg:") && Base::strExists($msg . "", ":ExceMsg}}")) {
  1309. $msg = Base::getMiddle($msg, "{{ExceMsg:", ":ExceMsg}}");
  1310. $catch = $msg?$msg:$catch;
  1311. }
  1312. return $catch;
  1313. }
  1314. }
  1315. /**
  1316. * 获取数组的第几个值
  1317. * @param $arr
  1318. * @param int $i
  1319. * @return array
  1320. */
  1321. public static function getArray($arr, $i = 1)
  1322. {
  1323. $array = [];
  1324. $j = 1;
  1325. foreach ($arr AS $item) {
  1326. $array[] = $item;
  1327. if ($i >= $j) {
  1328. break;
  1329. }
  1330. $j++;
  1331. }
  1332. return $array;
  1333. }
  1334. /**
  1335. * 小时转天/小时
  1336. * @param $hour
  1337. * @return string
  1338. */
  1339. public static function forumHourDay($hour)
  1340. {
  1341. $hour = intval($hour);
  1342. if ($hour > 24) {
  1343. $day = floor($hour / 24);
  1344. $hour-= $day * 24;
  1345. return $day.'天'.$hour.'小时';
  1346. }
  1347. return $hour.'小时';
  1348. }
  1349. /**
  1350. * 时间格式化
  1351. * @param $date
  1352. * @return false|string
  1353. */
  1354. public static function forumDate($date)
  1355. {
  1356. $dur = time() - $date;
  1357. if ($date > strtotime(date("Y-m-d"))) {
  1358. //今天
  1359. if ($dur < 60) {
  1360. return max($dur, 1) . '秒前';
  1361. } elseif ($dur < 3600) {
  1362. return floor($dur / 60) . '分钟前';
  1363. } elseif ($dur < 86400) {
  1364. return floor($dur / 3600) . '小时前';
  1365. } else {
  1366. return date("H:i", $date);
  1367. }
  1368. } elseif ($date > strtotime(date("Y-m-d", strtotime("-1 day")))) {
  1369. //昨天
  1370. return '昨天';
  1371. } elseif ($date > strtotime(date("Y-m-d", strtotime("-2 day")))) {
  1372. //前天
  1373. return '前天';
  1374. } elseif ($dur > 86400) {
  1375. //x天前
  1376. return floor($dur / 86400) . '天前';
  1377. }
  1378. return date("Y-m-d", $date);
  1379. }
  1380. /**
  1381. * 获取时间戳今天的第一秒时间戳
  1382. * @param $time
  1383. * @return false|int
  1384. */
  1385. public static function dayTimeF($time)
  1386. {
  1387. return strtotime(date("Y-m-d 00:00:00", self::isNumber($time) ? $time : strtotime($time)));
  1388. }
  1389. /**
  1390. * 获取时间戳今天的最后一秒时间戳
  1391. * @param $time
  1392. * @return false|int
  1393. */
  1394. public static function dayTimeE($time)
  1395. {
  1396. return strtotime(date("Y-m-d 23:59:59", self::isNumber($time) ? $time : strtotime($time)));
  1397. }
  1398. /**
  1399. * 用户名、邮箱、手机账号、银行卡号中间字符串以*隐藏
  1400. * @param $str
  1401. * @return mixed|string
  1402. */
  1403. public static function cardFormat($str)
  1404. {
  1405. if (strpos($str, '@')) {
  1406. $email_array = explode("@", $str);
  1407. $prevfix = (strlen($email_array[0]) < 4) ? "" : substr($str, 0, 3); //邮箱前缀
  1408. $count = 0;
  1409. $str = preg_replace('/([\d\w+_-]{0,100})@/', '***@', $str, -1, $count);
  1410. return $prevfix . $str;
  1411. }
  1412. if (Base::isMobile($str)) {
  1413. return substr($str, 0, 3) . "****" . substr($str, -4);
  1414. }
  1415. $pattern = '/([\d]{4})([\d]{4})([\d]{4})([\d]{4})([\d]{0,})?/i';
  1416. if (preg_match($pattern, $str)) {
  1417. return preg_replace($pattern, '$1 **** **** **** $5', $str);
  1418. }
  1419. $pattern = '/([\d]{4})([\d]{4})([\d]{4})([\d]{0,})?/i';
  1420. if (preg_match($pattern, $str)) {
  1421. return preg_replace($pattern, '$1 **** **** $4', $str);
  1422. }
  1423. $pattern = '/([\d]{4})([\d]{4})([\d]{0,})?/i';
  1424. if (preg_match($pattern, $str)) {
  1425. return preg_replace($pattern, '$1 **** $3', $str);
  1426. }
  1427. return substr($str, 0, 3) . "***" . substr($str, -1);
  1428. }
  1429. /**
  1430. * 数字每4位加一空格
  1431. * @param $str
  1432. * @param string $interval
  1433. * @return string
  1434. */
  1435. public static function fourFormat($str, $interval = " ")
  1436. {
  1437. if (!is_numeric($str)) return $str;
  1438. //
  1439. $text = '';
  1440. for ($i = 0; $i < strlen($str); $i++) {
  1441. $text .= $str[$i];
  1442. if ($i % 4 == 3) {
  1443. $text .= $interval;
  1444. }
  1445. }
  1446. return $text;
  1447. }
  1448. /**
  1449. * 保留两位小数点
  1450. * @param $str
  1451. * @param bool $float
  1452. * @return float
  1453. */
  1454. public static function twoFloat($str, $float = false)
  1455. {
  1456. $str = sprintf("%.2f", floatval($str));
  1457. if ($float === true) {
  1458. $str = floatval($str);
  1459. }
  1460. return $str;
  1461. }
  1462. /**
  1463. * 获取时间戳
  1464. * @param bool $refresh
  1465. * @return int
  1466. */
  1467. public static function time($refresh = false)
  1468. {
  1469. global $_A;
  1470. if (!isset($_A["__static_time"]) || $refresh === true) {
  1471. $_A["__static_time"] = time();
  1472. }
  1473. return $_A["__static_time"];
  1474. }
  1475. /**
  1476. * 获取毫秒时间戳
  1477. * @return float
  1478. */
  1479. public static function msecTime()
  1480. {
  1481. list($msec, $sec) = explode(' ', microtime());
  1482. $time = explode(".", $sec . ($msec * 1000));
  1483. return $time[0];
  1484. }
  1485. /**
  1486. * 时间差(不够1个小时算一个小时)
  1487. * @param int $s 开始时间戳
  1488. * @param int $e 结束时间戳
  1489. * @return string
  1490. */
  1491. public static function timeDiff($s, $e)
  1492. {
  1493. $d = $e - $s;
  1494. if ($d > 86400) {
  1495. $day = floor($d / 86400);
  1496. $hour = ceil(($d - ($day * 86400)) / 3600);
  1497. if ($hour > 0) {
  1498. return $day . '天' . $hour . '小时';
  1499. } else {
  1500. return $day . '天';
  1501. }
  1502. } elseif ($d > 3600) {
  1503. return ceil($d / 3600) . '小时';
  1504. } elseif ($d > 60) {
  1505. return ceil($d / 60) . '分钟';
  1506. } elseif ($d > 1) {
  1507. return '1分钟内';
  1508. } else {
  1509. return '0秒';
  1510. }
  1511. }
  1512. /**
  1513. * 获取IP地址
  1514. * @return string
  1515. */
  1516. public static function getIp()
  1517. {
  1518. global $_A;
  1519. if (!isset($_A["__static_ip"])) {
  1520. if (getenv('HTTP_CLIENT_IP') and strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
  1521. $onlineip = getenv('HTTP_CLIENT_IP');
  1522. } elseif (getenv('HTTP_X_FORWARDED_FOR') and strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
  1523. $onlineip = getenv('HTTP_X_FORWARDED_FOR');
  1524. } elseif (getenv('REMOTE_ADDR') and strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
  1525. $onlineip = getenv('REMOTE_ADDR');
  1526. } elseif (isset($_SERVER['REMOTE_ADDR']) and $_SERVER['REMOTE_ADDR'] and strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
  1527. $onlineip = $_SERVER['REMOTE_ADDR'];
  1528. } elseif (Request::header('X-Real-IP')) {
  1529. $onlineip = Request::header('X-Real-IP');
  1530. } else {
  1531. $onlineip = '0,0,0,0';
  1532. }
  1533. preg_match("/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/", $onlineip, $match);
  1534. $_A["__static_ip"] = $match[0] ? $match[0] : 'unknown';
  1535. }
  1536. return $_A["__static_ip"];
  1537. }
  1538. /**
  1539. * 获取IP地址
  1540. * @param string $ip
  1541. * @return array|mixed
  1542. */
  1543. public static function getIpInfo($ip = '')
  1544. {
  1545. if (empty($ip)) {
  1546. $ip = self::getIp();
  1547. }
  1548. $cacheKey = "getIpInfo::" . md5($ip);
  1549. $result = Cache::rememberForever($cacheKey, function() use ($ip) {
  1550. return Ihttp::ihttp_request("http://ip.taobao.com/service/getIpInfo.php?accessKey=alibaba-inc&ip=" . $ip, [], [], 8);
  1551. });
  1552. if (Base::isError($result)) {
  1553. return $result;
  1554. }
  1555. $data = json_decode($result['data'], true);
  1556. if (!is_array($data) || intval($data['code']) != 0) {
  1557. Cache::forget($cacheKey);
  1558. return Base::retError("error ip: -1");
  1559. }
  1560. $data = $data['data'];
  1561. if (!is_array($data) || !isset($data['country'])) {
  1562. return Base::retError("error ip: -2");
  1563. }
  1564. $data['text'] = $data['country'];
  1565. $data['textSmall'] = $data['country'];
  1566. if ($data['region'] && $data['region'] != $data['country'] && $data['region'] != "XX") {
  1567. $data['text'].= " " . $data['region'];
  1568. $data['textSmall'] = $data['region'];
  1569. }
  1570. if ($data['city'] && $data['city'] != $data['region'] && $data['city'] != "XX") {
  1571. $data['text'].= " " . $data['city'];
  1572. $data['textSmall'].= " " . $data['city'];
  1573. }
  1574. if ($data['county'] && $data['county'] != $data['city'] && $data['county'] != "XX") {
  1575. $data['text'].= " " . $data['county'];
  1576. $data['textSmall'].= " " . $data['county'];
  1577. }
  1578. return Base::retSuccess("success", $data);
  1579. }
  1580. /**
  1581. * 是否是中国IP:-1错误、1是、0否
  1582. * @param string $ip
  1583. * @return int
  1584. */
  1585. public static function isCnIp($ip = '')
  1586. {
  1587. if (empty($ip)) {
  1588. $ip = self::getIp();
  1589. }
  1590. $cacheKey = "isCnIp::" . md5($ip);
  1591. //
  1592. $result = Cache::remember($cacheKey, now()->addMinutes(10), function () use ($ip) {
  1593. $file = dirname(__FILE__) . '/ip/all_cn.txt';
  1594. if (!file_exists($file)) {
  1595. return -1;
  1596. }
  1597. $in = false;
  1598. $myFile = fopen($file, "r");
  1599. $i = 0;
  1600. while (!feof($myFile)) {
  1601. $i++;
  1602. $cidr = trim(fgets($myFile));
  1603. if (Base::ipInRange($ip, $cidr)) {
  1604. $in = true;
  1605. break;
  1606. }
  1607. }
  1608. fclose($myFile);
  1609. return $in ? 1 : 0;
  1610. });
  1611. if ($result === -1) {
  1612. Cache::forget($cacheKey);
  1613. }
  1614. //
  1615. return intval($result);
  1616. }
  1617. /**
  1618. * 验证IP地址范围
  1619. * $range 支持多种写法
  1620. * - Wildcard: 1.2.3.*
  1621. * - CIRD:1.2.3/24 或者 1.2.3.4/255.255.255.0
  1622. * - Start-End: 1.2.3.0-1.2.3.255
  1623. * @param $ip
  1624. * @param $range
  1625. * @return bool
  1626. */
  1627. public static function ipInRange($ip, $range)
  1628. {
  1629. if (substr_count($ip, '.') == 3 && $ip == $range) {
  1630. return true;
  1631. }
  1632. if (strpos($range, '/') !== false) {
  1633. list($range, $netmask) = explode('/', $range, 2);
  1634. if (strpos($netmask, '.') !== false) {
  1635. $netmask = str_replace('*', '0', $netmask);
  1636. $netmask_dec = ip2long($netmask);
  1637. return ((ip2long($ip) & $netmask_dec) == (ip2long($range) & $netmask_dec));
  1638. } else {
  1639. $x = explode('.', $range);
  1640. while (count($x) < 4) {
  1641. $x[] = '0';
  1642. }
  1643. list($a, $b, $c, $d) = $x;
  1644. $range = sprintf("%u.%u.%u.%u", empty($a) ? '0' : $a, empty($b) ? '0' : $b, empty($c) ? '0' : $c, empty($d) ? '0' : $d);
  1645. $range_dec = ip2long($range);
  1646. $ip_dec = ip2long($ip);
  1647. $wildcard_dec = pow(2, (32 - $netmask)) - 1;
  1648. $netmask_dec = ~$wildcard_dec;
  1649. return (($ip_dec & $netmask_dec) == ($range_dec & $netmask_dec));
  1650. }
  1651. } else {
  1652. if (strpos($range, '*') !== false) {
  1653. $lower = str_replace('*', '0', $range);
  1654. $upper = str_replace('*', '255', $range);
  1655. $range = "$lower-$upper";
  1656. }
  1657. if (strpos($range, '-') !== false) {
  1658. list($lower, $upper) = explode('-', $range, 2);
  1659. $lower_dec = (float)sprintf("%u", ip2long($lower));
  1660. $upper_dec = (float)sprintf("%u", ip2long($upper));
  1661. $ip_dec = (float)sprintf("%u", ip2long($ip));
  1662. return (($ip_dec >= $lower_dec) && ($ip_dec <= $upper_dec));
  1663. }
  1664. return false;
  1665. }
  1666. }
  1667. /**
  1668. * php://input 字符串解析到变量并获取指定值
  1669. * @param $key
  1670. * @return array
  1671. */
  1672. public static function getContentsParse($key)
  1673. {
  1674. parse_str(Request::getContent(), $input);
  1675. if ($key) {
  1676. $input = isset($input[$key])?$input[$key]:array();
  1677. }
  1678. return is_array($input)?$input:array($input);
  1679. }
  1680. /**
  1681. * 多维 array_values
  1682. * @param $array
  1683. * @param string $keyName
  1684. * @param string $valName
  1685. * @return array
  1686. */
  1687. public static function array_values_recursive($array, $keyName = 'key', $valName = 'item') {
  1688. if (is_array($array) && count($array) > 0) {
  1689. $temp = [];
  1690. foreach ($array as $key => $value) {
  1691. $continue = false;
  1692. if (is_array($value) && count($value) > 0) {
  1693. $continue = true;
  1694. foreach ($value AS $item) {
  1695. if (!is_array($item)) {
  1696. $continue = false;
  1697. break;
  1698. }
  1699. }
  1700. }
  1701. $temp[] = [
  1702. $keyName => $key,
  1703. $valName => $continue ? self::array_values_recursive($value, $keyName, $valName) : $value,
  1704. ];
  1705. }
  1706. return $temp;
  1707. }
  1708. return $array;
  1709. }
  1710. /**
  1711. * 获取tonken
  1712. * @return string
  1713. */
  1714. public static function getToken()
  1715. {
  1716. global $_A;
  1717. if (!isset($_A["__static_token"])) {
  1718. $_A["__static_token"] = Base::nullShow(Request::header('token'), Request::input('token'));
  1719. }
  1720. return $_A["__static_token"];
  1721. }
  1722. /**
  1723. * 设置tonken
  1724. * @param $token
  1725. */
  1726. public static function setToken($token)
  1727. {
  1728. global $_A;
  1729. $_A["__static_token"] = $token;
  1730. }
  1731. /**
  1732. * 是否微信
  1733. * @return bool
  1734. */
  1735. public static function isWechat()
  1736. {
  1737. return strpos(Request::server('HTTP_USER_AGENT'), 'MicroMessenger') !== false;
  1738. }
  1739. /**
  1740. * 获取浏览器类型
  1741. * @return string
  1742. */
  1743. public static function browser()
  1744. {
  1745. $user_agent = Request::server('HTTP_USER_AGENT');
  1746. if (strpos($user_agent, 'AlipayClient') !== false) {
  1747. return 'alipay';
  1748. }elseif (strpos($user_agent, 'MicroMessenger') !== false) {
  1749. return 'weixin';
  1750. }else{
  1751. return 'none';
  1752. }
  1753. }
  1754. /**
  1755. * 返回根据距离sql排序语句
  1756. * @param $lat
  1757. * @param $lng
  1758. * @param string $latName
  1759. * @param string $lngName
  1760. * @return string
  1761. */
  1762. public static function acos($lat , $lng, $latName = 'lat', $lngName = 'lng') {
  1763. $lat = floatval($lat);
  1764. $lng = floatval($lng);
  1765. return 'ACOS(
  1766. SIN(('.$lat.' * 3.1415) / 180) * SIN(('.$latName.' * 3.1415) / 180) + COS(('.$lat.' * 3.1415) / 180) * COS(('.$latName.' * 3.1415) / 180) * COS(
  1767. ('.$lng.' * 3.1415) / 180 - ('.$lngName.' * 3.1415) / 180
  1768. )
  1769. ) * 6380';
  1770. }
  1771. /**
  1772. * 获取分页详细信息
  1773. * @param LengthAwarePaginator $lists
  1774. * @param bool $getTotal
  1775. * @return array
  1776. */
  1777. public static function getPageInfo(LengthAwarePaginator $lists, $getTotal = true)
  1778. {
  1779. return [
  1780. "currentPage" => $lists->currentPage(),
  1781. "firstItem" => $lists->firstItem(),
  1782. "hasMorePages" => $lists->hasMorePages(),
  1783. "lastItem" => $lists->lastItem(),
  1784. "lastPage" => $lists->lastPage(),
  1785. "nextPageUrl" => $lists->nextPageUrl(),
  1786. "previousPageUrl" => $lists->previousPageUrl(),
  1787. "perPage" => $lists->perPage(),
  1788. "total" => $getTotal === true ? $lists->total() : -1,
  1789. ];
  1790. }
  1791. /**
  1792. * 获取分页数据
  1793. * @param $lists
  1794. * @param bool $getTotal
  1795. * @return array
  1796. */
  1797. public static function getPageList($lists, $getTotal = true)
  1798. {
  1799. $data = Base::getPageInfo($lists, $getTotal);
  1800. $data['lists'] = Base::coll2array($lists);
  1801. return $data;
  1802. }
  1803. /**
  1804. * 上传文件
  1805. * @param array $param [ type=[文件类型], file=>Request::file, path=>文件路径, fileName=>文件名称, scale=>[压缩原图宽,高, 压缩方式], size=>限制大小KB, autoThumb=>false不要自动生成缩略图 ]
  1806. * @return array [name=>原文件名, size=>文件大小(单位KB),file=>绝对地址, path=>相对地址, url=>全路径地址, ext=>文件后缀名]
  1807. */
  1808. public static function upload($param)
  1809. {
  1810. $file = $param['file'];
  1811. if (empty($file)) {
  1812. return Base::retError("您没有选择要上传的文件!");
  1813. }
  1814. if($file->isValid()){
  1815. Base::makeDir(public_path($param['path']));
  1816. //
  1817. switch ($param['type']) {
  1818. case 'png':
  1819. $type = ['png'];
  1820. break;
  1821. case 'png+jpg':
  1822. $type = ['jpg', 'jpeg', 'png'];
  1823. break;
  1824. case 'image':
  1825. $type = ['jpg', 'jpeg', 'gif', 'png'];
  1826. break;
  1827. case 'video':
  1828. $type = ['rm', 'rmvb', 'wmv', 'avi', 'mpg', 'mpeg', 'mp4'];
  1829. break;
  1830. case 'audio':
  1831. $type = ['mp3', 'wma', 'wav', 'amr'];
  1832. break;
  1833. case 'excel':
  1834. $type = ['xls', 'xlsx'];
  1835. break;
  1836. case 'app':
  1837. $type = ['apk'];
  1838. break;
  1839. case 'zip':
  1840. $type = ['zip'];
  1841. break;
  1842. case 'file':
  1843. $type = ['jpg', 'jpeg', 'png', 'gif', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'esp'];
  1844. break;
  1845. default:
  1846. return Base::retError('错误的类型参数');
  1847. }
  1848. $extension = strtolower($file->getClientOriginalExtension());
  1849. if ($type && is_array($type) && !in_array($extension, $type)) {
  1850. return Base::retError(['文件格式错误,限制类型:%!', implode(",", $type)]);
  1851. }
  1852. try {
  1853. $fileSize = $file->getSize();
  1854. if ($param['size'] > 0 && $fileSize > $param['size'] * 1024) {
  1855. return Base::retError(['文件大小超限,最大限制:%KB!', $param['size']]);
  1856. }
  1857. } catch (Exception $e) {
  1858. $fileSize = 0;
  1859. }
  1860. $scaleName = "";
  1861. if ($param['fileName']) {
  1862. $fileName = $param['fileName'];
  1863. }else{
  1864. if ($param['scale'] && is_array($param['scale'])) {
  1865. list($width, $height) = $param['scale'];
  1866. if ($width > 0 || $height > 0) {
  1867. $scaleName = "_{WIDTH}x{HEIGHT}";
  1868. if (isset($param['scale'][2])) {
  1869. $scaleName.= $param['scale'][2];
  1870. }
  1871. }
  1872. }
  1873. $fileName = md5_file($file) . '.' . $extension;
  1874. $scaleName = md5_file($file) . $scaleName . '.' . $extension;
  1875. }
  1876. //
  1877. $file->move(public_path($param['path']), $fileName);
  1878. //
  1879. $array = [
  1880. "name" => $file->getClientOriginalName(), //原文件名
  1881. "size" => Base::twoFloat($fileSize / 1024, true), //大小KB
  1882. "file" => public_path($param['path'].$fileName), //目录的完整路径 "D:\www....KzZ.jpg"
  1883. "path" => $param['path'].$fileName, //相对路径 "uploads/pic....KzZ.jpg"
  1884. "url" => Base::fillUrl($param['path'].$fileName), //完整的URL "https://.....hhsKzZ.jpg"
  1885. "thumb" => '', //缩略图(预览图) "https://.....hhsKzZ.jpg_thumb.jpg"
  1886. "width" => -1, //图片宽度
  1887. "height" => -1, //图片高度
  1888. "ext" => $extension, //文件后缀名
  1889. ];
  1890. if (!is_file($array['file'])) {
  1891. return Base::retError('上传失败!');
  1892. }
  1893. //iOS照片颠倒处理
  1894. if (in_array($extension, ['jpg', 'jpeg']) && function_exists('exif_read_data')) {
  1895. $data = imagecreatefromstring(file_get_contents($array['file']));
  1896. $exif = @exif_read_data($array['file']);
  1897. if (!empty($exif['Orientation'])) {
  1898. switch ($exif['Orientation']) {
  1899. case 8:
  1900. $data = imagerotate($data, 90, 0);
  1901. break;
  1902. case 3:
  1903. $data = imagerotate($data, 180, 0);
  1904. break;
  1905. case 6:
  1906. $data = imagerotate($data, -90, 0);
  1907. break;
  1908. default:
  1909. $data = null;
  1910. break;
  1911. }
  1912. if ($data !== null) {
  1913. imagejpeg($data, $array['file']);
  1914. }
  1915. }
  1916. }
  1917. //
  1918. if (in_array($param['type'], ['png', 'png+jpg', 'image'])) {
  1919. //图片尺寸
  1920. $paramet = getimagesize($array['file']);
  1921. $array['width'] = $paramet[0];
  1922. $array['height'] = $paramet[1];
  1923. //原图压缩
  1924. if ($param['scale'] && is_array($param['scale'])) {
  1925. list($width, $height) = $param['scale'];
  1926. if (($width > 0 && $array['width'] > $width) || ($height > 0 && $array['height'] > $height)) {
  1927. $cut = ($width > 0 && $height > 0) ? 1 : -1;
  1928. $cut = $param['scale'][2] ?? $cut;
  1929. //图片压缩
  1930. $tmpFile = $array['file'] . '_tmp.jpg';
  1931. if (Base::imgThumb($array['file'], $tmpFile, $width, $height, $cut)) {
  1932. $tmpSize = filesize($tmpFile);
  1933. if ($tmpSize > $fileSize) {
  1934. @unlink($tmpFile);
  1935. }else{
  1936. @unlink($array['file']);
  1937. rename($tmpFile, $array['file']);
  1938. }
  1939. }
  1940. //图片尺寸
  1941. $paramet = getimagesize($array['file']);
  1942. $array['width'] = $paramet[0];
  1943. $array['height'] = $paramet[1];
  1944. //重命名
  1945. if ($scaleName) {
  1946. $scaleName = str_replace(['{WIDTH}', '{HEIGHT}'], [$array['width'], $array['height']], $scaleName);
  1947. if (rename($array['file'], Base::rightDelete($array['file'], $fileName) . $scaleName)) {
  1948. $array['file'] = Base::rightDelete($array['file'], $fileName) . $scaleName;
  1949. $array['path'] = Base::rightDelete($array['path'], $fileName) . $scaleName;
  1950. $array['url'] = Base::rightDelete($array['url'], $fileName) . $scaleName;
  1951. }
  1952. }
  1953. }
  1954. }
  1955. //生成缩略图
  1956. $array['thumb'] = $array['path'];
  1957. if ($param['autoThumb'] === "false") $param['autoThumb'] = false;
  1958. if ($param['autoThumb'] !== false) {
  1959. if (Base::imgThumb($array['file'], $array['file']."_thumb.jpg", 180, 0)) {
  1960. $array['thumb'].= "_thumb.jpg";
  1961. }
  1962. }
  1963. $array['thumb'] = Base::fillUrl($array['thumb']);
  1964. }
  1965. //
  1966. return Base::retSuccess('success', $array);
  1967. }else{
  1968. return Base::retError($file->getErrorMessage());
  1969. }
  1970. }
  1971. /**
  1972. * 生成缩略图
  1973. * @param string $src_img 源图绝对完整地址{带文件名及后缀名}
  1974. * @param string $dst_img 目标图绝对完整地址{带文件名及后缀名}
  1975. * @param int $width 缩略图宽{0:此时目标高度不能为0,目标宽度为源图宽*(目标高度/源图高)}
  1976. * @param int $height 缩略图高{0:此时目标宽度不能为0,目标高度为源图高*(目标宽度/源图宽)}
  1977. * @param int $cut 是否裁切{宽,高必须非0}:1是、0否、-1或'auto'保持等比
  1978. * @param int $proportion 缩放{0:不缩放, 0<this<1:缩放到相应比例(此时宽高限制和裁切均失效)}
  1979. * @return bool
  1980. */
  1981. public static function imgThumb($src_img, $dst_img, $width = 75, $height = 75, $cut = 0, $proportion = 0)
  1982. {
  1983. if (!is_file($src_img)) {
  1984. return false;
  1985. }
  1986. if (empty($dst_img)) {
  1987. $dst_img = $src_img;
  1988. }
  1989. $st = pathinfo($src_img, PATHINFO_EXTENSION);
  1990. if (!in_array(strtolower($st), array('jpg', 'jpeg', 'png', 'gif', 'bmp'))) {
  1991. return false;
  1992. }
  1993. $ot = pathinfo($dst_img, PATHINFO_EXTENSION);
  1994. $otfunc = 'image' . ($ot == 'jpg' ? 'jpeg' : $ot);
  1995. $srcinfo = getimagesize($src_img);
  1996. $src_w = $srcinfo[0];
  1997. $src_h = $srcinfo[1];
  1998. $type = strtolower(substr(image_type_to_extension($srcinfo[2]), 1));
  1999. if (empty($type)) {
  2000. return false;
  2001. }
  2002. $createfun = 'imagecreatefrom' . ($type == 'jpg' ? 'jpeg' : $type);
  2003. $dst_h = $height;
  2004. $dst_w = $width;
  2005. $x = $y = 0;
  2006. /**
  2007. * 缩略图不超过源图尺寸(前提是宽或高只有一个)
  2008. */
  2009. if (($width > $src_w && $height > $src_h) || ($height > $src_h && $width == 0) || ($width > $src_w && $height == 0)) {
  2010. $proportion = 1;
  2011. }
  2012. if ($width > $src_w) {
  2013. $dst_w = $width = $src_w;
  2014. }
  2015. if ($height > $src_h) {
  2016. $dst_h = $height = $src_h;
  2017. }
  2018. if (!$width && !$height && !$proportion) {
  2019. return false;
  2020. }
  2021. if (!$proportion) {
  2022. if ($cut == 'auto' || $cut == -1) {
  2023. if ($dst_w && $dst_h) {
  2024. $wB = $dst_w / $src_w;
  2025. $hB = $dst_h / $src_h;
  2026. if ($wB > $hB) {
  2027. $dst_w = 0;
  2028. }else{
  2029. $dst_h = 0;
  2030. }
  2031. }
  2032. $cut = 0;
  2033. }
  2034. if ($cut == 0) {
  2035. if ($dst_w && $dst_h) {
  2036. if ($dst_w / $src_w > $dst_h / $src_h) {
  2037. $dst_w = $src_w * ($dst_h / $src_h);
  2038. $x = 0 - ($dst_w - $width) / 2;
  2039. } else {
  2040. $dst_h = $src_h * ($dst_w / $src_w);
  2041. $y = 0 - ($dst_h - $height) / 2;
  2042. }
  2043. } else if ($dst_w xor $dst_h) {
  2044. if ($dst_w && !$dst_h) //有宽无高
  2045. {
  2046. $propor = $dst_w / $src_w;
  2047. $height = $dst_h = $src_h * $propor;
  2048. } else if (!$dst_w && $dst_h) //有高无宽
  2049. {
  2050. $propor = $dst_h / $src_h;
  2051. $width = $dst_w = $src_w * $propor;
  2052. }
  2053. }
  2054. } else {
  2055. if (!$dst_h) //裁剪时无高
  2056. {
  2057. $height = $dst_h = $dst_w;
  2058. }
  2059. if (!$dst_w) //裁剪时无宽
  2060. {
  2061. $width = $dst_w = $dst_h;
  2062. }
  2063. $propor = min(max($dst_w / $src_w, $dst_h / $src_h), 1);
  2064. $dst_w = (int)round($src_w * $propor);
  2065. $dst_h = (int)round($src_h * $propor);
  2066. $x = ($width - $dst_w) / 2;
  2067. $y = ($height - $dst_h) / 2;
  2068. }
  2069. } else {
  2070. $proportion = min($proportion, 1);
  2071. $height = $dst_h = $src_h * $proportion;
  2072. $width = $dst_w = $src_w * $proportion;
  2073. }
  2074. if (!function_exists($createfun)) {
  2075. return false;
  2076. }
  2077. $src = $createfun($src_img);
  2078. $dst = imagecreatetruecolor($width ? $width : $dst_w, $height ? $height : $dst_h);
  2079. try {
  2080. $white = imagecolorallocate($dst, 255, 255, 255);
  2081. imagefill($dst, 0, 0, $white);
  2082. } catch (Exception $e) {
  2083. }
  2084. if (function_exists('imagecopyresampled')) {
  2085. imagecopyresampled($dst, $src, $x, $y, 0, 0, $dst_w, $dst_h, $src_w, $src_h);
  2086. } else {
  2087. imagecopyresized($dst, $src, $x, $y, 0, 0, $dst_w, $dst_h, $src_w, $src_h);
  2088. }
  2089. $otfunc($dst, $dst_img);
  2090. imagedestroy($dst);
  2091. imagedestroy($src);
  2092. return true;
  2093. }
  2094. /**
  2095. * 排列组合(无重复)
  2096. * @param $arr
  2097. * @param $m
  2098. * @return array
  2099. */
  2100. public static function getCombinationToString($arr, $m)
  2101. {
  2102. $result = [];
  2103. if ($m == 1) {
  2104. return $arr;
  2105. }
  2106. if ($m == count($arr)) {
  2107. $result[] = implode(',', $arr);
  2108. return $result;
  2109. }
  2110. $temp_firstelement = $arr[0];
  2111. unset($arr[0]);
  2112. $arr = array_values($arr);
  2113. $temp_list1 = self::getCombinationToString($arr, ($m - 1));
  2114. foreach ($temp_list1 as $s) {
  2115. $s = $temp_firstelement . ',' . $s;
  2116. $result[] = $s;
  2117. }
  2118. unset($temp_list1);
  2119. $temp_list2 = self::getCombinationToString($arr, $m);
  2120. foreach ($temp_list2 as $s) {
  2121. $result[] = $s;
  2122. }
  2123. unset($temp_list2);
  2124. return $result;
  2125. }
  2126. /**
  2127. * 不同元素交叉组合(多个数组)
  2128. * @return array
  2129. */
  2130. public static function getNewArray()
  2131. {
  2132. $args = func_get_args();
  2133. $pailie = function ($arr1, $arr2) {
  2134. $arr = [];
  2135. $k = 0;
  2136. foreach ($arr1 as $k1 => $v1) {
  2137. foreach ($arr2 as $k2 => $v2) {
  2138. $arr[$k] = $v1 . "," . $v2;
  2139. $k++;
  2140. }
  2141. }
  2142. return $arr;
  2143. };
  2144. $arr = [];
  2145. foreach ($args as $k => $v) {
  2146. if (isset($args[$k + 1]) && $args[$k + 1]) {
  2147. switch ($k) {
  2148. case 0:
  2149. $arr[$k] = $pailie($v, $args[$k + 1]);
  2150. break;
  2151. default:
  2152. $arr[$k] = $pailie($arr[$k - 1], $args[$k + 1]);
  2153. break;
  2154. }
  2155. }
  2156. }
  2157. $key = count($arr) - 1;
  2158. return array_values($arr[$key]);
  2159. }
  2160. /**
  2161. * 获取当前是本月第几个星期
  2162. * @return false|float
  2163. */
  2164. public static function getMonthWeek()
  2165. {
  2166. $time = strtotime(date("Y-m-01"));
  2167. $w = date('w', $time);
  2168. $j = date("j");
  2169. return ceil(($j + $w) / 7);
  2170. }
  2171. /**
  2172. * 把返回的数据集转换成Tree
  2173. * @param array $list 要转换的数据集
  2174. * @param string $pk id标记字段
  2175. * @param string $pid parent标记字段
  2176. * @param string $child 生成子类字段
  2177. * @param int $root
  2178. * @return array
  2179. */
  2180. public static function list2Tree($list, $pk='id', $pid = 'pid', $child = 'children', $root = 0) {
  2181. if (!is_array($list)) {
  2182. return [];
  2183. }
  2184. // 创建基于主键的数组引用
  2185. $aRefer = [];
  2186. foreach ($list as $key => $data) {
  2187. $list[$key][$child] = [];
  2188. $aRefer[$data[$pk]] = & $list[$key];
  2189. }
  2190. $tree = [];
  2191. foreach ($list as $key => $data) {
  2192. // 判断是否存在parent
  2193. $parentId = $data[$pid];
  2194. if ($root === $parentId) {
  2195. $tree[] = & $list[$key];
  2196. } else {
  2197. if (isset($aRefer[$parentId])) {
  2198. $parent = & $aRefer[$parentId];
  2199. $parent[$child][] = & $list[$key];
  2200. }
  2201. }
  2202. }
  2203. return $tree;
  2204. }
  2205. /**
  2206. * 遍历获取文件
  2207. * @param $dir
  2208. * @return array
  2209. */
  2210. public static function readDir($dir)
  2211. {
  2212. $files = array();
  2213. $dir_list = scandir($dir);
  2214. foreach ($dir_list as $file) {
  2215. if ($file != '..' && $file != '.') {
  2216. if (is_dir($dir . '/' . $file)) {
  2217. $files = array_merge($files, self::readDir($dir . '/' . $file));
  2218. } else {
  2219. $files[] = $dir . "/" . $file;
  2220. }
  2221. }
  2222. }
  2223. return $files;
  2224. }
  2225. /**
  2226. * 获取中文字符拼音首字母
  2227. * @param $str
  2228. * @return string
  2229. */
  2230. public static function getFirstCharter($str)
  2231. {
  2232. if (empty($str)) {
  2233. return '';
  2234. }
  2235. $fchar = ord($str[0]);
  2236. if ($fchar >= ord('A') && $fchar <= ord('z')) return strtoupper($str[0]);
  2237. $s1 = iconv('UTF-8', 'gb2312', $str);
  2238. $s2 = iconv('gb2312', 'UTF-8', $s1);
  2239. $s = $s2 == $str ? $s1 : $str;
  2240. $asc = ord($s[0]) * 256 + ord($s[1]) - 65536;
  2241. if ($asc >= -20319 && $asc <= -20284) return 'A';
  2242. if ($asc >= -20283 && $asc <= -19776) return 'B';
  2243. if ($asc >= -19775 && $asc <= -19219) return 'C';
  2244. if ($asc >= -19218 && $asc <= -18711) return 'D';
  2245. if ($asc >= -18710 && $asc <= -18527) return 'E';
  2246. if ($asc >= -18526 && $asc <= -18240) return 'F';
  2247. if ($asc >= -18239 && $asc <= -17923) return 'G';
  2248. if ($asc >= -17922 && $asc <= -17418) return 'H';
  2249. if ($asc >= -17417 && $asc <= -16475) return 'J';
  2250. if ($asc >= -16474 && $asc <= -16213) return 'K';
  2251. if ($asc >= -16212 && $asc <= -15641) return 'L';
  2252. if ($asc >= -15640 && $asc <= -15166) return 'M';
  2253. if ($asc >= -15165 && $asc <= -14923) return 'N';
  2254. if ($asc >= -14922 && $asc <= -14915) return 'O';
  2255. if ($asc >= -14914 && $asc <= -14631) return 'P';
  2256. if ($asc >= -14630 && $asc <= -14150) return 'Q';
  2257. if ($asc >= -14149 && $asc <= -14091) return 'R';
  2258. if ($asc >= -14090 && $asc <= -13319) return 'S';
  2259. if ($asc >= -13318 && $asc <= -12839) return 'T';
  2260. if ($asc >= -12838 && $asc <= -12557) return 'W';
  2261. if ($asc >= -12556 && $asc <= -11848) return 'X';
  2262. if ($asc >= -11847 && $asc <= -11056) return 'Y';
  2263. if ($asc >= -11055 && $asc <= -10247) return 'Z';
  2264. return '#';
  2265. }
  2266. /**
  2267. * 缓存数据
  2268. * @param $title
  2269. * @param null $value
  2270. * @return mixed|null
  2271. */
  2272. public static function cacheData($title, $value = null)
  2273. {
  2274. $title = "cacheData::" . $title;
  2275. $tmp = DB::table('tmp')->where('title', $title)->select('value')->first();
  2276. if ($value !== null ) {
  2277. if (empty($tmp)) {
  2278. DB::table('tmp')->insert(['title'=>$title, 'value'=>$value]);
  2279. }else{
  2280. DB::table('tmp')->where('title', $title)->update(['value'=>$value]);
  2281. }
  2282. return $value;
  2283. }else{
  2284. return $tmp->value;
  2285. }
  2286. }
  2287. }