common.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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. use think\facade\Db;
  13. // 高德地图Key
  14. define('AMAP_KEY', '937f431e40453c79c1c18af4a69c6b79');
  15. function page_result1($code=0, $msg='', $data=array())
  16. {
  17. exit(json_encode(array(
  18. 'code' => $code,
  19. 'msg' => $msg,
  20. 'data' => $data
  21. )));
  22. }
  23. /**
  24. * a.合成图片信息 复制一张图片的矩形区域到另外一张图片的矩形区域
  25. * @param [type] $bg_image [目标图]
  26. * @param [type] $sub_image [被添加图]
  27. * @param [type] $add_x [目标图x坐标位置]
  28. * @param [type] $add_y [目标图y坐标位置]
  29. * @param [type] $add_w [目标图宽度区域]
  30. * @param [type] $add_h [目标图高度区域]
  31. * @param [type] $out_image [输出图路径]
  32. * @return [type] [description]
  33. */
  34. function image_copy_image($bg_image, $sub_image, $add_x, $add_y, $add_w, $add_h, $out_image)
  35. {
  36. if ($sub_image) {
  37. $bg_image_c = imagecreatefromstring(file_get_contents($bg_image));
  38. $sub_image_c = imagecreatefromstring(file_get_contents($sub_image));
  39. imagecopyresampled($bg_image_c, $sub_image_c, $add_x, $add_y, 0, 0, $add_w, $add_h, imagesx($sub_image_c), imagesy($sub_image_c));
  40. //保存到out_image
  41. imagejpeg($bg_image_c, $out_image, 80);
  42. imagedestroy($sub_image_c);
  43. imagedestroy($bg_image_c);
  44. return true;
  45. }
  46. }
  47. function image_copy_text($dst_path, $text, $font, $size, $picwith, $x, $y, $red, $grn, $blu){
  48. $dst = imagecreatefromstring(file_get_contents($dst_path));
  49. $arr = imagettfbbox($size,0,$font,$text);
  50. $text_width = $arr[2]-$arr[0];
  51. $x = $picwith==0 ? $x : intval(($picwith - $text_width)/2);
  52. //打上文字
  53. $black = imagecolorallocate($dst, $red, $grn, $blu);//字体颜色0x00, 0x00, 0x00
  54. imagefttext($dst, $size, 0, $x, $y, $black, $font, $text);
  55. //输出图片
  56. list($dst_w, $dst_h, $dst_type) = getimagesize($dst_path);
  57. switch ($dst_type) {
  58. case 1://GIF
  59. header('Content-Type: image/gif');
  60. imagegif($dst, $dst_path);
  61. break;
  62. case 2://JPG
  63. header('Content-Type: image/jpeg');
  64. imagejpeg($dst, $dst_path);
  65. break;
  66. case 3://PNG
  67. header('Content-Type: image/png');
  68. imagepng($dst, $dst_path);
  69. break;
  70. default:
  71. break;
  72. }
  73. imagedestroy($dst);
  74. }
  75. function subtext($text, $length)
  76. {
  77. if(mb_strlen($text, 'utf8') > $length) {
  78. return mb_substr($text, 0, $length, 'utf8').'...';
  79. } else {
  80. return $text;
  81. }
  82. }
  83. /**
  84. * 公共数据导出实现功能
  85. * @param $expTitle 导出文件名
  86. * @param $expCellName 导出文件列名称
  87. * @param $expTableData 导出数据
  88. */
  89. function export_excel($expTitle, $expCellName, $expTableData)
  90. {
  91. $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
  92. $fileName = $expTitle . date('_Ymd');//or $xlsTitle 文件名称可根据自己情况设定
  93. $cellNum = count($expCellName);
  94. $dataNum = count($expTableData);
  95. $objPHPExcel = new PHPExcel();//方法一
  96. $cellName = array('A','B', 'C','D', 'E', 'F','G','H','I', 'J', 'K','L','M', 'N', 'O', 'P', 'Q','R','S', 'T','U','V', 'W', 'X','Y', 'Z', 'AA',
  97. 'AB', 'AC','AD','AE', 'AF','AG','AH','AI', 'AJ', 'AK', 'AL','AM','AN','AO','AP','AQ','AR', 'AS', 'AT','AU', 'AV','AW', 'AX',
  98. 'AY', 'AZ');
  99. //设置头部导出时间备注
  100. $objPHPExcel->getActiveSheet(0)->mergeCells('A1:' . $cellName[$cellNum - 1] . '1');//合并单元格
  101. $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle . ' 导出时间:' . date('Y-m-d H:i:s'));
  102. //设置列名称
  103. for ($i = 0; $i < $cellNum; $i++) {
  104. $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i] . '2', $expCellName[$i][1]);
  105. }
  106. //赋值
  107. for ($i = 0; $i < $dataNum; $i++) {
  108. for ($j = 0; $j < $cellNum; $j++) {
  109. $keyarr = explode(".", $expCellName[$j][0]);
  110. $value = $expTableData[$i];
  111. foreach ($keyarr as $k=>$v) {
  112. $value = $value[$v];
  113. }
  114. if (!empty($expCellName[$j][2])) {
  115. $value = $expCellName[$j][2][$value];
  116. }
  117. $objPHPExcel->getActiveSheet(0)->setCellValueExplicit(
  118. $cellName[$j] . ($i + 3),
  119. $value,
  120. PHPExcel_Cell_DataType::TYPE_STRING
  121. );
  122. }
  123. }
  124. ob_end_clean();//这一步非常关键,用来清除缓冲区防止导出的excel乱码
  125. header('pragma:public');
  126. header('Content-type:application/vnd.ms-excel;charset=utf-8;name="' . $xlsTitle . '.xls"');
  127. header("Content-Disposition:attachment;filename=$fileName.xls");//"xls"参考下一条备注
  128. $objWriter = \PHPExcel_IOFactory::createWriter(
  129. $objPHPExcel,
  130. 'Excel2007'
  131. );//"Excel2007"生成2007版本的xlsx,"Excel5"生成2003版本的xls
  132. $objWriter->save('php://output');
  133. }
  134. /**
  135. * excel表格读取
  136. * @param string $filename 文件路劲
  137. */
  138. function read_excel($filename)
  139. {
  140. //设置excel格式
  141. $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
  142. if ($ext=='xlsx') {
  143. $reader = PHPExcel_IOFactory::createReader('Excel2007');
  144. } else {
  145. $reader = PHPExcel_IOFactory::createReader('Excel5');
  146. }
  147. //载入excel文件
  148. $excel = $reader->load($filename);
  149. //读取第一张表
  150. $sheet = $excel->getSheet(0);
  151. //获取总行数
  152. $row_num = $sheet->getHighestRow();
  153. //获取总列数
  154. $col_num = $sheet->getHighestColumn();
  155. $data = []; //数组形式获取表格数据
  156. for ($col='A';$col<=$col_num;$col++) {
  157. //从第二行开始,去除表头(若无表头则从第一行开始)
  158. for ($row=2;$row<=$row_num;$row++) {
  159. $data[$row-2][] = $sheet->getCell($col.$row)->getValue();
  160. }
  161. }
  162. return $data;
  163. }
  164. //二维数组去重
  165. function assoc_unique($arr, $key) {
  166. $tmp_arr = array();
  167. foreach ($arr as $k => $v) {
  168. if (in_array($v[$key], $tmp_arr)) {//搜索$v[$key]是否在$tmp_arr数组中存在,若存在返回true
  169. unset($arr[$k]);
  170. } else {
  171. $tmp_arr[] = $v[$key];
  172. }
  173. }
  174. sort($arr); //sort函数对数组进行排序
  175. return $arr;
  176. }
  177. /**
  178. * 阿里云身份证信息识别
  179. */
  180. function aliyun_ocr_idcard($file)
  181. {
  182. $url = "https://dm-51.data.aliyun.com/rest/160601/ocr/ocr_idcard.json";
  183. $appcode = config('wxconfig.aliAppCode');
  184. // $file = "你的文件路径";
  185. //如果输入带有inputs, 设置为True,否则设为False
  186. $is_old_format = false;
  187. //如果没有configure字段,config设为空
  188. $config = array(
  189. "side" => "face"
  190. );
  191. //$config = array()
  192. if ($fp = fopen($file, "rb", 0)) {
  193. $binary = fread($fp, filesize($file)); // 文件读取
  194. fclose($fp);
  195. $base64 = base64_encode($binary); // 转码
  196. }
  197. $headers = array();
  198. array_push($headers, "Authorization:APPCODE " . $appcode);
  199. //根据API的要求,定义相对应的Content-Type
  200. array_push($headers, "Content-Type".":"."application/json; charset=UTF-8");
  201. $querys = "";
  202. if ($is_old_format == true) {
  203. $request = array();
  204. $request["image"] = array(
  205. "dataType" => 50,
  206. "dataValue" => "$base64"
  207. );
  208. if (count($config) > 0) {
  209. $request["configure"] = array(
  210. "dataType" => 50,
  211. "dataValue" => json_encode($config)
  212. );
  213. }
  214. $body = json_encode(array("inputs" => array($request)));
  215. } else {
  216. $request = array(
  217. "image" => "$base64"
  218. );
  219. if (count($config) > 0) {
  220. $request["configure"] = json_encode($config);
  221. }
  222. $body = json_encode($request);
  223. }
  224. $method = "POST";
  225. $curl = curl_init();
  226. curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
  227. curl_setopt($curl, CURLOPT_URL, $url);
  228. curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
  229. curl_setopt($curl, CURLOPT_FAILONERROR, false);
  230. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  231. curl_setopt($curl, CURLOPT_HEADER, true);
  232. if (1 == strpos("$".$url, "https://")) {
  233. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  234. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
  235. }
  236. curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
  237. $result = curl_exec($curl);
  238. $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
  239. $rheader = substr($result, 0, $header_size);
  240. $rbody = substr($result, $header_size);
  241. $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  242. if ($httpCode == 200) {
  243. if ($is_old_format) {
  244. $output = json_decode($rbody, true);
  245. $result_str = $output["outputs"][0]["outputValue"]["dataValue"];
  246. } else {
  247. $result_str = $rbody;
  248. }
  249. $result_arr = json_decode($result_str, true);
  250. if ($result_arr['success']==false) {
  251. return false;
  252. } else {
  253. return array(
  254. "name" => $result_arr['name'],
  255. "nationality" => $result_arr['nationality'],
  256. "num" => $result_arr['num'],
  257. "sex" => $result_arr['sex'],
  258. "birth" => date('Y-m-d', strtotime($result_arr['birth'])),
  259. "nationality" => $result_arr['nationality'],
  260. "address" => $result_arr['address']
  261. );
  262. }
  263. return $result_str;
  264. } else {
  265. return false;
  266. }
  267. }
  268. // 两个日期间数组
  269. function periodDate($start_time, $end_time)
  270. {
  271. $start_time = strtotime($start_time);
  272. $end_time = strtotime($end_time);
  273. $i=0;
  274. while ($start_time<=$end_time) {
  275. $arr[date('Y-m-d', $start_time)] = 0;
  276. $start_time = strtotime('+1 day', $start_time);
  277. $i++;
  278. }
  279. return $arr;
  280. }
  281. // 数组键值分开
  282. function arrKeyVal($arr)
  283. {
  284. $keyArr = array();
  285. $valArr = array();
  286. if (!empty($arr)) {
  287. foreach ($arr as $k=>$v) {
  288. $keyArr[] = $k;
  289. $valArr[] = $v;
  290. }
  291. }
  292. return array('keyarr'=>$keyArr, 'valarr'=>$valArr);
  293. }
  294. //获取ip
  295. // function get_client_ip() {
  296. // $ip = $_SERVER['REMOTE_ADDR'];
  297. // if (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {
  298. // $ip = $_SERVER['HTTP_CLIENT_IP'];
  299. // } elseif(isset($_SERVER['HTTP_X_FORWARDED_FOR']) AND preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
  300. // foreach ($matches[0] AS $xip) {
  301. // if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
  302. // $ip = $xip;
  303. // break;
  304. // }
  305. // }
  306. // }
  307. // return $ip;
  308. // }
  309. //能否发布
  310. function is_released($workerid)
  311. {
  312. $comjobs_count = Db::name('comjobs')
  313. ->where('workerid',$workerid)
  314. ->count();
  315. $demand_count = Db::name("demand")
  316. ->where('workerid',$workerid)
  317. ->count();
  318. $supply_data = Db::name("supply")
  319. ->where('workerid',$workerid)
  320. ->count();
  321. $count = $comjobs_count + $demand_count + $supply_data;
  322. if($count >= 3)
  323. {
  324. $rtn['code'] = 1001;
  325. $rtn['msg'] = "您的审核还未通过,最多只能发3条信息";
  326. return $rtn;
  327. }else{
  328. $rtn['code'] = 0;
  329. // $rtn['code'] = 1001;
  330. }
  331. return $rtn;
  332. }
  333. /**
  334. * 根据经纬度和半径计算出范围
  335. * @param string $lat 纬度
  336. * @param String $lng 经度
  337. * @param float $radius 半径
  338. * @return Array 范围数组
  339. */
  340. function calcScope($lat, $lng, $radius) {
  341. $degree = (24901*1609)/360.0;
  342. $dpmLat = 1/$degree;
  343. $radiusLat = $dpmLat*$radius;
  344. $minLat = $lat - $radiusLat; // 最小纬度
  345. $maxLat = $lat + $radiusLat; // 最大纬度
  346. $mpdLng = $degree*cos($lat * (PI/180));
  347. $dpmLng = 1 / $mpdLng;
  348. $radiusLng = $dpmLng*$radius;
  349. $minLng = $lng - $radiusLng; // 最小经度
  350. $maxLng = $lng + $radiusLng; // 最大经度
  351. /** 返回范围数组 */
  352. $scope = array(
  353. 'minLat' => $minLat,
  354. 'maxLat' => $maxLat,
  355. 'minLng' => $minLng,
  356. 'maxLng' => $maxLng
  357. );
  358. return $scope;
  359. }
  360. /**
  361. * 根据经纬度和半径查询在此范围内的所有的对象
  362. * @param String $lat 纬度
  363. * @param String $lng 经度
  364. * @param float $radius 半径
  365. * @return Array 计算出来的结果
  366. */
  367. //public function searchByLatAndLng($lat, $lng, $radius) {
  368. // $scope = $this->calcScope($lat, $lng, $radius); // 调用范围计算函数,获取最大最小经纬度
  369. // /** 查询经纬度在 $radius 范围内的对象的详细地址 */
  370. // $sql = 'SELECT `字段` FROM `表名` WHERE `Latitude` < '.$scope['maxLat'].' and `Latitude` > '.$scope['minLat'].' and `Longitude` < '.$scope['maxLng'].' and `Longitude` > '.$scope['minLng'];
  371. // $stmt = self::$db->query($sql);
  372. // $res = $stmt->fetchAll(PDO::FETCH_ASSOC); // 获取查询结果并返回
  373. // return $res;
  374. //}
  375. /**
  376. * 获取两个经纬度之间的距离
  377. * @param string $lat1 纬一
  378. * @param String $lng1 经一
  379. * @param String $lat2 纬二
  380. * @param String $lng2 经二
  381. * @return float 返回两点之间的距离
  382. */
  383. function calcDistance($lat1, $lng1, $lat2, $lng2) {
  384. /** 转换数据类型为 double */
  385. $lat1 = doubleval($lat1);
  386. $lng1 = doubleval($lng1);
  387. $lat2 = doubleval($lat2);
  388. $lng2 = doubleval($lng2);
  389. /** 以下算法是 Google 出来的,与大多数经纬度计算工具结果一致 */
  390. $theta = $lng1 - $lng2;
  391. $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
  392. $dist = acos($dist);
  393. $dist = rad2deg($dist);
  394. $miles = $dist * 60 * 1.1515;
  395. return ($miles * 1.609344);
  396. }
  397. //$lon1 用户当前经度 $lat1用户当前纬度 $lon2数据库经度的字段名 $lat2数据库纬度的字段名
  398. function distance_sql($lon1='116.434164',$lat1='39.909843',$lon2='longitude',$lat2='latitude')
  399. {
  400. $sql = "round(6378.138*2*asin(sqrt(pow(sin( ({$lat1}*pi()/180-{$lat2}*pi()/180)/2),2)+cos({$lat1}*pi()/180)*cos({$lat2}*pi()/180)* pow(sin( ({$lon1}*pi()/180-{$lon2}*pi()/180)/2),2)))*1000) ";
  401. return $sql;
  402. }
  403. /**
  404. * CURL请求
  405. * @param $url 请求url地址
  406. * @param $method 请求方法 get post
  407. * @param null $postfields post数据数组
  408. * @param array $headers 请求header信息
  409. * @return mixed
  410. */
  411. function http_request($url, $method = "GET", $postfields = null, $headers = [])
  412. {
  413. $method = strtoupper($method);
  414. $ci = curl_init();
  415. /* Curl settings */
  416. curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
  417. curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
  418. curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间,如果设置为0,则无限等待 */
  419. curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
  420. curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
  421. switch ($method) {
  422. case "POST":
  423. curl_setopt($ci, CURLOPT_POST, true);
  424. if (!empty($postfields)) {
  425. $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
  426. curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
  427. }
  428. break;
  429. default:
  430. curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
  431. break;
  432. }
  433. $ssl = preg_match('/^https:\/\//i', $url) ? TRUE : FALSE;
  434. curl_setopt($ci, CURLOPT_URL, $url);
  435. if ($ssl) {
  436. curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
  437. curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
  438. }
  439. //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
  440. curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
  441. curl_setopt($ci, CURLOPT_MAXREDIRS, 2); /* 指定最多的HTTP重定向的数量,这个选项是和CURLOPT_FOLLOWLOCATION一起使用的 */
  442. curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
  443. curl_setopt($ci, CURLINFO_HEADER_OUT, true);
  444. /* curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
  445. $response = curl_exec($ci);
  446. curl_close($ci);
  447. return $response;
  448. }