Base.php 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188
  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. * JSON返回
  1100. * @param $param
  1101. * @return string
  1102. */
  1103. public static function jsonEcho($param)
  1104. {
  1105. global $_GPC;
  1106. //
  1107. $json = json_encode($param);
  1108. $callback = $_GPC['callback'];
  1109. if ($callback) {
  1110. return $callback . '(' . $json . ')';
  1111. } else {
  1112. return $json;
  1113. }
  1114. }
  1115. /**
  1116. * 数组返回 正确
  1117. * @param $msg
  1118. * @param array $data
  1119. * @param int $ret
  1120. * @return array
  1121. */
  1122. public static function retSuccess($msg, $data = [], $ret = 1)
  1123. {
  1124. return array(
  1125. 'ret' => $ret,
  1126. 'msg' => $msg,
  1127. 'data' => $data
  1128. );
  1129. }
  1130. /**
  1131. * 数组返回 错误
  1132. * @param $msg
  1133. * @param array $data
  1134. * @param int $ret
  1135. * @return array
  1136. */
  1137. public static function retError($msg, $data = [], $ret = 0)
  1138. {
  1139. return array(
  1140. 'ret' => $ret,
  1141. 'msg' => $msg,
  1142. 'data' => $data
  1143. );
  1144. }
  1145. /**
  1146. * Ajax 错误返回
  1147. * @param $msg
  1148. * @param array $data
  1149. * @param int $ret
  1150. * @return array|void
  1151. */
  1152. public static function ajaxError($msg, $data = [], $ret = 0)
  1153. {
  1154. if (Request::input('__Access-Control-Allow-Origin') || Request::header('Content-Type') === 'application/json' || Request::header('platform')) {
  1155. return Base::retError($msg, $data, $ret);
  1156. }else{
  1157. return abort(404);
  1158. }
  1159. }
  1160. /**
  1161. * JSON返回 正确
  1162. * @param $msg
  1163. * @param array $data
  1164. * @param int $ret
  1165. * @return string
  1166. */
  1167. public static function jsonSuccess($msg, $data = [], $ret = 1)
  1168. {
  1169. return Base::jsonEcho(Base::retSuccess($msg, $data, $ret));
  1170. }
  1171. /**
  1172. * JSON返回 错误
  1173. * @param $msg
  1174. * @param array $data
  1175. * @param int $ret
  1176. * @return string
  1177. */
  1178. public static function jsonError($msg, $data = [], $ret = 0)
  1179. {
  1180. return Base::jsonEcho(Base::retError($msg, $data, $ret));
  1181. }
  1182. /**
  1183. * 是否错误
  1184. * @param $param
  1185. * @return bool
  1186. */
  1187. public static function isError($param)
  1188. {
  1189. return intval($param['ret']) <= 0;
  1190. }
  1191. /**
  1192. * 异常模板
  1193. * @param $msg
  1194. * @param bool $catch
  1195. * @return bool
  1196. */
  1197. public static function Exce($msg, $catch = false)
  1198. {
  1199. if ($catch === false) {
  1200. return "{{ExceMsg:".$msg.":ExceMsg}}";
  1201. }else{
  1202. if (Base::strExists($msg . "", "{{ExceMsg:") && Base::strExists($msg . "", ":ExceMsg}}")) {
  1203. $msg = Base::getMiddle($msg, "{{ExceMsg:", ":ExceMsg}}");
  1204. $catch = $msg?$msg:$catch;
  1205. }
  1206. return $catch;
  1207. }
  1208. }
  1209. /**
  1210. * 获取数组的第几个值
  1211. * @param $arr
  1212. * @param int $i
  1213. * @return array
  1214. */
  1215. public static function getArray($arr, $i = 1)
  1216. {
  1217. $array = [];
  1218. $j = 1;
  1219. foreach ($arr AS $item) {
  1220. $array[] = $item;
  1221. if ($i >= $j) {
  1222. break;
  1223. }
  1224. $j++;
  1225. }
  1226. return $array;
  1227. }
  1228. /**
  1229. * 小时转天/小时
  1230. * @param $hour
  1231. * @return string
  1232. */
  1233. public static function forumHourDay($hour)
  1234. {
  1235. $hour = intval($hour);
  1236. if ($hour > 24) {
  1237. $day = floor($hour / 24);
  1238. $hour-= $day * 24;
  1239. return $day.'天'.$hour.'小时';
  1240. }
  1241. return $hour.'小时';
  1242. }
  1243. /**
  1244. * 时间格式化
  1245. * @param $date
  1246. * @return false|string
  1247. */
  1248. public static function forumDate($date)
  1249. {
  1250. $dur = time() - $date;
  1251. if ($date > strtotime(date("Y-m-d"))) {
  1252. //今天
  1253. if ($dur < 60) {
  1254. return max($dur, 1) . '秒前';
  1255. } elseif ($dur < 3600) {
  1256. return floor($dur / 60) . '分钟前';
  1257. } elseif ($dur < 86400) {
  1258. return floor($dur / 3600) . '小时前';
  1259. } else {
  1260. return date("H:i", $date);
  1261. }
  1262. } elseif ($date > strtotime(date("Y-m-d", strtotime("-1 day")))) {
  1263. //昨天
  1264. return '昨天';
  1265. } elseif ($date > strtotime(date("Y-m-d", strtotime("-2 day")))) {
  1266. //前天
  1267. return '前天';
  1268. } elseif ($dur > 86400) {
  1269. //x天前
  1270. return floor($dur / 86400) . '天前';
  1271. }
  1272. return date("Y-m-d", $date);
  1273. }
  1274. /**
  1275. * 获取时间戳今天的第一秒时间戳
  1276. * @param $time
  1277. * @return false|int
  1278. */
  1279. public static function dayTimeF($time)
  1280. {
  1281. return strtotime(date("Y-m-d 00:00:00", self::isNumber($time) ? $time : strtotime($time)));
  1282. }
  1283. /**
  1284. * 获取时间戳今天的最后一秒时间戳
  1285. * @param $time
  1286. * @return false|int
  1287. */
  1288. public static function dayTimeE($time)
  1289. {
  1290. return strtotime(date("Y-m-d 23:59:59", self::isNumber($time) ? $time : strtotime($time)));
  1291. }
  1292. /**
  1293. * 用户名、邮箱、手机账号、银行卡号中间字符串以*隐藏
  1294. * @param $str
  1295. * @return mixed|string
  1296. */
  1297. public static function cardFormat($str)
  1298. {
  1299. if (strpos($str, '@')) {
  1300. $email_array = explode("@", $str);
  1301. $prevfix = (strlen($email_array[0]) < 4) ? "" : substr($str, 0, 3); //邮箱前缀
  1302. $count = 0;
  1303. $str = preg_replace('/([\d\w+_-]{0,100})@/', '***@', $str, -1, $count);
  1304. return $prevfix . $str;
  1305. }
  1306. if (Base::isMobile($str)) {
  1307. return substr($str, 0, 3) . "****" . substr($str, -4);
  1308. }
  1309. $pattern = '/([\d]{4})([\d]{4})([\d]{4})([\d]{4})([\d]{0,})?/i';
  1310. if (preg_match($pattern, $str)) {
  1311. return preg_replace($pattern, '$1 **** **** **** $5', $str);
  1312. }
  1313. $pattern = '/([\d]{4})([\d]{4})([\d]{4})([\d]{0,})?/i';
  1314. if (preg_match($pattern, $str)) {
  1315. return preg_replace($pattern, '$1 **** **** $4', $str);
  1316. }
  1317. $pattern = '/([\d]{4})([\d]{4})([\d]{0,})?/i';
  1318. if (preg_match($pattern, $str)) {
  1319. return preg_replace($pattern, '$1 **** $3', $str);
  1320. }
  1321. return substr($str, 0, 3) . "***" . substr($str, -1);
  1322. }
  1323. /**
  1324. * 数字每4位加一空格
  1325. * @param $str
  1326. * @param string $interval
  1327. * @return string
  1328. */
  1329. public static function fourFormat($str, $interval = " ")
  1330. {
  1331. if (!is_numeric($str)) return $str;
  1332. //
  1333. $text = '';
  1334. for ($i = 0; $i < strlen($str); $i++) {
  1335. $text .= $str[$i];
  1336. if ($i % 4 == 3) {
  1337. $text .= $interval;
  1338. }
  1339. }
  1340. return $text;
  1341. }
  1342. /**
  1343. * 保留两位小数点
  1344. * @param $str
  1345. * @param bool $float
  1346. * @return float
  1347. */
  1348. public static function twoFloat($str, $float = false)
  1349. {
  1350. $str = sprintf("%.2f", floatval($str));
  1351. if ($float === true) {
  1352. $str = floatval($str);
  1353. }
  1354. return $str;
  1355. }
  1356. /**
  1357. * 获取时间戳
  1358. * @param bool $refresh
  1359. * @return int
  1360. */
  1361. public static function time($refresh = false)
  1362. {
  1363. global $_A;
  1364. if (!isset($_A["__static_time"]) || $refresh === true) {
  1365. $_A["__static_time"] = time();
  1366. }
  1367. return $_A["__static_time"];
  1368. }
  1369. /**
  1370. * 获取毫秒时间戳
  1371. * @return float
  1372. */
  1373. public static function msecTime()
  1374. {
  1375. list($msec, $sec) = explode(' ', microtime());
  1376. $time = explode(".", $sec . ($msec * 1000));
  1377. return $time[0];
  1378. }
  1379. /**
  1380. * 时间差(不够1个小时算一个小时)
  1381. * @param int $s 开始时间戳
  1382. * @param int $e 结束时间戳
  1383. * @return string
  1384. */
  1385. public static function timeDiff($s, $e)
  1386. {
  1387. $d = $e - $s;
  1388. if ($d > 86400) {
  1389. $day = floor($d / 86400);
  1390. $hour = ceil(($d - ($day * 86400)) / 3600);
  1391. if ($hour > 0) {
  1392. return $day . '天' . $hour . '小时';
  1393. } else {
  1394. return $day . '天';
  1395. }
  1396. } elseif ($d > 3600) {
  1397. return ceil($d / 3600) . '小时';
  1398. } elseif ($d > 60) {
  1399. return ceil($d / 60) . '分钟';
  1400. } elseif ($d > 1) {
  1401. return '1分钟内';
  1402. } else {
  1403. return '0秒';
  1404. }
  1405. }
  1406. /**
  1407. * 获取IP地址
  1408. * @return string
  1409. */
  1410. public static function getIp()
  1411. {
  1412. global $_A;
  1413. if (!isset($_A["__static_ip"])) {
  1414. if (getenv('HTTP_CLIENT_IP') and strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
  1415. $onlineip = getenv('HTTP_CLIENT_IP');
  1416. } elseif (getenv('HTTP_X_FORWARDED_FOR') and strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
  1417. $onlineip = getenv('HTTP_X_FORWARDED_FOR');
  1418. } elseif (getenv('REMOTE_ADDR') and strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
  1419. $onlineip = getenv('REMOTE_ADDR');
  1420. } elseif (isset($_SERVER['REMOTE_ADDR']) and $_SERVER['REMOTE_ADDR'] and strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
  1421. $onlineip = $_SERVER['REMOTE_ADDR'];
  1422. } elseif (Request::header('X-Real-IP-Swoole-Y3MTXN')) {
  1423. $onlineip = Request::header('X-Real-IP-Swoole-Y3MTXN');
  1424. } else {
  1425. $onlineip = '0,0,0,0';
  1426. }
  1427. preg_match("/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/", $onlineip, $match);
  1428. $_A["__static_ip"] = $match[0] ? $match[0] : 'unknown';
  1429. }
  1430. return $_A["__static_ip"];
  1431. }
  1432. /**
  1433. * 获取IP地址
  1434. * @param string $ip
  1435. * @return array|mixed
  1436. */
  1437. public static function getIpInfo($ip = '')
  1438. {
  1439. if (empty($ip)) {
  1440. $ip = self::getIp();
  1441. }
  1442. $cacheKey = "getIpInfo::" . md5($ip);
  1443. $result = Cache::rememberForever($cacheKey, function() use ($ip) {
  1444. return Ihttp::ihttp_request("http://ip.taobao.com/service/getIpInfo.php?ip=" . $ip, [], [], 8);
  1445. });
  1446. if (Base::isError($result)) {
  1447. return $result;
  1448. }
  1449. $data = json_decode($result['data'], true);
  1450. if (!is_array($data) || intval($data['code']) != 0) {
  1451. Cache::forget($cacheKey);
  1452. return Base::retError("error ip: -1");
  1453. }
  1454. $data = $data['data'];
  1455. if (!is_array($data) || !isset($data['country'])) {
  1456. return Base::retError("error ip: -2");
  1457. }
  1458. $data['text'] = $data['country'];
  1459. $data['textSmall'] = $data['country'];
  1460. if ($data['region'] && $data['region'] != $data['country'] && $data['region'] != "XX") {
  1461. $data['text'].= " " . $data['region'];
  1462. $data['textSmall'] = $data['region'];
  1463. }
  1464. if ($data['city'] && $data['city'] != $data['region'] && $data['city'] != "XX") {
  1465. $data['text'].= " " . $data['city'];
  1466. $data['textSmall'].= " " . $data['city'];
  1467. }
  1468. if ($data['county'] && $data['county'] != $data['city'] && $data['county'] != "XX") {
  1469. $data['text'].= " " . $data['county'];
  1470. $data['textSmall'].= " " . $data['county'];
  1471. }
  1472. return Base::retSuccess("success", $data);
  1473. }
  1474. /**
  1475. * 是否是中国IP:-1错误、1是、0否
  1476. * @param string $ip
  1477. * @return int
  1478. */
  1479. public static function isCnIp($ip = '')
  1480. {
  1481. if (empty($ip)) {
  1482. $ip = self::getIp();
  1483. }
  1484. $cacheKey = "isCnIp::" . md5($ip);
  1485. //
  1486. $result = Cache::remember($cacheKey, now()->addMinutes(10), function () use ($ip) {
  1487. $file = dirname(__FILE__) . '/ip/all_cn.txt';
  1488. if (!file_exists($file)) {
  1489. return -1;
  1490. }
  1491. $in = false;
  1492. $myFile = fopen($file, "r");
  1493. $i = 0;
  1494. while (!feof($myFile)) {
  1495. $i++;
  1496. $cidr = trim(fgets($myFile));
  1497. if (Base::ipInRange($ip, $cidr)) {
  1498. $in = true;
  1499. break;
  1500. }
  1501. }
  1502. fclose($myFile);
  1503. return $in ? 1 : 0;
  1504. });
  1505. if ($result === -1) {
  1506. Cache::forget($cacheKey);
  1507. }
  1508. //
  1509. return intval($result);
  1510. }
  1511. /**
  1512. * 验证IP地址范围
  1513. * $range 支持多种写法
  1514. * - Wildcard: 1.2.3.*
  1515. * - CIRD:1.2.3/24 或者 1.2.3.4/255.255.255.0
  1516. * - Start-End: 1.2.3.0-1.2.3.255
  1517. * @param $ip
  1518. * @param $range
  1519. * @return bool
  1520. */
  1521. public static function ipInRange($ip, $range)
  1522. {
  1523. if (substr_count($ip, '.') == 3 && $ip == $range) {
  1524. return true;
  1525. }
  1526. if (strpos($range, '/') !== false) {
  1527. list($range, $netmask) = explode('/', $range, 2);
  1528. if (strpos($netmask, '.') !== false) {
  1529. $netmask = str_replace('*', '0', $netmask);
  1530. $netmask_dec = ip2long($netmask);
  1531. return ((ip2long($ip) & $netmask_dec) == (ip2long($range) & $netmask_dec));
  1532. } else {
  1533. $x = explode('.', $range);
  1534. while (count($x) < 4) {
  1535. $x[] = '0';
  1536. }
  1537. list($a, $b, $c, $d) = $x;
  1538. $range = sprintf("%u.%u.%u.%u", empty($a) ? '0' : $a, empty($b) ? '0' : $b, empty($c) ? '0' : $c, empty($d) ? '0' : $d);
  1539. $range_dec = ip2long($range);
  1540. $ip_dec = ip2long($ip);
  1541. $wildcard_dec = pow(2, (32 - $netmask)) - 1;
  1542. $netmask_dec = ~$wildcard_dec;
  1543. return (($ip_dec & $netmask_dec) == ($range_dec & $netmask_dec));
  1544. }
  1545. } else {
  1546. if (strpos($range, '*') !== false) {
  1547. $lower = str_replace('*', '0', $range);
  1548. $upper = str_replace('*', '255', $range);
  1549. $range = "$lower-$upper";
  1550. }
  1551. if (strpos($range, '-') !== false) {
  1552. list($lower, $upper) = explode('-', $range, 2);
  1553. $lower_dec = (float)sprintf("%u", ip2long($lower));
  1554. $upper_dec = (float)sprintf("%u", ip2long($upper));
  1555. $ip_dec = (float)sprintf("%u", ip2long($ip));
  1556. return (($ip_dec >= $lower_dec) && ($ip_dec <= $upper_dec));
  1557. }
  1558. return false;
  1559. }
  1560. }
  1561. /**
  1562. * php://input 字符串解析到变量并获取指定值
  1563. * @param $key
  1564. * @return array
  1565. */
  1566. public static function getContentsParse($key)
  1567. {
  1568. parse_str(Request::getContent(), $input);
  1569. if ($key) {
  1570. $input = isset($input[$key])?$input[$key]:array();
  1571. }
  1572. return is_array($input)?$input:array($input);
  1573. }
  1574. /**
  1575. * 多维 array_values
  1576. * @param $array
  1577. * @param string $keyName
  1578. * @param string $valName
  1579. * @return array
  1580. */
  1581. public static function array_values_recursive($array, $keyName = 'key', $valName = 'item') {
  1582. if (is_array($array) && count($array) > 0) {
  1583. $temp = [];
  1584. foreach ($array as $key => $value) {
  1585. $continue = false;
  1586. if (is_array($value) && count($value) > 0) {
  1587. $continue = true;
  1588. foreach ($value AS $item) {
  1589. if (!is_array($item)) {
  1590. $continue = false;
  1591. break;
  1592. }
  1593. }
  1594. }
  1595. $temp[] = [
  1596. $keyName => $key,
  1597. $valName => $continue ? self::array_values_recursive($value, $keyName, $valName) : $value,
  1598. ];
  1599. }
  1600. return $temp;
  1601. }
  1602. return $array;
  1603. }
  1604. /**
  1605. * 获取tonken
  1606. * @return string
  1607. */
  1608. public static function getToken()
  1609. {
  1610. global $_A;
  1611. if (!isset($_A["__static_token"])) {
  1612. $_A["__static_token"] = Base::nullShow(Request::header('token'), Request::input('token'));
  1613. }
  1614. return $_A["__static_token"];
  1615. }
  1616. /**
  1617. * 设置tonken
  1618. * @param $token
  1619. */
  1620. public static function setToken($token)
  1621. {
  1622. global $_A;
  1623. $_A["__static_token"] = $token;
  1624. }
  1625. /**
  1626. * 是否微信
  1627. * @return bool
  1628. */
  1629. public static function isWechat()
  1630. {
  1631. return strpos(Request::server('HTTP_USER_AGENT'), 'MicroMessenger') !== false;
  1632. }
  1633. /**
  1634. * 获取浏览器类型
  1635. * @return string
  1636. */
  1637. public static function browser()
  1638. {
  1639. $user_agent = Request::server('HTTP_USER_AGENT');
  1640. if (strpos($user_agent, 'AlipayClient') !== false) {
  1641. return 'alipay';
  1642. }elseif (strpos($user_agent, 'MicroMessenger') !== false) {
  1643. return 'weixin';
  1644. }else{
  1645. return 'none';
  1646. }
  1647. }
  1648. /**
  1649. * 返回根据距离sql排序语句
  1650. * @param $lat
  1651. * @param $lng
  1652. * @param string $latName
  1653. * @param string $lngName
  1654. * @return string
  1655. */
  1656. public static function acos($lat , $lng, $latName = 'lat', $lngName = 'lng') {
  1657. $lat = floatval($lat);
  1658. $lng = floatval($lng);
  1659. return 'ACOS(
  1660. SIN(('.$lat.' * 3.1415) / 180) * SIN(('.$latName.' * 3.1415) / 180) + COS(('.$lat.' * 3.1415) / 180) * COS(('.$latName.' * 3.1415) / 180) * COS(
  1661. ('.$lng.' * 3.1415) / 180 - ('.$lngName.' * 3.1415) / 180
  1662. )
  1663. ) * 6380';
  1664. }
  1665. /**
  1666. * 获取分页详细信息
  1667. * @param LengthAwarePaginator $lists
  1668. * @param bool $getTotal
  1669. * @return array
  1670. */
  1671. public static function getPageInfo(LengthAwarePaginator $lists, $getTotal = true)
  1672. {
  1673. return [
  1674. "currentPage" => $lists->currentPage(),
  1675. "firstItem" => $lists->firstItem(),
  1676. "hasMorePages" => $lists->hasMorePages(),
  1677. "lastItem" => $lists->lastItem(),
  1678. "lastPage" => $lists->lastPage(),
  1679. "nextPageUrl" => $lists->nextPageUrl(),
  1680. "previousPageUrl" => $lists->previousPageUrl(),
  1681. "perPage" => $lists->perPage(),
  1682. "total" => $getTotal === true ? $lists->total() : -1,
  1683. ];
  1684. }
  1685. /**
  1686. * 获取分页数据
  1687. * @param $lists
  1688. * @param bool $getTotal
  1689. * @return array
  1690. */
  1691. public static function getPageList($lists, $getTotal = true)
  1692. {
  1693. $data = Base::getPageInfo($lists, $getTotal);
  1694. $data['lists'] = Base::coll2array($lists);
  1695. return $data;
  1696. }
  1697. /**
  1698. * 上传文件
  1699. * @param array $param [ type=[文件类型], file=>Request::file, path=>文件路径, fileName=>文件名称, scale=>[压缩原图宽,高, 压缩方式], size=>限制大小KB, autoThumb=>false不要自动生成缩略图 ]
  1700. * @return array [name=>原文件名, size=>文件大小(单位KB),file=>绝对地址, path=>相对地址, url=>全路径地址, ext=>文件后缀名]
  1701. */
  1702. public static function upload($param)
  1703. {
  1704. $file = $param['file'];
  1705. if (empty($file)) {
  1706. return Base::retError("您没有选择要上传的文件!");
  1707. }
  1708. if($file->isValid()){
  1709. Base::makeDir(public_path($param['path']));
  1710. //
  1711. switch ($param['type']) {
  1712. case 'png':
  1713. $type = ['png'];
  1714. break;
  1715. case 'png+jpg':
  1716. $type = ['jpg', 'jpeg', 'png'];
  1717. break;
  1718. case 'image':
  1719. $type = ['jpg', 'jpeg', 'gif', 'png'];
  1720. break;
  1721. case 'video':
  1722. $type = ['rm', 'rmvb', 'wmv', 'avi', 'mpg', 'mpeg', 'mp4'];
  1723. break;
  1724. case 'audio':
  1725. $type = ['mp3', 'wma', 'wav', 'amr'];
  1726. break;
  1727. case 'excel':
  1728. $type = ['xls', 'xlsx'];
  1729. break;
  1730. case 'app':
  1731. $type = ['apk'];
  1732. break;
  1733. case 'zip':
  1734. $type = ['zip'];
  1735. break;
  1736. case 'file':
  1737. $type = ['jpg', 'jpeg', 'png', 'gif', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'esp'];
  1738. break;
  1739. default:
  1740. return Base::retError('错误的类型参数');
  1741. }
  1742. $extension = strtolower($file->getClientOriginalExtension());
  1743. if ($type && is_array($type) && !in_array($extension, $type)) {
  1744. return Base::retError('文件格式错误,限制类型:'.implode(",", $type));
  1745. }
  1746. try {
  1747. $fileSize = $file->getSize();
  1748. if ($param['size'] > 0 && $fileSize > $param['size'] * 1024) {
  1749. return Base::retError('文件大小超限,最大限制:' . $param['size'] . 'kB');
  1750. }
  1751. } catch (Exception $e) {
  1752. $fileSize = 0;
  1753. }
  1754. $scaleName = "";
  1755. if ($param['fileName']) {
  1756. $fileName = $param['fileName'];
  1757. }else{
  1758. if ($param['scale'] && is_array($param['scale'])) {
  1759. list($width, $height) = $param['scale'];
  1760. if ($width > 0 || $height > 0) {
  1761. $scaleName = "_{WIDTH}x{HEIGHT}";
  1762. if (isset($param['scale'][2])) {
  1763. $scaleName.= $param['scale'][2];
  1764. }
  1765. }
  1766. }
  1767. $fileName = md5_file($file) . '.' . $extension;
  1768. $scaleName = md5_file($file) . $scaleName . '.' . $extension;
  1769. }
  1770. //
  1771. $file->move($param['path'], $fileName);
  1772. //
  1773. $array = [
  1774. "name" => $file->getClientOriginalName(), //原文件名
  1775. "size" => Base::twoFloat($fileSize / 1024, true), //大小KB
  1776. "file" => public_path($param['path'].$fileName), //目录的完整路径 "D:\www....KzZ.jpg"
  1777. "path" => $param['path'].$fileName, //相对路径 "uploads/pic....KzZ.jpg"
  1778. "url" => Base::fillUrl($param['path'].$fileName), //完整的URL "https://.....hhsKzZ.jpg"
  1779. "thumb" => '', //缩略图(预览图) "https://.....hhsKzZ.jpg_thumb.jpg"
  1780. "width" => -1, //图片宽度
  1781. "height" => -1, //图片高度
  1782. "ext" => $extension, //文件后缀名
  1783. ];
  1784. if (!is_file($array['file'])) {
  1785. return Base::retError('上传失败!');
  1786. }
  1787. //iOS照片颠倒处理
  1788. if (in_array($extension, ['jpg', 'jpeg']) && function_exists('exif_read_data')) {
  1789. $data = imagecreatefromstring(file_get_contents($array['file']));
  1790. $exif = @exif_read_data($array['file']);
  1791. if (!empty($exif['Orientation'])) {
  1792. switch ($exif['Orientation']) {
  1793. case 8:
  1794. $data = imagerotate($data, 90, 0);
  1795. break;
  1796. case 3:
  1797. $data = imagerotate($data, 180, 0);
  1798. break;
  1799. case 6:
  1800. $data = imagerotate($data, -90, 0);
  1801. break;
  1802. default:
  1803. $data = null;
  1804. break;
  1805. }
  1806. if ($data !== null) {
  1807. imagejpeg($data, $array['file']);
  1808. }
  1809. }
  1810. }
  1811. //
  1812. if (in_array($param['type'], ['png', 'png+jpg', 'image'])) {
  1813. //图片尺寸
  1814. $paramet = getimagesize($array['file']);
  1815. $array['width'] = $paramet[0];
  1816. $array['height'] = $paramet[1];
  1817. //原图压缩
  1818. if ($param['scale'] && is_array($param['scale'])) {
  1819. list($width, $height) = $param['scale'];
  1820. if (($width > 0 && $array['width'] > $width) || ($height > 0 && $array['height'] > $height)) {
  1821. $cut = ($width > 0 && $height > 0) ? 1 : -1;
  1822. $cut = $param['scale'][2] ?? $cut;
  1823. //图片压缩
  1824. $tmpFile = $array['file'] . '_tmp.jpg';
  1825. if (Base::imgThumb($array['file'], $tmpFile, $width, $height, $cut)) {
  1826. $tmpSize = filesize($tmpFile);
  1827. if ($tmpSize > $fileSize) {
  1828. @unlink($tmpFile);
  1829. }else{
  1830. @unlink($array['file']);
  1831. rename($tmpFile, $array['file']);
  1832. }
  1833. }
  1834. //图片尺寸
  1835. $paramet = getimagesize($array['file']);
  1836. $array['width'] = $paramet[0];
  1837. $array['height'] = $paramet[1];
  1838. //重命名
  1839. if ($scaleName) {
  1840. $scaleName = str_replace(['{WIDTH}', '{HEIGHT}'], [$array['width'], $array['height']], $scaleName);
  1841. if (rename($array['file'], Base::rightDelete($array['file'], $fileName) . $scaleName)) {
  1842. $array['file'] = Base::rightDelete($array['file'], $fileName) . $scaleName;
  1843. $array['path'] = Base::rightDelete($array['path'], $fileName) . $scaleName;
  1844. $array['url'] = Base::rightDelete($array['url'], $fileName) . $scaleName;
  1845. }
  1846. }
  1847. }
  1848. }
  1849. //生成缩略图
  1850. $array['thumb'] = $array['path'];
  1851. if ($param['autoThumb'] === "false") $param['autoThumb'] = false;
  1852. if ($param['autoThumb'] !== false) {
  1853. if (Base::imgThumb($array['file'], $array['file']."_thumb.jpg", 180, 0)) {
  1854. $array['thumb'].= "_thumb.jpg";
  1855. }
  1856. }
  1857. $array['thumb'] = Base::fillUrl($array['thumb']);
  1858. }
  1859. //
  1860. return Base::retSuccess('success', $array);
  1861. }else{
  1862. return Base::retError($file->getErrorMessage());
  1863. }
  1864. }
  1865. /**
  1866. * 生成缩略图
  1867. * @param string $src_img 源图绝对完整地址{带文件名及后缀名}
  1868. * @param string $dst_img 目标图绝对完整地址{带文件名及后缀名}
  1869. * @param int $width 缩略图宽{0:此时目标高度不能为0,目标宽度为源图宽*(目标高度/源图高)}
  1870. * @param int $height 缩略图高{0:此时目标宽度不能为0,目标高度为源图高*(目标宽度/源图宽)}
  1871. * @param int $cut 是否裁切{宽,高必须非0}:1是、0否、-1或'auto'保持等比
  1872. * @param int $proportion 缩放{0:不缩放, 0<this<1:缩放到相应比例(此时宽高限制和裁切均失效)}
  1873. * @return bool
  1874. */
  1875. public static function imgThumb($src_img, $dst_img, $width = 75, $height = 75, $cut = 0, $proportion = 0)
  1876. {
  1877. if (!is_file($src_img)) {
  1878. return false;
  1879. }
  1880. if (empty($dst_img)) {
  1881. $dst_img = $src_img;
  1882. }
  1883. $st = pathinfo($src_img, PATHINFO_EXTENSION);
  1884. if (!in_array(strtolower($st), array('jpg', 'jpeg', 'png', 'gif', 'bmp'))) {
  1885. return false;
  1886. }
  1887. $ot = pathinfo($dst_img, PATHINFO_EXTENSION);
  1888. $otfunc = 'image' . ($ot == 'jpg' ? 'jpeg' : $ot);
  1889. $srcinfo = getimagesize($src_img);
  1890. $src_w = $srcinfo[0];
  1891. $src_h = $srcinfo[1];
  1892. $type = strtolower(substr(image_type_to_extension($srcinfo[2]), 1));
  1893. if (empty($type)) {
  1894. return false;
  1895. }
  1896. $createfun = 'imagecreatefrom' . ($type == 'jpg' ? 'jpeg' : $type);
  1897. $dst_h = $height;
  1898. $dst_w = $width;
  1899. $x = $y = 0;
  1900. /**
  1901. * 缩略图不超过源图尺寸(前提是宽或高只有一个)
  1902. */
  1903. if (($width > $src_w && $height > $src_h) || ($height > $src_h && $width == 0) || ($width > $src_w && $height == 0)) {
  1904. $proportion = 1;
  1905. }
  1906. if ($width > $src_w) {
  1907. $dst_w = $width = $src_w;
  1908. }
  1909. if ($height > $src_h) {
  1910. $dst_h = $height = $src_h;
  1911. }
  1912. if (!$width && !$height && !$proportion) {
  1913. return false;
  1914. }
  1915. if (!$proportion) {
  1916. if ($cut == 'auto' || $cut == -1) {
  1917. if ($dst_w && $dst_h) {
  1918. $wB = $dst_w / $src_w;
  1919. $hB = $dst_h / $src_h;
  1920. if ($wB > $hB) {
  1921. $dst_w = 0;
  1922. }else{
  1923. $dst_h = 0;
  1924. }
  1925. }
  1926. $cut = 0;
  1927. }
  1928. if ($cut == 0) {
  1929. if ($dst_w && $dst_h) {
  1930. if ($dst_w / $src_w > $dst_h / $src_h) {
  1931. $dst_w = $src_w * ($dst_h / $src_h);
  1932. $x = 0 - ($dst_w - $width) / 2;
  1933. } else {
  1934. $dst_h = $src_h * ($dst_w / $src_w);
  1935. $y = 0 - ($dst_h - $height) / 2;
  1936. }
  1937. } else if ($dst_w xor $dst_h) {
  1938. if ($dst_w && !$dst_h) //有宽无高
  1939. {
  1940. $propor = $dst_w / $src_w;
  1941. $height = $dst_h = $src_h * $propor;
  1942. } else if (!$dst_w && $dst_h) //有高无宽
  1943. {
  1944. $propor = $dst_h / $src_h;
  1945. $width = $dst_w = $src_w * $propor;
  1946. }
  1947. }
  1948. } else {
  1949. if (!$dst_h) //裁剪时无高
  1950. {
  1951. $height = $dst_h = $dst_w;
  1952. }
  1953. if (!$dst_w) //裁剪时无宽
  1954. {
  1955. $width = $dst_w = $dst_h;
  1956. }
  1957. $propor = min(max($dst_w / $src_w, $dst_h / $src_h), 1);
  1958. $dst_w = (int)round($src_w * $propor);
  1959. $dst_h = (int)round($src_h * $propor);
  1960. $x = ($width - $dst_w) / 2;
  1961. $y = ($height - $dst_h) / 2;
  1962. }
  1963. } else {
  1964. $proportion = min($proportion, 1);
  1965. $height = $dst_h = $src_h * $proportion;
  1966. $width = $dst_w = $src_w * $proportion;
  1967. }
  1968. if (!function_exists($createfun)) {
  1969. return false;
  1970. }
  1971. $src = $createfun($src_img);
  1972. $dst = imagecreatetruecolor($width ? $width : $dst_w, $height ? $height : $dst_h);
  1973. try {
  1974. $white = imagecolorallocate($dst, 255, 255, 255);
  1975. imagefill($dst, 0, 0, $white);
  1976. } catch (Exception $e) {
  1977. }
  1978. if (function_exists('imagecopyresampled')) {
  1979. imagecopyresampled($dst, $src, $x, $y, 0, 0, $dst_w, $dst_h, $src_w, $src_h);
  1980. } else {
  1981. imagecopyresized($dst, $src, $x, $y, 0, 0, $dst_w, $dst_h, $src_w, $src_h);
  1982. }
  1983. $otfunc($dst, $dst_img);
  1984. imagedestroy($dst);
  1985. imagedestroy($src);
  1986. return true;
  1987. }
  1988. /**
  1989. * 排列组合(无重复)
  1990. * @param $arr
  1991. * @param $m
  1992. * @return array
  1993. */
  1994. public static function getCombinationToString($arr, $m)
  1995. {
  1996. $result = [];
  1997. if ($m == 1) {
  1998. return $arr;
  1999. }
  2000. if ($m == count($arr)) {
  2001. $result[] = implode(',', $arr);
  2002. return $result;
  2003. }
  2004. $temp_firstelement = $arr[0];
  2005. unset($arr[0]);
  2006. $arr = array_values($arr);
  2007. $temp_list1 = self::getCombinationToString($arr, ($m - 1));
  2008. foreach ($temp_list1 as $s) {
  2009. $s = $temp_firstelement . ',' . $s;
  2010. $result[] = $s;
  2011. }
  2012. unset($temp_list1);
  2013. $temp_list2 = self::getCombinationToString($arr, $m);
  2014. foreach ($temp_list2 as $s) {
  2015. $result[] = $s;
  2016. }
  2017. unset($temp_list2);
  2018. return $result;
  2019. }
  2020. /**
  2021. * 不同元素交叉组合(多个数组)
  2022. * @return array
  2023. */
  2024. public static function getNewArray()
  2025. {
  2026. $args = func_get_args();
  2027. $pailie = function ($arr1, $arr2) {
  2028. $arr = [];
  2029. $k = 0;
  2030. foreach ($arr1 as $k1 => $v1) {
  2031. foreach ($arr2 as $k2 => $v2) {
  2032. $arr[$k] = $v1 . "," . $v2;
  2033. $k++;
  2034. }
  2035. }
  2036. return $arr;
  2037. };
  2038. $arr = [];
  2039. foreach ($args as $k => $v) {
  2040. if (isset($args[$k + 1]) && $args[$k + 1]) {
  2041. switch ($k) {
  2042. case 0:
  2043. $arr[$k] = $pailie($v, $args[$k + 1]);
  2044. break;
  2045. default:
  2046. $arr[$k] = $pailie($arr[$k - 1], $args[$k + 1]);
  2047. break;
  2048. }
  2049. }
  2050. }
  2051. $key = count($arr) - 1;
  2052. return array_values($arr[$key]);
  2053. }
  2054. /**
  2055. * 缓存数据
  2056. * @param $title
  2057. * @param null $value
  2058. * @return mixed|null
  2059. */
  2060. public static function cacheData($title, $value = null)
  2061. {
  2062. $title = "cacheData::" . $title;
  2063. $tmp = DB::table('tmp')->where('title', $title)->select('value')->first();
  2064. if ($value !== null ) {
  2065. if (empty($tmp)) {
  2066. DB::table('tmp')->insert(['title'=>$title, 'value'=>$value]);
  2067. }else{
  2068. DB::table('tmp')->where('title', $title)->update(['value'=>$value]);
  2069. }
  2070. return $value;
  2071. }else{
  2072. return $tmp->value;
  2073. }
  2074. }
  2075. }