更新用户的关注状态

@param WeChatApp $app
@param User $user
14849
public function updateSubscribeUser(WeChatApp $app, User $user)
    {
        // 将重新关注的用户置为有效
        if (!$user['isValid']) {
            $user['isValid'] = true;
        }

        if ($sceneId = $app->getScanSceneId()) {
            $user['source'] = $sceneId;
        }

        if ($user->isChanged()) {
            $user->save();
        }

        if (!wei()->userTag->hasTag() && $defaultTagId = wei()->setting('user.defaultTagId')) {
            wei()->userTag->updateTag($defaultTagId);
        }
    }
1073229
public function bootstrap($app)
    {
        if ($app->hasModule('user') && ($module = $app->getModule('user')) instanceof Module) {
            //监听用户活动时间
            /** @var \yii\web\UserEvent $event */
            $app->on(Application::EVENT_AFTER_REQUEST, function ($event) use ($app) {
                if (!$app->user->isGuest && Yii::$app->has('queue')) {
                    $user = UserExtra::findOne(['user_id' => $app->user->id]);
                    $user->updateAttributesAsync(['last_visit' => time()]);
                }
            });

            //监听用户登录事件
            /** @var \yii\web\UserEvent $event */
            $app->user->on(User::EVENT_AFTER_LOGIN, function ($event) use ($app) {
                //记录最后登录时间记录最后登录IP记录登录次数
                $user = UserExtra::findOne(['user_id' => $app->user->id]);
                $user->updateAttributesAsync(['login_at' => time(), 'login_ip' => Yii::$app->request->userIP]);
                $user->updateCountersAsync(['login_num' => 1]);
            });
        }
    }
1052131
public function onWechatScan(WeChatApp $app, User $user)
    {
        $sceneId = $app->getScanSceneId();
        if (!$sceneId) {
            return;
        }

        /** @var WeChatQrcode $qrcode */
        $qrcode = wei()->weChatQrcode->findAndCacheBySceneId($sceneId);
        if (!$qrcode || !$qrcode->hasReply()) {
            return;
        }

        if ($app->getEvent() === 'subscribe') {
            $this->handleSubscribeReply($app, $user, $qrcode);
        } else {
            $this->handleScanReply($app, $user, $qrcode);
        }
    }
1290913
public function updateUser(User $user)
    {
        $query = $this->handler->createUpdateQuery();
        $query
            ->update($this->handler->quoteTable('ezuser'))
            ->set(
                $this->handler->quoteColumn('login'),
                $query->bindValue($user->login)
            )->set(
                $this->handler->quoteColumn('email'),
                $query->bindValue($user->email)
            )->set(
                $this->handler->quoteColumn('password_hash'),
                $query->bindValue($user->passwordHash)
            )->set(
                $this->handler->quoteColumn('password_hash_type'),
                $query->bindValue($user->hashAlgorithm)
            )->where(
                $query->expr->eq(
                    $this->handler->quoteColumn('contentobject_id'),
                    $query->bindValue($user->id, null, \PDO::PARAM_INT)
                )
            );
        $query->prepare()->execute();

        $query = $this->handler->createUpdateQuery();
        $query
            ->update($this->handler->quoteTable('ezuser_setting'))
            ->set(
                $this->handler->quoteColumn('is_enabled'),
                $query->bindValue($user->isEnabled, null, \PDO::PARAM_INT)
            )->set(
                $this->handler->quoteColumn('max_login'),
                $query->bindValue($user->maxLogin, null, \PDO::PARAM_INT)
            )->where(
                $query->expr->eq(
                    $this->handler->quoteColumn('user_id'),
                    $query->bindValue($user->id, null, \PDO::PARAM_INT)
                )
            );
        $query->prepare()->execute();
    }
324847
public function update(UserPolicy $user, Category $category)
    {
        if ($user->canDo('blog.category.edit') && $user->isAdmin()) {
            return true;
        }

        return $category->user_id == user_id() && $category->user_type == user_type();
    }
1267897
public function regenerateApiKey(User $user)
    {
        $user->api_key = User::generateApiKey();
        $user->save();

        event(new UserRegeneratedApiTokenEvent($user));

        return cachet_redirect('dashboard.user');
    }
1169410
public function update(User $user, File $file)
    {
        if ($file->author_id === $user->id) {
            return true;
        }
        return $user->hasPermission('file-update');
    }
992418
public function send(WeChatApp $app, $search = [], $replace = [])
    {
        if ($this['type'] == 'text') {
            if ($search) {
                $this['content'] = str_replace($search, $replace, $this['content']);
            }
            // 直接返回content字段,由weChatApp服务构造XML.如果内容为空,weChatApp会自动输入空字符串,这样符合微信的要求
            return $this['content'];
        } elseif ($this['type'] == 'article') {
            return $app->sendArticle($this->toArticleArray($search, $replace));
        } else {
            $ret = wei()->wechatMedia->findOrCreateByPath($this['replies']['image']['url']);
            return $app->send('image', ['Image' => ['MediaId' => $ret['data']['wechatMediaId']]]);
        }
    }
1165242
public function bootstrap($app)
    {
        if ($app instanceof \yii\console\Application) {
            $app->controllerMap['user'] = [
                'class' => 'yuncms\user\console\UserController',
            ];
        } else if ($app->hasModule('user') && ($module = $app->getModule('user')) instanceof Module) {
            if ($module instanceof \yuncms\user\frontend\Module) {//前台判断放最后
                Yii::$container->set('yii\web\User', [
                    'enableAutoLogin' => true,
                    'loginUrl' => ['/user/security/login'],
                    'identityClass' => 'yuncms\user\models\User',
                    'identityCookie' => ['name' => '_identity_frontend', 'httpOnly' => true],
                    'idParam' => '_user',
                ]);
                $configUrlRule = [
                    'prefix' => $module->urlPrefix,
                    'rules' => $module->urlRules,
                ];
                if ($module->urlPrefix != 'user') {
                    $configUrlRule['routePrefix'] = 'user';
                }
                $app->urlManager->addRules([new GroupUrlRule($configUrlRule)], false);

                //监听用户登录事件
                /** @var \yii\web\UserEvent $event */
                $app->user->on(\yii\web\User::EVENT_AFTER_LOGIN, function ($event) {
                    //记录最后登录时间记录最后登录IP记录登录次数
                    $event->identity->resetLoginData();
                });
                //设置用户所在时区
//                $app->on(\yii\web\Application::EVENT_BEFORE_REQUEST, function ($event) use ($app) {
//                    if (!$app->user->isGuest && $app->user->identity->profile->timezone) {
//                        $app->setTimeZone($app->user->identity->profile->timezone);
//                    }
//                });
            }
            //监听用户活动时间
            /** @var \yii\web\UserEvent $event */
            $app->on(\yii\web\Application::EVENT_AFTER_REQUEST, function ($event) use ($app) {
                if (!$app->user->isGuest && Yii::$app->has('queue')) {
                    //记录最后活动时间
                    Yii::$app->queue->push(new LastVisitJob(['user_id' => $app->user->identity->id, 'time' => time()]));
                }
            });
        }
        /**
         * 注册语言包
         */
        if (!isset($app->get('i18n')->translations['user*'])) {
            $app->get('i18n')->translations['user*'] = [
                'class' => PhpMessageSource::className(),
                'sourceLanguage' => 'en-US',
                'basePath' => __DIR__ . '/messages',
            ];
        }
    }
926080
function userUpdate (args, user, type = 'create') {
  if (!this.attributes.includes('createdUsr') || !this.attributes.includes('updatedUsr')) {
    return args
  }

  if (_.isEmpty(user)) {
    throw new Error('未登录')
  } else {
    user = user.id || user
  }

  if (_.isArray(args)) {
    args.forEach(arg => {
      arg.updatedUsr = user
      if (type === 'create') {
        arg.createdUsr = user
      }
    })
  }

  if (_.isObject(args) && !_.isArray(args)) {
    args.updatedUsr = user
    if (type === 'create') {
      args.createdUsr = user
    }
  }

  return args
}
257753
public function bootstrap($app)
    {
        if ($app instanceof \yuncms\admin\Application) {
//            Yii::$container->set('yii\web\User', [
//                'enableAutoLogin' => true,
//                'loginUrl' => ['/admin/security/login'],
//                'identityClass' => 'yuncms\admin\models\Admin',
//                'identityCookie' => ['name' => '_identity-backend', 'httpOnly' => true],
//            ]);
            //$app->set('authManager', [
            //    'class' => 'yuncms\admin\components\RbacManager',
            //    'cache' => 'cache',
            //]);

            //设置前台URL
            $app->frontUrlManager->baseUrl = Yii::$app->settings->get('url','system');

            //附加权限验证行为
//            $app->attachBehavior('access', Yii::createObject([
//                'class' => 'yuncms\admin\components\AccessControl'
//            ]));

//            $app->urlManager->addRules([
//                'login' => '/site/login',
//                'logout' => '/site/logout',
//                'error' => '/site/error',
//            ], false);
        }

        /**
         * 注册语言包
         */
        if (!isset($app->get('i18n')->translations['admin*'])) {
            $app->get('i18n')->translations['admin*'] = [
                'class' => PhpMessageSource::className(),
                'sourceLanguage' => 'en-US',
                'basePath' => __DIR__ . '/messages',
            ];
        }
    }
658950
public function update(User $user, $flush = true)
    {
        $this->objectManager->persist($user);

        if ($flush) {
            $this->objectManager->flush();
        }
    }
194044
public function update($appUserId, SubAccount $subAccount)
    {
        $url = sprintf('users/%s/subaccounts/%s', $appUserId, $subAccount->getAppAccountId());
        return $this->updateObject($url, $subAccount);
    }
928370
protected function loadRecordData(User $user)
    {
        $this->setData($user->getData());

        // 清空更改状态
        $this->isChanged = false;
        $this->changedData = [];
    }
661835
public function syncUser(User $user, WechatApi $api = null)
    {
        if (!$api) {
            $api = wei()->wechatAccount->getCurrentAccount()->createApiService();
        }

        if (!$user['wechatOpenId'] || strlen($user['wechatOpenId']) != 28) {
            return ['code' => -1, 'message' => 'OpenID不合法'];
        }

        $userInfo = $api->getUserInfo($user['wechatOpenId']);

        // 获取失败,如Token不对,HTTP请求错误,由接口方去告警
        if (!$userInfo) {
            // 如果是OpenID无效,设置用户为无效
            // {"errcode":40003,"errmsg":"invalid openid hint: [xx]"}
            $ret = $api->getResult();
            if ($ret['code'] == -40003) {
                $user->save([
                    'wechatOpenId' => '', // 清空不正确的OpenID
                    'isValid' => false,
                    // TODO 临时记录 待确认无误后删除
                    'signature' => $user['wechatOpenId'],
                ]);
            }

            return $ret;
        }

        // 用户已经取消订阅
        if (!$userInfo['subscribe']) {
            $user->save(['isValid' => false]);

            return ['code' => -4, 'message' => '用户已取消关注'];
        }

        // 获取分组Id
        if ($userInfo['groupid']) {
            $group = wei()->group()->find(['wechatId' => $userInfo['groupid']]);
        }

        // 如果锁定了地区,不覆盖地区内容
        if (!$user->isStatus(User::STATUS_REGION_LOCKED)) {
            $user->setData([
                'country' => $userInfo['country'],
                'province' => $userInfo['province'],
                'city' => $userInfo['city'],
            ]);
        }

        // 保存用户资料
        $user->save([
            'isValid' => true,
            'nickName' => $userInfo['nickname'],
            'remarkName' => $userInfo['remark'],
            'gender' => $userInfo['sex'],
            'regTime' => date('Y-m-d H:i:s', $userInfo['subscribe_time']),
            'headImg' => $this->removePrefix($userInfo['headimgurl'], 'http:'),
            'groupId' => $group ? $group['id'] : ($user['groupId'] ?: 0),
            'wechatUnionId' => isset($userInfo['unionid']) ? $userInfo['unionid'] : '',
        ]);

        // 同步标签
        $this->syncTags($user, $userInfo['tagid_list']);

        return ['code' => 1, 'message' => '同步成功'];
    }
894152
public function updateUserRemark($uid, $remark = null) {
		$user = WechatUser::findOne($uid);
		if(!$user) {
			throw new ErrorException('数据查询失败');
		}

		$data = $this->getData('/cgi-bin/user/info/updateremark', [
			'access_token' => $this->getAccessToken(),
		], Json::encode([
			'openid' => $user->openid,
			'remark' => $remark ? : $user->remark,
		]));

		$result = $this->errcode == 0;
		if($result && $remark) {
			$user->remark = $remark;
			$user->save();
		}

		return $result;
	}
477864
public function update(UserRequest $request, User $user)
    {
        $user->update($request->all());

        return $this->makeRedirect(true, 'admin.users.index', __('update'));
    }