Base.php 69 KB

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