liufumingren 7b18287328 fix: 全项目清理 PHP 7.4 升级遗留(open_basedir 临时目录、implode 反序、null 取下标、嵌套三元)
一、open_basedir 不能再写 /tmp(7.4 池子把白名单收紧,Monolog/EasyWeChat 会抛异常)
- addons/shopro/library/Wechat.php:easywechat 日志改到 runtime/easywechat/
- addons/epay/library/Yansongda/Supports/Logger.php:epay 日志默认路径改到 runtime/epay/
- application/admin/library/traits/Backend.php:CSV 导入临时文件改到 runtime/temp/

二、implode 参数反序(7.4 起 E_DEPRECATED,TP5 会抛异常)
- application/api/controller/Datas.php
- application/index/controller/wms/Pda.php
- 另修正 Wms.php 中 1 处(拆分面单提示)

三、null 取下标(7.4 起 "Trying to access array offset on value of type null")
- 覆盖 71 个文件 135 行:find()/value()/json_decode()/redis get 等结果未判空即取下标处,
  统一 (\['k'] ?? null) 兜底;foreach 目标用 ?? [];in_array/count 等数组参数用 ?? []
- 涉及 api/*、admin/shopro/*、addons/shopro/*、addons/epay/*、index/wms/* 等

四、嵌套三元未加括号(7.4 弃用)
- application/index/controller/wms/Wms.php getPackingprice 2 处,补括号后与旧版本解析顺序一致

验证:74 个文件、148 行改动,逐行括号/引号配平与 HEAD 一致,未改动 vendor/ 与 thinkphp/;
剩余扫描命中均为写目标、unset、或已被 if(!\){error()} 拦截的假阳性。

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-25 09:47:48 +08:00

729 lines
27 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace app\api\controller;
use think\Db;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Validate;
use addons\shopro\library\Wechat;
use addons\shopro\model\UserOauth;
use fast\Http;
/**
* 会员接口
*/
class User extends Api
{
protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third','wxOfficialAccountOauth','wxMiniProgramOauth','getWxMiniProgramSessionKey','loginByUUid'];
protected $noNeedRight = '*';
public function _initialize()
{
parent::_initialize();
if (!Config::get('fastadmin.usercenter')) {
$this->error(__('User center already closed'));
}
$this->redis = new \Redis();
$this->redis->connect('127.0.0.1', 6379);
$this->redis->auth('qwe2019@');
$this->redis->select(10);
}
/**
* 会员中心
*/
public function index()
{
$this->success('', [$this->auth->getUserinfo(),$this->auth->getRuleList()]);
}
/**
* 会员登录
*
* @ApiMethod (POST)
* @param string $account 账号
* @param string $password 密码
*/
public function login()
{
$account = $this->request->post('account');
$password = $this->request->post('password');
if (!$account || !$password) {
$this->error(__('Invalid parameters'));
}
$ret = $this->auth->login($account, $password);
if ($ret) {
$data = ['userinfo' => $this->auth->getUserinfo()];
$this->success(__('Logged in successful'), $data);
} else {
$this->error($this->auth->getError());
}
}
public function userData()
{
$data=[];
$this->success('用户数据', $data);
}
public function loginByUUid(){
$uuid = $this->request->post('uuid');
$user = \app\common\model\User::where(["tmp_code"=>$uuid])->find();
if($user){
$ret = $this->auth->direct($user->id);
}
if($ret){
$data = ['userinfo' => $this->auth->getUserinfo()];
$this->success(__('Logged in successful'), $data);
} else {
$this->error($this->auth->getError());
}
}
/**
* 手机验证码登录
*
* @ApiMethod (POST)
* @param string $mobile 手机号
* @param string $captcha 验证码
*/
public function mobilelogin()
{
$mobile = $this->request->post('mobile');
$captcha = $this->request->post('captcha');
if (!$mobile || !$captcha) {
$this->error(__('Invalid parameters'));
}
if (!Validate::regex($mobile, "^1\d{10}$")) {
$this->error(__('Mobile is incorrect'));
}
if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
$this->error(__('Captcha is incorrect'));
}
$user = \app\common\model\User::getByMobile($mobile);
if ($user) {
if ($user->status != 'normal') {
$this->error(__('Account is locked'));
}
//如果已经有账号则直接登录
$ret = $this->auth->direct($user->id);
} else {
$ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
}
if ($ret) {
Sms::flush($mobile, 'mobilelogin');
$data = ['userinfo' => $this->auth->getUserinfo()];
$this->success(__('Logged in successful'), $data);
} else {
$this->error($this->auth->getError());
}
}
/**
* 注册会员
*
* @ApiMethod (POST)
* @param string $username 用户名
* @param string $password 密码
* @param string $email 邮箱
* @param string $mobile 手机号
* @param string $code 验证码
*/
public function register()
{
$username = $this->request->post('username');
$password = $this->request->post('password');
$email = $this->request->post('email');
$mobile = $this->request->post('mobile');
$code = $this->request->post('code');
if (!$username || !$password) {
$this->error(__('Invalid parameters'));
}
if ($email && !Validate::is($email, "email")) {
$this->error(__('Email is incorrect'));
}
if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
$this->error(__('Mobile is incorrect'));
}
$ret = Sms::check($mobile, $code, 'register');
if (!$ret) {
$this->error(__('Captcha is incorrect'));
}
$ret = $this->auth->register($username, $password, $email, $mobile, []);
if ($ret) {
$data = ['userinfo' => $this->auth->getUserinfo()];
$this->success(__('Sign up successful'), $data);
} else {
$this->error($this->auth->getError());
}
}
/**
* 退出登录
* @ApiMethod (POST)
*/
public function logout()
{
if (!$this->request->isPost()) {
$this->error(__('Invalid parameters'));
}
$this->auth->logout();
$this->success(__('Logout successful'));
}
/**
* 修改会员个人信息
*
* @ApiMethod (POST)
* @param string $avatar 头像地址
* @param string $username 用户名
* @param string $nickname 昵称
* @param string $bio 个人简介
*/
public function profile()
{
$user = $this->auth->getUser();
$username = $this->request->post('username');
$nickname = $this->request->post('nickname');
$bio = $this->request->post('bio');
$avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
if ($username) {
$exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
if ($exists) {
$this->error(__('Username already exists'));
}
$user->username = $username;
}
if ($nickname) {
$exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
if ($exists) {
$this->error(__('Nickname already exists'));
}
$user->nickname = $nickname;
}
$user->bio = $bio;
$user->avatar = $avatar;
$user->save();
$this->success();
}
/**
* 修改邮箱
*
* @ApiMethod (POST)
* @param string $email 邮箱
* @param string $captcha 验证码
*/
public function changeemail()
{
$user = $this->auth->getUser();
$email = $this->request->post('email');
$captcha = $this->request->post('captcha');
if (!$email || !$captcha) {
$this->error(__('Invalid parameters'));
}
if (!Validate::is($email, "email")) {
$this->error(__('Email is incorrect'));
}
if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
$this->error(__('Email already exists'));
}
$result = Ems::check($email, $captcha, 'changeemail');
if (!$result) {
$this->error(__('Captcha is incorrect'));
}
$verification = $user->verification;
$verification->email = 1;
$user->verification = $verification;
$user->email = $email;
$user->save();
Ems::flush($email, 'changeemail');
$this->success();
}
/**
* 修改手机号
*
* @ApiMethod (POST)
* @param string $mobile 手机号
* @param string $captcha 验证码
*/
public function changemobile()
{
$user = $this->auth->getUser();
$mobile = $this->request->post('mobile');
$captcha = $this->request->post('captcha');
if (!$mobile || !$captcha) {
$this->error(__('Invalid parameters'));
}
if (!Validate::regex($mobile, "^1\d{10}$")) {
$this->error(__('Mobile is incorrect'));
}
if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
$this->error(__('Mobile already exists'));
}
$result = Sms::check($mobile, $captcha, 'changemobile');
if (!$result) {
$this->error(__('Captcha is incorrect'));
}
$verification = $user->verification;
$verification->mobile = 1;
$user->verification = $verification;
$user->mobile = $mobile;
$user->save();
Sms::flush($mobile, 'changemobile');
$this->success();
}
/**
* 第三方登录
*
* @ApiMethod (POST)
* @param string $platform 平台名称
* @param string $code Code码
*/
public function third()
{
$url = url('user/index');
$platform = $this->request->post("platform");
$code = $this->request->post("code");
$config = get_addon_config('third');
if (!$config || !isset($config[$platform])) {
$this->error(__('Invalid parameters'));
}
$app = new \addons\third\library\Application($config);
//通过code换access_token和绑定会员
$result = $app->{$platform}->getUserInfo(['code' => $code]);
if ($result) {
$loginret = \addons\third\library\Service::connect($platform, $result);
if ($loginret) {
$data = [
'userinfo' => $this->auth->getUserinfo(),
'thirdinfo' => $result
];
$this->success(__('Logged in successful'), $data);
}
}
$this->error(__('Operation failed'), $url);
}
public function wxOfficialAccountOauth()
{
$token = '';
$params = $this->request->get();
$code = $params['appid'];
$payload = json_decode(htmlspecialchars_decode($params['payload']), true);
// 解析前端主机
if (($payload['event'] ?? null)!== 'login' && ($payload['token'] ?? null)!== '') {
$this->auth->init($payload['token']);
}
$wechat = new Wechat('wxOfficialAccount',$code);
$oauth = $wechat->oauth();
$decryptData = $oauth->user()->getOriginal();
$decryptData['watermark']['appid'] = $params['appid'];
$token = Db::transaction(function () use ($payload, $decryptData) {
try {
$token = $this->oauthLoginOrRegisterOrBindOrRefresh($payload['event'], $decryptData, 'wxOfficialAccount', 'Wechat');
return $token;
} catch (\Exception $e) {
$this->error($e->getMessage());
}
});
// 跳转回前端
if ($token) {
header('Location: ' . $payload['host'] . 'pages/public/loading/?token=' . $token);
} else {
header('Location: ' . $payload['host']);
}
exit;
}
/**
* 获取微信小程序session_key
*
* @param string $code 加密code
* @param boolean $autoLogin 是否自动登录(需已注册会员)
*/
public function getWxMiniProgramSessionKey()
{
$post = $this->request->post();
$autoLogin = $post['autoLogin'];
$appid = $post['appid'];
$wechat = new Wechat('wxMiniProgram',$appid);
$decryptSession = $wechat->code($post['code']);
if (!isset($decryptSession['session_key'])) {
$this->error('未获取session_key,请重启应用');
}
$uuid = Random::uuid();
\think\Cache::set($uuid, $decryptSession, 24 * 3600 * 30); // 强制30天过期
$userOauth = UserOauth::get([
'provider' => 'Wechat',
'platform' => 'wxMiniProgram',
'openid' => $decryptSession['openid'],
'user_id' => ['neq', 0]
]);
if ($userOauth) {
$userOauth->save(['session_key' => $decryptSession['session_key']]);
}
if ($autoLogin && $userOauth) {
$ret = $this->auth->direct($userOauth->user_id);
if ($ret) {
$token = $this->auth->getToken();
$this->success(__('Logged in successful'), ['token' => $token, 'session_id' => $uuid, 'openid' => $decryptSession['openid']]);
} else {
$this->error($this->auth->getError());
}
}
$this->success('', ['session_id' => $uuid]);
}
/**
* 微信小程序登录
*
* @param string $session_key session_key
* @param string $signature 校验签名
* @param string $iv 解密向量
* @param string $encryptedData 需解密完整用户信息
* @param boolean $refresh 重新获取或刷新最新的用户信息 (用户头像失效或微信客户端修改昵称等情况)
*/
public function wxMiniProgramOauth()
{
$post = $this->request->post();
$post['encryptedData'] = $this->request->post('encryptedData', null, null);
$token = Db::transaction(function () use ($post) {
try {
$appid = $post['appid'];
$wechat = new Wechat('wxMiniProgram',$appid);
$decryptSession = \think\Cache::get($post['session_id']);
if (!$decryptSession || !isset($decryptSession['openid'])) {
throw new \Exception('未获取到登录态,请重试');
}
$decryptUserInfo = $wechat->decryptData($decryptSession['session_key'], $post['iv'], $post['encryptedData']); // 客户端传值数据都不可信,需服务端解密用户信息
$decryptUserInfo = array_merge($decryptUserInfo, $decryptSession);
//组装decryptData
$decryptData = array_change_key_case($decryptUserInfo, CASE_LOWER);
if (empty($decryptData['openid'])) {
throw new \Exception('code错误,请重试');
}
$decryptData['session_key'] = $decryptSession['session_key'];
$decryptData['mobile'] = isset($decryptUserInfo['purePhoneNumber'])?$decryptUserInfo['purePhoneNumber']:'';
return $this->oauthLoginOrRegisterOrBindOrRefresh($post['event'], $decryptData, 'wxMiniProgram', 'Wechat');
} catch (\Exception $e) {
$this->error($e->getMessage());
}
});
if ($token) {
$this->success(__('Logged in successful'), ['token' => $token]);
} else {
$this->error($this->auth->getError());
}
}
private function oauthLoginOrRegisterOrBindOrRefresh($event, $decryptData, $platform, $provider, $keeptime = 0)
{
$oauthData = $decryptData;
$Appsmodel = new \app\common\model\Apps;
$APP = $Appsmodel->where(['app_id'=>$decryptData['watermark']['appid']])->find();
$warehouseId = 0;
if($APP){
$warehouseId = $APP['warehouse_id'];
}
$oauthData = array_merge($oauthData, [
'provider' => $provider,
'platform' => $platform,
]);
if ($platform === 'wxMiniProgram' || $platform === 'App') {
$oauthData['expire_in'] = 7200;
$oauthData['expiretime'] = time() + 7200;
}
$userOauth = UserOauth::where(['openid' => $decryptData['openid'], 'user_id' => ['neq', 0]])->where('platform', $platform)->where('provider', $provider)->lock(true)->find();
switch ($event) {
case 'login': // 登录(自动注册)
if (!$userOauth) { // 没有找到第三方登录信息 创建新用户
//默认创建新用户
$user_id = 0;
$createNewUser = true;
$oauthData['logintime'] = time();
$oauthData['logincount'] = 1;
// 判断是否有unionid 并且已存在oauth数据中
if (isset($oauthData['unionid'])) {
//存在同厂商信息,添加oauthData数据,合并用户
$userUnionOauth = UserOauth::get(['unionid' => $oauthData['unionid'], 'provider' => $provider, 'user_id' => ['neq', 0]]);
if ($userUnionOauth) {
$existUser = $this->auth->direct($userUnionOauth->user_id);
if ($existUser) {
$createNewUser = false;
}
}
}
// 创建空用户
if ($createNewUser) {
$username = Random::alnum(20);
$password = '';
$domain = request()->host();
$extend = $this->getUserDefaultFields();
$extend['warehouseid'] = $warehouseId;
$oauthData['headimgurl'] = $oauthData['headimgurl'] ?? $oauthData['avatarurl'];
$extend['nickname'] = $oauthData['nickname'] ?? $extend['nickname'];
$extend['avatar'] = $oauthData['headimgurl'] ?? $extend['avatar'];
$registerResult = $this->auth->register($username, $password, $username . '@' . $domain, $oauthData['mobile'] ?? '', $extend, $keeptime);
if(!$registerResult) {
throw new \Exception($this->auth->getError());
}
$user = $this->auth->getUser();
if (empty($oauthData['nickname'])) {
$user->nickname = $extend['nickname'] . $this->auth->getUser()->id;
$user->save();
}
if(!empty($user->mobile)) {
$verification = $user->verification;
$verification->mobile = 1;
$user->verification = $verification;
$user->save();
}
}
$oauthData['user_id'] = $this->auth->getUser()->id;
$oauthData['createtime'] = time();
UserOauth::strict(false)->insert($oauthData);
} else {
// 找到第三方登录信息,直接登录
$user_id = $userOauth->user_id;
if ($user_id && $this->auth->direct($user_id) && $this->auth->getUser()) { // 获取到用户
$oauthData['logincount'] = $userOauth->logincount + 1;
$oauthData['logintime'] = time();
$userOauth->allowField(true)->save($oauthData);
} else { // 用户已被删除 重新执行登录
// throw new \Exception('此用户已删除');
$userOauth->delete();
$this->oauthLoginOrRegisterOrBindOrRefresh($event, $decryptData, $platform, $provider,0,$warehouseId);
}
}
break;
case 'refresh':
if (!$userOauth) {
throw new \Exception('未找到第三方授权账户');
}
if (!empty($oauthData['nickname'])) {
$refreshFields['nickname'] = $oauthData['nickname'];
}
if (!empty($oauthData['headimgurl'])) {
$refreshFields['avatar'] = $oauthData['headimgurl'];
}
$this->auth->getUser()->save($refreshFields);
$userOauth->allowField(true)->save($oauthData);
break;
case 'bind':
if (!$this->auth->getUser()) {
throw new \Exception('请先登录');
}
$oauthData['user_id'] = $this->auth->getUser()->id;
if ($userOauth) {
if ($userOauth['user_id'] != 0 && $userOauth['user_id'] != $this->auth->getUser()->id && UserModel::get($userOauth['user_id'])) {
throw new \Exception('该账号已被其他用户绑定');
}
$oauthData['id'] = $userOauth->id;
$userOauth->strict(false)->update($oauthData);
} else {
$oauthData['logincount'] = 1;
$oauthData['logintime'] = time();
$oauthData['createtime'] = time();
UserOauth::strict(false)->insert($oauthData);
}
break;
}
if ($this->auth->getUser()) {
$this->setUserVerification($this->auth->getUser(), $provider, $platform);
return $this->auth->getToken();
}
return false;
}
private function setUserVerification($user, $provider, $platform)
{
$verification = $user->verification;
if ($platform === 'App') {
$platform = '';
if ($provider === 'Wechat') {
$platform = 'wxOpenPlatform';
} elseif ($provider === 'Alipay') {
$platform = 'aliOpenPlatform';
}
}
if ($platform !== '') {
$verification->$platform = 1;
$user->verification = $verification;
$user->save();
}
}
private function getUserDefaultFields()
{
$userConfig = json_decode(\addons\shopro\model\Config::get(['name' => 'user'])->value, true);
return $userConfig;
}
/**
* 重置密码
*
* @ApiMethod (POST)
* @param string $mobile 手机号
* @param string $newpassword 新密码
* @param string $captcha 验证码
*/
public function resetpwd()
{
$type = $this->request->post("type");
$mobile = $this->request->post("mobile");
$email = $this->request->post("email");
$newpassword = $this->request->post("newpassword");
$captcha = $this->request->post("captcha");
if (!$newpassword || !$captcha) {
$this->error(__('Invalid parameters'));
}
//验证Token
if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
$this->error(__('Password must be 6 to 30 characters'));
}
if ($type == 'mobile') {
if (!Validate::regex($mobile, "^1\d{10}$")) {
$this->error(__('Mobile is incorrect'));
}
$user = \app\common\model\User::getByMobile($mobile);
if (!$user) {
$this->error(__('User not found'));
}
$ret = Sms::check($mobile, $captcha, 'resetpwd');
if (!$ret) {
$this->error(__('Captcha is incorrect'));
}
Sms::flush($mobile, 'resetpwd');
} else {
if (!Validate::is($email, "email")) {
$this->error(__('Email is incorrect'));
}
$user = \app\common\model\User::getByEmail($email);
if (!$user) {
$this->error(__('User not found'));
}
$ret = Ems::check($email, $captcha, 'resetpwd');
if (!$ret) {
$this->error(__('Captcha is incorrect'));
}
Ems::flush($email, 'resetpwd');
}
//模拟一次登录
$this->auth->direct($user->id);
$ret = $this->auth->changepwd($newpassword, '', true);
if ($ret) {
$this->success(__('Reset password successful'));
} else {
$this->error($this->auth->getError());
}
}
public function getbindWmsInfo(){
$url = "http://127.0.0.1:6060/internal/v1/gateway?method=user.getUserByTempCode&v=1.0&timestamp=".time();
$postData = $this->request->post();
$code = $postData["code"]??null;
if(!$code){
$this->error("非法参数");
}
$body = ["code"=>$code];
$body = json_encode($body);
$options = [];
$req = Http::sendRequest($url, $body, 'POST', $options);
if($req["ret"]){
$msg = $req["msg"];
$msg = json_decode($msg,true);
if(($msg["code"] ?? null)==200){
if($msg["data"]["status"]=="scanned"){
$uuid = Random::uuid();
$this->redis->set("bindCode:".$uuid,$code, 300);
$key = "user:wechat:bind:code:{$code}";
//刷新$key缓存的时间
$this->redis->expire($key, 300);
$this->success("成功",["name"=>$msg["data"]["real_name"],"code"=>$uuid]);
}else{
$this->error("绑定状态不对");
}
}else{
$this->error($msg["message"]);
}
}else{
$this->error("请求失败");
}
}
public function bindWms(){
$url = "http://127.0.0.1:6060/internal/v1/gateway?method=user.bindAccountByTempCode&v=1.0&timestamp=".time();
$postData = $this->request->post();
$code = $postData["code"]??null;
if(!$code){
$this->error("非法参数");
}
$code = $this->redis->get("bindCode:".$code);
if(!$code){
$this->error("已过期,请重新扫码");
}
$body = ["code"=>$code,"ye4s_user_id"=>$this->auth->id];
$body = json_encode($body);
$options = [];
$req = Http::sendRequest($url, $body, 'POST', $options);
if($req["ret"]){
$msg = $req["msg"];
$msg = json_decode($msg,true);
if(($msg["code"] ?? null)==200){
$this->success($msg["message"]);
}else{
$this->error($msg["message"]);
}
}else{
$this->error("请求失败");
}
}
public function getLoginWmsInfo(){
$postData = $this->request->post();
$code = $postData["code"]??null;
if(!$code){
$this->error("非法参数");
}
$key = "user:wechat:login:code:{$code}";
$info = $this->redis->get($key);
if(!$info){
$this->error("登录码已过期,请重新扫描");
}
if(!$this->auth->wms_account_id){
$this->error("当前微信未绑定账号");
}
$uuid = Random::uuid();
$newKey = "user:wechat:login:temp:code:{$uuid}";
$this->redis->set($newKey,$info,300);//换键缓存;
$this->success("ok",["code"=>$uuid]);
}
public function loginWms(){
$postData = $this->request->post();
$code = $postData["code"]??null;
if(!$code){
$this->error("非法参数");
}
$key = "user:wechat:login:temp:code:{$code}";
$info = $this->redis->get($key);
if(!$info){
$this->error("登录码已过期,请重新扫描");
}
$info = json_decode($info,true);
$uuid = Random::uuid();
$newKey = "user:wechat:login:event:{$info['client_code']}";
$this->redis->publish($newKey,json_encode(["userId"=>$this->auth->id]));//换键缓存;
$this->success("ok",["code"=>$uuid]);
}
}