Base.php 73 KB

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