common.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: 流年 <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. // 应用公共文件
  12. /*
  13. * 用户是否登录
  14. */
  15. function is_login($type){
  16. $user = session($type.'_auth');
  17. if (empty($user)) {
  18. return false;
  19. }
  20. return $user;
  21. }
  22. function is_admin(){
  23. $user = is_login('admin');
  24. $role_id = $user['role']['id'];
  25. if ($role_id == 1) {
  26. return true;
  27. }
  28. return false;
  29. }
  30. /**
  31. * 获取本站token
  32. */
  33. function getlocaltoken($name){
  34. $where['name'] = $name;
  35. $user = $User->where($where)->find();
  36. if (!$user) {
  37. return false;
  38. }
  39. $time = $this->request->time();
  40. $token_expire = $user['token_expire'];
  41. if (!empty($token_expire)) {
  42. list($token,$expire) = explode('|', $token_expire);
  43. if ($time < $expire) {
  44. return $token;
  45. }
  46. }
  47. $token = md5(guid());
  48. $expire = $this->request->time() + 7200;
  49. $user->token = $token .'|'.$expire;
  50. $user->save();
  51. return $token;
  52. }
  53. /**
  54. * 是否是微信浏览器
  55. * @return bool
  56. */
  57. function isWxClient(){
  58. return strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false;
  59. }
  60. /**
  61. * 判断是否支付宝内置浏览器访问
  62. * @return bool
  63. */
  64. function isAliClient(){
  65. return strpos($_SERVER['HTTP_USER_AGENT'], 'Alipay') !== false;
  66. }
  67. /**
  68. * 远程获取数据
  69. */
  70. function curl($url, $data = '',$headers = [],$timeout = 60,$issplit = false) {
  71. $ch = curl_init();
  72. curl_setopt($ch, CURLOPT_URL,$url);
  73. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  74. @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  75. curl_setopt($ch, CURLOPT_HEADER, 0);
  76. @curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
  77. if ($data) {
  78. curl_setopt($ch, CURLOPT_POST, 1);
  79. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  80. }
  81. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  82. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  83. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  84. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  85. curl_setopt($ch, CURLOPT_SSLVERSION, 1);
  86. curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1");
  87. if (!empty($headers) && is_array($headers)) {
  88. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  89. }
  90. ob_start();
  91. $res = curl_exec($ch);
  92. $headersize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
  93. $header = substr($res, 0, $headersize);
  94. $body = substr($res, $headersize);
  95. ob_end_clean();
  96. curl_close($ch);
  97. unset($ch);
  98. if ($issplit) {
  99. return ['header'=>$header,'body'=>$body];
  100. }
  101. return $res;
  102. }
  103. /**
  104. * 获取随机数
  105. */
  106. function random($length, $numeric = FALSE) {
  107. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  108. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  109. if ($numeric) {
  110. $hash = '';
  111. } else {
  112. $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
  113. $length--;
  114. }
  115. $max = strlen($seed) - 1;
  116. for ($i = 0; $i < $length; $i++) {
  117. $hash .= $seed{mt_rand(0, $max)};
  118. }
  119. $hash=strtoupper($hash);
  120. return $hash;
  121. }
  122. function getNonceStr($length = 32) {
  123. $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
  124. $str ="";
  125. for ( $i = 0; $i < $length; $i++ ) {
  126. $str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);
  127. }
  128. return $str;
  129. }
  130. /*生成全球唯一标识*/
  131. function guid($fix=true){
  132. $left=$fix?chr(123):'';
  133. $right=$fix?chr(125):'';
  134. if (function_exists('com_create_guid')){
  135. $uuid=com_create_guid();
  136. if(!$fix){
  137. $uuid=substr($uuid,1,-1);
  138. }
  139. return $uuid;
  140. }else{
  141. mt_srand((double)microtime()*10000);
  142. $charid = strtoupper(md5(uniqid(rand(), true)));
  143. $hyphen = chr(45);
  144. $uuid = $left
  145. .substr($charid, 0, 8).$hyphen
  146. .substr($charid, 8, 4).$hyphen
  147. .substr($charid,12, 4).$hyphen
  148. .substr($charid,16, 4).$hyphen
  149. .substr($charid,20,12)
  150. .$right;
  151. return $uuid;
  152. }
  153. }
  154. //生成二维码
  155. function createqrcode($data,$level = 'L',$size=4){
  156. $name = md5($data);
  157. vendor("phpqrcode.phpqrcode");
  158. $relativePath = 'uploads'.DS.date('Ymd',request()->time());
  159. $absolutePath = ROOT_PATH.'public'.DS. $relativePath;
  160. $file = $absolutePath.DS.$name.".png";
  161. if (!is_file($file)) {
  162. is_dir($absolutePath)?'':mkdir($absolutePath, 0755, true);
  163. $object = new \QRcode();
  164. $object->png($data,$file, 'L',6);
  165. }
  166. return request()->domain(). DS.$relativePath.DS.$name.".png";
  167. }
  168. //redis连接
  169. function redis_connect(){
  170. vendor("Predis.autoload");
  171. $redis = new \Predis\Client(array(
  172. 'scheme' => 'tcp',
  173. 'host' => '127.0.0.1',
  174. 'port' => 6379,
  175. ));
  176. $password = \think\Config::get('redis.password');
  177. if (!empty($password)) {
  178. $redis->auth($password);
  179. }
  180. return $redis;
  181. }
  182. /**
  183. * 自增长单号
  184. */
  185. function aino($prefix='',$format='Ymd',$length=3){;
  186. $redis = redis_connect();
  187. $date = empty($format)?'':date($format);
  188. $key = $prefix.$date;
  189. $no = $redis->incr($key);
  190. if ($no == 1) {
  191. $redis->expireat($key,strtotime($date) + 86400);
  192. }
  193. $no = str_pad($no,$length,"0",STR_PAD_LEFT);
  194. $no = $key.$no;
  195. return $no;
  196. }
  197. /**
  198. * 获取文件路径
  199. */
  200. function getfileurl($id){
  201. $File = model('File');
  202. $file = $File->where(['id'=>$id])->find();
  203. return DS. 'public' . DS . 'uploads' .DS .$file['name'];
  204. }
  205. /**
  206. * 获取配置信息
  207. */
  208. function cnf($key,$value = null){
  209. if (is_null($value) && is_string($key)) {
  210. $value = model('Config')->where(['key'=>$key])->value("value");
  211. $value = json_decode($value,true);
  212. return $value;
  213. } else {
  214. $value = json_encode($value,JSON_UNESCAPED_UNICODE);
  215. return model('Config')->where(['key'=>$key])->update(["value"=>$value]);
  216. }
  217. }
  218. /**
  219. * 字符串截取,支持中文和其他编码
  220. * @static
  221. * @access public
  222. * @param string $str 需要转换的字符串
  223. * @param string $start 开始位置
  224. * @param string $length 截取长度
  225. * @param string $charset 编码格式
  226. * @param string $suffix 截断显示字符
  227. * @return string
  228. */
  229. function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true) {
  230. if(function_exists("mb_substr"))
  231. $slice = mb_substr($str, $start, $length, $charset);
  232. elseif(function_exists('iconv_substr')) {
  233. $slice = iconv_substr($str,$start,$length,$charset);
  234. if(false === $slice) {
  235. $slice = '';
  236. }
  237. }else{
  238. $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
  239. $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
  240. $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
  241. $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
  242. preg_match_all($re[$charset], $str, $match);
  243. $slice = join("",array_slice($match[0], $start, $length));
  244. }
  245. return $suffix ? $slice.'...' : $slice;
  246. }
  247. function amount_format($amount){
  248. $amount = trim($amount);
  249. return sprintf("%.2f",substr(sprintf("%.3f", $amount), 0, -1));
  250. }
  251. function sendtomobile($mobile,$content,$ajax = true){
  252. }
  253. function sendtoemail($email,$content,$ajax = true){
  254. $sms_cnf = cnf('sms');
  255. $email_cnf = $sms_cnf['mobile'];
  256. require_once VENDOR_PATH.'PHPMailer/src/Exception.php';
  257. require_once VENDOR_PATH.'PHPMailer/src/PHPMailer.php';
  258. require_once VENDOR_PATH.'PHPMailer/src/SMTP.php';
  259. $mail = new \PHPMailer\PHPMailer\PHPMailer(true); //实例化
  260. try {
  261. $sms_cnf = cnf('sms');
  262. $email_cnf = $sms_cnf['email'];
  263. $mail->isSMTP();
  264. $mail->CharSet = "UTF-8";
  265. $mail->Host = $email_cnf['smtp'];
  266. $mail->Port = 465;
  267. $mail->SMTPAuth = true;
  268. $mail->SMTPSecure = "ssl";
  269. $mail->CharSet = "UTF-8";
  270. $mail->Encoding = "base64";
  271. $mail->Username = $email_cnf['account'];
  272. $mail->Password = $email_cnf['password'];
  273. $mail->From = $email_cnf['account'];
  274. $mail->FromName = $email_cnf['from'];
  275. $mail->AddAddress($email, "Hello");
  276. $mail->IsHTML(true);
  277. $mail->Subject = '【'.$email_cnf['from'].'】';
  278. $mail->Body = $content;
  279. $mail->Send();
  280. if ($ajax) {
  281. output(0,'发送成功');
  282. }
  283. return true;
  284. }catch (\PHPMailer\PHPMailer\Exception $e) {
  285. output(1,'发送失败1');
  286. }
  287. }
  288. function output($code,$msg,$data = [],$count = 0,$pages = 1){
  289. try {
  290. // 返回JSON数据格式到客户端 包含状态信息
  291. $count = $count == 0?count($data):$count;
  292. $data = json_encode(['code'=>$code,'msg'=>$msg,'data'=>$data,'count'=>$count,'pages'=>$pages], JSON_UNESCAPED_UNICODE);
  293. if ($data === false) {
  294. throw new \InvalidArgumentException(json_last_error_msg());
  295. }
  296. header('Content-type: application/json');
  297. echo $data;exit();
  298. } catch (\Exception $e) {
  299. if ($e->getPrevious()) {
  300. throw $e->getPrevious();
  301. }
  302. throw $e;
  303. }
  304. }
  305. function oplog($position,$user_id){
  306. $request = request();
  307. $Log = model('Log');
  308. $Log->user_id = $user_id;
  309. $Log->action = $request->module() . '/' . $request->controller() . '/' . $request->action();
  310. $Log->params = $request->param();
  311. $Log->position = $position;
  312. $Log->save();
  313. }
  314. function common_curl($url, $param, $dataType = 0, $header = [])
  315. {
  316. $headers = [
  317. "Content-type:application/json;charset=utf-8",
  318. "Accept:*/*",
  319. "Connection:close",
  320. "User-Agent:DSMall/6.1.0;PHP-Curl",
  321. ];
  322. //dataType 1是 x-www-form形式 0是默认的json形式
  323. if ($dataType == 1) {
  324. $post_data = http_build_query($param);//重点
  325. $curl = curl_init();
  326. curl_setopt($curl, CURLOPT_URL, $url);
  327. // curl_setopt($curl, CURLOPT_HEADER, 0);//不抓取头部信息。只返回数据
  328. curl_setopt($curl, CURLOPT_TIMEOUT, (int)10);//超时设置
  329. curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
  330. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//1表示不返回bool值
  331. curl_setopt($curl, CURLOPT_POST, 1);
  332. curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);//重点
  333. curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
  334. // curl_setopt(curl,CURLOPTHTTPHEADER,$header);
  335. $result = curl_exec($curl);
  336. curl_close($curl);
  337. $result = json_decode($result, 1);
  338. return $result;
  339. } else {
  340. $ch = curl_init($url);
  341. curl_setopt($ch, CURLOPT_HEADER, 0);
  342. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  343. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  344. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  345. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  346. curl_setopt($ch, CURLOPT_POST, 1);
  347. curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($param));
  348. $result = curl_exec($ch);
  349. if (curl_errno($ch)) $result = curl_error($ch);
  350. curl_close($ch);
  351. $result = json_decode($result, 1);
  352. return $result;
  353. }
  354. }