Base.php 65 KB

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