common.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  1. <?php
  2. // 公共助手函数
  3. use Symfony\Component\VarExporter\VarExporter;
  4. use think\exception\HttpResponseException;
  5. use think\Response;
  6. use think\Db;
  7. if (!function_exists('__')) {
  8. /**
  9. * 获取语言变量值
  10. * @param string $name 语言变量名
  11. * @param array $vars 动态变量值
  12. * @param string $lang 语言
  13. * @return mixed
  14. */
  15. function __($name, $vars = [], $lang = '')
  16. {
  17. if (is_numeric($name) || !$name) {
  18. return $name;
  19. }
  20. if (!is_array($vars)) {
  21. $vars = func_get_args();
  22. array_shift($vars);
  23. $lang = '';
  24. }
  25. return \think\Lang::get($name, $vars, $lang);
  26. }
  27. }
  28. if (!function_exists('format_bytes')) {
  29. /**
  30. * 将字节转换为可读文本
  31. * @param int $size 大小
  32. * @param string $delimiter 分隔符
  33. * @param int $precision 小数位数
  34. * @return string
  35. */
  36. function format_bytes($size, $delimiter = '', $precision = 2)
  37. {
  38. $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
  39. for ($i = 0; $size >= 1024 && $i < 6; $i++) {
  40. $size /= 1024;
  41. }
  42. return round($size, $precision) . $delimiter . $units[$i];
  43. }
  44. }
  45. if (!function_exists('datetime')) {
  46. /**
  47. * 将时间戳转换为日期时间
  48. * @param int $time 时间戳
  49. * @param string $format 日期时间格式
  50. * @return string
  51. */
  52. function datetime($time, $format = 'Y-m-d H:i:s')
  53. {
  54. $time = is_numeric($time) ? $time : strtotime($time);
  55. return date($format, $time);
  56. }
  57. }
  58. if (!function_exists('human_date')) {
  59. /**
  60. * 获取语义化时间
  61. * @param int $time 时间
  62. * @param int $local 本地时间
  63. * @return string
  64. */
  65. function human_date($time, $local = null)
  66. {
  67. return \fast\Date::human($time, $local);
  68. }
  69. }
  70. if (!function_exists('cdnurl')) {
  71. /**
  72. * 获取上传资源的CDN的地址
  73. * @param string $url 资源相对地址
  74. * @param boolean $domain 是否显示域名 或者直接传入域名
  75. * @return string
  76. */
  77. function cdnurl($url, $domain = false)
  78. {
  79. $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
  80. $cdnurl = \think\Config::get('upload.cdnurl');
  81. $url = preg_match($regex, $url) || ($cdnurl && stripos($url, $cdnurl) === 0) ? $url : $cdnurl . $url;
  82. if ($domain && !preg_match($regex, $url)) {
  83. $domain = is_bool($domain) ? request()->domain() : $domain;
  84. $url = $domain . $url;
  85. }
  86. return $url;
  87. }
  88. }
  89. if (!function_exists('is_really_writable')) {
  90. /**
  91. * 判断文件或文件夹是否可写
  92. * @param string $file 文件或目录
  93. * @return bool
  94. */
  95. function is_really_writable($file)
  96. {
  97. if (DIRECTORY_SEPARATOR === '/') {
  98. return is_writable($file);
  99. }
  100. if (is_dir($file)) {
  101. $file = rtrim($file, '/') . '/' . md5(mt_rand());
  102. if (($fp = @fopen($file, 'ab')) === false) {
  103. return false;
  104. }
  105. fclose($fp);
  106. @chmod($file, 0777);
  107. @unlink($file);
  108. return true;
  109. } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
  110. return false;
  111. }
  112. fclose($fp);
  113. return true;
  114. }
  115. }
  116. if (!function_exists('rmdirs')) {
  117. /**
  118. * 删除文件夹
  119. * @param string $dirname 目录
  120. * @param bool $withself 是否删除自身
  121. * @return boolean
  122. */
  123. function rmdirs($dirname, $withself = true)
  124. {
  125. if (!is_dir($dirname)) {
  126. return false;
  127. }
  128. $files = new RecursiveIteratorIterator(
  129. new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
  130. RecursiveIteratorIterator::CHILD_FIRST
  131. );
  132. foreach ($files as $fileinfo) {
  133. $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
  134. $todo($fileinfo->getRealPath());
  135. }
  136. if ($withself) {
  137. @rmdir($dirname);
  138. }
  139. return true;
  140. }
  141. }
  142. if (!function_exists('copydirs')) {
  143. /**
  144. * 复制文件夹
  145. * @param string $source 源文件夹
  146. * @param string $dest 目标文件夹
  147. */
  148. function copydirs($source, $dest)
  149. {
  150. if (!is_dir($dest)) {
  151. mkdir($dest, 0755, true);
  152. }
  153. foreach (
  154. $iterator = new RecursiveIteratorIterator(
  155. new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
  156. RecursiveIteratorIterator::SELF_FIRST
  157. ) as $item
  158. ) {
  159. if ($item->isDir()) {
  160. $sontDir = $dest . DS . $iterator->getSubPathName();
  161. if (!is_dir($sontDir)) {
  162. mkdir($sontDir, 0755, true);
  163. }
  164. } else {
  165. copy($item, $dest . DS . $iterator->getSubPathName());
  166. }
  167. }
  168. }
  169. }
  170. if (!function_exists('mb_ucfirst')) {
  171. function mb_ucfirst($string)
  172. {
  173. return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
  174. }
  175. }
  176. if (!function_exists('addtion')) {
  177. /**
  178. * 附加关联字段数据
  179. * @param array $items 数据列表
  180. * @param mixed $fields 渲染的来源字段
  181. * @return array
  182. */
  183. function addtion($items, $fields)
  184. {
  185. if (!$items || !$fields) {
  186. return $items;
  187. }
  188. $fieldsArr = [];
  189. if (!is_array($fields)) {
  190. $arr = explode(',', $fields);
  191. foreach ($arr as $k => $v) {
  192. $fieldsArr[$v] = ['field' => $v];
  193. }
  194. } else {
  195. foreach ($fields as $k => $v) {
  196. if (is_array($v)) {
  197. $v['field'] = isset($v['field']) ? $v['field'] : $k;
  198. } else {
  199. $v = ['field' => $v];
  200. }
  201. $fieldsArr[$v['field']] = $v;
  202. }
  203. }
  204. foreach ($fieldsArr as $k => &$v) {
  205. $v = is_array($v) ? $v : ['field' => $v];
  206. $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
  207. $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
  208. $v['column'] = isset($v['column']) ? $v['column'] : 'name';
  209. $v['model'] = isset($v['model']) ? $v['model'] : '';
  210. $v['table'] = isset($v['table']) ? $v['table'] : '';
  211. $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
  212. }
  213. unset($v);
  214. $ids = [];
  215. $fields = array_keys($fieldsArr);
  216. foreach ($items as $k => $v) {
  217. foreach ($fields as $m => $n) {
  218. if (isset($v[$n])) {
  219. $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
  220. }
  221. }
  222. }
  223. $result = [];
  224. foreach ($fieldsArr as $k => $v) {
  225. if ($v['model']) {
  226. $model = new $v['model'];
  227. } else {
  228. $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
  229. }
  230. $primary = $v['primary'] ? $v['primary'] : $model->getPk();
  231. $result[$v['field']] = isset($ids[$v['field']]) ? $model->where($primary, 'in', $ids[$v['field']])->column($v['column'], $primary) : [];
  232. }
  233. foreach ($items as $k => &$v) {
  234. foreach ($fields as $m => $n) {
  235. if (isset($v[$n])) {
  236. $curr = array_flip(explode(',', $v[$n]));
  237. $linedata = array_intersect_key($result[$n], $curr);
  238. $v[$fieldsArr[$n]['display']] = $fieldsArr[$n]['column'] == '*' ? $linedata : implode(',', $linedata);
  239. }
  240. }
  241. }
  242. return $items;
  243. }
  244. }
  245. if (!function_exists('var_export_short')) {
  246. /**
  247. * 使用短标签打印或返回数组结构
  248. * @param mixed $data
  249. * @param boolean $return 是否返回数据
  250. * @return string
  251. */
  252. function var_export_short($data, $return = true)
  253. {
  254. return var_export($data, $return);
  255. $replaced = [];
  256. $count = 0;
  257. //判断是否是对象
  258. if (is_resource($data) || is_object($data)) {
  259. return var_export($data, $return);
  260. }
  261. //判断是否有特殊的键名
  262. $specialKey = false;
  263. array_walk_recursive($data, function (&$value, &$key) use (&$specialKey) {
  264. if (is_string($key) && (stripos($key, "\n") !== false || stripos($key, "array (") !== false)) {
  265. $specialKey = true;
  266. }
  267. });
  268. if ($specialKey) {
  269. return var_export($data, $return);
  270. }
  271. array_walk_recursive($data, function (&$value, &$key) use (&$replaced, &$count, &$stringcheck) {
  272. if (is_object($value) || is_resource($value)) {
  273. $replaced[$count] = var_export($value, true);
  274. $value = "##<{$count}>##";
  275. } else {
  276. if (is_string($value) && (stripos($value, "\n") !== false || stripos($value, "array (") !== false)) {
  277. $index = array_search($value, $replaced);
  278. if ($index === false) {
  279. $replaced[$count] = var_export($value, true);
  280. $value = "##<{$count}>##";
  281. } else {
  282. $value = "##<{$index}>##";
  283. }
  284. }
  285. }
  286. $count++;
  287. });
  288. $dump = var_export($data, true);
  289. $dump = preg_replace('#(?:\A|\n)([ ]*)array \(#i', '[', $dump); // Starts
  290. $dump = preg_replace('#\n([ ]*)\),#', "\n$1],", $dump); // Ends
  291. $dump = preg_replace('#=> \[\n\s+\],\n#', "=> [],\n", $dump); // Empties
  292. $dump = preg_replace('#\)$#', "]", $dump); //End
  293. if ($replaced) {
  294. $dump = preg_replace_callback("/'##<(\d+)>##'/", function ($matches) use ($replaced) {
  295. return isset($replaced[$matches[1]]) ? $replaced[$matches[1]] : "''";
  296. }, $dump);
  297. }
  298. if ($return === true) {
  299. return $dump;
  300. } else {
  301. echo $dump;
  302. }
  303. }
  304. }
  305. if (!function_exists('letter_avatar')) {
  306. /**
  307. * 首字母头像
  308. * @param $text
  309. * @return string
  310. */
  311. function letter_avatar($text)
  312. {
  313. $total = unpack('L', hash('adler32', $text, true))[1];
  314. $hue = $total % 360;
  315. list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);
  316. $bg = "rgb({$r},{$g},{$b})";
  317. $color = "#ffffff";
  318. $first = mb_strtoupper(mb_substr($text, 0, 1));
  319. $src = base64_encode('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" width="100" height="100"></rect><text x="50" y="50" font-size="50" text-copy="fast" fill="' . $color . '" text-anchor="middle" text-rights="admin" dominant-baseline="central">' . $first . '</text></svg>');
  320. $value = 'data:image/svg+xml;base64,' . $src;
  321. return $value;
  322. }
  323. }
  324. if (!function_exists('hsv2rgb')) {
  325. function hsv2rgb($h, $s, $v)
  326. {
  327. $r = $g = $b = 0;
  328. $i = floor($h * 6);
  329. $f = $h * 6 - $i;
  330. $p = $v * (1 - $s);
  331. $q = $v * (1 - $f * $s);
  332. $t = $v * (1 - (1 - $f) * $s);
  333. switch ($i % 6) {
  334. case 0:
  335. $r = $v;
  336. $g = $t;
  337. $b = $p;
  338. break;
  339. case 1:
  340. $r = $q;
  341. $g = $v;
  342. $b = $p;
  343. break;
  344. case 2:
  345. $r = $p;
  346. $g = $v;
  347. $b = $t;
  348. break;
  349. case 3:
  350. $r = $p;
  351. $g = $q;
  352. $b = $v;
  353. break;
  354. case 4:
  355. $r = $t;
  356. $g = $p;
  357. $b = $v;
  358. break;
  359. case 5:
  360. $r = $v;
  361. $g = $p;
  362. $b = $q;
  363. break;
  364. }
  365. return [
  366. floor($r * 255),
  367. floor($g * 255),
  368. floor($b * 255)
  369. ];
  370. }
  371. }
  372. if (!function_exists('check_nav_active')) {
  373. /**
  374. * 检测会员中心导航是否高亮
  375. */
  376. function check_nav_active($url, $classname = 'active')
  377. {
  378. $auth = \app\common\library\Auth::instance();
  379. $requestUrl = $auth->getRequestUri();
  380. $url = ltrim($url, '/');
  381. return $requestUrl === str_replace(".", "/", $url) ? $classname : '';
  382. }
  383. }
  384. if (!function_exists('check_cors_request')) {
  385. /**
  386. * 跨域检测
  387. */
  388. function check_cors_request()
  389. {
  390. if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN']) {
  391. $info = parse_url($_SERVER['HTTP_ORIGIN']);
  392. $domainArr = explode(',', config('fastadmin.cors_request_domain'));
  393. $domainArr[] = request()->host(true);
  394. if (in_array("*", $domainArr) || in_array($_SERVER['HTTP_ORIGIN'], $domainArr) || (isset($info['host']) && in_array($info['host'], $domainArr))) {
  395. header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
  396. } else {
  397. $response = Response::create('跨域检测无效', 'html', 403);
  398. throw new HttpResponseException($response);
  399. }
  400. header('Access-Control-Allow-Credentials: true');
  401. header('Access-Control-Max-Age: 86400');
  402. if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  403. if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
  404. header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
  405. }
  406. if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
  407. header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
  408. }
  409. $response = Response::create('', 'html');
  410. throw new HttpResponseException($response);
  411. }
  412. }
  413. }
  414. }
  415. if (!function_exists('xss_clean')) {
  416. /**
  417. * 清理XSS
  418. */
  419. function xss_clean($content, $is_image = false)
  420. {
  421. return \app\common\library\Security::instance()->xss_clean($content, $is_image);
  422. }
  423. }
  424. if (!function_exists('check_ip_allowed')) {
  425. /**
  426. * 检测IP是否允许
  427. * @param string $ip IP地址
  428. */
  429. function check_ip_allowed($ip = null)
  430. {
  431. $ip = is_null($ip) ? request()->ip() : $ip;
  432. $forbiddenipArr = config('site.forbiddenip');
  433. $forbiddenipArr = !$forbiddenipArr ? [] : $forbiddenipArr;
  434. $forbiddenipArr = is_array($forbiddenipArr) ? $forbiddenipArr : array_filter(explode("\n", str_replace("\r\n", "\n", $forbiddenipArr)));
  435. if ($forbiddenipArr && \Symfony\Component\HttpFoundation\IpUtils::checkIp($ip, $forbiddenipArr)) {
  436. $response = Response::create('请求无权访问', 'html', 403);
  437. throw new HttpResponseException($response);
  438. }
  439. }
  440. }
  441. if (!function_exists('build_suffix_image')) {
  442. /**
  443. * 生成文件后缀图片
  444. * @param string $suffix 后缀
  445. * @param null $background
  446. * @return string
  447. */
  448. function build_suffix_image($suffix, $background = null)
  449. {
  450. $suffix = mb_substr(strtoupper($suffix), 0, 4);
  451. $total = unpack('L', hash('adler32', $suffix, true))[1];
  452. $hue = $total % 360;
  453. list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);
  454. $background = $background ? $background : "rgb({$r},{$g},{$b})";
  455. $icon = <<<EOT
  456. <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 512 512" style="enable-background:new 0 0 512 512;" xml:space="preserve">
  457. <path style="fill:#E2E5E7;" d="M128,0c-17.6,0-32,14.4-32,32v448c0,17.6,14.4,32,32,32h320c17.6,0,32-14.4,32-32V128L352,0H128z"/>
  458. <path style="fill:#B0B7BD;" d="M384,128h96L352,0v96C352,113.6,366.4,128,384,128z"/>
  459. <polygon style="fill:#CAD1D8;" points="480,224 384,128 480,128 "/>
  460. <path style="fill:{$background};" d="M416,416c0,8.8-7.2,16-16,16H48c-8.8,0-16-7.2-16-16V256c0-8.8,7.2-16,16-16h352c8.8,0,16,7.2,16,16 V416z"/>
  461. <path style="fill:#CAD1D8;" d="M400,432H96v16h304c8.8,0,16-7.2,16-16v-16C416,424.8,408.8,432,400,432z"/>
  462. <g><text><tspan x="220" y="380" font-size="124" font-family="Verdana, Helvetica, Arial, sans-serif" fill="white" text-anchor="middle">{$suffix}</tspan></text></g>
  463. </svg>
  464. EOT;
  465. return $icon;
  466. }
  467. }
  468. //结果集信息里,多个字段需要增加domain_cdnurl
  469. function list_domain_image($list,$field){
  470. if(!$list || empty($list)){
  471. return $list;
  472. }
  473. foreach($list as $vo => $info){
  474. $list[$vo] = info_domain_image($info,$field);
  475. }
  476. return $list;
  477. }
  478. //单条信息里,多个字段需要增加domain_cdnurl
  479. //支持image,images
  480. function info_domain_image($data,$field){
  481. if(!$data || empty($data)){
  482. return $data;
  483. }
  484. foreach($data as $key => $val){
  485. if(in_array($key,$field)){
  486. $data[$key] = one_domain_image($val);
  487. }
  488. }
  489. return $data;
  490. }
  491. //支持单个字段,需要增加domain_cdnurl
  492. //支持image,images
  493. function one_domain_image($one){
  494. if(!$one){
  495. return $one;
  496. }
  497. if(strpos($one,',')){
  498. //逗号隔开的多个图片
  499. $one = explode(',',$one);
  500. foreach($one as $k => $v){
  501. $one[$k] = localpath_to_netpath($v);
  502. }
  503. $one = implode(',',$one);
  504. }else{
  505. $one = localpath_to_netpath($one);
  506. }
  507. return $one;
  508. }
  509. //本地地址转换为网络地址
  510. function localpath_to_netpath($path)
  511. {
  512. if (empty($path)) {
  513. return '';
  514. } elseif (strrpos($path, 'http') !== false) {
  515. return $path;
  516. } else {
  517. return config('upload.cdnurl') . str_replace("\\", "/", $path);
  518. }
  519. }
  520. function p($arr) {
  521. header('content-type:text/html;charset=utf-8');
  522. echo '<pre>';
  523. print_r($arr);
  524. echo '</pre>';
  525. }
  526. /**
  527. * 手机格式验证
  528. * @param string $mobile 验证的手机号码
  529. * @return boolean
  530. */
  531. function is_mobile($mobile) {
  532. if (!empty($mobile)) {
  533. return preg_match('/^1[3|4|5|6|7|8|9][0-9]\d{8}$/', $mobile);
  534. }
  535. return false;
  536. }
  537. //处理时间戳: *时*分*秒
  538. function process_time($time) {
  539. $result = '';
  540. $hour = '';
  541. $minute = '00';
  542. if ($time > 3600) {
  543. $hour = (string)floor($time / 3600);
  544. $time = $time - $hour * 3600;
  545. }
  546. if ($time > 60) {
  547. $minute = (string)floor($time / 60);
  548. $time = $time - $minute * 60;
  549. if ($minute < 10) {
  550. $minute = '0' . $minute;
  551. }
  552. }
  553. if ($time < 10) {
  554. $second = (string)('0' . $time);
  555. } else {
  556. $second = (string)$time;
  557. }
  558. if ($hour) {
  559. $result = $hour . ':';
  560. }
  561. $result = $result . $minute . ':' . $second;
  562. return $result;
  563. }
  564. /**
  565. * [getMillisecond 获取毫秒级时间戳]
  566. * @return [type] [description]
  567. */
  568. function getMillisecond() {
  569. list($t1, $t2) = explode(' ', microtime());
  570. return (float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
  571. }
  572. /**
  573. * CURL请求
  574. * @param $url 请求url地址
  575. * @param $method 请求方法 get post
  576. * @param null $postfields post数据数组
  577. * @param array $headers 请求header信息
  578. * @param bool|false $debug 调试开启 默认false
  579. * @return mixed
  580. */
  581. function httpRequest($url = '', $method = '', $postfields = null, $headers = array(), $debug = false) {
  582. $method = strtoupper($method);
  583. $ci = curl_init();
  584. /* Curl settings */
  585. curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
  586. curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
  587. curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间,如果设置为0,则无限等待 */
  588. curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
  589. curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
  590. switch ($method) {
  591. case "POST":
  592. curl_setopt($ci, CURLOPT_POST, true);
  593. if (!empty($postfields)) {
  594. $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
  595. curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
  596. }
  597. break;
  598. default:
  599. curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
  600. break;
  601. }
  602. $ssl = preg_match('/^https:\/\//i',$url) ? TRUE : FALSE;
  603. curl_setopt($ci, CURLOPT_URL, $url);
  604. if($ssl){
  605. curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
  606. curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
  607. }
  608. //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
  609. //curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
  610. curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量,这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
  611. curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
  612. curl_setopt($ci, CURLINFO_HEADER_OUT, true);
  613. /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
  614. $response = curl_exec($ci);
  615. $requestinfo = curl_getinfo($ci);
  616. $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
  617. if ($debug) {
  618. echo "=====post data======\r\n";
  619. var_dump($postfields);
  620. echo "=====info===== \r\n";
  621. print_r($requestinfo);
  622. echo "=====response=====\r\n";
  623. print_r($response);
  624. }
  625. curl_close($ci);
  626. return $response;
  627. //return array($http_code, $response,$requestinfo);
  628. }
  629. /**
  630. * 资金记录
  631. * param int $balance 变动的金额数量,减少时传:-$balance,增加时直接传:$balance
  632. * param string $desc 描述
  633. * param int $user_id 登录用户id
  634. * $type 类型:1=充值,2=支付,3=后台
  635. * $relation_id 充值ID/订单ID/会员ID
  636. * return int
  637. */
  638. function create_log($balance = 0, $desc = '', $user_id = 0, $type = 0, $relation_id = 0) {
  639. $map['id'] = $user_id;
  640. $user = Db::name('user');
  641. $user_info = $user->where($map)->field('id, money')->find();
  642. if ($user_info['money'] < 0) {
  643. return -3;
  644. }
  645. // 查询log日志
  646. $user_account = Db::name('user_money_log');
  647. $data = array();
  648. $log = array();
  649. $silver_logs = $user_account->where(['user_id' => $user_id])->order('id desc')->limit(10)->select();
  650. $all_count = count($silver_logs); //日志记录数量
  651. if ($all_count < 1) {
  652. if ($user_info['money'] > 0) {
  653. return -7;
  654. }
  655. } else {
  656. $all_change_silver = array();
  657. if ($all_count == 1) { // 只有一条日志 变动金额=余额
  658. if ($silver_logs[0]['after'] != $silver_logs[0]['money']) {
  659. // add_error_user($silver_logs[0]['user_id'], 0);
  660. return -8;
  661. }
  662. }
  663. $log_count = $all_count - 1;
  664. $last_user_silver = '';
  665. foreach ($silver_logs as $key => $value) {
  666. if ($key == $log_count) {
  667. $last_user_silver = $value['after'];
  668. break;
  669. }
  670. $all_change_silver[] = $value['money'];
  671. }
  672. //变动金额+最初余额=最新余额
  673. // $new_silver = $last_user_silver + array_sum($all_change_silver); // 最新余额+变动总金额
  674. // $silver_difference = abs($new_silver - $silver_logs[0]['user_diamond']);
  675. $new_silver = $last_user_silver + array_sum($all_change_silver); // 最新余额+变动总金额
  676. $silver_difference = abs(number_format($new_silver, 2, '.', '') - number_format($silver_logs[0]['after'], 2, '.', ''));
  677. // p($silver_difference);die;
  678. if ($silver_difference > 1) {
  679. // add_error_user($silver_logs[0]['user_id'], 0);
  680. return -9;
  681. }
  682. }
  683. $log['user_id'] = $user_id;
  684. $log['type'] = $type;
  685. $log['money'] = $balance;
  686. $log['before'] = $user_info['money'];
  687. $log['after'] = $user_info['money'] + $balance;
  688. $log['memo'] = $desc;
  689. $log['relation_id'] = $relation_id;
  690. $log['createtime'] = time();
  691. $data['money'] = $log['after'];
  692. if ($data['money'] < 0) {
  693. return -12;
  694. }
  695. if ($balance != 0) {
  696. $change_result = $user->where($map)->where(['money' => $user_info['money']])->setField($data); // 更改用户余额
  697. if ($change_result !== false) {
  698. $rows = $user_account->insertGetId($log);
  699. if ($rows > 0) {
  700. return 1;
  701. } else {
  702. return -10;
  703. }
  704. } else {
  705. return -11;
  706. }
  707. }
  708. return 1;
  709. }
  710. /**
  711. * 成长值记录
  712. * param int $balance 变动的数量,减少时传:-$balance,增加时直接传:$balance
  713. * param string $desc 描述
  714. * param int $user_id 登录用户id
  715. * $type 类型:1=登录,2=充值,3=微信支付活动,4=活动取消扣除
  716. * $relation_id 充值记录ID/订单ID
  717. * return int
  718. */
  719. function create_growth_log($balance = 0, $desc = '', $user_id = 0, $type = 0, $relation_id = 0) {
  720. $map['id'] = $user_id;
  721. $user = Db::name('user');
  722. $user_info = $user->where($map)->field('id, growthvalue')->find();
  723. if ($user_info['growthvalue'] < 0) {
  724. return -3;
  725. }
  726. // 查询log日志
  727. $user_account = Db::name('user_growth_log');
  728. $data = array();
  729. $log = array();
  730. $silver_logs = $user_account->where(['user_id' => $user_id])->order('id desc')->limit(10)->select();
  731. $all_count = count($silver_logs); //日志记录数量
  732. if ($all_count < 1) {
  733. if ($user_info['growthvalue'] > 0) {
  734. return -7;
  735. }
  736. } else {
  737. $all_change_silver = array();
  738. if ($all_count == 1) { // 只有一条日志 变动金额=余额
  739. if ($silver_logs[0]['after'] != $silver_logs[0]['growth']) {
  740. // add_error_user($silver_logs[0]['user_id'], 0);
  741. return -8;
  742. }
  743. }
  744. $log_count = $all_count - 1;
  745. $last_user_silver = '';
  746. foreach ($silver_logs as $key => $value) {
  747. if ($key == $log_count) {
  748. $last_user_silver = $value['after'];
  749. break;
  750. }
  751. $all_change_silver[] = $value['growth'];
  752. }
  753. //变动金额+最初余额=最新余额
  754. // $new_silver = $last_user_silver + array_sum($all_change_silver); // 最新余额+变动总金额
  755. // $silver_difference = abs($new_silver - $silver_logs[0]['user_diamond']);
  756. $new_silver = $last_user_silver + array_sum($all_change_silver); // 最新余额+变动总金额
  757. $silver_difference = abs(number_format($new_silver, 2, '.', '') - number_format($silver_logs[0]['after'], 2, '.', ''));
  758. // p($silver_difference);die;
  759. if ($silver_difference > 1) {
  760. // add_error_user($silver_logs[0]['user_id'], 0);
  761. return -9;
  762. }
  763. }
  764. $log['user_id'] = $user_id;
  765. $log['type'] = $type;
  766. $log['growth'] = $balance;
  767. $log['before'] = $user_info['growthvalue'];
  768. $log['after'] = $user_info['growthvalue'] + $balance;
  769. $log['memo'] = $desc;
  770. $log['relation_id'] = $relation_id;
  771. $log['createtime'] = time();
  772. $data['growthvalue'] = $log['after'];
  773. if ($data['growthvalue'] < 0) {
  774. return -12;
  775. }
  776. if ($balance != 0) {
  777. $change_result = $user->where($map)->where(['growthvalue' => $user_info['growthvalue']])->setField($data); // 更改用户余额
  778. if ($change_result !== false) {
  779. $rows = $user_account->insertGetId($log);
  780. if ($rows > 0) {
  781. return 1;
  782. } else {
  783. return -10;
  784. }
  785. } else {
  786. return -11;
  787. }
  788. }
  789. return 1;
  790. }
  791. //生日转年龄
  792. function birthtime_to_age($birthtime){
  793. // $birthtime = strtotime('1990-11-06');
  794. if(!$birthtime){
  795. return 0;
  796. }
  797. list($y1,$m1,$d1) = explode("-",date("Y-m-d",$birthtime));
  798. list($y2,$m2,$d2) = explode("-",date("Y-m-d",time()));
  799. $age = $y2 - $y1;
  800. if((int)($m2.$d2) < (int)($m1.$d1))
  801. {$age -= 1;}
  802. if($age < 0){
  803. $age = 0;
  804. }
  805. return $age;
  806. }