Base.php 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412
  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 $search
  984. * @param $replace
  985. * @param $subject
  986. * @param int $limit
  987. * @return string|string[]|null
  988. */
  989. public static function strReplaceLimit($search, $replace, $subject, $limit = -1)
  990. {
  991. if (is_array($search)) {
  992. foreach ($search as $k => $v) {
  993. $search[$k] = '`' . preg_quote($search[$k], '`') . '`';
  994. }
  995. } else {
  996. $search = '`' . preg_quote($search, '`') . '`';
  997. }
  998. return preg_replace($search, $replace, $subject, $limit);
  999. }
  1000. /**
  1001. * 获取或设置
  1002. * @param $setname //配置名称
  1003. * @param bool $array //保存内容
  1004. * @param bool $isCache //读取缓存
  1005. * @return array
  1006. */
  1007. public static function setting($setname, $array = false, $isCache = false)
  1008. {
  1009. global $_A;
  1010. if (empty($setname)) {
  1011. return [];
  1012. }
  1013. if ($array === false && isset($_A["__static_setting_" . $setname])) {
  1014. return $_A["__static_setting_" . $setname];
  1015. }
  1016. $setting = [];
  1017. $setrow = DBCache::table('setting')->where('title', $setname)->cache($isCache)->first();
  1018. if (!empty($setrow)) {
  1019. $setting = Base::string2array($setrow['setting']);
  1020. } else {
  1021. DB::table('setting')->insert(['title' => $setname]);
  1022. }
  1023. if ($array !== false) {
  1024. $setting = $array;
  1025. DB::table('setting')->where('title', $setname)->update(['setting' => (is_array($array) ? Base::array2string($array) : $array)]);
  1026. DBCache::table('setting')->where('title', $setname)->removeCache()->first();
  1027. }
  1028. $_A["__static_setting_" . $setname] = $setting;
  1029. return $setting;
  1030. }
  1031. /**
  1032. * 获取设置值
  1033. * @param $setname
  1034. * @param $keyname
  1035. * @param $defaultVal
  1036. * @return mixed
  1037. */
  1038. public static function settingFind($setname, $keyname, $defaultVal = '')
  1039. {
  1040. $array = Base::setting($setname);
  1041. return isset($array[$keyname]) ? $array[$keyname] : $defaultVal;
  1042. }
  1043. /**
  1044. * 秒 (转) 年、天、时、分、秒
  1045. * @param $time
  1046. * @return array|bool
  1047. */
  1048. public static function sec2time($time)
  1049. {
  1050. if (is_numeric($time)) {
  1051. $value = array(
  1052. "years" => 0, "days" => 0, "hours" => 0,
  1053. "minutes" => 0, "seconds" => 0,
  1054. );
  1055. /*
  1056. if($time >= 31536000){
  1057. $value["years"] = floor($time/31536000);
  1058. $time = ($time%31536000);
  1059. }
  1060. */
  1061. if ($time >= 86400) {
  1062. $value["days"] = floor($time / 86400);
  1063. $time = ($time % 86400);
  1064. }
  1065. if ($time >= 3600) {
  1066. $value["hours"] = floor($time / 3600);
  1067. $time = ($time % 3600);
  1068. }
  1069. if ($time >= 60) {
  1070. $value["minutes"] = floor($time / 60);
  1071. $time = ($time % 60);
  1072. }
  1073. $value["seconds"] = floor($time);
  1074. return (array)$value;
  1075. } else {
  1076. return (bool)FALSE;
  1077. }
  1078. }
  1079. /**
  1080. * 年、天、时、分、秒 (转) 秒
  1081. * @param $value
  1082. * @return int
  1083. */
  1084. public static function time2sec($value)
  1085. {
  1086. $time = intval($value["seconds"]);
  1087. $time += intval($value["minutes"] * 60);
  1088. $time += intval($value["hours"] * 3600);
  1089. $time += intval($value["days"] * 86400);
  1090. $time += intval($value["years"] * 31536000);
  1091. return $time;
  1092. }
  1093. /**
  1094. * 阿拉伯数字转化为中文
  1095. * @param $num
  1096. * @return string
  1097. */
  1098. public static function chinaNum($num)
  1099. {
  1100. $china = array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九');
  1101. $arr = str_split($num);
  1102. $txt = '';
  1103. for ($i = 0; $i < count($arr); $i++) {
  1104. $txt .= $china[$arr[$i]];
  1105. }
  1106. return $txt;
  1107. }
  1108. /**
  1109. * 阿拉伯数字转化为中文(用于星期,七改成日)
  1110. * @param $num
  1111. * @return string
  1112. */
  1113. public static function chinaNumZ($num)
  1114. {
  1115. return str_replace("七", "日", Base::chinaNum($num));
  1116. }
  1117. /**
  1118. * 获取(时间戳转)今天是星期几,只返回(几)
  1119. * @param string|number $unixTime
  1120. * @return string
  1121. */
  1122. public static function getTimeWeek($unixTime = '')
  1123. {
  1124. $unixTime = is_numeric($unixTime) ? $unixTime : Base::time();
  1125. $weekarray = ['日', '一', '二', '三', '四', '五', '六'];
  1126. return $weekarray[date('w', $unixTime)];
  1127. }
  1128. /**
  1129. * 获取(时间戳转)现在时间段:深夜、凌晨、早晨、上午.....
  1130. * @param string|number $unixTime
  1131. * @return string
  1132. */
  1133. public static function getTimeDayeSegment($unixTime = '')
  1134. {
  1135. $unixTime = is_numeric($unixTime) ? $unixTime : Base::time();
  1136. $H = date('H', $unixTime);
  1137. if ($H >= 19) {
  1138. return '晚上';
  1139. } elseif ($H >= 18) {
  1140. return '傍晚';
  1141. } elseif ($H >= 13) {
  1142. return '下午';
  1143. } elseif ($H >= 12) {
  1144. return '中午';
  1145. } elseif ($H >= 8) {
  1146. return '上午';
  1147. } elseif ($H >= 5) {
  1148. return '早晨';
  1149. } elseif ($H >= 1) {
  1150. return '凌晨';
  1151. } elseif ($H >= 0) {
  1152. return '深夜';
  1153. } else {
  1154. return '';
  1155. }
  1156. }
  1157. /**
  1158. * 国际化(替换国际语言)
  1159. * @param $val
  1160. * @return mixed
  1161. */
  1162. public static function Lang($val)
  1163. {
  1164. $repArray = [];
  1165. if (is_array($val)) {
  1166. if (self::strExists($val[0], '%') && count($val) > 1) {
  1167. $repArray = array_slice($val, 1);
  1168. }
  1169. $val = $val[0];
  1170. }
  1171. $data = self::langData();
  1172. if (isset($data[$val]) && $data[$val] !== null) {
  1173. $val = $data[$val];
  1174. }
  1175. if ($repArray) {
  1176. foreach ($repArray AS $item) {
  1177. $val = self::strReplaceLimit('%', $item, $val, 1);
  1178. }
  1179. }
  1180. return $val;
  1181. }
  1182. /**
  1183. * 加载语言数据
  1184. * @param bool $refresh
  1185. * @return array|mixed
  1186. */
  1187. public static function langData($refresh = false)
  1188. {
  1189. global $_A;
  1190. if (!isset($_A["__static_langdata"]) || $refresh === true) {
  1191. $_A["__static_langdata"] = [];
  1192. $language = trim(Request::header('language'));
  1193. $langpath = resource_path('lang/' . $language . '/general.php');
  1194. if (file_exists($langpath)) {
  1195. $data = include $langpath;
  1196. if (is_array($data)) {
  1197. $_A["__static_langdata"] = $data;
  1198. }
  1199. }
  1200. }
  1201. return $_A["__static_langdata"];
  1202. }
  1203. /**
  1204. * JSON返回
  1205. * @param $param
  1206. * @return string
  1207. */
  1208. public static function jsonEcho($param)
  1209. {
  1210. global $_GPC;
  1211. //
  1212. $json = json_encode($param);
  1213. $callback = $_GPC['callback'];
  1214. if ($callback) {
  1215. return $callback . '(' . $json . ')';
  1216. } else {
  1217. return $json;
  1218. }
  1219. }
  1220. /**
  1221. * 数组返回 正确
  1222. * @param $msg
  1223. * @param array $data
  1224. * @param int $ret
  1225. * @return array
  1226. */
  1227. public static function retSuccess($msg, $data = [], $ret = 1)
  1228. {
  1229. return array(
  1230. 'ret' => $ret,
  1231. 'msg' => self::Lang($msg),
  1232. 'data' => $data
  1233. );
  1234. }
  1235. /**
  1236. * 数组返回 错误
  1237. * @param $msg
  1238. * @param array $data
  1239. * @param int $ret
  1240. * @return array
  1241. */
  1242. public static function retError($msg, $data = [], $ret = 0)
  1243. {
  1244. return array(
  1245. 'ret' => $ret,
  1246. 'msg' => self::Lang($msg),
  1247. 'data' => $data
  1248. );
  1249. }
  1250. /**
  1251. * Ajax 错误返回
  1252. * @param $msg
  1253. * @param array $data
  1254. * @param int $ret
  1255. * @return array|void
  1256. */
  1257. public static function ajaxError($msg, $data = [], $ret = 0)
  1258. {
  1259. if (Request::input('__Access-Control-Allow-Origin') || Request::header('Content-Type') === 'application/json') {
  1260. return Base::retError($msg, $data, $ret);
  1261. }else{
  1262. return abort(404);
  1263. }
  1264. }
  1265. /**
  1266. * JSON返回 正确
  1267. * @param $msg
  1268. * @param array $data
  1269. * @param int $ret
  1270. * @return string
  1271. */
  1272. public static function jsonSuccess($msg, $data = [], $ret = 1)
  1273. {
  1274. return Base::jsonEcho(Base::retSuccess($msg, $data, $ret));
  1275. }
  1276. /**
  1277. * JSON返回 错误
  1278. * @param $msg
  1279. * @param array $data
  1280. * @param int $ret
  1281. * @return string
  1282. */
  1283. public static function jsonError($msg, $data = [], $ret = 0)
  1284. {
  1285. return Base::jsonEcho(Base::retError($msg, $data, $ret));
  1286. }
  1287. /**
  1288. * 是否错误
  1289. * @param $param
  1290. * @return bool
  1291. */
  1292. public static function isError($param)
  1293. {
  1294. return intval($param['ret']) <= 0;
  1295. }
  1296. /**
  1297. * 异常模板
  1298. * @param $msg
  1299. * @param bool $catch
  1300. * @return bool
  1301. */
  1302. public static function Exce($msg, $catch = false)
  1303. {
  1304. if ($catch === false) {
  1305. return "{{ExceMsg:".$msg.":ExceMsg}}";
  1306. }else{
  1307. if (Base::strExists($msg . "", "{{ExceMsg:") && Base::strExists($msg . "", ":ExceMsg}}")) {
  1308. $msg = Base::getMiddle($msg, "{{ExceMsg:", ":ExceMsg}}");
  1309. $catch = $msg?$msg:$catch;
  1310. }
  1311. return $catch;
  1312. }
  1313. }
  1314. /**
  1315. * 获取数组的第几个值
  1316. * @param $arr
  1317. * @param int $i
  1318. * @return array
  1319. */
  1320. public static function getArray($arr, $i = 1)
  1321. {
  1322. $array = [];
  1323. $j = 1;
  1324. foreach ($arr AS $item) {
  1325. $array[] = $item;
  1326. if ($i >= $j) {
  1327. break;
  1328. }
  1329. $j++;
  1330. }
  1331. return $array;
  1332. }
  1333. /**
  1334. * 小时转天/小时
  1335. * @param $hour
  1336. * @return string
  1337. */
  1338. public static function forumHourDay($hour)
  1339. {
  1340. $hour = intval($hour);
  1341. if ($hour > 24) {
  1342. $day = floor($hour / 24);
  1343. $hour-= $day * 24;
  1344. return $day.'天'.$hour.'小时';
  1345. }
  1346. return $hour.'小时';
  1347. }
  1348. /**
  1349. * 时间格式化
  1350. * @param $date
  1351. * @return false|string
  1352. */
  1353. public static function forumDate($date)
  1354. {
  1355. $dur = time() - $date;
  1356. if ($date > strtotime(date("Y-m-d"))) {
  1357. //今天
  1358. if ($dur < 60) {
  1359. return max($dur, 1) . '秒前';
  1360. } elseif ($dur < 3600) {
  1361. return floor($dur / 60) . '分钟前';
  1362. } elseif ($dur < 86400) {
  1363. return floor($dur / 3600) . '小时前';
  1364. } else {
  1365. return date("H:i", $date);
  1366. }
  1367. } elseif ($date > strtotime(date("Y-m-d", strtotime("-1 day")))) {
  1368. //昨天
  1369. return '昨天';
  1370. } elseif ($date > strtotime(date("Y-m-d", strtotime("-2 day")))) {
  1371. //前天
  1372. return '前天';
  1373. } elseif ($dur > 86400) {
  1374. //x天前
  1375. return floor($dur / 86400) . '天前';
  1376. }
  1377. return date("Y-m-d", $date);
  1378. }
  1379. /**
  1380. * 获取时间戳今天的第一秒时间戳
  1381. * @param $time
  1382. * @return false|int
  1383. */
  1384. public static function dayTimeF($time)
  1385. {
  1386. return strtotime(date("Y-m-d 00:00:00", self::isNumber($time) ? $time : strtotime($time)));
  1387. }
  1388. /**
  1389. * 获取时间戳今天的最后一秒时间戳
  1390. * @param $time
  1391. * @return false|int
  1392. */
  1393. public static function dayTimeE($time)
  1394. {
  1395. return strtotime(date("Y-m-d 23:59:59", self::isNumber($time) ? $time : strtotime($time)));
  1396. }
  1397. /**
  1398. * 用户名、邮箱、手机账号、银行卡号中间字符串以*隐藏
  1399. * @param $str
  1400. * @return mixed|string
  1401. */
  1402. public static function cardFormat($str)
  1403. {
  1404. if (strpos($str, '@')) {
  1405. $email_array = explode("@", $str);
  1406. $prevfix = (strlen($email_array[0]) < 4) ? "" : substr($str, 0, 3); //邮箱前缀
  1407. $count = 0;
  1408. $str = preg_replace('/([\d\w+_-]{0,100})@/', '***@', $str, -1, $count);
  1409. return $prevfix . $str;
  1410. }
  1411. if (Base::isMobile($str)) {
  1412. return substr($str, 0, 3) . "****" . substr($str, -4);
  1413. }
  1414. $pattern = '/([\d]{4})([\d]{4})([\d]{4})([\d]{4})([\d]{0,})?/i';
  1415. if (preg_match($pattern, $str)) {
  1416. return preg_replace($pattern, '$1 **** **** **** $5', $str);
  1417. }
  1418. $pattern = '/([\d]{4})([\d]{4})([\d]{4})([\d]{0,})?/i';
  1419. if (preg_match($pattern, $str)) {
  1420. return preg_replace($pattern, '$1 **** **** $4', $str);
  1421. }
  1422. $pattern = '/([\d]{4})([\d]{4})([\d]{0,})?/i';
  1423. if (preg_match($pattern, $str)) {
  1424. return preg_replace($pattern, '$1 **** $3', $str);
  1425. }
  1426. return substr($str, 0, 3) . "***" . substr($str, -1);
  1427. }
  1428. /**
  1429. * 数字每4位加一空格
  1430. * @param $str
  1431. * @param string $interval
  1432. * @return string
  1433. */
  1434. public static function fourFormat($str, $interval = " ")
  1435. {
  1436. if (!is_numeric($str)) return $str;
  1437. //
  1438. $text = '';
  1439. for ($i = 0; $i < strlen($str); $i++) {
  1440. $text .= $str[$i];
  1441. if ($i % 4 == 3) {
  1442. $text .= $interval;
  1443. }
  1444. }
  1445. return $text;
  1446. }
  1447. /**
  1448. * 保留两位小数点
  1449. * @param $str
  1450. * @param bool $float
  1451. * @return float
  1452. */
  1453. public static function twoFloat($str, $float = false)
  1454. {
  1455. $str = sprintf("%.2f", floatval($str));
  1456. if ($float === true) {
  1457. $str = floatval($str);
  1458. }
  1459. return $str;
  1460. }
  1461. /**
  1462. * 获取时间戳
  1463. * @param bool $refresh
  1464. * @return int
  1465. */
  1466. public static function time($refresh = false)
  1467. {
  1468. global $_A;
  1469. if (!isset($_A["__static_time"]) || $refresh === true) {
  1470. $_A["__static_time"] = time();
  1471. }
  1472. return $_A["__static_time"];
  1473. }
  1474. /**
  1475. * 获取毫秒时间戳
  1476. * @return float
  1477. */
  1478. public static function msecTime()
  1479. {
  1480. list($msec, $sec) = explode(' ', microtime());
  1481. $time = explode(".", $sec . ($msec * 1000));
  1482. return $time[0];
  1483. }
  1484. /**
  1485. * 时间差(不够1个小时算一个小时)
  1486. * @param int $s 开始时间戳
  1487. * @param int $e 结束时间戳
  1488. * @return string
  1489. */
  1490. public static function timeDiff($s, $e)
  1491. {
  1492. $d = $e - $s;
  1493. if ($d > 86400) {
  1494. $day = floor($d / 86400);
  1495. $hour = ceil(($d - ($day * 86400)) / 3600);
  1496. if ($hour > 0) {
  1497. return $day . '天' . $hour . '小时';
  1498. } else {
  1499. return $day . '天';
  1500. }
  1501. } elseif ($d > 3600) {
  1502. return ceil($d / 3600) . '小时';
  1503. } elseif ($d > 60) {
  1504. return ceil($d / 60) . '分钟';
  1505. } elseif ($d > 1) {
  1506. return '1分钟内';
  1507. } else {
  1508. return '0秒';
  1509. }
  1510. }
  1511. /**
  1512. * 获取IP地址
  1513. * @return string
  1514. */
  1515. public static function getIp()
  1516. {
  1517. global $_A;
  1518. if (!isset($_A["__static_ip"])) {
  1519. if (getenv('HTTP_CLIENT_IP') and strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
  1520. $onlineip = getenv('HTTP_CLIENT_IP');
  1521. } elseif (getenv('HTTP_X_FORWARDED_FOR') and strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
  1522. $onlineip = getenv('HTTP_X_FORWARDED_FOR');
  1523. } elseif (getenv('REMOTE_ADDR') and strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
  1524. $onlineip = getenv('REMOTE_ADDR');
  1525. } elseif (isset($_SERVER['REMOTE_ADDR']) and $_SERVER['REMOTE_ADDR'] and strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
  1526. $onlineip = $_SERVER['REMOTE_ADDR'];
  1527. } elseif (Request::header('X-Real-IP')) {
  1528. $onlineip = Request::header('X-Real-IP');
  1529. } else {
  1530. $onlineip = '0,0,0,0';
  1531. }
  1532. preg_match("/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/", $onlineip, $match);
  1533. $_A["__static_ip"] = $match[0] ? $match[0] : 'unknown';
  1534. }
  1535. return $_A["__static_ip"];
  1536. }
  1537. /**
  1538. * 获取IP地址
  1539. * @param string $ip
  1540. * @return array|mixed
  1541. */
  1542. public static function getIpInfo($ip = '')
  1543. {
  1544. if (empty($ip)) {
  1545. $ip = self::getIp();
  1546. }
  1547. $cacheKey = "getIpInfo::" . md5($ip);
  1548. $result = Cache::rememberForever($cacheKey, function() use ($ip) {
  1549. return Ihttp::ihttp_request("http://ip.taobao.com/service/getIpInfo.php?accessKey=alibaba-inc&ip=" . $ip, [], [], 8);
  1550. });
  1551. if (Base::isError($result)) {
  1552. return $result;
  1553. }
  1554. $data = json_decode($result['data'], true);
  1555. if (!is_array($data) || intval($data['code']) != 0) {
  1556. Cache::forget($cacheKey);
  1557. return Base::retError("error ip: -1");
  1558. }
  1559. $data = $data['data'];
  1560. if (!is_array($data) || !isset($data['country'])) {
  1561. return Base::retError("error ip: -2");
  1562. }
  1563. $data['text'] = $data['country'];
  1564. $data['textSmall'] = $data['country'];
  1565. if ($data['region'] && $data['region'] != $data['country'] && $data['region'] != "XX") {
  1566. $data['text'].= " " . $data['region'];
  1567. $data['textSmall'] = $data['region'];
  1568. }
  1569. if ($data['city'] && $data['city'] != $data['region'] && $data['city'] != "XX") {
  1570. $data['text'].= " " . $data['city'];
  1571. $data['textSmall'].= " " . $data['city'];
  1572. }
  1573. if ($data['county'] && $data['county'] != $data['city'] && $data['county'] != "XX") {
  1574. $data['text'].= " " . $data['county'];
  1575. $data['textSmall'].= " " . $data['county'];
  1576. }
  1577. return Base::retSuccess("success", $data);
  1578. }
  1579. /**
  1580. * 是否是中国IP:-1错误、1是、0否
  1581. * @param string $ip
  1582. * @return int
  1583. */
  1584. public static function isCnIp($ip = '')
  1585. {
  1586. if (empty($ip)) {
  1587. $ip = self::getIp();
  1588. }
  1589. $cacheKey = "isCnIp::" . md5($ip);
  1590. //
  1591. $result = Cache::remember($cacheKey, now()->addMinutes(10), function () use ($ip) {
  1592. $file = dirname(__FILE__) . '/ip/all_cn.txt';
  1593. if (!file_exists($file)) {
  1594. return -1;
  1595. }
  1596. $in = false;
  1597. $myFile = fopen($file, "r");
  1598. $i = 0;
  1599. while (!feof($myFile)) {
  1600. $i++;
  1601. $cidr = trim(fgets($myFile));
  1602. if (Base::ipInRange($ip, $cidr)) {
  1603. $in = true;
  1604. break;
  1605. }
  1606. }
  1607. fclose($myFile);
  1608. return $in ? 1 : 0;
  1609. });
  1610. if ($result === -1) {
  1611. Cache::forget($cacheKey);
  1612. }
  1613. //
  1614. return intval($result);
  1615. }
  1616. /**
  1617. * 验证IP地址范围
  1618. * $range 支持多种写法
  1619. * - Wildcard: 1.2.3.*
  1620. * - CIRD:1.2.3/24 或者 1.2.3.4/255.255.255.0
  1621. * - Start-End: 1.2.3.0-1.2.3.255
  1622. * @param $ip
  1623. * @param $range
  1624. * @return bool
  1625. */
  1626. public static function ipInRange($ip, $range)
  1627. {
  1628. if (substr_count($ip, '.') == 3 && $ip == $range) {
  1629. return true;
  1630. }
  1631. if (strpos($range, '/') !== false) {
  1632. list($range, $netmask) = explode('/', $range, 2);
  1633. if (strpos($netmask, '.') !== false) {
  1634. $netmask = str_replace('*', '0', $netmask);
  1635. $netmask_dec = ip2long($netmask);
  1636. return ((ip2long($ip) & $netmask_dec) == (ip2long($range) & $netmask_dec));
  1637. } else {
  1638. $x = explode('.', $range);
  1639. while (count($x) < 4) {
  1640. $x[] = '0';
  1641. }
  1642. list($a, $b, $c, $d) = $x;
  1643. $range = sprintf("%u.%u.%u.%u", empty($a) ? '0' : $a, empty($b) ? '0' : $b, empty($c) ? '0' : $c, empty($d) ? '0' : $d);
  1644. $range_dec = ip2long($range);
  1645. $ip_dec = ip2long($ip);
  1646. $wildcard_dec = pow(2, (32 - $netmask)) - 1;
  1647. $netmask_dec = ~$wildcard_dec;
  1648. return (($ip_dec & $netmask_dec) == ($range_dec & $netmask_dec));
  1649. }
  1650. } else {
  1651. if (strpos($range, '*') !== false) {
  1652. $lower = str_replace('*', '0', $range);
  1653. $upper = str_replace('*', '255', $range);
  1654. $range = "$lower-$upper";
  1655. }
  1656. if (strpos($range, '-') !== false) {
  1657. list($lower, $upper) = explode('-', $range, 2);
  1658. $lower_dec = (float)sprintf("%u", ip2long($lower));
  1659. $upper_dec = (float)sprintf("%u", ip2long($upper));
  1660. $ip_dec = (float)sprintf("%u", ip2long($ip));
  1661. return (($ip_dec >= $lower_dec) && ($ip_dec <= $upper_dec));
  1662. }
  1663. return false;
  1664. }
  1665. }
  1666. /**
  1667. * php://input 字符串解析到变量并获取指定值
  1668. * @param $key
  1669. * @return array
  1670. */
  1671. public static function getContentsParse($key)
  1672. {
  1673. parse_str(Request::getContent(), $input);
  1674. if ($key) {
  1675. $input = isset($input[$key])?$input[$key]:array();
  1676. }
  1677. return is_array($input)?$input:array($input);
  1678. }
  1679. /**
  1680. * 多维 array_values
  1681. * @param $array
  1682. * @param string $keyName
  1683. * @param string $valName
  1684. * @return array
  1685. */
  1686. public static function array_values_recursive($array, $keyName = 'key', $valName = 'item') {
  1687. if (is_array($array) && count($array) > 0) {
  1688. $temp = [];
  1689. foreach ($array as $key => $value) {
  1690. $continue = false;
  1691. if (is_array($value) && count($value) > 0) {
  1692. $continue = true;
  1693. foreach ($value AS $item) {
  1694. if (!is_array($item)) {
  1695. $continue = false;
  1696. break;
  1697. }
  1698. }
  1699. }
  1700. $temp[] = [
  1701. $keyName => $key,
  1702. $valName => $continue ? self::array_values_recursive($value, $keyName, $valName) : $value,
  1703. ];
  1704. }
  1705. return $temp;
  1706. }
  1707. return $array;
  1708. }
  1709. /**
  1710. * 获取tonken
  1711. * @return string
  1712. */
  1713. public static function getToken()
  1714. {
  1715. global $_A;
  1716. if (!isset($_A["__static_token"])) {
  1717. $_A["__static_token"] = Base::nullShow(Request::header('token'), Request::input('token'));
  1718. }
  1719. return $_A["__static_token"];
  1720. }
  1721. /**
  1722. * 设置tonken
  1723. * @param $token
  1724. */
  1725. public static function setToken($token)
  1726. {
  1727. global $_A;
  1728. $_A["__static_token"] = $token;
  1729. }
  1730. /**
  1731. * 是否微信
  1732. * @return bool
  1733. */
  1734. public static function isWechat()
  1735. {
  1736. return strpos(Request::server('HTTP_USER_AGENT'), 'MicroMessenger') !== false;
  1737. }
  1738. /**
  1739. * 获取浏览器类型
  1740. * @return string
  1741. */
  1742. public static function browser()
  1743. {
  1744. $user_agent = Request::server('HTTP_USER_AGENT');
  1745. if (strpos($user_agent, 'AlipayClient') !== false) {
  1746. return 'alipay';
  1747. }elseif (strpos($user_agent, 'MicroMessenger') !== false) {
  1748. return 'weixin';
  1749. }else{
  1750. return 'none';
  1751. }
  1752. }
  1753. /**
  1754. * 返回根据距离sql排序语句
  1755. * @param $lat
  1756. * @param $lng
  1757. * @param string $latName
  1758. * @param string $lngName
  1759. * @return string
  1760. */
  1761. public static function acos($lat , $lng, $latName = 'lat', $lngName = 'lng') {
  1762. $lat = floatval($lat);
  1763. $lng = floatval($lng);
  1764. return 'ACOS(
  1765. SIN(('.$lat.' * 3.1415) / 180) * SIN(('.$latName.' * 3.1415) / 180) + COS(('.$lat.' * 3.1415) / 180) * COS(('.$latName.' * 3.1415) / 180) * COS(
  1766. ('.$lng.' * 3.1415) / 180 - ('.$lngName.' * 3.1415) / 180
  1767. )
  1768. ) * 6380';
  1769. }
  1770. /**
  1771. * 获取分页详细信息
  1772. * @param LengthAwarePaginator $lists
  1773. * @param bool $getTotal
  1774. * @return array
  1775. */
  1776. public static function getPageInfo(LengthAwarePaginator $lists, $getTotal = true)
  1777. {
  1778. return [
  1779. "currentPage" => $lists->currentPage(),
  1780. "firstItem" => $lists->firstItem(),
  1781. "hasMorePages" => $lists->hasMorePages(),
  1782. "lastItem" => $lists->lastItem(),
  1783. "lastPage" => $lists->lastPage(),
  1784. "nextPageUrl" => $lists->nextPageUrl(),
  1785. "previousPageUrl" => $lists->previousPageUrl(),
  1786. "perPage" => $lists->perPage(),
  1787. "total" => $getTotal === true ? $lists->total() : -1,
  1788. ];
  1789. }
  1790. /**
  1791. * 获取分页数据
  1792. * @param $lists
  1793. * @param bool $getTotal
  1794. * @return array
  1795. */
  1796. public static function getPageList($lists, $getTotal = true)
  1797. {
  1798. $data = Base::getPageInfo($lists, $getTotal);
  1799. $data['lists'] = Base::coll2array($lists);
  1800. return $data;
  1801. }
  1802. /**
  1803. * 上传文件
  1804. * @param array $param [ type=[文件类型], file=>Request::file, path=>文件路径, fileName=>文件名称, scale=>[压缩原图宽,高, 压缩方式], size=>限制大小KB, autoThumb=>false不要自动生成缩略图 ]
  1805. * @return array [name=>原文件名, size=>文件大小(单位KB),file=>绝对地址, path=>相对地址, url=>全路径地址, ext=>文件后缀名]
  1806. */
  1807. public static function upload($param)
  1808. {
  1809. $file = $param['file'];
  1810. if (empty($file)) {
  1811. return Base::retError("您没有选择要上传的文件!");
  1812. }
  1813. if($file->isValid()){
  1814. Base::makeDir(public_path($param['path']));
  1815. //
  1816. switch ($param['type']) {
  1817. case 'png':
  1818. $type = ['png'];
  1819. break;
  1820. case 'png+jpg':
  1821. $type = ['jpg', 'jpeg', 'png'];
  1822. break;
  1823. case 'image':
  1824. $type = ['jpg', 'jpeg', 'gif', 'png'];
  1825. break;
  1826. case 'video':
  1827. $type = ['rm', 'rmvb', 'wmv', 'avi', 'mpg', 'mpeg', 'mp4'];
  1828. break;
  1829. case 'audio':
  1830. $type = ['mp3', 'wma', 'wav', 'amr'];
  1831. break;
  1832. case 'excel':
  1833. $type = ['xls', 'xlsx'];
  1834. break;
  1835. case 'app':
  1836. $type = ['apk'];
  1837. break;
  1838. case 'zip':
  1839. $type = ['zip'];
  1840. break;
  1841. case 'file':
  1842. $type = ['jpg', 'jpeg', 'png', 'gif', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'esp'];
  1843. break;
  1844. default:
  1845. return Base::retError('错误的类型参数');
  1846. }
  1847. $extension = strtolower($file->getClientOriginalExtension());
  1848. if ($type && is_array($type) && !in_array($extension, $type)) {
  1849. return Base::retError(['文件格式错误,限制类型:%!', implode(",", $type)]);
  1850. }
  1851. try {
  1852. $fileSize = $file->getSize();
  1853. if ($param['size'] > 0 && $fileSize > $param['size'] * 1024) {
  1854. return Base::retError(['文件大小超限,最大限制:%KB!', $param['size']]);
  1855. }
  1856. } catch (Exception $e) {
  1857. $fileSize = 0;
  1858. }
  1859. $scaleName = "";
  1860. if ($param['fileName']) {
  1861. $fileName = $param['fileName'];
  1862. }else{
  1863. if ($param['scale'] && is_array($param['scale'])) {
  1864. list($width, $height) = $param['scale'];
  1865. if ($width > 0 || $height > 0) {
  1866. $scaleName = "_{WIDTH}x{HEIGHT}";
  1867. if (isset($param['scale'][2])) {
  1868. $scaleName.= $param['scale'][2];
  1869. }
  1870. }
  1871. }
  1872. $fileName = md5_file($file) . '.' . $extension;
  1873. $scaleName = md5_file($file) . $scaleName . '.' . $extension;
  1874. }
  1875. //
  1876. $file->move(public_path($param['path']), $fileName);
  1877. //
  1878. $array = [
  1879. "name" => $file->getClientOriginalName(), //原文件名
  1880. "size" => Base::twoFloat($fileSize / 1024, true), //大小KB
  1881. "file" => public_path($param['path'].$fileName), //目录的完整路径 "D:\www....KzZ.jpg"
  1882. "path" => $param['path'].$fileName, //相对路径 "uploads/pic....KzZ.jpg"
  1883. "url" => Base::fillUrl($param['path'].$fileName), //完整的URL "https://.....hhsKzZ.jpg"
  1884. "thumb" => '', //缩略图(预览图) "https://.....hhsKzZ.jpg_thumb.jpg"
  1885. "width" => -1, //图片宽度
  1886. "height" => -1, //图片高度
  1887. "ext" => $extension, //文件后缀名
  1888. ];
  1889. if (!is_file($array['file'])) {
  1890. return Base::retError('上传失败!');
  1891. }
  1892. //iOS照片颠倒处理
  1893. if (in_array($extension, ['jpg', 'jpeg']) && function_exists('exif_read_data')) {
  1894. $data = imagecreatefromstring(file_get_contents($array['file']));
  1895. $exif = @exif_read_data($array['file']);
  1896. if (!empty($exif['Orientation'])) {
  1897. switch ($exif['Orientation']) {
  1898. case 8:
  1899. $data = imagerotate($data, 90, 0);
  1900. break;
  1901. case 3:
  1902. $data = imagerotate($data, 180, 0);
  1903. break;
  1904. case 6:
  1905. $data = imagerotate($data, -90, 0);
  1906. break;
  1907. default:
  1908. $data = null;
  1909. break;
  1910. }
  1911. if ($data !== null) {
  1912. imagejpeg($data, $array['file']);
  1913. }
  1914. }
  1915. }
  1916. //
  1917. if (in_array($param['type'], ['png', 'png+jpg', 'image'])) {
  1918. //图片尺寸
  1919. $paramet = getimagesize($array['file']);
  1920. $array['width'] = $paramet[0];
  1921. $array['height'] = $paramet[1];
  1922. //原图压缩
  1923. if ($param['scale'] && is_array($param['scale'])) {
  1924. list($width, $height) = $param['scale'];
  1925. if (($width > 0 && $array['width'] > $width) || ($height > 0 && $array['height'] > $height)) {
  1926. $cut = ($width > 0 && $height > 0) ? 1 : -1;
  1927. $cut = $param['scale'][2] ?? $cut;
  1928. //图片压缩
  1929. $tmpFile = $array['file'] . '_tmp.jpg';
  1930. if (Base::imgThumb($array['file'], $tmpFile, $width, $height, $cut)) {
  1931. $tmpSize = filesize($tmpFile);
  1932. if ($tmpSize > $fileSize) {
  1933. @unlink($tmpFile);
  1934. }else{
  1935. @unlink($array['file']);
  1936. rename($tmpFile, $array['file']);
  1937. }
  1938. }
  1939. //图片尺寸
  1940. $paramet = getimagesize($array['file']);
  1941. $array['width'] = $paramet[0];
  1942. $array['height'] = $paramet[1];
  1943. //重命名
  1944. if ($scaleName) {
  1945. $scaleName = str_replace(['{WIDTH}', '{HEIGHT}'], [$array['width'], $array['height']], $scaleName);
  1946. if (rename($array['file'], Base::rightDelete($array['file'], $fileName) . $scaleName)) {
  1947. $array['file'] = Base::rightDelete($array['file'], $fileName) . $scaleName;
  1948. $array['path'] = Base::rightDelete($array['path'], $fileName) . $scaleName;
  1949. $array['url'] = Base::rightDelete($array['url'], $fileName) . $scaleName;
  1950. }
  1951. }
  1952. }
  1953. }
  1954. //生成缩略图
  1955. $array['thumb'] = $array['path'];
  1956. if ($param['autoThumb'] === "false") $param['autoThumb'] = false;
  1957. if ($param['autoThumb'] !== false) {
  1958. if (Base::imgThumb($array['file'], $array['file']."_thumb.jpg", 180, 0)) {
  1959. $array['thumb'].= "_thumb.jpg";
  1960. }
  1961. }
  1962. $array['thumb'] = Base::fillUrl($array['thumb']);
  1963. }
  1964. //
  1965. return Base::retSuccess('success', $array);
  1966. }else{
  1967. return Base::retError($file->getErrorMessage());
  1968. }
  1969. }
  1970. /**
  1971. * 生成缩略图
  1972. * @param string $src_img 源图绝对完整地址{带文件名及后缀名}
  1973. * @param string $dst_img 目标图绝对完整地址{带文件名及后缀名}
  1974. * @param int $width 缩略图宽{0:此时目标高度不能为0,目标宽度为源图宽*(目标高度/源图高)}
  1975. * @param int $height 缩略图高{0:此时目标宽度不能为0,目标高度为源图高*(目标宽度/源图宽)}
  1976. * @param int $cut 是否裁切{宽,高必须非0}:1是、0否、-1或'auto'保持等比
  1977. * @param int $proportion 缩放{0:不缩放, 0<this<1:缩放到相应比例(此时宽高限制和裁切均失效)}
  1978. * @return bool
  1979. */
  1980. public static function imgThumb($src_img, $dst_img, $width = 75, $height = 75, $cut = 0, $proportion = 0)
  1981. {
  1982. if (!is_file($src_img)) {
  1983. return false;
  1984. }
  1985. if (empty($dst_img)) {
  1986. $dst_img = $src_img;
  1987. }
  1988. $st = pathinfo($src_img, PATHINFO_EXTENSION);
  1989. if (!in_array(strtolower($st), array('jpg', 'jpeg', 'png', 'gif', 'bmp'))) {
  1990. return false;
  1991. }
  1992. $ot = pathinfo($dst_img, PATHINFO_EXTENSION);
  1993. $otfunc = 'image' . ($ot == 'jpg' ? 'jpeg' : $ot);
  1994. $srcinfo = getimagesize($src_img);
  1995. $src_w = $srcinfo[0];
  1996. $src_h = $srcinfo[1];
  1997. $type = strtolower(substr(image_type_to_extension($srcinfo[2]), 1));
  1998. if (empty($type)) {
  1999. return false;
  2000. }
  2001. $createfun = 'imagecreatefrom' . ($type == 'jpg' ? 'jpeg' : $type);
  2002. $dst_h = $height;
  2003. $dst_w = $width;
  2004. $x = $y = 0;
  2005. /**
  2006. * 缩略图不超过源图尺寸(前提是宽或高只有一个)
  2007. */
  2008. if (($width > $src_w && $height > $src_h) || ($height > $src_h && $width == 0) || ($width > $src_w && $height == 0)) {
  2009. $proportion = 1;
  2010. }
  2011. if ($width > $src_w) {
  2012. $dst_w = $width = $src_w;
  2013. }
  2014. if ($height > $src_h) {
  2015. $dst_h = $height = $src_h;
  2016. }
  2017. if (!$width && !$height && !$proportion) {
  2018. return false;
  2019. }
  2020. if (!$proportion) {
  2021. if ($cut == 'auto' || $cut == -1) {
  2022. if ($dst_w && $dst_h) {
  2023. $wB = $dst_w / $src_w;
  2024. $hB = $dst_h / $src_h;
  2025. if ($wB > $hB) {
  2026. $dst_w = 0;
  2027. }else{
  2028. $dst_h = 0;
  2029. }
  2030. }
  2031. $cut = 0;
  2032. }
  2033. if ($cut == 0) {
  2034. if ($dst_w && $dst_h) {
  2035. if ($dst_w / $src_w > $dst_h / $src_h) {
  2036. $dst_w = $src_w * ($dst_h / $src_h);
  2037. $x = 0 - ($dst_w - $width) / 2;
  2038. } else {
  2039. $dst_h = $src_h * ($dst_w / $src_w);
  2040. $y = 0 - ($dst_h - $height) / 2;
  2041. }
  2042. } else if ($dst_w xor $dst_h) {
  2043. if ($dst_w && !$dst_h) //有宽无高
  2044. {
  2045. $propor = $dst_w / $src_w;
  2046. $height = $dst_h = $src_h * $propor;
  2047. } else if (!$dst_w && $dst_h) //有高无宽
  2048. {
  2049. $propor = $dst_h / $src_h;
  2050. $width = $dst_w = $src_w * $propor;
  2051. }
  2052. }
  2053. } else {
  2054. if (!$dst_h) //裁剪时无高
  2055. {
  2056. $height = $dst_h = $dst_w;
  2057. }
  2058. if (!$dst_w) //裁剪时无宽
  2059. {
  2060. $width = $dst_w = $dst_h;
  2061. }
  2062. $propor = min(max($dst_w / $src_w, $dst_h / $src_h), 1);
  2063. $dst_w = (int)round($src_w * $propor);
  2064. $dst_h = (int)round($src_h * $propor);
  2065. $x = ($width - $dst_w) / 2;
  2066. $y = ($height - $dst_h) / 2;
  2067. }
  2068. } else {
  2069. $proportion = min($proportion, 1);
  2070. $height = $dst_h = $src_h * $proportion;
  2071. $width = $dst_w = $src_w * $proportion;
  2072. }
  2073. if (!function_exists($createfun)) {
  2074. return false;
  2075. }
  2076. $src = $createfun($src_img);
  2077. $dst = imagecreatetruecolor($width ? $width : $dst_w, $height ? $height : $dst_h);
  2078. try {
  2079. $white = imagecolorallocate($dst, 255, 255, 255);
  2080. imagefill($dst, 0, 0, $white);
  2081. } catch (Exception $e) {
  2082. }
  2083. if (function_exists('imagecopyresampled')) {
  2084. imagecopyresampled($dst, $src, $x, $y, 0, 0, $dst_w, $dst_h, $src_w, $src_h);
  2085. } else {
  2086. imagecopyresized($dst, $src, $x, $y, 0, 0, $dst_w, $dst_h, $src_w, $src_h);
  2087. }
  2088. $otfunc($dst, $dst_img);
  2089. imagedestroy($dst);
  2090. imagedestroy($src);
  2091. return true;
  2092. }
  2093. /**
  2094. * 排列组合(无重复)
  2095. * @param $arr
  2096. * @param $m
  2097. * @return array
  2098. */
  2099. public static function getCombinationToString($arr, $m)
  2100. {
  2101. $result = [];
  2102. if ($m == 1) {
  2103. return $arr;
  2104. }
  2105. if ($m == count($arr)) {
  2106. $result[] = implode(',', $arr);
  2107. return $result;
  2108. }
  2109. $temp_firstelement = $arr[0];
  2110. unset($arr[0]);
  2111. $arr = array_values($arr);
  2112. $temp_list1 = self::getCombinationToString($arr, ($m - 1));
  2113. foreach ($temp_list1 as $s) {
  2114. $s = $temp_firstelement . ',' . $s;
  2115. $result[] = $s;
  2116. }
  2117. unset($temp_list1);
  2118. $temp_list2 = self::getCombinationToString($arr, $m);
  2119. foreach ($temp_list2 as $s) {
  2120. $result[] = $s;
  2121. }
  2122. unset($temp_list2);
  2123. return $result;
  2124. }
  2125. /**
  2126. * 不同元素交叉组合(多个数组)
  2127. * @return array
  2128. */
  2129. public static function getNewArray()
  2130. {
  2131. $args = func_get_args();
  2132. $pailie = function ($arr1, $arr2) {
  2133. $arr = [];
  2134. $k = 0;
  2135. foreach ($arr1 as $k1 => $v1) {
  2136. foreach ($arr2 as $k2 => $v2) {
  2137. $arr[$k] = $v1 . "," . $v2;
  2138. $k++;
  2139. }
  2140. }
  2141. return $arr;
  2142. };
  2143. $arr = [];
  2144. foreach ($args as $k => $v) {
  2145. if (isset($args[$k + 1]) && $args[$k + 1]) {
  2146. switch ($k) {
  2147. case 0:
  2148. $arr[$k] = $pailie($v, $args[$k + 1]);
  2149. break;
  2150. default:
  2151. $arr[$k] = $pailie($arr[$k - 1], $args[$k + 1]);
  2152. break;
  2153. }
  2154. }
  2155. }
  2156. $key = count($arr) - 1;
  2157. return array_values($arr[$key]);
  2158. }
  2159. /**
  2160. * 获取当前是本月第几个星期
  2161. * @return false|float
  2162. */
  2163. public static function getMonthWeek()
  2164. {
  2165. $time = strtotime(date("Y-m-01"));
  2166. $w = date('w', $time);
  2167. $j = date("j");
  2168. return ceil(($j + $w) / 7);
  2169. }
  2170. /**
  2171. * 把返回的数据集转换成Tree
  2172. * @param array $list 要转换的数据集
  2173. * @param string $pk id标记字段
  2174. * @param string $pid parent标记字段
  2175. * @param string $child 生成子类字段
  2176. * @param int $root
  2177. * @return array
  2178. */
  2179. public static function list2Tree($list, $pk='id', $pid = 'pid', $child = 'children', $root = 0) {
  2180. if (!is_array($list)) {
  2181. return [];
  2182. }
  2183. // 创建基于主键的数组引用
  2184. $aRefer = [];
  2185. foreach ($list as $key => $data) {
  2186. $list[$key][$child] = [];
  2187. $aRefer[$data[$pk]] = & $list[$key];
  2188. }
  2189. $tree = [];
  2190. foreach ($list as $key => $data) {
  2191. // 判断是否存在parent
  2192. $parentId = $data[$pid];
  2193. if ($root === $parentId) {
  2194. $tree[] = & $list[$key];
  2195. } else {
  2196. if (isset($aRefer[$parentId])) {
  2197. $parent = & $aRefer[$parentId];
  2198. $parent[$child][] = & $list[$key];
  2199. }
  2200. }
  2201. }
  2202. return $tree;
  2203. }
  2204. /**
  2205. * 遍历获取文件
  2206. * @param $dir
  2207. * @return array
  2208. */
  2209. public static function readDir($dir)
  2210. {
  2211. $files = array();
  2212. $dir_list = scandir($dir);
  2213. foreach ($dir_list as $file) {
  2214. if ($file != '..' && $file != '.') {
  2215. if (is_dir($dir . '/' . $file)) {
  2216. $files = array_merge($files, self::readDir($dir . '/' . $file));
  2217. } else {
  2218. $files[] = $dir . "/" . $file;
  2219. }
  2220. }
  2221. }
  2222. return $files;
  2223. }
  2224. /**
  2225. * 获取中文字符拼音首字母
  2226. * @param $str
  2227. * @return string
  2228. */
  2229. public static function getFirstCharter($str)
  2230. {
  2231. if (empty($str)) {
  2232. return '';
  2233. }
  2234. $fchar = ord($str[0]);
  2235. if ($fchar >= ord('A') && $fchar <= ord('z')) return strtoupper($str[0]);
  2236. $s1 = iconv('UTF-8', 'gb2312', $str);
  2237. $s2 = iconv('gb2312', 'UTF-8', $s1);
  2238. $s = $s2 == $str ? $s1 : $str;
  2239. $asc = ord($s[0]) * 256 + ord($s[1]) - 65536;
  2240. if ($asc >= -20319 && $asc <= -20284) return 'A';
  2241. if ($asc >= -20283 && $asc <= -19776) return 'B';
  2242. if ($asc >= -19775 && $asc <= -19219) return 'C';
  2243. if ($asc >= -19218 && $asc <= -18711) return 'D';
  2244. if ($asc >= -18710 && $asc <= -18527) return 'E';
  2245. if ($asc >= -18526 && $asc <= -18240) return 'F';
  2246. if ($asc >= -18239 && $asc <= -17923) return 'G';
  2247. if ($asc >= -17922 && $asc <= -17418) return 'H';
  2248. if ($asc >= -17417 && $asc <= -16475) return 'J';
  2249. if ($asc >= -16474 && $asc <= -16213) return 'K';
  2250. if ($asc >= -16212 && $asc <= -15641) return 'L';
  2251. if ($asc >= -15640 && $asc <= -15166) return 'M';
  2252. if ($asc >= -15165 && $asc <= -14923) return 'N';
  2253. if ($asc >= -14922 && $asc <= -14915) return 'O';
  2254. if ($asc >= -14914 && $asc <= -14631) return 'P';
  2255. if ($asc >= -14630 && $asc <= -14150) return 'Q';
  2256. if ($asc >= -14149 && $asc <= -14091) return 'R';
  2257. if ($asc >= -14090 && $asc <= -13319) return 'S';
  2258. if ($asc >= -13318 && $asc <= -12839) return 'T';
  2259. if ($asc >= -12838 && $asc <= -12557) return 'W';
  2260. if ($asc >= -12556 && $asc <= -11848) return 'X';
  2261. if ($asc >= -11847 && $asc <= -11056) return 'Y';
  2262. if ($asc >= -11055 && $asc <= -10247) return 'Z';
  2263. return '#';
  2264. }
  2265. /**
  2266. * 缓存数据
  2267. * @param $title
  2268. * @param null $value
  2269. * @return mixed|null
  2270. */
  2271. public static function cacheData($title, $value = null)
  2272. {
  2273. $title = "cacheData::" . $title;
  2274. $tmp = DB::table('tmp')->where('title', $title)->select('value')->first();
  2275. if ($value !== null ) {
  2276. if (empty($tmp)) {
  2277. DB::table('tmp')->insert(['title'=>$title, 'value'=>$value]);
  2278. }else{
  2279. DB::table('tmp')->where('title', $title)->update(['value'=>$value]);
  2280. }
  2281. return $value;
  2282. }else{
  2283. return $tmp->value;
  2284. }
  2285. }
  2286. }