Index.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace addons\qrcode\controller;
  3. use think\addons\Controller;
  4. use think\exception\HttpResponseException;
  5. use think\Response;
  6. /**
  7. * 二维码生成
  8. *
  9. */
  10. class Index extends Controller
  11. {
  12. public function index()
  13. {
  14. return $this->view->fetch();
  15. }
  16. // 生成二维码
  17. public function build()
  18. {
  19. $config = get_addon_config('qrcode');
  20. if (isset($config['limitreferer']) && $config['limitreferer']) {
  21. $referer = $this->request->server('HTTP_REFERER', '');
  22. $refererInfo = parse_url($referer);
  23. $refererHost = $referer && $refererInfo ? $refererInfo['host'] : '';
  24. $refererHostArr = explode('.', $refererHost);
  25. $wildcardDomain = '';
  26. if (count($refererHostArr) > 2) {
  27. $refererHostArr[0] = '*';
  28. $wildcardDomain = implode('.', $refererHostArr);
  29. }
  30. $allowRefererList = $config['allowrefererlist'] ?? '';
  31. $domainArr = explode("\n", str_replace("\r", "", $allowRefererList));
  32. $domainArr = array_filter(array_unique($domainArr));
  33. $domainArr[] = request()->host(true);
  34. $inAllowList = false;
  35. if (in_array('*', $domainArr) || ($refererHost && in_array($refererHost, $domainArr)) || ($wildcardDomain && in_array($wildcardDomain, $domainArr))) {
  36. $inAllowList = true;
  37. }
  38. if (!$inAllowList && (!$referer && $config['allowemptyreferer'])) {
  39. $inAllowList = true;
  40. }
  41. if (!$inAllowList) {
  42. $response = Response::create('暂无权限', 'html', 403);
  43. throw new HttpResponseException($response);
  44. }
  45. }
  46. $params = $this->request->get();
  47. $params = array_intersect_key($params, array_flip(['text', 'size', 'padding', 'errorlevel', 'foreground', 'background', 'logo', 'logosize', 'logopath', 'label', 'labelfontsize', 'labelalignment']));
  48. $params['text'] = $this->request->get('text', $config['text'], 'trim');
  49. $params['label'] = $this->request->get('label', $config['label'], 'trim');
  50. $qrCode = \addons\qrcode\library\Service::qrcode($params);
  51. $mimetype = $config['format'] == 'png' ? 'image/png' : 'image/svg+xml';
  52. $response = Response::create()->header("Content-Type", $mimetype);
  53. // 直接显示二维码
  54. header('Content-Type: ' . $qrCode->getContentType());
  55. $response->content($qrCode->writeString());
  56. // 写入到文件
  57. if ($config['writefile']) {
  58. $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/';
  59. if (!is_dir($qrcodePath)) {
  60. @mkdir($qrcodePath);
  61. }
  62. if (is_really_writable($qrcodePath)) {
  63. $filePath = $qrcodePath . md5(implode('', $params)) . '.' . $config['format'];
  64. $qrCode->writeFile($filePath);
  65. }
  66. }
  67. return $response;
  68. }
  69. }