helpers.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. <?php
  2. use HyperDown\Parser;
  3. use Intervention\Image\Facades\Image;
  4. use Illuminate\Support\Facades\Mail;
  5. use Illuminate\Support\Facades\Auth;
  6. if ( !function_exists('ajax_return') ) {
  7. /**
  8. * ajax返回数据
  9. *
  10. * @param string $data 需要返回的数据
  11. * @param int $status_code
  12. * @return \Illuminate\Http\JsonResponse
  13. */
  14. function ajax_return($status_code = 200, $data = '')
  15. {
  16. //如果如果是错误 返回错误信息
  17. if ($status_code != 200) {
  18. //增加status_code
  19. $data = ['status_code' => $status_code, 'message' => $data,];
  20. return response()->json($data, $status_code);
  21. }
  22. //如果是对象 先转成数组
  23. if (is_object($data)) {
  24. $data = $data->toArray();
  25. }
  26. /**
  27. * 将数组递归转字符串
  28. * @param array $arr 需要转的数组
  29. * @return array 转换后的数组
  30. */
  31. function to_string($arr)
  32. {
  33. // app 禁止使用和为了统一字段做的判断
  34. $reserved_words = [];
  35. foreach ($arr as $k => $v) {
  36. //如果是对象先转数组
  37. if (is_object($v)) {
  38. $v = $v->toArray();
  39. }
  40. //如果是数组;则递归转字符串
  41. if (is_array($v)) {
  42. $arr[$k] = to_string($v);
  43. } else {
  44. //判断是否有移动端禁止使用的字段
  45. in_array($k, $reserved_words, true) && die('不允许使用【' . $k . '】这个键名 —— 此提示是helper.php 中的ajaxReturn函数返回的');
  46. //转成字符串类型
  47. $arr[$k] = strval($v);
  48. }
  49. }
  50. return $arr;
  51. }
  52. //判断是否有返回的数据
  53. if (is_array($data)) {
  54. //先把所有字段都转成字符串类型
  55. $data = to_string($data);
  56. }
  57. return response()->json($data, $status_code);
  58. }
  59. }
  60. if ( !function_exists('send_email') ) {
  61. /**
  62. * 发送邮件函数
  63. *
  64. * @param $email 收件人邮箱 如果群发 则传入数组
  65. * @param $name 收件人名称
  66. * @param $subject 标题
  67. * @param array $data 邮件模板中用的变量 示例:['name'=>'帅白','phone'=>'110']
  68. * @param string $template 邮件模板
  69. * @return array 发送状态
  70. */
  71. function send_email($email, $name, $subject, $data = [], $template = 'emails.test')
  72. {
  73. Mail::send($template, $data, function ($message) use ($email, $name, $subject) {
  74. //如果是数组;则群发邮件
  75. if (is_array($email)) {
  76. foreach ($email as $k => $v) {
  77. $message->to($v, $name)->subject($subject);
  78. }
  79. } else {
  80. $message->to($email, $name)->subject($subject);
  81. }
  82. });
  83. if (count(Mail::failures()) > 0) {
  84. $data = array('status_code' => 500, 'message' => '邮件发送失败');
  85. } else {
  86. $data = array('status_code' => 200, 'message' => '邮件发送成功');
  87. }
  88. return $data;
  89. }
  90. }
  91. if ( !function_exists('upload') ) {
  92. /**
  93. * 上传文件函数
  94. *
  95. * @param $file 表单的name名
  96. * @param string $path 上传的路径
  97. * @param bool $childPath 是否根据日期生成子目录
  98. * @return array 上传的状态
  99. */
  100. function upload($file, $path = 'upload', $childPath = true)
  101. {
  102. //判断请求中是否包含name=file的上传文件
  103. if (!request()->hasFile($file)) {
  104. $data = ['status_code' => 500, 'message' => '上传文件为空'];
  105. return $data;
  106. }
  107. $file = request()->file($file);
  108. //判断文件上传过程中是否出错
  109. if (!$file->isValid()) {
  110. $data = ['status_code' => 500, 'message' => '文件上传出错'];
  111. return $data;
  112. }
  113. //兼容性的处理路径的问题
  114. if ($childPath == true) {
  115. $path = './' . trim($path, './') . '/' . date('Ymd') . '/';
  116. } else {
  117. $path = './' . trim($path, './') . '/';
  118. }
  119. if (!is_dir($path)) {
  120. mkdir($path, 0755, true);
  121. }
  122. //获取上传的文件名
  123. $oldName = $file->getClientOriginalName();
  124. //组合新的文件名
  125. $newName = uniqid() . '.' . $file->getClientOriginalExtension();
  126. //上传失败
  127. if (!$file->move($path, $newName)) {
  128. $data = ['status_code' => 500, 'message' => '保存文件失败'];
  129. return $data;
  130. }
  131. //上传成功
  132. $data = ['status_code' => 200, 'message' => '上传成功', 'data' => ['old_name' => $oldName, 'new_name' => $newName, 'path' => trim($path, '.')]];
  133. return $data;
  134. }
  135. }
  136. if ( !function_exists('get_uid') ) {
  137. /**
  138. * 返回登录的用户id
  139. *
  140. * @return mixed 用户id
  141. */
  142. function get_uid()
  143. {
  144. return Auth::id();
  145. }
  146. }
  147. if (!function_exists('save_to_file')) {
  148. /**
  149. * 将数组已json格式写入文件
  150. * @param string $fileName 文件名
  151. * @param array $data 数组
  152. */
  153. function save_to_file($fileName = 'test', $data = array())
  154. {
  155. $path = storage_path('tmp' . DIRECTORY_SEPARATOR);
  156. is_dir($path) || mkdir($path);
  157. $fileName = str_replace('.php', '', $fileName);
  158. $fileName = $path . $fileName . '_' . date('Y-m-d_H-i-s', time()) . '.php';
  159. file_put_contents($fileName, json_encode($data));
  160. }
  161. }
  162. if ( !function_exists('re_substr') ) {
  163. /**
  164. * 字符串截取,支持中文和其他编码
  165. *
  166. * @param string $str 需要转换的字符串
  167. * @param integer $start 开始位置
  168. * @param string $length 截取长度
  169. * @param boolean $suffix 截断显示字符
  170. * @param string $charset 编码格式
  171. * @return string
  172. */
  173. function re_substr($str, $start = 0, $length, $suffix = true, $charset = "utf-8") {
  174. $slice = mb_substr($str, $start, $length, $charset);
  175. $omit = mb_strlen($str) >= $length ? '...' : '';
  176. return $suffix ? $slice.$omit : $slice;
  177. }
  178. }
  179. if ( !function_exists('Add_text_water') ) {
  180. /**
  181. * 给图片添加文字水印
  182. *
  183. * @param $file
  184. * @param $text
  185. * @param string $color
  186. * @return mixed
  187. */
  188. function Add_text_water($file, $text, $color = '#0B94C1') {
  189. $image = Image::make($file);
  190. $image->text($text, $image->width()-20, $image->height()-30, function($font) use($color) {
  191. $font->file(public_path('fonts/msyh.ttf'));
  192. $font->size(15);
  193. $font->color($color);
  194. $font->align('right');
  195. $font->valign('bottom');
  196. });
  197. $image->save($file);
  198. return $image;
  199. }
  200. }
  201. if ( !function_exists('word_time') ) {
  202. /**
  203. * 把日期或者时间戳转为距离现在的时间
  204. *
  205. * @param $time
  206. * @return bool|string
  207. */
  208. function word_time($time) {
  209. // 如果是日期格式的时间;则先转为时间戳
  210. if (!is_integer($time)) {
  211. $time = strtotime($time);
  212. }
  213. $int = time() - $time;
  214. if ($int <= 2){
  215. $str = sprintf('刚刚', $int);
  216. }elseif ($int < 60){
  217. $str = sprintf('%d秒前', $int);
  218. }elseif ($int < 3600){
  219. $str = sprintf('%d分钟前', floor($int / 60));
  220. }elseif ($int < 86400){
  221. $str = sprintf('%d小时前', floor($int / 3600));
  222. }elseif ($int < 1728000){
  223. $str = sprintf('%d天前', floor($int / 86400));
  224. }else{
  225. $str = date('Y-m-d H:i:s', $time);
  226. }
  227. return $str;
  228. }
  229. }
  230. if ( !function_exists('markdown_to_html') ) {
  231. /**
  232. * 把markdown转为html
  233. *
  234. * @param $markdown
  235. * @return mixed|string
  236. */
  237. function markdown_to_html($markdown)
  238. {
  239. // 正则匹配到全部的iframe
  240. preg_match_all('/&lt;iframe.*iframe&gt;/', $markdown, $iframe);
  241. // 如果有iframe 则先替换为临时字符串
  242. if (!empty($iframe[0])) {
  243. $tmp = [];
  244. // 组合临时字符串
  245. foreach ($iframe[0] as $k => $v) {
  246. $tmp[] = '【iframe'.$k.'】';
  247. }
  248. // 替换临时字符串
  249. $markdown = str_replace($iframe[0], $tmp, $markdown);
  250. // 讲iframe转义
  251. $replace = array_map(function ($v){
  252. return htmlspecialchars_decode($v);
  253. }, $iframe[0]);
  254. }
  255. // markdown转html
  256. $parser = new Parser();
  257. $html = $parser->makeHtml($markdown);
  258. $html = str_replace('<code class="', '<code class="lang-', $html);
  259. // 将临时字符串替换为iframe
  260. if (!empty($iframe[0])) {
  261. $html = str_replace($tmp, $replace, $html);
  262. }
  263. return $html;
  264. }
  265. }
  266. if ( !function_exists('strip_html_tags') ) {
  267. /**
  268. * 删除指定标签
  269. *
  270. * @param array $tags 删除的标签 数组形式
  271. * @param string $str html字符串
  272. * @param bool $content true保留标签的内容text
  273. * @return mixed
  274. */
  275. function strip_html_tags($tags, $str, $content = true)
  276. {
  277. $html = [];
  278. // 是否保留标签内的text字符
  279. if($content){
  280. foreach ($tags as $tag) {
  281. $html[] = '/(<' . $tag . '.*?>(.|\n)*?<\/' . $tag . '>)/is';
  282. }
  283. }else{
  284. foreach ($tags as $tag) {
  285. $html[] = "/(<(?:\/" . $tag . "|" . $tag . ")[^>]*>)/is";
  286. }
  287. }
  288. $data = preg_replace($html, '', $str);
  289. return $data;
  290. }
  291. }
  292. if (!function_exists('flash_message')){
  293. /**
  294. * 添加成功或者失败的提示
  295. *
  296. * @param string $message
  297. * @param bool $success
  298. */
  299. function flash_message($message = '成功', $success = true)
  300. {
  301. $className = $success ? 'alert-success' : 'alert-danger';
  302. session()->flash('alert-message', $message);
  303. session()->flash('alert-class', $className);
  304. }
  305. }
  306. if (!function_exists('curl_get_contents')) {
  307. /**
  308. * 使用curl获取远程数据
  309. * @param string $url url连接
  310. * @return string 获取到的数据
  311. */
  312. function curl_get_contents($url){
  313. set_time_limit(0);
  314. $ch=curl_init();
  315. curl_setopt($ch, CURLOPT_URL, $url); //设置访问的url地址
  316. curl_setopt($ch, CURLOPT_TIMEOUT, 5); //设置超时
  317. curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); //用户访问代理 User-Agent
  318. curl_setopt($ch, CURLOPT_REFERER,$_SERVER['HTTP_HOST']); //设置 referer
  319. curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1); //跟踪301
  320. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //返回结果
  321. $r=curl_exec($ch);
  322. curl_close($ch);
  323. return $r;
  324. }
  325. }
  326. if (! function_exists('redis')) {
  327. /**
  328. * redis的便捷操作方法
  329. *
  330. * @param $key
  331. * @param null $value
  332. * @param null $expire
  333. * @return bool|string
  334. */
  335. function redis($key = null, $value = null, $expire = null)
  336. {
  337. if (is_null($key)) {
  338. return app('redis');
  339. }
  340. if (is_null($value)) {
  341. $content = Redis::get($key);
  342. if (is_null($content)) {
  343. return null;
  344. }
  345. return is_null($content) ? null : unserialize($content);
  346. }
  347. Redis::set($key, serialize($value));
  348. if (! is_null($expire)) {
  349. Redis::expire($key, $expire);
  350. }
  351. }
  352. }