<?php
namespace CorporateTrainingBundle\Controller\Admin;
use AppBundle\Common\ArrayToolkit;
use AppBundle\Common\ChangelogToolkit;
use AppBundle\Common\CurlToolkit;
use AppBundle\Controller\Admin\BaseController;
use Biz\CloudPlatform\CloudAPIFactory;
use Biz\Role\Util\PermissionBuilder;
use Biz\System\Service\CacheService;
use CorporateTrainingBundle\Biz\Focus\Service\FocusService;
use CorporateTrainingBundle\Biz\OfflineActivity\Service\OfflineActivityService;
use CorporateTrainingBundle\Biz\ProjectPlan\Service\ProjectPlanService;
use CorporateTrainingBundle\System;
use ESCloud\SDK\Service\PlatformNewsService;
use ExamPlugin\Biz\Exam\Service\ExamService;
use OfflineCourseProPlugin\Biz\OfflineClass\Service\OfflineClassService;
use Symfony\Component\HttpFoundation\Request;
class AnalysisController extends BaseController
{
private $homePageQuickEntranceCodes = [
'admin_train_teach_manage_my_teaching_courses',
'admin_train_teach_manage_my_teaching_offline_courses',
'admin_train_exam_manage_list',
'admin_project_plan_manage',
'admin_role_manage',
'admin_block',
'admin_setting_theme',
'admin_setting_mobile_settings',
];
public function indexAction(Request $request)
{
$currentUser = $this->getCurrentUser();
$quickEntrances = $this->getUserQuickEntrances();
$userProfile = $this->getUserService()->getUserProfile($currentUser['id']);
$homePageQuickEntranceCodes = $this->homePageQuickEntranceCodes;
if ($userProfile['quick_entrance']) {
$homePageQuickEntranceCodes = $userProfile['quick_entrance'];
}
$quickEntrances = $this->getHomePageQuickEntrances($quickEntrances, $homePageQuickEntranceCodes);
return $this->render('admin/default/corporate-training-admin-index.html.twig', [
'quickEntrances' => $quickEntrances,
'showChatGroupQrCode' => 'none' == $this->getSchoolLevelKey(),
]);
}
public function chooseQuickEntrancesAction(Request $request)
{
$currentUser = $this->getCurrentUser();
if ('POST' == $request->getMethod()) {
$params = $request->request->all();
$params['data'] = json_decode($params['data'], true);
if (empty($params['data'])) {
$params['data'] = [-1];
}
$updatedUserProfile = $this->getUserService()->updateUserProfile($currentUser['id'], ['quick_entrance' => $params['data']]);
$quickEntrances = $this->getUserQuickEntrances();
$quickEntrances = $this->getHomePageQuickEntrances($quickEntrances, $updatedUserProfile['quick_entrance']);
return $this->render('admin/default/quick-entrance.html.twig', [
'quickEntrances' => $quickEntrances,
]);
}
$userProfile = $this->getUserService()->getUserProfile($currentUser['id']);
$quickEntrances = $this->getUserQuickEntrances();
$homePageQuickEntranceCodes = $this->homePageQuickEntranceCodes;
if ($userProfile['quick_entrance']) {
$homePageQuickEntranceCodes = $userProfile['quick_entrance'];
}
foreach ($quickEntrances as &$item) {
if (!empty($item['data'])) {
foreach ($item['data'] as &$entrance) {
if (in_array($entrance['code'], $homePageQuickEntranceCodes)) {
$entrance['checked'] = true;
} else {
$entrance['checked'] = false;
}
}
}
}
return $this->render('admin/default/quick-entrance-model.html.twig', [
'quickEntrances' => $quickEntrances,
]);
}
protected function getHomePageQuickEntrances($quickEntrances, $homePageQuickEntranceCodes)
{
foreach ($quickEntrances as &$item) {
if (!empty($item['data'])) {
$item['data'] = array_filter(
$item['data'],
function ($entrance) use ($homePageQuickEntranceCodes) {
return in_array($entrance['code'], $homePageQuickEntranceCodes, true);
}
);
}
}
return $quickEntrances;
}
protected function getUserQuickEntrances()
{
$currentUser = $this->getCurrentUser();
$tree = PermissionBuilder::instance()->findAllPermissionTree(true);
$allPermissions = $tree->toArray();
$modules = $allPermissions['children'][0]['children'];
$quickEntrances = [];
foreach ($modules as $module) {
$quickEntrances[$module['code']]['data'] = $this->getQuickEntrancesArray($module);
$quickEntrances[$module['code']]['name'] = $this->trans($module['name'], [], 'menu');
}
return $quickEntrances;
}
private function getQuickEntrancesArray($module)
{
$currentUser = $this->getCurrentUser();
if (isset($module['quick_entrance']) && $module['quick_entrance'] && $currentUser->hasPermission($module['code'])) {
$module['name'] = $this->trans($module['name'], [], 'menu');
$moduleQuickEntrances = [$module];
} else {
$moduleQuickEntrances = [];
}
if (isset($module['children'])) {
foreach ($module['children'] as $child) {
$moduleQuickEntrances = array_merge($moduleQuickEntrances, $this->getQuickEntrancesArray($child));
}
}
return $moduleQuickEntrances;
}
public function systemStatusAction(Request $request)
{
list($mainAppUpgrade, $upgradeAppCount) = $this->checkCloudAppUpgradeInfo();
list($android, $ios) = $this->getMobileAppVersion();
$mobileSetting = $this->getSettingService()->get('mobile', []);
$mailStatus = $this->isMailEnabled();
$eduCloudStatus = $this->getEduCloudStatus();
return $this->render('admin/default/corporate-training-system-status.html.twig', [
'upgradeAppCount' => $upgradeAppCount,
'mainAppUpgrade' => $mainAppUpgrade,
'android' => $android,
'ios' => $ios,
'mobileSetting' => $mobileSetting,
'mailServiceStatus' => $mailStatus,
'eduCloudStatus' => $eduCloudStatus,
]);
}
public function systemDataOverviewAction()
{
list($allUsersCount, $newUsersCount) = $this->getUsersNumberData();
list($allCoursesCount, $newCoursesCount) = $this->getCoursesData();
list($allTeachersCount, $newTeachersCount) = $this->getTeachersData();
list($allProjectCount, $newProjectCount) = $this->getProjectData();
list($allExamCount, $newExamCount) = $this->getExamData();
list($allActivityCount, $newActivityCount) = $this->getActivityData();
$data = [
'all' => [
'usersCount' => $allUsersCount,
'coursesCount' => $allCoursesCount,
'teachersCount' => $allTeachersCount,
'projectCount' => $allProjectCount,
'examCount' => $allExamCount,
'activityCount' => $allActivityCount,
],
'new' => [
'usersCount' => $newUsersCount,
'coursesCount' => $newCoursesCount,
'teachersCount' => $newTeachersCount,
'projectCount' => $newProjectCount,
'examCount' => $newExamCount,
'activityCount' => $newActivityCount,
],
];
return $this->createJsonResponse($data);
}
public function businessAdviceAction()
{
$advice = [];
if (!$this->isWithoutNetwork() && $this->isSdkAvailable()) {
try {
$advice = $this->getPlatformNewsSdkService()->getAdvice(4, 'training');
} catch (\Exception $e) {
$advice = [];
}
}
return $this->render('admin/default/admin-business-advice.html.twig', [
'advice' => $advice,
]);
}
public function announcementsAction()
{
$result = [];
if (!$this->isWithoutNetwork() && $this->isSdkAvailable()) {
try {
$result = $this->getPlatformNewsSdkService()->getAnnouncements(1, 'training');
} catch (\Exception $e) {
$result = [];
}
}
return $this->render('admin/default/admin-announcements-right.html.twig', [
'announcement' => empty($result['details']) ? [] : array_pop($result['details']),
'showChatGroupQrCode' => 'none' == $this->getSchoolLevelKey(),
]);
}
protected function isWithoutNetwork()
{
$developer = $this->getSettingService()->get('developer');
return empty($developer['without_network']) ? false : (bool) $developer['without_network'];
}
protected function isSdkAvailable()
{
$storage = $this->getSettingService()->get('storage', []);
if (empty($storage['cloud_access_key']) || empty($storage['cloud_secret_key'])) {
return false;
}
return true;
}
private function isMailEnabled()
{
$cloudEmail = $this->getSettingService()->get('cloud_email_crm', []);
if (!empty($cloudEmail) && 'enable' === $cloudEmail['status']) {
return true;
}
$mailer = $this->getSettingService()->get('mailer', []);
if (!empty($mailer) && $mailer['enabled']) {
return true;
}
return false;
}
private function getUsersNumberData()
{
$defaultConditions = [
'locked' => 0,
'noType' => 'system',
];
$defaultConditions = $this->fillOrgCode($defaultConditions);
$allUsersCount = $this->getUserService()->countUsers($defaultConditions);
$defaultConditions['startTime'] = strtotime(date('Y').'-01-01 00:00:00');
$newUsersCount = $this->getUserService()->countUsers($defaultConditions);
return [$allUsersCount, $newUsersCount];
}
private function getCoursesData()
{
$defaultConditions = ['orgIds' => $this->prepareOrgIds([])];
$allOnlineCoursesCount = $this->getCourseSetService()->countCourseSets($defaultConditions);
$projectPlans = $this->getProjectPlanService()->searchProjectPlans($defaultConditions, [], 0, PHP_INT_MAX, ['id']);
$defaultConditions['startTime'] = strtotime(date('Y').'-01-01 00:00:00');
$newOnlineCoursesCount = $this->getCourseSetService()->countCourseSets($defaultConditions);
$defaultConditions = ['targetType' => 'projectPlan', 'targetIds' => array_column($projectPlans, 'id') ?: [-1]];
$allOfflineCoursesCount = $this->getOfflineCourseService()->countOfflineCourses($defaultConditions);
$defaultConditions['startTime'] = strtotime(date('Y').'-01-01 00:00:00');
$newOfflineCoursesCount = $this->getOfflineCourseService()->countOfflineCourses($defaultConditions);
if ($this->isPluginInstalled('OfflineCoursePro')) {
$offlineClasses = $this->getOfflineClassService()->searchClasses(['orgIds' => $this->prepareOrgIds([])], [], 0, PHP_INT_MAX, ['id']);
$defaultConditions = ['targetType' => 'offlineClass', 'targetIds' => array_column($offlineClasses, 'id') ?: [-1]];
$allOfflineCoursesCount += $this->getOfflineCourseService()->countOfflineCourses($defaultConditions);
$defaultConditions['startTime'] = strtotime(date('Y').'-01-01 00:00:00');
$newOfflineCoursesCount += $this->getOfflineCourseService()->countOfflineCourses($defaultConditions);
}
return [$allOnlineCoursesCount + $allOfflineCoursesCount, $newOnlineCoursesCount + $newOfflineCoursesCount];
}
private function getExamData()
{
if (!$this->isPluginInstalled('exam')) {
return [0, 0];
}
$conditions = ['orgIds' => $this->prepareOrgIds([])];
$allExamCount = $this->getExamService()->countExams($conditions);
$conditions['createdTime_GE'] = strtotime(date('Y').'-01-01 00:00:00');
$newExamCount = $this->getExamService()->countExams($conditions);
return [$allExamCount, $newExamCount];
}
private function getActivityData()
{
$conditions = ['orgIds' => $this->prepareOrgIds([])];
$allActivityCount = $this->getOfflineActivityService()->countOfflineActivities($conditions);
$conditions['createdTime_GE'] = strtotime(date('Y').'-01-01 00:00:00');
$newActivityCount = $this->getOfflineActivityService()->countOfflineActivities($conditions);
return [$allActivityCount, $newActivityCount];
}
private function getTeachersData()
{
$defaultConditions = [
'locked' => 0,
'noType' => 'system',
'roles' => 'ROLE_TEACHER',
];
$defaultConditions = $this->fillOrgCode($defaultConditions);
$allTeachersCount = $this->getUserService()->countUsers($defaultConditions);
$defaultConditions['startTime'] = strtotime(date('Y').'-01-01 00:00:00');
$newTeachersCount = $this->getUserService()->countUsers($defaultConditions);
return [$allTeachersCount, $newTeachersCount];
}
private function getProjectData()
{
$defaultConditions = ['orgIds' => $this->prepareOrgIds([])];
$allOfflineClassCount = 0;
$newOfflineClassCount = 0;
$allProjectPlansCount = $this->getProjectPlanService()->countProjectPlans($defaultConditions);
$defaultConditions['createdTime_GE'] = strtotime(date('Y').'-01-01 00:00:00');
$newProjectPlansCount = $this->getProjectPlanService()->countProjectPlans($defaultConditions);
if ($this->isPluginInstalled('OfflineCoursePro')) {
$allOfflineClassCount = $this->getOfflineClassService()->countClasses(['orgIds' => $this->prepareOrgIds([])]);
$newOfflineClassCount = $this->getOfflineClassService()->countClasses($defaultConditions);
}
return [$allProjectPlansCount + $allOfflineClassCount, $newProjectPlansCount + $newOfflineClassCount];
}
/**
* @return \CorporateTrainingBundle\Biz\OfflineCourse\Service\Impl\OfflineCourseServiceImpl
*/
protected function getOfflineCourseService()
{
return $this->createService('CorporateTrainingBundle:OfflineCourse:OfflineCourseService');
}
/**
* @return OfflineActivityService
*/
protected function getOfflineActivityService()
{
return $this->createService('OfflineActivity:OfflineActivityService');
}
/**
* @return ExamService
*/
protected function getExamService()
{
return $this->createService('ExamPlugin:Exam:ExamService');
}
private function checkCloudAppUpgradeInfo()
{
$apps = $this->getAppService()->checkAppUpgrades();
$upgradeAppCount = count($apps);
if (!is_null($apps)) {
$indexApps = ArrayToolkit::index($apps, 'code');
}
$mainAppUpgrade = empty($indexApps['TRAININGMAIN']) ? [] : $indexApps['TRAININGMAIN'];
if ($mainAppUpgrade) {
$upgradeAppCount = $upgradeAppCount - 1;
}
return [$mainAppUpgrade, $upgradeAppCount];
}
private function getMobileAppVersion()
{
return [$this->getMobileVersion('android'), $this->getMobileVersion('iphone')];
}
private function getEduCloudStatus()
{
try {
$api = CloudAPIFactory::create('root');
$overview = $api->get("/cloud/{$api->getAccessKey()}/overview");
if (!$overview['enabled']) {
return false;
}
if (!($overview['accessCloud'])) {
return false;
}
return true;
} catch (\Exception $e) {
return false;
}
}
private function getMobileVersion($system)
{
$mobileVersion = CurlToolkit::request('GET', "http://www.edusoho.com/version/edusoho-training-{$system}", []);
if (empty($mobileVersion)) {
return;
}
return $mobileVersion;
}
/**
* @return FocusService
*/
protected function getFocusService()
{
return $this->createService('CorporateTrainingBundle:Focus:FocusService');
}
protected function getAppService()
{
return $this->createService('CloudPlatform:AppService');
}
protected function getSettingService()
{
return $this->createService('System:SettingService');
}
/**
* @return ProjectPlanService
*/
protected function getProjectPlanService()
{
return $this->createService('CorporateTrainingBundle:ProjectPlan:ProjectPlanService');
}
/**
* 管理后台-首页-更新日志
*
* @return \Symfony\Component\HttpFoundation\JsonResponse
*/
public function changelogAction(Request $request)
{
$rootDir = $this->container->getParameter('kernel.root_dir');
$changelogPath = dirname($rootDir).'/src/CorporateTrainingBundle/CHANGELOG';
$changelog = explode(PHP_EOL.PHP_EOL, file_get_contents($changelogPath));
$currentChangeLog = ChangelogToolkit::parseSingleChangelog($changelog[0]);
$currentChangeLog['jumpUrl'] = $this->generateUrl('changelog_list');
return $this->createJsonResponse($currentChangeLog);
}
/**
* 管理后台-首页-帮助中心
*
* @return \Symfony\Component\HttpFoundation\JsonResponse
*/
public function helpCenterAction(Request $request)
{
$url = $request->query->get('url', '');
$cacheName = md5('admin_help_center_'.$url);
$helpCenterInfo = $this->getCacheService()->get($cacheName);
if (null == $helpCenterInfo) {
$ctHelpCenterUri = 'https://ct.edusoho.com/faq/api/hotlist?';
$params = [
'version' => System::CT_VERSION,
'url' => $url,
];
if ('/admin/' == $url || '/admin' == $url) {
unset($params['url']);
}
$ctHelpCenterUrl = $ctHelpCenterUri.http_build_query($params);
$helpCenterInfo = CurlToolkit::request('GET', $ctHelpCenterUrl, [], []);
if (!empty($helpCenterInfo)) {
$this->getCacheService()->clear($cacheName);
$this->getCacheService()->set($cacheName, $helpCenterInfo, time() + rand(3, 7) * 24 * 60 * 60);
}
}
return $this->createJsonResponse($helpCenterInfo);
}
protected function getSchoolLevelKey()
{
$settings = $this->getSettingService()->get('storage', []);
if (empty($settings['cloud_access_key']) || empty($settings['cloud_secret_key'])) {
return 'none';
}
$info = [];
try {
$info = CloudAPIFactory::create('root')->get('/me');
} catch (\RuntimeException $e) {
$info['error'] = 'error';
}
if (empty($info['userLevel'])) {
return 'none';
}
if (in_array($info['userLevel'], ['none', 'license', 'custom', 'saas'])) {
return $info['userLevel'];
}
return 'none';
}
/**
* @return OfflineClassService
*/
protected function getOfflineClassService()
{
return $this->createService('OfflineCourseProPlugin:OfflineClass:OfflineClassService');
}
protected function getCourseSetService()
{
return $this->createService('Course:CourseSetService');
}
/**
* @return CacheService
*/
protected function getCacheService()
{
return $this->createService('System:CacheService');
}
/**
* @return PlatformNewsService
*/
protected function getPlatformNewsSdkService()
{
$biz = $this->getBiz();
return $biz['ESCloudSdk.platformNews'];
}
}