src/CorporateTrainingBundle/Biz/User/Service/Impl/UserServiceImpl.php line 52

Open in your IDE?
  1. <?php
  2. namespace CorporateTrainingBundle\Biz\User\Service\Impl;
  3. use AppBundle\Common\ArrayToolkit;
  4. use Biz\System\Service\SessionService;
  5. use Biz\User\Service\Impl\UserServiceImpl as BaseServiceImpl;
  6. use Biz\User\Service\NotificationService;
  7. use Biz\User\Service\TokenService;
  8. use Codeages\Biz\Framework\Event\Event;
  9. use CorporateTrainingBundle\Biz\Post\Service\PostService;
  10. use CorporateTrainingBundle\Biz\User\Service\UserService;
  11. use CorporateTrainingBundle\Common\Constant\CTConst;
  12. use PostMapPlugin\Biz\Rank\Service\RankService;
  13. class UserServiceImpl extends BaseServiceImpl implements UserService
  14. {
  15.     public function applyAiCoachProjection($id, array $roles, array $orgs$postId$enabled$syncOrgs true)
  16.     {
  17.         $user $this->getUser($id);
  18.         if (empty($user)) {
  19.             throw $this->createNotFoundException('User'$id'用户不存在');
  20.         }
  21.         $fields = [
  22.             'roles' => array_values(array_unique($roles)),
  23.             'postId' => (int) $postId,
  24.             'locked' => $enabled 1,
  25.             'updatedTime' => time(),
  26.         ];
  27.         if ($syncOrgs) {
  28.             $fields['orgIds'] = ArrayToolkit::column($orgs'id');
  29.             $fields['orgCodes'] = ArrayToolkit::column($orgs'orgCode');
  30.         }
  31.         $updatedUser $this->getUserDao()->update($id$fields);
  32.         if ($syncOrgs) {
  33.             $this->getUserOrgService()->setUserOrgs($id$orgs);
  34.         }
  35.         $this->getPostMemberService()->deletePostMembersByUserId($id);
  36.         if ($postId 0) {
  37.             $this->getPostMemberService()->becomePostMember($id$postId);
  38.         }
  39.         $this->dispatchEvent('user.role.change', new Event($updatedUser, ['oldRoles' => $user['roles']]));
  40.         $this->dispatchEvent('user.change_post', new Event($updatedUser, [
  41.             'oldUser' => $user,
  42.             'source' => 'ai_coach_projection',
  43.         ]));
  44.         return $updatedUser;
  45.     }
  46.     public function getUserWithOrgScopes($id)
  47.     {
  48.         $user $this->getUserDao()->get($id);
  49.         if (!($user)) {
  50.             return null;
  51.         }
  52.         $user UserSerialize::unserialize($user);
  53.         $user['lineOrgIds'] = $this->getUserlineOrgIds($user);
  54.         $user['manageOrgIds'] = $this->getUserManageOrgIds($user);
  55.         $user['manageOrgCodes'] = $this->getUserManageOrgCodes($user);
  56.         return $user;
  57.     }
  58.     public function searchUsers(array $conditions, array $orderBy$start$limit$columns = [])
  59.     {
  60.         if (isset($conditions['nickname'])) {
  61.             $conditions['nickname'] = strtoupper($conditions['nickname']);
  62.         }
  63.         if (empty($conditions['locked']) && empty($conditions['noNeedLocked'])) {
  64.             $conditions['locked'] = 0;
  65.         }
  66.         if (empty($conditions['type'])) {
  67.             $conditions['excludeTypes'] = ['deleted''system'];
  68.         }
  69.         if (isset($conditions['type']) && 'all' === $conditions['type']) {
  70.             unset($conditions['type']);
  71.         }
  72.         unset($conditions['noNeedLocked']);
  73.         $users $this->getUserDao()->searchUsers($conditions$orderBy$start$limit$columns);
  74.         return UserSerialize::unserializes($users);
  75.     }
  76.     public function searchUsersByIds(array $userIds, array $orderBy$start$limit, array $columns = [])
  77.     {
  78.         if (empty($userIds)) {
  79.             return [];
  80.         }
  81.         $users $this->getUserDao()->searchUsers(['userIds' => $userIds], $orderBy$start$limit$columns);
  82.         return UserSerialize::unserializes($users);
  83.     }
  84.     public function findUserIdsByPermission($permission, array $conditions)
  85.     {
  86.         $roleCodes $this->findRoleCodesWithPermission($permission);
  87.         if (empty($roleCodes)) {
  88.             return [];
  89.         }
  90.         $userIds = [];
  91.         foreach ($roleCodes as $roleCode) {
  92.             $roleConditions array_merge($conditions, ['roles' => $roleCode]);
  93.             $list $this->searchUsers($roleConditions, [], 0PHP_INT_MAX, ['id']);
  94.             $userIds array_merge($userIdsArrayToolkit::column($list'id'));
  95.         }
  96.         return ArrayToolkit::uniqueValue($userIds);
  97.     }
  98.     private function findRoleCodesWithPermission($permissionCode)
  99.     {
  100.         $roles $this->getRoleService()->searchRoles([], 'created'0PHP_INT_MAX);
  101.         $roleCodes = [];
  102.         foreach ($roles as $role) {
  103.             if (!empty($role['data']) && in_array($permissionCode$role['data'], true)) {
  104.                 $roleCodes[] = $role['code'];
  105.             }
  106.         }
  107.         return $roleCodes;
  108.     }
  109.     public function findDeletedUsers()
  110.     {
  111.         return $this->getUserDao()->findDeleteUsers();
  112.     }
  113.     public function findDeletedAndLockedUsers()
  114.     {
  115.         return $this->getUserDao()->findDeletedAndLockedUsers();
  116.     }
  117.     public function findDeletedAndLockedUsersByIds($userIds)
  118.     {
  119.         return $this->getUserDao()->findDeletedAndLockedUsersByIds($userIds);
  120.     }
  121.     public function findUsersByNicknames($nicknames)
  122.     {
  123.         return $this->getUserDao()->findByNicknames($nicknames);
  124.     }
  125.     public function findByVerifiedMobiles(array $verifiedMobiles)
  126.     {
  127.         return $this->getUserDao()->findByVerifiedMobiles($verifiedMobiles);
  128.     }
  129.     public function findByEmails(array $emails)
  130.     {
  131.         return $this->getUserDao()->findByEmails($emails);
  132.     }
  133.     public function findByIds(array $ids)
  134.     {
  135.         return $this->getUserDao()->findByIds($ids);
  136.     }
  137.     public function findUserIdsByConditions($conditions)
  138.     {
  139.         // 如果设置了 noNeedLocked,则不强制设置 locked,允许查询全部用户
  140.         if (!isset($conditions['noNeedLocked']) && empty($conditions['locked'])) {
  141.             $conditions['locked'] = 0;
  142.         }
  143.         if (empty($conditions['type'])) {
  144.             $conditions['noType'] = 'deleted';
  145.         }
  146.         if (isset($conditions['userIds']) && count($conditions['userIds']) > 15000) {
  147.             $existIds $conditions['userIds'];
  148.             unset($conditions['userIds']);
  149.             $userIds $this->getUserDao()->search($conditions, [], 0PHP_INT_MAX, ['id']);
  150.             $userIds array_intersect($existIdsarray_column($userIds'id'));
  151.             return empty($userIds) ? [-1] : $userIds;
  152.         }
  153.         $userIds $this->getUserDao()->search($conditions, [], 0PHP_INT_MAX, ['id']);
  154.         return empty($userIds) ? [-1] : array_column($userIds'id');
  155.     }
  156.     public function initPassword($id$newPassword)
  157.     {
  158.         $connection $this->getKernel()->getConnection();
  159.         $connection->beginTransaction();
  160.         $user $this->getUserDao()->get($id);
  161.         try {
  162.             $init = [
  163.                 'pwdInit' => '1',
  164.                 'type' => 'init' == $user['type'] ? 'default' $user['type'],
  165.             ];
  166.             $this->getAuthService()->changePassword($idnull$newPassword);
  167.             $this->getUserDao()->update($id$init);
  168.             $this->changePasswordUpgraded($id);
  169.             $connection->commit();
  170.         } catch (\Exception $e) {
  171.             $connection->rollback();
  172.             throw $e;
  173.         }
  174.         return $this->getUserDao()->update($id$init);
  175.     }
  176.     public function changePwdInit($id)
  177.     {
  178.         $init = [
  179.             'pwdInit' => '1',
  180.         ];
  181.         return $this->getUserDao()->update($id$init);
  182.     }
  183.     public function changePasswordUpgraded($id)
  184.     {
  185.         $fields = [
  186.             'passwordUpgraded' => 1,
  187.         ];
  188.         return $this->getUserDao()->update($id$fields);
  189.     }
  190.     public function readGuide($id)
  191.     {
  192.         $user $this->getUser($id);
  193.         if (empty($user)) {
  194.             throw $this->createNotFoundException('User'$id'用户不存在');
  195.         }
  196.         return $this->getUserDao()->update($id, ['readGuide' => 1]);
  197.     }
  198.     public function changeUserPost($id$postId)
  199.     {
  200.         $user $this->getUser($id);
  201.         if (empty($user)) {
  202.             throw $this->createNotFoundException('User'$id'用户不存在');
  203.         }
  204.         $post $this->getPostService()->getPost($postId);
  205.         if (empty($post)) {
  206.             throw $this->createNotFoundException('Post'$id'岗位不存在');
  207.         }
  208.         $updatedUser $this->getUserDao()->update($id, ['postId' => $postId]);
  209.         $this->getPostMemberService()->becomePostMember($user['id'], $post['id']);
  210.         $this->dispatchEvent('user.change_post', new Event($updatedUser, ['oldUser' => $user]));
  211.         $this->getLogService()->info('user''post_change'"修改用户{$user['nickname']}岗位为{$post['name']}成功");
  212.         return $updatedUser;
  213.     }
  214.     public function findUserProfilesByTrueName($truename)
  215.     {
  216.         if (empty($truename)) {
  217.             return null;
  218.         }
  219.         return $this->getProfileDao()->findByTrueName($truename);
  220.     }
  221.     public function statisticsOrgUserNumGroupByOrgId()
  222.     {
  223.         return $this->getUserDao()->statisticsOrgUserNumGroupByOrgId();
  224.     }
  225.     public function statisticsPostUserNumGroupByPostId()
  226.     {
  227.         return $this->getUserDao()->statisticsPostUserNumGroupByPostId();
  228.     }
  229.     public function batchUpdatePost($ids$postId)
  230.     {
  231.         $ids explode(','$ids);
  232.         $connection $this->getKernel()->getConnection();
  233.         $connection->beginTransaction();
  234.         try {
  235.             foreach ($ids as $id) {
  236.                 $this->changeUserPost($id$postId);
  237.             }
  238.             $connection->commit();
  239.         } catch (\Exception $e) {
  240.             $connection->rollback();
  241.             throw $e;
  242.         }
  243.     }
  244.     public function countUsersByLockedStatus()
  245.     {
  246.         return [
  247.             'enable' => $this->countUsers(['locked' => 0'noType' => 'system']),
  248.             'disable' => $this->countUsers(['locked' => 1]),
  249.         ];
  250.     }
  251.     public function isOverMaxUsersNumber()
  252.     {
  253.         return true;
  254.     }
  255.     public function changeUserOrgs($userId$orgCodes)
  256.     {
  257.         $user $this->getUser($userId);
  258.         if (empty($user) || ($user['orgCodes'] == $orgCodes)) {
  259.             return [];
  260.         }
  261.         $orgCodes $this->filterOrgCodes($orgCodes);
  262.         $orgs $this->getOrgService()->findOrgsByOrgCodes($orgCodes);
  263.         $existOrgCodes ArrayToolkit::column($orgs'orgCode');
  264.         if (array_diff($orgCodes$existOrgCodes)) {
  265.             throw $this->createNotFoundException('Org Not Found');
  266.         }
  267.         $this->getKernel()->getConnection()->beginTransaction();
  268.         try {
  269.             $fields = [
  270.                 'orgCodes' => empty($orgCodes) ? [1.] : ArrayToolkit::column($orgs'orgCode'),
  271.                 'orgIds' => empty($orgCodes) ? [1] : ArrayToolkit::column($orgs'id'),
  272.             ];
  273.             $this->getUserDao()->update($userId$fields);
  274.             $this->getUserOrgService()->setUserOrgs($userId$orgs);
  275.             $this->getKernel()->getConnection()->commit();
  276.         } catch (\Exception $e) {
  277.             $this->getKernel()->getConnection()->rollBack();
  278.             throw $e;
  279.         }
  280.         return $user;
  281.     }
  282.     public function getUserBindByTypeAndFromId($type$fromId)
  283.     {
  284.         return $this->getUserBindDao()->getByTypeAndFromId($this->getUserBindType($type), $fromId);
  285.     }
  286.     public function getUserBindByTypeAndUserId($type$toId)
  287.     {
  288.         $user $this->getUserDao()->get($toId);
  289.         if (empty($user)) {
  290.             throw $this->createNotFoundException("User#{$toId} Not Found");
  291.         }
  292.         if (!$this->typeInOAuthClient($type)) {
  293.             throw $this->createInvalidArgumentException('Invalid Type');
  294.         }
  295.         return $this->getUserBindDao()->getByToIdAndType($this->getUserBindType($type), $toId);
  296.     }
  297.     public function bindUser($type$fromId$toId$token)
  298.     {
  299.         $user $this->getUserDao()->get($toId);
  300.         if (empty($user)) {
  301.             throw $this->createNotFoundException("User#{$toId} Not Found");
  302.         }
  303.         if (!$this->typeInOAuthClient($type)) {
  304.             throw $this->createInvalidArgumentException('Invalid Type');
  305.         }
  306.         if ('weixinweb' == $type || 'weixinmob' == $type) {
  307.             $type 'weixin';
  308.         }
  309.         if ('dingtalkweb' == $type || 'dingtalkmob' == $type) {
  310.             $type 'dingtalk';
  311.         }
  312.         if ('feishuweb' == $type || 'feishumob' == $type) {
  313.             $type 'feishu';
  314.         }
  315.         if ($this->isUserBound($toId$type)) {
  316.             throw $this->createAccessDeniedException('account already bound');
  317.         }
  318.         $bind $this->getUserBindDao()->create([
  319.             'type' => $type,
  320.             'fromId' => $fromId,
  321.             'toId' => $toId,
  322.             'token' => empty($token['token']) ? '' $token['token'],
  323.             'createdTime' => time(),
  324.             'expiredTime' => empty($token['expiredTime']) ? $token['expiredTime'],
  325.         ]);
  326.         $this->dispatchEvent('user.bind', new Event($bind));
  327.     }
  328.     public function isUserBound($userId$type)
  329.     {
  330.         $bind $this->getUserBindDao()->getByToIdAndType($this->getUserBindType($type), $userId);
  331.         return !empty($bind) ? true false;
  332.     }
  333.     public function batchUpdateOrgs($userIds$orgCodes)
  334.     {
  335.         $currentUser $this->getCurrentUser();
  336.         $userIds $this->filterUserIds($userIds);
  337.         foreach ($userIds as $userId) {
  338.             if ($currentUser['id'] == $userId) {
  339.                 continue;
  340.             }
  341.             $this->changeUserOrgs($userId$orgCodes);
  342.         }
  343.     }
  344.     public function batchLockUser(array $userIds)
  345.     {
  346.         if (!$this->getCurrentUser()->hasPermission('admin_user_lock')) {
  347.             throw $this->createAccessDeniedException($this->trans('admin.role.no_permission'));
  348.         }
  349.         $currentUser $this->getCurrentUser();
  350.         $userIds array_diff($userIds, [$currentUser['id']]);
  351.         if (empty($userIds)) {
  352.             return;
  353.         }
  354.         $users $this->searchUsers(
  355.             ['userIds' => $userIds'locked' => 0],
  356.             [],
  357.             0,
  358.             count($userIds),
  359.             ['id']
  360.         );
  361.         foreach ($users as $user) {
  362.             $this->lockUser($user['id']);
  363.             $this->kickUserLogout($user['id']);
  364.         }
  365.     }
  366.     public function batchDeleteUser($userIds)
  367.     {
  368.         $currentUser $this->getCurrentUser();
  369.         foreach ($userIds as $userId) {
  370.             if ($currentUser['id'] == $userId) {
  371.                 continue;
  372.             }
  373.             $this->deleteUser($userId);
  374.         }
  375.     }
  376.     public function batchWaveUserNotificationNum(array $userIds)
  377.     {
  378.         if (empty($userIds)) {
  379.             return;
  380.         }
  381.         $this->getUserDao()->wave($userIds, ['newNotificationNum' => 1]);
  382.     }
  383.     public function findUserIdsByNickNameOrTrueName($name)
  384.     {
  385.         $userIdsByNickname $this->getUserDao()->findUserIds(['nickname' => $name]);
  386.         $userIdsByNickname ArrayToolkit::column($userIdsByNickname'id');
  387.         $userIdsByTruename $this->getProfileDao()->findUserIds(['truename' => $name]);
  388.         $userIdsByTruename ArrayToolkit::column($userIdsByTruename'id');
  389.         return array_merge($userIdsByNickname$userIdsByTruename);
  390.     }
  391.     /**
  392.      * 批量设置讲师
  393.      *
  394.      * @param $userIds
  395.      */
  396.     public function batchSetTeachers($userIds)
  397.     {
  398.         if (empty($userIds)) {
  399.             return;
  400.         }
  401.         $users $this->searchUsers(['userIds' => $userIds], [], 0count($userIds), ['id''roles']);
  402.         $updateUsers = [];
  403.         foreach ($users as $user) {
  404.             if (in_array('ROLE_TEACHER'$user['roles'])) {
  405.                 continue;
  406.             }
  407.             $updateUsers[$user['id']] = ['roles' => array_merge($user['roles'], ['ROLE_TEACHER'])];
  408.         }
  409.         if (empty($updateUsers)) {
  410.             return;
  411.         }
  412.         $this->getUserDao()->batchUpdate(array_keys($updateUsers), $updateUsers'id');
  413.         $this->getLogService()->info('user''user_batch_set_teacher''批量设置讲师'.json_encode($userIds));
  414.     }
  415.     public function setTeacher($userId)
  416.     {
  417.         $user $this->getUser($userId);
  418.         if (empty($user)) {
  419.             return false;
  420.         }
  421.         if (!in_array('ROLE_TEACHER'$user['roles'])) {
  422.             $this->changeUserRoles($userIdarray_merge($user['roles'], ['ROLE_TEACHER']));
  423.         }
  424.         return true;
  425.     }
  426.     /**
  427.      * 设置导师.
  428.      */
  429.     public function setMentor($userId)
  430.     {
  431.         $user $this->getUser($userId);
  432.         if (empty($user)) {
  433.             return false;
  434.         }
  435.         if (!in_array('ROLE_MENTOR'$user['roles'])) {
  436.             $this->changeUserRoles($userIdarray_merge($user['roles'], ['ROLE_MENTOR']));
  437.         }
  438.         return true;
  439.     }
  440.     /**
  441.      * 批量设置管理范围
  442.      *
  443.      * @param $userIds
  444.      * @param $orgIds
  445.      */
  446.     public function batchSetUserManagePermissions($userIds$orgIds)
  447.     {
  448.         if (empty($userIds)) {
  449.             return;
  450.         }
  451.         foreach ($userIds as $userId) {
  452.             $manageOrgIds $this->getManagePermissionService()->findUserManageOrgIdsByUserId($userId);
  453.             if (!$this->getManagePermissionService()->checkOrgManagePermission($orgIds$manageOrgIds)) {
  454.                 continue;
  455.             }
  456.             $this->getManagePermissionOrgService()->setUserManagePermissionOrgs($userId$orgIds);
  457.         }
  458.         $this->getLogService()->info('user''user_batch_set_permissions''批量设置管理范围'.json_encode($userIds));
  459.     }
  460.     public function getTotalUserCount(array $conditions)
  461.     {
  462.         $conditions['locked'] = 0;
  463.         $conditions['noType'] = 'system';
  464.         $userCount $this->countUsers(ArrayToolkit::parts($conditions, ['locked''noType']));
  465.         $userIncreaseCount $this->countUsers(ArrayToolkit::parts($conditions, ['startTime''noType']));
  466.         $conditions['locked'] = 1;
  467.         $userIncreaseLockedCount $this->countUsers(ArrayToolkit::parts($conditions, ['locked''updatedTime_GE''noType']));
  468.         return $userCount $userIncreaseCount $userIncreaseLockedCount;
  469.     }
  470.     protected function kickUserLogout($userId)
  471.     {
  472.         $this->getSessionService()->clearByUserId($userId);
  473.         $tokens $this->getTokenService()->findTokensByUserIdAndType($userId'mobile_login');
  474.         if (!empty($tokens)) {
  475.             foreach ($tokens as $token) {
  476.                 $this->getTokenService()->destoryToken($token['token']);
  477.             }
  478.         }
  479.     }
  480.     protected function filterOrgCodes($orgCodes)
  481.     {
  482.         if (is_array($orgCodes)) {
  483.             return $orgCodes;
  484.         } else {
  485.             return explode('|'$orgCodes);
  486.         }
  487.     }
  488.     protected function filterUserIds($userIds)
  489.     {
  490.         if (is_array($userIds)) {
  491.             return $userIds;
  492.         } else {
  493.             return explode(','$userIds);
  494.         }
  495.     }
  496.     public function initOrgsRelation()
  497.     {
  498.         $org $this->getOrgService()->getOrgByOrgCode(CTConst::ROOT_ORG_CODE);
  499.         $users $this->searchUsers([], [], 0PHP_INT_MAX);
  500.         if (!empty($users)) {
  501.             foreach ($users as $user) {
  502.                 $this->getUserOrgService()->setUserOrgs($user['id'], [$org]);
  503.             }
  504.         }
  505.         return $this->getUserDao()->initOrgsRelation();
  506.     }
  507.     public function initSystemUsers()
  508.     {
  509.         $users = [
  510.             [
  511.                 'type' => 'system',
  512.                 'roles' => ['ROLE_USER''ROLE_SUPER_ADMIN'],
  513.             ],
  514.         ];
  515.         $headquarterOrg $this->getOrgService()->getHeadquarterOrg();
  516.         foreach ($users as $user) {
  517.             $existsUser $this->getUserDao()->getUserByType($user['type']);
  518.             if (!empty($existsUser)) {
  519.                 continue;
  520.             }
  521.             $user['nickname'] = $this->generateNickname($user).'(系统用户)';
  522.             $user['emailVerified'] = 1;
  523.             $user['password'] = $this->getRandomChar();
  524.             $user['email'] = $this->generateEmail($user);
  525.             $user['salt'] = base_convert(sha1(uniqid(mt_rand(), true)), 1636);
  526.             $user['password'] = $this->getPasswordEncoder()->encodePassword($user['password'], $user['salt']);
  527.             $user UserSerialize::unserialize(
  528.                 $this->getUserDao()->create(UserSerialize::serialize($user))
  529.             );
  530.             $profile = [];
  531.             $profile['id'] = $user['id'];
  532.             $this->getProfileDao()->create($profile);
  533.             $this->getManagePermissionOrgService()->setUserManagePermissionOrgs($user['id'], [$headquarterOrg['id'] ?? 1]);
  534.         }
  535.     }
  536.     public function updateUserHireDate($userId$hireDate)
  537.     {
  538.         return $this->getUserDao()->update($userId, ['hireDate' => $hireDate]);
  539.     }
  540.     public function findFollowersByFromId($fromId)
  541.     {
  542.         return $this->getFriendDao()->findFollowingsByFromId($fromId);
  543.     }
  544.     public function sortPromoteUser($ids)
  545.     {
  546.         if (!empty($ids)) {
  547.             foreach ($ids as $index => $id) {
  548.                 $this->promoteUser($id$index 1);
  549.             }
  550.         }
  551.     }
  552.     public function getUserCustomColumns($id)
  553.     {
  554.         $profile $this->getUserProfile($id);
  555.         $customColumns $profile['custom_column'];
  556.         $defaultColumns = [
  557.             'onlineCourse',
  558.             'offlineCourse',
  559.             'classroom',
  560.             'postCourse',
  561.             'projectPlan',
  562.             'offlineActivity',
  563.         ];
  564.         return !empty($customColumns) ? $customColumns $defaultColumns;
  565.     }
  566.     public function updateUserCustomColumns($id$columns)
  567.     {
  568.         $this->updateUserProfile($id, ['custom_column' => $columns]);
  569.         return $this->getUserCustomColumns($id);
  570.     }
  571.     public function updateUserBind($id$fields)
  572.     {
  573.         return $this->getUserBindDao()->update($id$fields);
  574.     }
  575.     public function getDingTalkUsers($userIds)
  576.     {
  577.         return $this->getUserBindDao()->search(['type' => 'dingtalk''toIds' => $userIds], [], 0PHP_INT_MAX);
  578.     }
  579.     public function searchUserBinds($conditions$orderBys$start$limit$columns = [])
  580.     {
  581.         return $this->getUserBindDao()->search($conditions$orderBys$start$limit$columns);
  582.     }
  583.     public function countUserBinds($conditions)
  584.     {
  585.         return $this->getUserBindDao()->count($conditions);
  586.     }
  587.     public function batchDeleteUserBinds($conditions)
  588.     {
  589.         try {
  590.             $this->beginTransaction();
  591.             $this->getUserBindDao()->batchDelete($conditions);
  592.             $this->commit();
  593.         } catch (\Exception $e) {
  594.             $this->rollback();
  595.             throw $e;
  596.         }
  597.         return true;
  598.     }
  599.     public function batchSetPostAndManagePermissionsAndRolesAndOrgCodes($userIds$fields)
  600.     {
  601.         if (empty($userIds)) {
  602.             return;
  603.         }
  604.         $currentUser $this->getCurrentUser();
  605.         try {
  606.             $this->beginTransaction();
  607.             foreach ($userIds as $userId) {
  608.                 if (in_array('post'$fields['types'], true) && !empty($fields['postId'])) {
  609.                     $this->changeUserPost($userId$fields['postId']);
  610.                 }
  611.                 if (in_array('roles'$fields['types'], true) && !empty($fields['roles']) && $userId != $currentUser->getId()) {
  612.                     $this->changeUserRolesBatchDedicated($userId$fields['roles']);
  613.                 }
  614.                 if (in_array('org'$fields['types'], true) && $userId != $currentUser->getId()) {
  615.                     $this->changeUserOrgBatchDedicated($userId$fields['orgIds']);
  616.                 }
  617.                 if (in_array('orgCode'$fields['types'], true) && $userId != $currentUser->getId()) {
  618.                     $this->changeUserOrgCodeBatchDedicated($userId$fields['orgCodes']);
  619.                 }
  620.             }
  621.             $this->commit();
  622.         } catch (\Exception $e) {
  623.             $this->rollback();
  624.             throw $e;
  625.         }
  626.     }
  627.     public function findUserFromIdsByType($type$userIds)
  628.     {
  629.         if (empty($userIds) || $userIds === [-1]) {
  630.             return [];
  631.         }
  632.         $users $this->getUserBindDao()->search(['type' => $type'toIds' => $userIds], [], 0count($userIds), ['fromId']);
  633.         return ArrayToolkit::column($users'fromId');
  634.     }
  635.     public function statisticsDistinctOrgUserNumGroupByOrgId()
  636.     {
  637.         return $this->getUserDao()->statisticsDistinctOrgUserNumGroupByOrgId();
  638.     }
  639.     public function findUserIdsByManageOrgIds($orgIds)
  640.     {
  641.         return $this->getUserOrgService()->findUserIdsByOrgIds($orgIds);
  642.     }
  643.     public function pickIdsByTruenameOrNicknameOrMobile($keyword)
  644.     {
  645.         return ArrayToolkit::uniqueValue(array_merge(
  646.             $this->getUserDao()->pickIdsByLikeNickname($keyword),
  647.             $this->getProfileDao()->pickIdsByLikeTruename($keyword),
  648.             $this->getUserDao()->pickIdsByLikeVerifiedMobile($keyword)
  649.         ));
  650.     }
  651.     public function pickIdsByPostId($postId)
  652.     {
  653.         return $this->getUserDao()->pickIdsByPostId($postId);
  654.     }
  655.     private function changeUserOrgCodeBatchDedicated($userId$orgCodes)
  656.     {
  657.         if ($this->getCurrentUser()->getId() == $userId) {
  658.             return;
  659.         }
  660.         $orgCodes explode(','$orgCodes);
  661.         $this->changeUserOrgs($userId$orgCodes);
  662.     }
  663.     private function changeUserOrgBatchDedicated($userId$orgIds)
  664.     {
  665.         $orgIds explode(','$orgIds);
  666.         $user $this->getUser($userId);
  667.         $user['manageOrgIds'] = $this->getManagePermissionService()->findUserManageOrgIdsByUserId($userId);
  668.         if (!$this->getManagePermissionService()->checkOrgManagePermission($orgIds$user['manageOrgIds'])) {
  669.             throw $this->createAccessDeniedException($this->trans('admin.manage.org_permission_beyond_error'));
  670.         }
  671.         $this->getManagePermissionOrgService()->setUserManagePermissionOrgs($userId$orgIds);
  672.     }
  673.     private function changeUserRolesBatchDedicated($userId$roles)
  674.     {
  675.         $currentUser $this->getCurrentUser();
  676.         $currentUserProfile $this->getUserProfile($currentUser['id']);
  677.         if (in_array('ROLE_TRAINING_ADMIN'$roles) && !in_array('ROLE_TEACHER'$roles)) {
  678.             $roles[] = 'ROLE_TEACHER';
  679.         }
  680.         $this->changeUserRoles($userId$roles);
  681.         if (!empty($roles)) {
  682.             $roleSet $this->getRoleService()->searchRoles([], 'created'09999);
  683.             $rolesByIndexCode = \AppBundle\Common\ArrayToolkit::index($roleSet'code');
  684.             $roleNames $this->getRoleNames($roles$rolesByIndexCode);
  685.             $message = [
  686.                 'userId' => $currentUser['id'],
  687.                 'userName' => !empty($currentUserProfile['truename']) ? $currentUserProfile['truename'] : $currentUser['nickname'],
  688.                 'role' => implode(','$roleNames),
  689.             ];
  690.             $this->getNotifiactionService()->notify($userId'role'$message);
  691.         }
  692.     }
  693.     protected function getRoleNames($roles$roleSet)
  694.     {
  695.         $roleNames = [];
  696.         $roles array_unique($roles);
  697.         global $kernel;
  698.         $userRoleDict $kernel->getContainer()->get('codeages_plugin.dict_twig_extension')->getDict('userRole');
  699.         $roleDictCodes array_keys($userRoleDict);
  700.         foreach ($roles as $role) {
  701.             if (in_array($role$roleDictCodes)) {
  702.                 $roleNames[] = $userRoleDict[$role];
  703.             } elseif ('ROLE_BACKEND' === $role) {
  704.                 continue;
  705.             } else {
  706.                 $role $roleSet[$role];
  707.                 $roleNames[] = $role['name'];
  708.             }
  709.         }
  710.         return $roleNames;
  711.     }
  712.     private function getUserBindType($type)
  713.     {
  714.         if ('workwechatweb' == $type || 'workwechatmob' == $type || 'work_wechat' == $type) {
  715.             $type 'work_wechat';
  716.         }
  717.         if ('weixinweb' == $type || 'weixinmob' == $type || 'weixin' == $type) {
  718.             $type 'weixin';
  719.         }
  720.         if ('dingtalkweb' == $type || 'dingtalkmob' == $type || 'dingtalk' == $type) {
  721.             $type 'dingtalk';
  722.         }
  723.         if ('feishuweb' == $type || 'feishumob' == $type || 'feishu' == $type) {
  724.             $type 'feishu';
  725.         }
  726.         return $type;
  727.     }
  728.     protected function convertOAuthType($type)
  729.     {
  730.         if ('weixinweb' == $type || 'weixinmob' == $type) {
  731.             $type 'weixin';
  732.         }
  733.         if ('dingtalkweb' == $type || 'dingtalkmob' == $type) {
  734.             $type 'dingtalk';
  735.         }
  736.         return $type;
  737.     }
  738.     /*
  739.      * 返回用户直属部门及直线向上所有父级部门id
  740.      */
  741.     protected function getUserLineOrgIds($user)
  742.     {
  743.         $orgIds = [];
  744.         foreach ($user['orgCodes'] as $orgCode) {
  745.             $orgIds array_merge($orgIdsexplode('.'substr($orgCode0, -1)));
  746.         }
  747.         return array_unique($orgIds);
  748.     }
  749.     /*
  750.      * 返回用户管理范围部门id
  751.      */
  752.     protected function getUserManageOrgIds($user)
  753.     {
  754.         return $this->getManagePermissionService()->findUserManageOrgIdsByUserId($user['id']);
  755.     }
  756.     /*
  757.      * 返回用户管理范围部门code
  758.      */
  759.     protected function getUserManageOrgCodes($user)
  760.     {
  761.         return $this->getManagePermissionService()->findUserManageOrgCodesByUserId($user['id']);
  762.     }
  763.     protected function getManagePermissionService()
  764.     {
  765.         return $this->createService('ManagePermission:ManagePermissionOrgService');
  766.     }
  767.     protected function getAuthService()
  768.     {
  769.         return $this->createService('User:AuthService');
  770.     }
  771.     /**
  772.      * @return PostService
  773.      */
  774.     protected function getPostService()
  775.     {
  776.         return $this->createService('CorporateTrainingBundle:Post:PostService');
  777.     }
  778.     /**
  779.      * @return RankService
  780.      */
  781.     protected function getRankService()
  782.     {
  783.         return $this->createService('PostMapPlugin:Rank:RankService');
  784.     }
  785.     /**
  786.      * @return \CorporateTrainingBundle\Biz\User\Service\UserOrgService
  787.      */
  788.     protected function getUserOrgService()
  789.     {
  790.         return $this->createService('User:UserOrgService');
  791.     }
  792.     protected function getPostMemberService()
  793.     {
  794.         return $this->createService('CorporateTrainingBundle:Post:PostMemberService');
  795.     }
  796.     /**
  797.      * @return SessionService
  798.      */
  799.     protected function getSessionService()
  800.     {
  801.         return $this->createService('System:SessionService');
  802.     }
  803.     /**
  804.      * @return TokenService
  805.      */
  806.     protected function getTokenService()
  807.     {
  808.         return $this->createService('User:TokenService');
  809.     }
  810.     /**
  811.      * @return NotificationService
  812.      */
  813.     protected function getNotifiactionService()
  814.     {
  815.         return $this->createService('User:NotificationService');
  816.     }
  817. }
  818. class UserSerialize
  819. {
  820.     public static function serialize(array $user)
  821.     {
  822.         return $user;
  823.     }
  824.     public static function unserialize(array $user null)
  825.     {
  826.         if (empty($user)) {
  827.             return;
  828.         }
  829.         $user self::_userRolesSort($user);
  830.         return $user;
  831.     }
  832.     public static function unserializes(array $users)
  833.     {
  834.         return array_map(
  835.             function ($user) {
  836.                 return UserSerialize::unserialize($user);
  837.             },
  838.             $users
  839.         );
  840.     }
  841.     private static function _userRolesSort($user)
  842.     {
  843.         if (!empty($user['roles'][1]) && 'ROLE_USER' == $user['roles'][1]) {
  844.             $temp $user['roles'][1];
  845.             $user['roles'][1] = $user['roles'][0];
  846.             $user['roles'][0] = $temp;
  847.         }
  848.         //交换学员角色跟roles数组第0个的位置;
  849.         return $user;
  850.     }
  851. }