Base.php 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178
  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. * @param bool $getTotal
  1663. * @return array
  1664. */
  1665. public static function getPageInfo(LengthAwarePaginator $lists, $getTotal = true)
  1666. {
  1667. return [
  1668. "currentPage" => $lists->currentPage(),
  1669. "firstItem" => $lists->firstItem(),
  1670. "hasMorePages" => $lists->hasMorePages(),
  1671. "lastItem" => $lists->lastItem(),
  1672. "lastPage" => $lists->lastPage(),
  1673. "nextPageUrl" => $lists->nextPageUrl(),
  1674. "previousPageUrl" => $lists->previousPageUrl(),
  1675. "perPage" => $lists->perPage(),
  1676. "total" => $getTotal === true ? $lists->total() : -1,
  1677. ];
  1678. }
  1679. /**
  1680. * 获取分页数据
  1681. * @param $lists
  1682. * @param bool $getTotal
  1683. * @return array
  1684. */
  1685. public static function getPageList($lists, $getTotal = true)
  1686. {
  1687. $data = Base::getPageInfo($lists, $getTotal);
  1688. $data['lists'] = Base::coll2array($lists);
  1689. return $data;
  1690. }
  1691. /**
  1692. * 上传文件
  1693. * @param array $param [ type=[文件类型], file=>Request::file, path=>文件路径, fileName=>文件名称, scale=>[压缩原图宽,高, 压缩方式], size=>限制大小KB, autoThumb=>false不要自动生成缩略图 ]
  1694. * @return array [name=>原文件名, size=>文件大小(单位KB),file=>绝对地址, path=>相对地址, url=>全路径地址]
  1695. */
  1696. public static function upload($param)
  1697. {
  1698. $file = $param['file'];
  1699. if (empty($file)) {
  1700. return Base::retError("您没有选择要上传的文件!");
  1701. }
  1702. if($file->isValid()){
  1703. Base::makeDir(public_path($param['path']));
  1704. //
  1705. switch ($param['type']) {
  1706. case 'png':
  1707. $type = ['png'];
  1708. break;
  1709. case 'png+jpg':
  1710. $type = ['jpg', 'jpeg', 'png'];
  1711. break;
  1712. case 'image':
  1713. $type = ['jpg', 'jpeg', 'gif', 'png'];
  1714. break;
  1715. case 'video':
  1716. $type = ['rm', 'rmvb', 'wmv', 'avi', 'mpg', 'mpeg', 'mp4'];
  1717. break;
  1718. case 'audio':
  1719. $type = ['mp3', 'wma', 'wav', 'amr'];
  1720. break;
  1721. case 'excel':
  1722. $type = ['xls', 'xlsx'];
  1723. break;
  1724. case 'app':
  1725. $type = ['apk'];
  1726. break;
  1727. case 'zip':
  1728. $type = ['zip'];
  1729. break;
  1730. default:
  1731. return Base::retError('错误的类型参数');
  1732. }
  1733. $extension = strtolower($file->getClientOriginalExtension());
  1734. if ($type && is_array($type) && !in_array($extension, $type)) {
  1735. return Base::retError('文件格式错误,限制类型:'.implode(",", $type));
  1736. }
  1737. try {
  1738. $fileSize = $file->getSize();
  1739. if ($param['size'] > 0 && $fileSize > $param['size'] * 1024) {
  1740. return Base::retError('文件大小超限,最大限制:' . $param['size'] . 'kB');
  1741. }
  1742. } catch (Exception $e) {
  1743. $fileSize = 0;
  1744. }
  1745. $scaleName = "";
  1746. if ($param['fileName']) {
  1747. $fileName = $param['fileName'];
  1748. }else{
  1749. if ($param['scale'] && is_array($param['scale'])) {
  1750. list($width, $height) = $param['scale'];
  1751. if ($width > 0 || $height > 0) {
  1752. $scaleName = "_{WIDTH}x{HEIGHT}";
  1753. if (isset($param['scale'][2])) {
  1754. $scaleName.= $param['scale'][2];
  1755. }
  1756. }
  1757. }
  1758. $fileName = md5_file($file) . '.' . $extension;
  1759. $scaleName = md5_file($file) . $scaleName . '.' . $extension;
  1760. }
  1761. //
  1762. $file->move($param['path'], $fileName);
  1763. //
  1764. $array = [
  1765. "name" => $file->getClientOriginalName(), //原文件名
  1766. "size" => Base::twoFloat($fileSize / 1024, true), //大小KB
  1767. "file" => public_path($param['path'].$fileName), //目录的完整路径 "D:\www....KzZ.jpg"
  1768. "path" => $param['path'].$fileName, //相对路径 "uploads/pic....KzZ.jpg"
  1769. "url" => Base::fillUrl($param['path'].$fileName), //完整的URL "https://.....hhsKzZ.jpg"
  1770. "thumb" => '', //缩略图(预览图) "https://.....hhsKzZ.jpg_thumb.jpg"
  1771. "width" => -1, //图片宽度
  1772. "height" => -1, //图片高度
  1773. ];
  1774. if (!is_file($array['file'])) {
  1775. return Base::retError('上传失败!');
  1776. }
  1777. //iOS照片颠倒处理
  1778. if (in_array($extension, ['jpg', 'jpeg']) && function_exists('exif_read_data')) {
  1779. $data = imagecreatefromstring(file_get_contents($array['file']));
  1780. $exif = @exif_read_data($array['file']);
  1781. if (!empty($exif['Orientation'])) {
  1782. switch ($exif['Orientation']) {
  1783. case 8:
  1784. $data = imagerotate($data, 90, 0);
  1785. break;
  1786. case 3:
  1787. $data = imagerotate($data, 180, 0);
  1788. break;
  1789. case 6:
  1790. $data = imagerotate($data, -90, 0);
  1791. break;
  1792. default:
  1793. $data = null;
  1794. break;
  1795. }
  1796. if ($data !== null) {
  1797. imagejpeg($data, $array['file']);
  1798. }
  1799. }
  1800. }
  1801. //
  1802. if (in_array($param['type'], ['png', 'png+jpg', 'image'])) {
  1803. //图片尺寸
  1804. $paramet = getimagesize($array['file']);
  1805. $array['width'] = $paramet[0];
  1806. $array['height'] = $paramet[1];
  1807. //原图压缩
  1808. if ($param['scale'] && is_array($param['scale'])) {
  1809. list($width, $height) = $param['scale'];
  1810. if (($width > 0 && $array['width'] > $width) || ($height > 0 && $array['height'] > $height)) {
  1811. $cut = ($width > 0 && $height > 0) ? 1 : -1;
  1812. $cut = $param['scale'][2] ?? $cut;
  1813. //图片压缩
  1814. $tmpFile = $array['file'] . '_tmp.jpg';
  1815. if (Base::imgThumb($array['file'], $tmpFile, $width, $height, $cut)) {
  1816. $tmpSize = filesize($tmpFile);
  1817. if ($tmpSize > $fileSize) {
  1818. @unlink($tmpFile);
  1819. }else{
  1820. @unlink($array['file']);
  1821. rename($tmpFile, $array['file']);
  1822. }
  1823. }
  1824. //图片尺寸
  1825. $paramet = getimagesize($array['file']);
  1826. $array['width'] = $paramet[0];
  1827. $array['height'] = $paramet[1];
  1828. //重命名
  1829. if ($scaleName) {
  1830. $scaleName = str_replace(['{WIDTH}', '{HEIGHT}'], [$array['width'], $array['height']], $scaleName);
  1831. if (rename($array['file'], Base::rightDelete($array['file'], $fileName) . $scaleName)) {
  1832. $array['file'] = Base::rightDelete($array['file'], $fileName) . $scaleName;
  1833. $array['path'] = Base::rightDelete($array['path'], $fileName) . $scaleName;
  1834. $array['url'] = Base::rightDelete($array['url'], $fileName) . $scaleName;
  1835. }
  1836. }
  1837. }
  1838. }
  1839. //生成缩略图
  1840. $array['thumb'] = $array['path'];
  1841. if ($param['autoThumb'] === "false") $param['autoThumb'] = false;
  1842. if ($param['autoThumb'] !== false) {
  1843. if (Base::imgThumb($array['file'], $array['file']."_thumb.jpg", 180, 0)) {
  1844. $array['thumb'].= "_thumb.jpg";
  1845. }
  1846. }
  1847. $array['thumb'] = Base::fillUrl($array['thumb']);
  1848. }
  1849. //
  1850. return Base::retSuccess('success', $array);
  1851. }else{
  1852. return Base::retError($file->getErrorMessage());
  1853. }
  1854. }
  1855. /**
  1856. * 生成缩略图
  1857. * @param string $src_img 源图绝对完整地址{带文件名及后缀名}
  1858. * @param string $dst_img 目标图绝对完整地址{带文件名及后缀名}
  1859. * @param int $width 缩略图宽{0:此时目标高度不能为0,目标宽度为源图宽*(目标高度/源图高)}
  1860. * @param int $height 缩略图高{0:此时目标宽度不能为0,目标高度为源图高*(目标宽度/源图宽)}
  1861. * @param int $cut 是否裁切{宽,高必须非0}:1是、0否、-1或'auto'保持等比
  1862. * @param int $proportion 缩放{0:不缩放, 0<this<1:缩放到相应比例(此时宽高限制和裁切均失效)}
  1863. * @return bool
  1864. */
  1865. public static function imgThumb($src_img, $dst_img, $width = 75, $height = 75, $cut = 0, $proportion = 0)
  1866. {
  1867. if (!is_file($src_img)) {
  1868. return false;
  1869. }
  1870. if (empty($dst_img)) {
  1871. $dst_img = $src_img;
  1872. }
  1873. $st = pathinfo($src_img, PATHINFO_EXTENSION);
  1874. if (!in_array(strtolower($st), array('jpg', 'jpeg', 'png', 'gif', 'bmp'))) {
  1875. return false;
  1876. }
  1877. $ot = pathinfo($dst_img, PATHINFO_EXTENSION);
  1878. $otfunc = 'image' . ($ot == 'jpg' ? 'jpeg' : $ot);
  1879. $srcinfo = getimagesize($src_img);
  1880. $src_w = $srcinfo[0];
  1881. $src_h = $srcinfo[1];
  1882. $type = strtolower(substr(image_type_to_extension($srcinfo[2]), 1));
  1883. if (empty($type)) {
  1884. return false;
  1885. }
  1886. $createfun = 'imagecreatefrom' . ($type == 'jpg' ? 'jpeg' : $type);
  1887. $dst_h = $height;
  1888. $dst_w = $width;
  1889. $x = $y = 0;
  1890. /**
  1891. * 缩略图不超过源图尺寸(前提是宽或高只有一个)
  1892. */
  1893. if (($width > $src_w && $height > $src_h) || ($height > $src_h && $width == 0) || ($width > $src_w && $height == 0)) {
  1894. $proportion = 1;
  1895. }
  1896. if ($width > $src_w) {
  1897. $dst_w = $width = $src_w;
  1898. }
  1899. if ($height > $src_h) {
  1900. $dst_h = $height = $src_h;
  1901. }
  1902. if (!$width && !$height && !$proportion) {
  1903. return false;
  1904. }
  1905. if (!$proportion) {
  1906. if ($cut == 'auto' || $cut == -1) {
  1907. if ($dst_w && $dst_h) {
  1908. $wB = $dst_w / $src_w;
  1909. $hB = $dst_h / $src_h;
  1910. if ($wB > $hB) {
  1911. $dst_w = 0;
  1912. }else{
  1913. $dst_h = 0;
  1914. }
  1915. }
  1916. $cut = 0;
  1917. }
  1918. if ($cut == 0) {
  1919. if ($dst_w && $dst_h) {
  1920. if ($dst_w / $src_w > $dst_h / $src_h) {
  1921. $dst_w = $src_w * ($dst_h / $src_h);
  1922. $x = 0 - ($dst_w - $width) / 2;
  1923. } else {
  1924. $dst_h = $src_h * ($dst_w / $src_w);
  1925. $y = 0 - ($dst_h - $height) / 2;
  1926. }
  1927. } else if ($dst_w xor $dst_h) {
  1928. if ($dst_w && !$dst_h) //有宽无高
  1929. {
  1930. $propor = $dst_w / $src_w;
  1931. $height = $dst_h = $src_h * $propor;
  1932. } else if (!$dst_w && $dst_h) //有高无宽
  1933. {
  1934. $propor = $dst_h / $src_h;
  1935. $width = $dst_w = $src_w * $propor;
  1936. }
  1937. }
  1938. } else {
  1939. if (!$dst_h) //裁剪时无高
  1940. {
  1941. $height = $dst_h = $dst_w;
  1942. }
  1943. if (!$dst_w) //裁剪时无宽
  1944. {
  1945. $width = $dst_w = $dst_h;
  1946. }
  1947. $propor = min(max($dst_w / $src_w, $dst_h / $src_h), 1);
  1948. $dst_w = (int)round($src_w * $propor);
  1949. $dst_h = (int)round($src_h * $propor);
  1950. $x = ($width - $dst_w) / 2;
  1951. $y = ($height - $dst_h) / 2;
  1952. }
  1953. } else {
  1954. $proportion = min($proportion, 1);
  1955. $height = $dst_h = $src_h * $proportion;
  1956. $width = $dst_w = $src_w * $proportion;
  1957. }
  1958. if (!function_exists($createfun)) {
  1959. return false;
  1960. }
  1961. $src = $createfun($src_img);
  1962. $dst = imagecreatetruecolor($width ? $width : $dst_w, $height ? $height : $dst_h);
  1963. try {
  1964. $white = imagecolorallocate($dst, 255, 255, 255);
  1965. imagefill($dst, 0, 0, $white);
  1966. } catch (Exception $e) {
  1967. }
  1968. if (function_exists('imagecopyresampled')) {
  1969. imagecopyresampled($dst, $src, $x, $y, 0, 0, $dst_w, $dst_h, $src_w, $src_h);
  1970. } else {
  1971. imagecopyresized($dst, $src, $x, $y, 0, 0, $dst_w, $dst_h, $src_w, $src_h);
  1972. }
  1973. $otfunc($dst, $dst_img);
  1974. imagedestroy($dst);
  1975. imagedestroy($src);
  1976. return true;
  1977. }
  1978. /**
  1979. * 排列组合(无重复)
  1980. * @param $arr
  1981. * @param $m
  1982. * @return array
  1983. */
  1984. public static function getCombinationToString($arr, $m)
  1985. {
  1986. $result = [];
  1987. if ($m == 1) {
  1988. return $arr;
  1989. }
  1990. if ($m == count($arr)) {
  1991. $result[] = implode(',', $arr);
  1992. return $result;
  1993. }
  1994. $temp_firstelement = $arr[0];
  1995. unset($arr[0]);
  1996. $arr = array_values($arr);
  1997. $temp_list1 = self::getCombinationToString($arr, ($m - 1));
  1998. foreach ($temp_list1 as $s) {
  1999. $s = $temp_firstelement . ',' . $s;
  2000. $result[] = $s;
  2001. }
  2002. unset($temp_list1);
  2003. $temp_list2 = self::getCombinationToString($arr, $m);
  2004. foreach ($temp_list2 as $s) {
  2005. $result[] = $s;
  2006. }
  2007. unset($temp_list2);
  2008. return $result;
  2009. }
  2010. /**
  2011. * 不同元素交叉组合(多个数组)
  2012. * @return array
  2013. */
  2014. public static function getNewArray()
  2015. {
  2016. $args = func_get_args();
  2017. $pailie = function ($arr1, $arr2) {
  2018. $arr = [];
  2019. $k = 0;
  2020. foreach ($arr1 as $k1 => $v1) {
  2021. foreach ($arr2 as $k2 => $v2) {
  2022. $arr[$k] = $v1 . "," . $v2;
  2023. $k++;
  2024. }
  2025. }
  2026. return $arr;
  2027. };
  2028. $arr = [];
  2029. foreach ($args as $k => $v) {
  2030. if (isset($args[$k + 1]) && $args[$k + 1]) {
  2031. switch ($k) {
  2032. case 0:
  2033. $arr[$k] = $pailie($v, $args[$k + 1]);
  2034. break;
  2035. default:
  2036. $arr[$k] = $pailie($arr[$k - 1], $args[$k + 1]);
  2037. break;
  2038. }
  2039. }
  2040. }
  2041. $key = count($arr) - 1;
  2042. return array_values($arr[$key]);
  2043. }
  2044. /**
  2045. * 缓存数据
  2046. * @param $title
  2047. * @param null $value
  2048. * @return mixed|null
  2049. */
  2050. public static function cacheData($title, $value = null)
  2051. {
  2052. $title = "cacheData::" . $title;
  2053. $tmp = DB::table('tmp')->where('title', $title)->select('value')->first();
  2054. if ($value !== null ) {
  2055. if (empty($tmp)) {
  2056. DB::table('tmp')->insert(['title'=>$title, 'value'=>$value]);
  2057. }else{
  2058. DB::table('tmp')->where('title', $title)->update(['value'=>$value]);
  2059. }
  2060. return $value;
  2061. }else{
  2062. return $tmp->value;
  2063. }
  2064. }
  2065. }