Index.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. <?php
  2. namespace addons\fastchat\controller;
  3. use addons\fastchat\library\Common;
  4. use fast\Random;
  5. use think\addons\Controller;
  6. use think\Config;
  7. use think\Cookie;
  8. use think\Db;
  9. class Index extends Controller
  10. {
  11. protected $noNeedLogin = ['initialize', 'load_message_prompt', 'upload'];
  12. protected $chat_config;
  13. protected $token_info = false;
  14. protected $token_list = [];// 要发送给前台的token(前台利用这些token链接websocket)
  15. public function _initialize()
  16. {
  17. // 跨域检测
  18. check_cors_request();
  19. parent::_initialize();
  20. $this->chat_config = get_addon_config('fastchat');
  21. $upload['upload'] = \app\common\model\Config::upload();
  22. $upload['upload']['cdnurl'] = $upload['upload']['cdnurl'] ? $upload['upload']['cdnurl'] : cdnurl('', true);
  23. $view_cdn = config('view_replace_str.__CDN__');
  24. $view_cdn = $view_cdn ? $view_cdn : cdnurl('', true);
  25. $this->chat_config = array_merge($this->chat_config, $upload, ['__CDN__' => $view_cdn]);
  26. // 配置排除
  27. $except_config = [
  28. 'worker_process_number',
  29. 'register_port',
  30. 'gateway_process_number',
  31. 'internal_start_port'
  32. ];
  33. foreach ($except_config as $key => $value) {
  34. if (in_array($value, $except_config)) {
  35. unset($this->chat_config[$value]);
  36. }
  37. }
  38. // 用户登录
  39. $modulename = $this->request->request('modulename');
  40. $tourists_token = $this->request->request('tourists_token');
  41. $this->token_list['fastchat_tourists_token'] = $tourists_token ? $tourists_token : Cookie::get('fastchat_user');
  42. if (!$modulename) {
  43. $this->result(null, 0, $this->chat_config['chat_name'] . ' 模块未知', 'json');
  44. }
  45. if ($modulename == 'admin') {
  46. // 验证管理员身份
  47. $auth = \app\admin\library\Auth::instance();
  48. if ($auth->isLogin()) {
  49. $this->token_info = Common::check_admin(false, $auth->id);
  50. if ($this->token_info) {
  51. // workerman 中不支持 PHP session和cookie,所以 $auth 类失效
  52. // 此处对管理员 token 加密稍作修改,供客服自动登录使用
  53. $keeptime = 864000;
  54. $expiretime = time() + $keeptime;
  55. // 原规则为单纯的id,若需修改附加的字符串,请将`Common::check_admin`方法里边的附加字符串一起修改
  56. $sign = $this->token_info['admin_id'] . 'fastchat_admin_sign_additional';
  57. $key = md5(md5($sign) . md5($keeptime) . md5($expiretime) . $this->token_info['token']);
  58. $cookie_data = [$this->token_info['admin_id'], $keeptime, $expiretime, $key];
  59. $this->token_list['fastchat_token'] = implode('|', $cookie_data);
  60. unset($this->token_info['token']);
  61. }
  62. }
  63. } else if ($modulename == 'user') {
  64. // 验证用户身份
  65. $auth = \app\common\library\Auth::instance();
  66. // $token = Cookie::get('token');
  67. $token = $this->request->header('session-token');
  68. if ($token) {
  69. $auth->init($token);
  70. if ($auth->isLogin()) {
  71. $this->token_info = Common::check_fa_user(null, $auth->id);
  72. $cookie_httponly = config('cookie.httponly');
  73. // workerman 中不支持 PHP session和cookie,所以 $auth 类失效
  74. // 在开启 $cookie_httponly 时,对用户的 token 加密稍作修改,供客服自动登录使用
  75. if ($this->token_info) {
  76. if (!$cookie_httponly) {
  77. $this->token_list['fastchat_token'] = $token;
  78. } else {
  79. // 若需修改附加的字符串,请将`Common::check_fa_user`方法里边的附加字符串一起修改
  80. // 先用 user_token 数据表中的token字段同样的加密算法对token进行加密,否则workerman无法识别用户身份
  81. $sign = Common::getEncryptedToken($token) . 'fastchat_user_sign_additional';
  82. $key = md5(md5($auth->id) . md5($sign));
  83. $cookie_data = [$auth->id, $key];
  84. $this->token_list['fastchat_token'] = implode('|', $cookie_data);
  85. }
  86. }
  87. }
  88. }
  89. if ($this->token_info && $this->token_list['fastchat_tourists_token']) {
  90. // 游客完成登录-游客信息转给用户
  91. Common::tourists_to_login($this->token_list['fastchat_tourists_token'], $this->token_info['user_id']);
  92. }
  93. } else if ($modulename == 'massager') { // 助教
  94. // $token = $this->request->header('session-token');
  95. }
  96. if (!$this->token_info && !$this->chat_config['anonymous_to_admin'] && !$this->chat_config['anonymous_to_user']) {
  97. $this->result(null, 403, $this->chat_config['chat_name'] . ' 禁止匿名用户', 'json');
  98. }
  99. if ($modulename != 'admin' && $this->token_list['fastchat_tourists_token'] && !$this->token_info) {
  100. // 验证游客身份
  101. $this->token_info = Common::check_tourists($this->token_list['fastchat_tourists_token']);
  102. }
  103. }
  104. public function initialize()
  105. {
  106. $config_data = $this->chat_config;
  107. $modulename = $this->request->request('modulename');
  108. if (!$this->token_info) {
  109. if ($modulename != 'admin') {
  110. // 建立游客身份
  111. $tourists_max_id = Db::name('fastchat_tourists')->max('id');
  112. $token = Random::uuid();
  113. $tourists = [
  114. 'avatar' => '',
  115. 'nickname' => '游客 ' . $tourists_max_id,
  116. 'token' => $token,
  117. 'createtime' => time()
  118. ];
  119. if (Db::name('fastchat_tourists')->insert($tourists)) {
  120. $tourists_id = Db::name('fastchat_tourists')->getLastInsID();
  121. $keeptime = 864000;
  122. $expiretime = time() + $keeptime;
  123. $key = md5(md5($tourists_id) . md5($keeptime) . md5($expiretime) . $token);
  124. $fastchat_tourists_cookie = [$tourists_id, $keeptime, $expiretime, $key];
  125. $fastchat_tourists = implode('|', $fastchat_tourists_cookie);
  126. $this->token_list['fastchat_tourists_token'] = $fastchat_tourists;
  127. Cookie::set('fastchat_user', $fastchat_tourists);
  128. // 为游客登录
  129. $this->token_info = Common::check_tourists($fastchat_tourists);
  130. } else {
  131. $this->result(null, 401, $this->chat_config['chat_name'] . ' 游客创建失败!', 'json');
  132. }
  133. } else {
  134. $this->result(null, 401, $this->chat_config['chat_name'] . ' 未登陆', 'json');
  135. }
  136. }
  137. $config_data['search_tip'] = Common::search_tip_fill($config_data['session_type']);
  138. $config_data['new_msg'] = Common::get_unread_messages($this->token_info['user_id']);
  139. $config_data['user_info'] = $this->token_info;
  140. $config_data['token_list'] = $this->token_list;
  141. $config_data['window_html'] = $this->view->fetch(ROOT_PATH . 'public/assets/addons/fastchat/tpl/chat_window.html', [], ['__CDN__' => $this->chat_config['__CDN__']]);
  142. $this->result($config_data, 1, 'ok', 'json');
  143. }
  144. public function index()
  145. {
  146. $this->error("当前插件暂无前台页面");
  147. }
  148. public function upload()
  149. {
  150. $file = $this->request->file('file');
  151. if (empty($file)) {
  152. $this->result(null, 0, '没有文件被上传或上传超过限制', 'json');
  153. }
  154. //判断是否已经存在附件
  155. $sha1 = $file->hash();
  156. $extparam = $this->request->post();
  157. $upload = Config::get('upload');
  158. preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);
  159. $type = strtolower($matches[2]);
  160. $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
  161. $size = (int)$upload['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);
  162. $fileInfo = $file->getInfo();
  163. $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
  164. $suffix = $suffix ? $suffix : 'file';
  165. $mimetypeArr = explode(',', strtolower($upload['mimetype']));
  166. $typeArr = explode('/', $fileInfo['type']);
  167. //禁止上传PHP和HTML文件
  168. if (in_array($fileInfo['type'], ['text/x-php', 'text/html']) || in_array($suffix, ['php', 'html', 'htm'])) {
  169. $this->error(__('上传格式限制'));
  170. }
  171. //验证文件后缀
  172. if ($upload['mimetype'] !== '*' &&
  173. (
  174. !in_array($suffix, $mimetypeArr)
  175. || (stripos($typeArr[0] . '/', $upload['mimetype']) !== false && (!in_array($fileInfo['type'], $mimetypeArr) && !in_array($typeArr[0] . '/*', $mimetypeArr)))
  176. )
  177. ) {
  178. $this->error(__('上传格式限制'));
  179. }
  180. //验证是否为图片文件
  181. $imagewidth = $imageheight = 0;
  182. if (in_array($fileInfo['type'], ['image/gif', 'image/jpg', 'image/jpeg', 'image/bmp', 'image/png', 'image/webp']) || in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'webp'])) {
  183. $imgInfo = getimagesize($fileInfo['tmp_name']);
  184. if (!$imgInfo || !isset($imgInfo[0]) || !isset($imgInfo[1])) {
  185. $this->error(__('上传的文件不是图片'));
  186. }
  187. $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
  188. $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
  189. }
  190. $replaceArr = [
  191. '{year}' => date("Y"),
  192. '{mon}' => date("m"),
  193. '{day}' => date("d"),
  194. '{hour}' => date("H"),
  195. '{min}' => date("i"),
  196. '{sec}' => date("s"),
  197. '{random}' => Random::alnum(16),
  198. '{random32}' => Random::alnum(32),
  199. '{filename}' => $suffix ? substr($fileInfo['name'], 0, strripos($fileInfo['name'], '.')) : $fileInfo['name'],
  200. '{suffix}' => $suffix,
  201. '{.suffix}' => $suffix ? '.' . $suffix : '',
  202. '{filemd5}' => md5_file($fileInfo['tmp_name']),
  203. ];
  204. $savekey = $upload['savekey'];
  205. $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);
  206. $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
  207. $fileName = substr($savekey, strripos($savekey, '/') + 1);
  208. $splInfo = $file->validate(['size' => $size])->move(ROOT_PATH . '/public' . $uploadDir, $fileName);
  209. if ($splInfo) {
  210. $admin_id = 0;
  211. $user_id = 0;
  212. if ($this->token_info) {
  213. $user_info = Common::user_info($this->token_info['user_id']);
  214. if ($user_info['session_type'] == 0) {
  215. $user_id = $user_info['id'];
  216. } else if ($user_info['session_type'] == 1) {
  217. $admin_id = $user_info['id'];
  218. }
  219. }
  220. $params = array(
  221. 'admin_id' => $admin_id,
  222. 'user_id' => $user_id,
  223. 'filesize' => $fileInfo['size'],
  224. 'imagewidth' => $imagewidth,
  225. 'imageheight' => $imageheight,
  226. 'imagetype' => $suffix,
  227. 'imageframes' => 0,
  228. 'mimetype' => $fileInfo['type'],
  229. 'url' => $uploadDir . $splInfo->getSaveName(),
  230. 'uploadtime' => time(),
  231. 'storage' => 'local',
  232. 'sha1' => $sha1,
  233. 'extparam' => json_encode($extparam),
  234. );
  235. $attachment = model("common/attachment");
  236. $attachment->data(array_filter($params));
  237. $attachment->save();
  238. \think\Hook::listen("upload_after", $attachment);
  239. $this->result(['url' => cdnurl($uploadDir . $splInfo->getSaveName(), true)], 1, null, 'json');
  240. } else {
  241. // 上传失败获取错误信息
  242. $this->result(null, 1, $file->getError(), 'json');
  243. }
  244. }
  245. /*供跨站下载来信提示音文件*/
  246. public function load_message_prompt()
  247. {
  248. $file = ROOT_PATH . 'public/assets/addons/fastchat/audio/message_prompt.wav';
  249. header("Content-type:application/octet-stream");
  250. $filename = basename($file);
  251. header("Content-Disposition:attachment;filename = " . $filename);
  252. header("Accept-ranges:bytes");
  253. header("Accept-length:" . filesize($file));
  254. readfile($file);
  255. }
  256. }