<?php
namespace EADPlataforma\Repository;
use EADPlataforma\Entity\Course;
use EADPlataforma\Entity\Product;
use EADPlataforma\Entity\LessonModule;
use EADPlataforma\Entity\Lesson;
use EADPlataforma\Entity\LessonLog;
use EADPlataforma\Entity\LessonLogOrigin;
use EADPlataforma\Entity\CourseTeam;
use EADPlataforma\Entity\Exam;
use EADPlataforma\Entity\ExamUser;
use EADPlataforma\Entity\Enrollment;
use EADPlataforma\Entity\Library;
use EADPlataforma\Entity\LessonXLibrary;
use EADPlataforma\Entity\LessonSupport;
use EADPlataforma\Entity\User;
use EADPlataforma\Entity\Trash;
use EADPlataforma\Enum\CourseEnum;
use EADPlataforma\Enum\CourseTeamEnum;
use EADPlataforma\Enum\LessonEnum;
use EADPlataforma\Enum\LessonModuleEnum;
use EADPlataforma\Enum\EnrollmentEnum;
use EADPlataforma\Enum\ExamEnum;
use EADPlataforma\Enum\UserEnum;
use EADPlataforma\Enum\LibraryEnum;
use EADPlataforma\Enum\LessonXLibraryEnum;
use EADPlataforma\Enum\ServicesEnum;
use EADPlataforma\Enum\NotificationEnum;
use EADPlataforma\Enum\TrashEnum;
use Firebase\JWT\JWT;
use \PDO;
/**
* @method Lesson|null find($id, $lockMode = null, $lockVersion = null)
* @method Lesson|null findOneBy(array $criteria, array $orderBy = null)
* @method Lesson[] findAll()
* @method Lesson[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class LessonRepository extends AbstractRepository
{
private $lessonIdsCourse = [];
public function getEntityClass(){
return Lesson::class;
}
public function getConnectionName(){
return "school";
}
public function setLessonTag(
Lesson $lesson,
User $user,
?string $content = null,
?string $link = null
): object
{
$stringUtil = $this->generalService->getUtil('StringUtil');
$cityName = ( $user->getCity() ? $user->getCity()->getName() : '' );
$stateUf = ( $user->getCity() ? $user->getCity()->getState()->getName() : '' );
$stateUf = ( $stateUf ? $stringUtil->getFirstWordAll($stateUf) : '' );
$client = $this->configuration->getClient();
$schoolName = $client->getBrand();
$schoolDocument = $client->getDocument();
$schoolDomain = $this->configuration->getActiveDomain();
$course = $lesson->getCourse();
$module = $lesson->getLessonModule();
$dataReplace = [
"[[aluno_id]]" => $user->getId(),
"[[aluno_nome]]" => $user->getName(),
"[[aluno_email]]" => $user->getEmail(),
"[[aluno_cpf]]" => $user->getDocument(),
"[[aluno_telefone]]" => $user->getPhone(),
"[[aluno_data_nascimento]]" => $user->getBirthdate('d/m/Y'),
"[[aluno_cidade]]" => $cityName,
"[[aluno_uf]]" => $stateUf,
"[[curso_titulo]]" => $course->getTitle(),
"[[curso_professor]]" => mb_strtoupper($course->getUser()->getName()),
"[[modulo_titulo]]" => $module->getTitle(),
"[[modulo_descricao]]" => $module->getDescription(),
"[[modulo_professor]]" => mb_strtoupper($module->getUser()->getName()),
"[[aula_titulo]]" => $lesson->getTitle(),
"[[aula_descricao]]" => $lesson->getDescription(),
"[[aula_professor]]" => mb_strtoupper($lesson->getUser()->getName()),
"[[ead_nome]]" => $schoolName,
"[[ead_cnpj]]" => $schoolDocument,
"[[ead_dominio]]" => $schoolDomain,
];
foreach($dataReplace as $key => $value){
if(!empty($link)){
$link = str_replace($key, $value, $link);
}
if(!empty($content)){
$content = str_replace($key, $value, $content);
}
}
return (object)[
"content" => $content,
"link" => $link,
];
}
public function getMeetCredentials(lesson $lesson, User $user)
{
$library = $lesson->getLibrary();
if(!$library){
return null;
}
$libraryType = $library->getType();
if($libraryType != LibraryEnum::CONTENT_CONFERENCE){
return null;
}
$info = $this->generalService->getServiceAccess(ServicesEnum::MEET);
$privateKey = $info->privateKey;
$publicKey = $info->publicKey;
$appId = $info->appId;
$fileService = $this->generalService->getService('FileService');
$photo = $fileService->getFilePathComplete(
$user->getPhoto(),
UserEnum::PATH_PROFILES,
true,
true
);
$courseRepository = $this->em->getRepository(Course::class);
$isStudent = $courseRepository->isStudent($lesson->getCourse());
$isAdmin = ($isStudent ? false : true );
$client = $this->getConfiguration()->getClient();
$clientId = $client->getClientId();
$formatClientId = [
"1" => "00000{$clientId}",
"2" => "0000{$clientId}",
"3" => "000{$clientId}",
"4" => "00{$clientId}",
"5" => "0{$clientId}",
];
if(isset($formatClientId[strlen($clientId)])){
$clientId = $formatClientId[strlen($clientId)];
}
$channelId = "{$clientId}-{$lesson->getId()}";
$userId = "{$clientId}-{$user->getId()}";
$payload = [
'iss' => 'chat',
'aud' => 'jitsi',
'exp' => time() + 7200,
'nbf' => time() - 10,
'room'=> '*',
'sub' => $appId,
'context' => [
'user' => [
'moderator' => $isAdmin ? "true" : "false",
'email' => $user->getEmail(),
'name' => $user->getName(),
'avatar' => $photo,
'id' => $userId,
"custom" => [
"clientId" => $clientId,
],
],
'features' => [
'recording' => $isAdmin ? "true" : "false",
'livestreaming' => "false",
'transcription' => "false",
'outbound-call' => "false"
]
]
];
$token = JWT::encode($payload, $privateKey, "RS256", $publicKey);
return (object)[
"token" => $token,
"room" => $channelId,
"appId" => $appId,
];
}
public function getLessonChatCredentialsNew(Lesson $lesson)
{
$library = $lesson->getLibrary();
if(!$this->getUser()){
return;
}
if(!$library){
return;
}
if(
$library->getType() != LibraryEnum::CONTENT_LIVE &&
$library->getType() != LibraryEnum::CONTENT_EXTERNAL_LIVE &&
$library->getType() != LibraryEnum::CONTENT_NEW_LIVE
){
return;
}
$courseRepository = $this->em->getRepository(Course::class);
$isStudent = $courseRepository->isStudent($lesson->getCourse());
if($lesson->getShowLiveChat() == LessonEnum::NO && $isStudent){
return;
}
$today = date('Y-m-d H:i:s');
$todayDate = date('Y-m-d');
$timeToday = strtotime($today);
$showLiveChat = LessonEnum::NO;
$liveDateStart = $library->getLiveStart();
$timeLiveEnd = date('Y-m-d', strtotime($liveDateStart));
$timeLiveStart = strtotime($liveDateStart . ' - 1 hours');
if($timeToday >= $timeLiveStart && $todayDate == $timeLiveEnd || !$isStudent){
$showLiveChat = LessonEnum::YES;
}
if($showLiveChat == LessonEnum::NO){
return;
}
$client = $this->getConfiguration()->getClient();
$clientId = $client->getClientId();
$formatClientId = [
"1" => "00000{$clientId}",
"2" => "0000{$clientId}",
"3" => "000{$clientId}",
"4" => "00{$clientId}",
"5" => "0{$clientId}",
];
if(isset($formatClientId[strlen($clientId)])){
$clientId = $formatClientId[strlen($clientId)];
}
$channelId = md5($clientId . $lesson->getId());
$userId = md5($clientId . $this->getUser()->getId());
$isAdmin = ($isStudent ? false : true );
$fileService = $this->generalService->getService('FileService');
$photo = $fileService->getFilePathComplete(
$this->getUser()->getPhoto(),
UserEnum::PATH_PROFILES,
true,
true
);
$tokenAuth = $this->generalService->getTokenCron();
$url = "https://chat.eadplataforma.app/api/users/token";
$ch = curl_init($url);
$dataPost = [
"isAdmin" => $isAdmin,
"id" => $userId,
"name" => $this->getUser()->getName(),
"roomId" => $channelId,
"photoSrc" => $photo,
"lessonId" => $lesson->getId(),
"clientId" => $clientId,
];
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($dataPost));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: {$tokenAuth}",
"Content-Type: application/json"
]);
$dataToken = curl_exec($ch);
$error = curl_error($ch);
$dataToken = json_decode($dataToken);
curl_close($ch);
return (object)[
"role" => ($isAdmin ? "admin" : "user"),
"userId" => $userId,
"userFoto" => $photo,
"userName" => $this->getUser()->getName(),
"channelId" => $channelId,
"channelLogo" => "",
"channelName" => $lesson->getTitle(),
"userToken" => (!empty($dataToken->token) ? $dataToken->token : null),
"clientId" => $clientId
];
}
public function getLessonChatCredentials(Lesson $lesson)
{
$library = $lesson->getLibrary();
if(!$this->getUser()){
return;
}
if(!$library){
return;
}
if(
$library->getType() != LibraryEnum::CONTENT_LIVE &&
$library->getType() != LibraryEnum::CONTENT_EXTERNAL_LIVE &&
$library->getType() != LibraryEnum::CONTENT_NEW_LIVE
){
return;
}
$courseRepository = $this->em->getRepository(Course::class);
$isStudent = $courseRepository->isStudent($lesson->getCourse());
if($lesson->getShowLiveChat() == LessonEnum::NO && $isStudent){
return;
}
$today = date('Y-m-d H:i:s');
$todayDate = date('Y-m-d');
$timeToday = strtotime($today);
$showLiveChat = LessonEnum::NO;
$liveDateStart = $library->getLiveStart();
$timeLiveEnd = date('Y-m-d', strtotime($liveDateStart));
$timeLiveStart = strtotime($liveDateStart . ' - 1 hours');
if($timeToday >= $timeLiveStart && $todayDate == $timeLiveEnd || !$isStudent){
$showLiveChat = LessonEnum::YES;
}
if($showLiveChat == LessonEnum::NO){
return;
}
$header = [
'typ' => 'JWT',
'alg' => 'HS256'
];
$info = $this->generalService->getServiceAccess(ServicesEnum::LIVECHAT);
$client = $this->getConfiguration()->getClient();
$clientId = $client->getClientId();
$formatClientId = [
"1" => "00000{$clientId}",
"2" => "0000{$clientId}",
"3" => "000{$clientId}",
"4" => "00{$clientId}",
"5" => "0{$clientId}",
];
if(isset($formatClientId[strlen($clientId)])){
$clientId = $formatClientId[strlen($clientId)];
}
$channelId = md5($clientId . $lesson->getId());
$clientStream = new \GetStream\StreamChat\Client($info->client, $info->token);
$channel = $clientStream->Channel("livestream", $channelId);
$userId = md5($clientId . $this->getUser()->getId());
$role = ($isStudent ? 'user' : 'admin' );
$stringUtil = $this->generalService->getUtil('StringUtil');
$chatToken = $info->token;
$segments = [];
$segments[] = $stringUtil->urlSafeB64Encode(json_encode($header));
$segments[] = $stringUtil->urlSafeB64Encode(json_encode([
"user_id" => $userId
]));
$signingInput = implode('.', $segments);
$signature = hash_hmac('SHA256', $signingInput, $chatToken, true);
$segments[] = $stringUtil->urlSafeB64Encode($signature);
$userToken = implode('.', $segments);
$fileService = $this->generalService->getService('FileService');
$photo = $fileService->getFilePathComplete(
$this->getUser()->getPhoto(),
UserEnum::PATH_PROFILES,
true,
true
);
return (object)[
"role" => $role,
"userId" => $userId,
"userFoto" => $photo,
"userName" => $this->getUser()->getName(),
"channelId" => $channelId,
"channelLogo" => "",
"channelName" => $lesson->getTitle(),
"userToken" => $userToken,
"clientId" => $info->client
];
}
public function getLessonTeacher(Lesson $lesson)
{
$userLesson = $lesson->getUser();
$userPermissionUtil = $this->generalService->getUtil('UserPermissionUtil');
$fileService = $this->generalService->getService('FileService');
$dataImg = [
"fileName" => $userLesson->getPhoto(),
"pathConst" => LessonEnum::PATH_PROFILES,
"option" => "l-user-profile-teacher",
"addUpload" => true,
"addStream" => true,
];
$request = $this->generalService->getRequest();
$teacher = (object)[
"id" => $userLesson->getId(),
"name" => $userLesson->getName(),
"canAccessAdm" => $userPermissionUtil->canAccessAdm(),
"username" => $userLesson->getUsername(),
"photo" => $fileService->getFilePathObj($dataImg),
"permissionName" => (
$userLesson->getUserProfile() ?
$userLesson->getUserProfile()->getName()
: null
),
];
return $teacher;
}
public function getLessonNextContent(Lesson $lesson, ?LessonLog $lessonLog = null)
{
$libraryRepository = $this->em->getRepository(Library::class);
$examRepository = $this->em->getRepository(Exam::class);
$nextExamLesson = $examRepository->getNextExamIdByLesson($lesson, true);
$lessonAfter = $this->getLessonIdAfterThat($lesson, true);
$course = $lesson->getCourse();
$courseId = $course->getId();
$isAccessible = false;
$acessMessage = null;
$lessonAfterClass = null;
$nextContent = null;
if($nextExamLesson || $lessonAfter){
$contentPagesNumber = null;
$contentDuration = null;
$contentType = null;
$contentThumb = null;
if($lessonAfter && empty($nextExamLesson)){
$lessonAfterClass = $this->find($lessonAfter->id);
if($lessonAfterClass){
$library = $lessonAfterClass->getLibrary();
if($library){
$contentPagesNumber = $library->getPagesNumber();
$contentDuration = $library->getDuration();
$contentType = $library->getType();
$libraryType = [
LibraryEnum::CONTENT_EMBED,
LibraryEnum::CONTENT_CONFERENCE,
LibraryEnum::CONTENT_TEXT,
LibraryEnum::CONTENT_FILES
];
if(!in_array($contentType, $libraryType)){
$contentThumb = $libraryRepository->getCover($library);
}
}
}
}
if($nextExamLesson){
$nextExamLessonClass = $examRepository->find($nextExamLesson->id);
$infoAccess = $examRepository->checkExamIsAccessible($nextExamLessonClass);
$isAccessible = $infoAccess->isAccessible;
$acessMessage = $infoAccess->message;
}else{
$enrollmentRepository = $this->em->getRepository(Enrollment::class);
$courseRepository = $this->em->getRepository(Course::class);
$enrollment = $enrollmentRepository->findOneBy([
"user" => $this->getUser()->getId(),
"course" => $courseId,
]);
if($enrollment){
$isStudent = $courseRepository->isStudent($course);
$infoAccess = $this->checkLessonIsAccessibleToUser(
$lessonAfterClass,
$enrollment,
$lessonLog,
$isStudent,
$lesson->getId()
);
$isAccessible = $infoAccess->isAccessible;
$acessMessage = $infoAccess->message;
}
}
$module = null;
if($lessonAfter){
$module = (object)[
"id" => (int)$lessonAfter->moduleId,
"title" => $lessonAfter->moduleTitle,
];
}
if($nextExamLesson){
$module = null;
if(!empty($nextExamLesson->moduleId)){
$module = (object)[
"id" => (int)$nextExamLesson->moduleId,
"title" => $nextExamLesson->moduleTitle,
];
}
}
$timeUtil = $this->generalService->getUtil('DateTimeUtil');
$nextContent = (object)[
"id" => (int)($nextExamLesson ? $nextExamLesson->id : $lessonAfter->id),
"lessonId" => (
$nextExamLesson ?
$nextExamLesson->lessonId :
(int)$lessonAfter->id
),
"module" => $module,
"courseId" => (
$nextExamLesson ?
$nextExamLesson->courseId :
(int)$lessonAfter->courseId
),
"title" => ($nextExamLesson ? $nextExamLesson->title : $lessonAfter->title),
"type" => (
$nextExamLesson ?
($nextExamLesson->type == ExamEnum::QUIZ ? 'quiz' : 'exam') :
'lesson'
),
"contentPagesNumber" => $contentPagesNumber,
"contentDuration" => $contentDuration ? $timeUtil->timeToSec($contentDuration) : null,
"contentType" => $contentType,
"contentThumb" => $contentThumb,
"isAccessible" => $isAccessible,
"acessMessage" => $acessMessage,
];
}
return $nextContent;
}
public function getLessonLastContent(Lesson $lesson)
{
$libraryRepository = $this->em->getRepository(Library::class);
$examRepository = $this->em->getRepository(Exam::class);
$lastExamLesson = $examRepository->getLastExamIdByLesson($lesson, true);
$lessonBefore = $this->getLessonIdBeforeThat($lesson, true);
$timeUtil = $this->generalService->getUtil('DateTimeUtil');
$lastContent = null;
if($lastExamLesson || $lessonBefore){
$contentPagesNumber = null;
$contentDuration = null;
$contentType = null;
$contentThumb = null;
if($lessonBefore && empty($lastExamLesson)){
$lessonBeforeClass = $this->find($lessonBefore->id);
if($lessonBeforeClass){
$library = $lessonBeforeClass->getLibrary();
if($library){
$contentPagesNumber = $library->getPagesNumber();
$contentDuration = $library->getDuration();
$contentType = $library->getType();
$libraryType = [
LibraryEnum::CONTENT_EMBED,
LibraryEnum::CONTENT_CONFERENCE,
LibraryEnum::CONTENT_TEXT,
LibraryEnum::CONTENT_FILES
];
if(!in_array($contentType, $libraryType)){
$contentThumb = $libraryRepository->getCover($library);
}
}
}
}
$module = (object)[
"id" => (int)$lessonBefore->moduleId,
"title" => $lessonBefore->moduleTitle,
];
if($lastExamLesson){
$module = null;
if(!empty($lastExamLesson->moduleId)){
$module = (object)[
"id" => (int)$lastExamLesson->moduleId,
"title" => $lastExamLesson->moduleTitle,
];
}
}
$lastContent = (object)[
"id" => (int)($lastExamLesson ? $lastExamLesson->id : $lessonBefore->id),
"lessonId" => (
$lastExamLesson ?
$lastExamLesson->lessonId :
(int)$lessonBefore->id
),
"module" => $module,
"courseId" => (
$lastExamLesson ?
$lastExamLesson->courseId :
(int)$lessonBefore->courseId
),
"title" => ($lastExamLesson ? $lastExamLesson->title : $lessonBefore->title),
"type" => (
$lastExamLesson ?
($lastExamLesson->type == ExamEnum::QUIZ ? 'quiz' : 'exam') :
'lesson'
),
"contentPagesNumber" => $contentPagesNumber,
"contentDuration" => $contentDuration ? $timeUtil->timeToSec($contentDuration) : null,
"contentType" => $contentType,
"contentThumb" => $contentThumb,
"isAccessible" => true,
"acessMessage" => null,
];
}
return $lastContent;
}
public function getShowLiveChat(Lesson $lesson, ?bool $isStudent = true)
{
$library = $lesson->getLibrary();
if(!$library){
return LessonEnum::NO;
}
if(
$library->getType() == LibraryEnum::CONTENT_LIVE ||
$library->getType() == LibraryEnum::CONTENT_NEW_LIVE
){
if($this->configuration->checkModuleIsAbleOnPlan('liveContentFunction')){
if($lesson->getShowLiveChat() == LessonEnum::YES){
$liveDateStart = $library->getLiveStart();
$timeLiveEnd = date('Y-m-d', strtotime($liveDateStart));
$timeLiveStart = strtotime($liveDateStart . ' - 1 hours');
$todayDate = date('Y-m-d');
$timeToday = strtotime($todayDate);
if(
$timeToday >= $timeLiveStart &&
$todayDate == $timeLiveEnd || !$isStudent
){
return LessonEnum::YES;
}
}
}
}
return LessonEnum::NO;
}
public function findItems(?Course $course)
{
$query = $this->createQueryBuilder('l');
if($course){
$query->andWhere('l.course = :courseId');
$query->setParameter('courseId', $course->getId());
}
return $query->orderBy('l.order', 'ASC')->getQuery()->getResult();
}
public function countLessons()
{
$query = $this->createQueryBuilder('l');
$query->select("COUNT(l.id) AS total");
$query->andWhere('l.deleted != :deleted');
$query->setParameter('deleted', LessonEnum::ITEM_DELETED);
$result = (object)$query->getQuery()->getOneOrNullResult();
return $result->total;
}
public function countLessonByLibrary(int $libraryId, ?Lesson $lesson = null)
{
$query = $this->createQueryBuilder('l');
$query->select("COUNT(l.id) AS total");
$query->andWhere('l.library = :library');
$query->andWhere('l.deleted != :deleted');
$query->setParameter('deleted', LessonEnum::ITEM_DELETED);
$query->setParameter('library', $libraryId);
if(!empty($lesson)){
$query->andWhere('l.id =! :lessonId');
$query->setParameter('lessonId', $lesson->getId());
}
$result = (object)$query->getQuery()->getOneOrNullResult();
return $result->total;
}
public function countAllLessonByLibraryType(?int $status = null, ?int $type = null)
{
$query = $this->createQueryBuilder('l');
$query->select("COUNT(l.id) AS total");
if(!is_null($type)){
$query->innerJoin('EADPlataforma:Library', 'lb', 'WITH', 'lb.id = l.library');
$query->andWhere('lb.type = :type');
$query->andWhere('lb.deleted = :deleted');
$query->setParameter('type', $type);
$query->setParameter('deleted', LibraryEnum::ITEM_NO_DELETED);
}
if(!empty($status)){
$query->andWhere('l.status = :status');
$query->setParameter('status', $status);
}
$query->andWhere('l.deleted = :deleted');
$query->setParameter('deleted', LessonEnum::ITEM_NO_DELETED);
$result = (object)$query->getQuery()->getOneOrNullResult();
return $result->total;
}
public function getAllLessonByLibraryLive(?int $user = null)
{
$query = $this->createQueryBuilder('l');
$query->innerJoin('EADPlataforma:Course', 'c', 'WITH', 'l.course = c.id');
$query->innerJoin('EADPlataforma:LessonModule', 'lm', 'WITH', 'l.lessonModule = lm.id');
$query->innerJoin('EADPlataforma:Library', 'lb', 'WITH', 'lb.id = l.library');
$query->andWhere('(
lb.type = :type OR
lb.type = :typeExternalLive OR
lb.type = :typeNewLive
)');
$query->setParameter('type', LibraryEnum::CONTENT_LIVE);
$query->setParameter('typeExternalLive', LibraryEnum::CONTENT_EXTERNAL_LIVE);
$query->setParameter('typeNewLive', LibraryEnum::CONTENT_NEW_LIVE);
if(!empty($user)){
$query->andWhere('(
l.user = :user OR
lm.user = :user OR
c.user = :user
)');
$query->setParameter('user', $user);
}
$query->andWhere('c.deleted = :deletedCourse');
$query->andWhere('lm.deleted = :deletedLessonModule');
$query->andWhere('lb.deleted = :deletedLibrary');
$query->andWhere('l.deleted = :deleted');
$query->setParameter('deletedCourse', CourseEnum::ITEM_NO_DELETED);
$query->setParameter('deletedLessonModule', LessonModuleEnum::ITEM_NO_DELETED);
$query->setParameter('deletedLibrary', LibraryEnum::ITEM_NO_DELETED);
$query->setParameter('deleted', LessonEnum::ITEM_NO_DELETED);
$data = $query->getQuery()->getResult();
return $data;
}
public function getAllLessons()
{
$query = $this->createQueryBuilder('l');
$query->select('
l.id AS lessonId,
c.id AS courseId,
lm.id AS lessonModuleId,
l.title AS lessonTitle,
c.title AS courseTitle,
lm.title AS lessonModuleTitle
');
$query->innerJoin(
'EADPlataforma:Course',
'c',
'WITH',
'c.id = l.course AND c.deleted = :courseDeleted'
);
$query->innerJoin(
'EADPlataforma:LessonModule',
'lm',
'WITH',
'lm.id = l.lessonModule AND lm.deleted = :lessonModuleDeleted'
);
$query->andWhere('l.deleted = :lessonDeleted');
$query->setParameter('courseDeleted', CourseEnum::ITEM_NO_DELETED);
$query->setParameter('lessonModuleDeleted', LessonModuleEnum::ITEM_NO_DELETED);
$query->setParameter('lessonDeleted', LessonEnum::ITEM_NO_DELETED);
$query->addOrderBy('c.order', 'ASC');
$query->addOrderBy('lm.order', 'ASC');
$query->addOrderBy('l.order', 'ASC');
$data = $query->getQuery()->getResult();
return $data;
}
public function getLessonPublicDemoById(int $lessonId)
{
$query = $this->createQueryBuilder('l');
$query->innerJoin(
'EADPlataforma:LessonModule',
'lm',
'WITH',
'lm.id = l.lessonModule AND lm.deleted = 0'
);
$query->innerJoin(
'EADPlataforma:Course',
'c',
'WITH',
'c.id = l.course AND c.deleted = 0'
);
$query->andWhere('l.deleted = 0');
$query->andWhere('l.id = :lessonId');
$query->andWhere('l.demonstration = :demonstration');
$query->andWhere('c.status = :courseStatus');
$query->andWhere('l.status = :lessonStatus');
$query->andWhere('lm.status = :lessonModuleStatus');
$query->setParameter('lessonId', $lessonId);
$query->setParameter('demonstration', LessonEnum::YES);
$query->setParameter('courseStatus', CourseEnum::PUBLISHED);
$query->setParameter('lessonStatus', LessonEnum::PUBLISHED);
$query->setParameter('lessonModuleStatus', LessonModuleEnum::PUBLISHED);
$data = $query->getQuery()->getOneOrNullResult();
return $data;
}
public function isLessonTeacher(Lesson $lesson, User $user)
{
if(!$lesson->getCourse()){
return false;
}
if(!$lesson->getLessonModule()){
return false;
}
$courseTeacherId = $lesson->getCourse()->getUser()->getId();
$lessonModuleTeacherId = $lesson->getLessonModule()->getUser()->getId();
$lessonTeacherId = $lesson->getUser()->getId();
if(
$courseTeacherId == $user->getId() ||
$lessonModuleTeacherId == $user->getId() ||
$lessonTeacherId == $user->getId()
){
return true;
}
return false;
}
public function checkLessonIsAccessibleToUser(
Lesson $lesson,
Enrollment $enrollment,
?LessonLog $log = null,
?bool $isStudent = true,
?int $lessonIdBefore = null,
?bool $blockIsNotAccess = false
)
{
$info = (object)[
"isAccessible" => false,
"isAccessPeriodExpired" => false,
"message" => null,
];
if(!$this->getUser()){
$info->message = $this->configuration->getLanguage('error_auth', 'lesson_view_error');
return $info;
}
$user = $enrollment->getUser();
$course = $lesson->getCourse();
$lessonModule = $lesson->getLessonModule();
$today = strtotime('now');
if(!$isStudent){
$info->isAccessible = true;
return $info;
}
if(!$enrollment){
$info->message = $this->configuration->getLanguage(
'error_enrollment_not_found',
'lesson_view'
);
return $info;
}
if(
$lesson->getStatus() == LessonEnum::DRAFT ||
$lessonModule->getStatus() == LessonModuleEnum::DRAFT ||
$course->getStatus() == CourseEnum::DRAFT
){
$info->message = $this->configuration->getLanguage(
'error_unavailable',
'lesson_view'
);
return $info;
}
if($enrollment->getStatus(false, true) == EnrollmentEnum::STATUS_EXPIRED){
$info->message = $this->configuration->getLanguage(
'error_enrollment_expired',
'lesson_view_error'
);
return $info;
}
$courseDateRelease = strtotime($course->getDateRelease());
if($courseDateRelease >= $today){
$info->message = "{$this->configuration->getLanguage(
'error_date_release',
'lesson_view_error'
)} {$course->getDateRelease('d/m/Y')}";
return $info;
}
$lessonModuleRepository = $this->em->getRepository(LessonModule::class);
$moduleInfo = $lessonModuleRepository->checkLessonModuleIsAccessibleToUser(
$lessonModule,
$enrollment,
$isStudent,
$lessonIdBefore
);
if(!$moduleInfo->isAccessible) {
return $moduleInfo;
}
$unlimitedexamFunction = $this->configuration->checkModuleIsAbleOnPlan(
'unlimitedExamFunction'
);
$hasLessonControl = $this->configuration->checkModuleIsAbleOnPlan(
'lessonControlFunction'
);
$examModule = $this->configuration->isModuleActive("exam_module");
if(!$hasLessonControl){
$info->isAccessible = true;
return $info;
}
$lessonLogRepository = $this->emEadmin->getRepository(LessonLog::class);
if(empty($log)){
$logLessonId = "{$course->getId()}#{$user->getId()}#{$lesson->getId()}";
$log = $lessonLogRepository->find($logLessonId);
}
if($log && !empty($log->getDateConclusion())){
$info->isAccessible = true;
$periodEnd = $lesson->getControlClosePeriod();
if(!empty($periodEnd)){
$dateEnd = strtotime("{$log->getDateConclusion()} + {$periodEnd} days");
if($dateEnd < $today){
$info->isAccessible = false;
$info->isAccessPeriodExpired = true;
}
}
return $info;
}
if($blockIsNotAccess){
$info->message = $this->configuration->getLanguage(
'error_required_incomplete',
'lesson_view_error'
);
return $info;
}
if($examModule){
if($log && empty($log->getDateConclusion()) || !$log){
$examUserRepository = $this->em->getRepository(ExamUser::class);
$currentExam = $examUserRepository->getCurrentExamOnCourseToUserByLesson(
$lesson,
$user
);
if($currentExam){
if($unlimitedexamFunction){
//check the exam type
if($currentExam->getType() == ExamEnum::LESSON){
$lessonExam = $currentExam->getLesson();
$lessonModuleExam = $lessonExam->getLessonModule();
//if exam is from this lesson redirect to exam
if($lessonExam->getId() != $lesson->getId()){
//if the exam is from a module before that redirect to exam
if($lessonModuleExam->getOrder() < $lessonModule->getOrder()){
$info->message = $this->configuration->getLanguage(
'error_required_incomplete',
'lesson_view_error'
);
return $info;
}else if(
$lessonExam->getOrder() < $lesson->getOrder() &&
$lessonModuleExam->getId() == $lessonModule->getId()
){ //if is the same module but the lesson is before that rediret to exam
$info->message = $this->configuration->getLanguage(
'error_required_incomplete',
'lesson_view_error'
);
return $info;
}
}
}else if($currentExam->getType() == ExamEnum::MODULE){
$lessonModuleExam = $currentExam->getLessonModule();
if(
$lessonModuleExam->getId() != $lessonModule->getId() &&
$lessonModuleExam->getOrder() < $lessonModule->getOrder()
){ //if is not the same module and the module is before that rediret to exam
$info->message = $this->configuration->getLanguage(
'error_required_incomplete',
'lesson_view_error'
);
return $info;
}
}
}
if($currentExam->getType() == ExamEnum::COURSE){
$info->message = $this->configuration->getLanguage(
'error_required_incomplete',
'lesson_view_error'
);
return $info;
}
}
if($unlimitedexamFunction){
$examRepository = $this->em->getRepository(Exam::class);
$exam = $examRepository->getCurrentNotStartedExamUser(
$lesson,
$user
);
if($exam){
$lessonExam = $exam->getLesson();
if(!$lessonExam || $lessonExam->getId() != $lesson->getId()){
$info->message = $this->configuration->getLanguage(
'error_required_incomplete',
'lesson_view_error'
);
return $info;
}
}
}
}
}
//if exist a lesson with requirement before that redirect to there
$currentLesson = $this->getCurrentLesson($lesson, $user);
if(!empty($currentLesson)){
if($currentLesson->getId() != $lesson->getId()){
$logId = "{$course->getId()}#{$user->getId()}#{$currentLesson->getId()}";
$logCurrent = $lessonLogRepository->find($logId);
if(empty($logCurrent)){
$info->message = $this->configuration->getLanguage(
'error_required_incomplete',
'lesson_view_error'
);
return $info;
}else if(empty($logCurrent->getDateConclusion())){
$info->message = $this->configuration->getLanguage(
'error_required_incomplete',
'lesson_view_error'
);
return $info;
}
}
}
if($lesson->getControlReleaseType() == LessonEnum::RELEASED){
$info->isAccessible = true;
return $info;
}else if($lesson->getControlReleaseType() == LessonEnum::FIXED_DATE){
$controlDateRelease = $lesson->getControlDateRelease();
$time = strtotime($controlDateRelease);
$todaySeconds = strtotime(date('Y-m-d H:i:s'));
$controlClosePeriod = $lesson->getControlClosePeriod();
if(!empty($controlClosePeriod)){
$timeLog = strtotime(
"{$controlDateRelease} + {$controlClosePeriod} day"
);
if($todaySeconds > $timeLog){
$timeLogText = date('d/m/Y H:i:s', $timeLog);
$info->message = "{$this->configuration->getLanguage(
'error_date_end',
'lesson_view_error'
)} {$timeLogText}";
return $info;
}
}
if($today >= $time){
$info->isAccessible = true;
return $info;
}
$timeText = date('d/m/Y H:i:s', $time);
$info->message = "{$this->configuration->getLanguage(
'error_date_release',
'lesson_view_error'
)} {$timeText}";
return $info;
}else if($lesson->getControlReleaseType() == LessonEnum::FLEXIBLE_DATE){
$controlReleasePeriod = $lesson->getControlReleasePeriod();
if($lesson->getControlReleaseAfterType() == LessonEnum::ENROLLMENT){
$time = strtotime(
"{$enrollment->getDateRegister()} + {$controlReleasePeriod} day"
);
$todaySeconds = strtotime(date('Y-m-d H:i:s'));
$controlClosePeriod = $lesson->getControlClosePeriod();
if(!empty($controlClosePeriod)){
/*
if($log && empty($log->getDateConclusion()) || !$log){
return false;
}
if($log->getComplete() == LessonEnum::NO){
return false;
}*/
if($log && !empty($log->getDateConclusion())){
$timeLog = strtotime(
"{$log->getDateConclusion()} + {$controlClosePeriod} day"
);
if($todaySeconds > $timeLog){
$timeLogText = date('d/m/Y H:i:s', $timeLog);
$info->message = "{$this->configuration->getLanguage(
'error_date_end',
'lesson_view_error'
)} {$timeLogText}";
return $info;
}
}
}
if($today >= $time){
$info->isAccessible = true;
return $info;
}
$timeText = date('d/m/Y H:i:s', $time);
$info->message = "{$this->configuration->getLanguage(
'error_date_release',
'lesson_view_error'
)} {$timeText}";
return $info;
}else if(
$lesson->getControlReleaseAfterType() == LessonEnum::LAST_LESSON &&
!empty($lessonIdBefore)
){
$logId = "{$course->getId()}#{$user->getId()}#{$lessonIdBefore}";
$logLast = $lessonLogRepository->find($logId);
if($logLast && !empty($logLast->getDateConclusion())){
$time = strtotime(
"{$logLast->getDateConclusion()} + {$controlReleasePeriod} day"
);
if($today >= $time){
$info->isAccessible = true;
return $info;
}
}
}
}
$info->message = $this->configuration->getLanguage('error_unavailable', 'lesson_view_error');
return $info;
}
public function getLessonDateReleaseAccess(
Lesson $lesson,
Enrollment $enrollment,
?bool $isStudent = true,
?int $lessonIdBefore = null
)
{
$date = date('Y-m-d H:i:s');
if(!$this->getUser()){
return $date;
}
$user = $enrollment->getUser();
$course = $lesson->getCourse();
$today = strtotime('now');
if(!$isStudent){
return $date;
}
if(!$enrollment){
return $date;
}
$lessonLogRepository = $this->emEadmin->getRepository(LessonLog::class);
if($lesson->getStatus() == LessonEnum::PUBLISHED){
if($lesson->getControlReleaseType() == LessonEnum::RELEASED){
return $date;
}else if($lesson->getControlReleaseType() == LessonEnum::FIXED_DATE){
return $lesson->getControlDateRelease();
}else if($lesson->getControlReleaseType() == LessonEnum::FLEXIBLE_DATE){
$controlReleasePeriod = $lesson->getControlReleasePeriod();
if($lesson->getControlReleaseAfterType() == LessonEnum::ENROLLMENT){
$time = strtotime(
"{$enrollment->getDateRegister()} + {$controlReleasePeriod} day"
);
return date('Y-m-d H:i:s', $time);
}else if(
$lesson->getControlReleaseAfterType() == LessonEnum::LAST_LESSON &&
!empty($lessonIdBefore)
){
$logId = "{$course->getId()}#{$user->getId()}#{$lessonIdBefore}";
$logLast = $lessonLogRepository->find($logId);
if($logLast){
$time = strtotime(
"{$logLast->getDateConclusion()} + {$controlReleasePeriod} day"
);
return date('Y-m-d H:i:s', $time);
}
}
}
}
return $date;
}
public function getCurrentLessonLogOrigin(Lesson $lessonBase)
{
$course = $lessonBase->getCourse();
$lessonModule = $lessonBase->getLessonModule();
$query = $this->createQueryBuilder('l');
$query->select('l.id');
$query->innerJoin(
'EADPlataforma:LessonModule',
'lm',
'WITH',
'lm.id = l.lessonModule'
);
$query->leftJoin(
'EADPlataforma:LessonLogOrigin',
'lg',
'WITH',
'lg.lesson = l.id AND lg.user = :user'
);
$query->andWhere('l.deleted = 0');
$query->andWhere('lm.deleted = 0');
$query->andWhere('l.controlRequirement = :requirement');
$query->andWhere('l.status = :lessonStatus');
$query->andWhere('lm.status = :lessonModuleStatus');
$query->andWhere('l.course = :course');
if($lessonBase->getOrder() == LessonEnum::YES){
$query->andWhere('(
( l.order <= :orderL AND lm.order = :orderLM ) OR ( lm.order < :orderLM )
)');
}else{
$query->andWhere('(
( l.order < :orderL AND lm.order = :orderLM ) OR ( lm.order < :orderLM )
)');
}
$query->andWhere('lg.dateConclusion IS NULL');
$query->setParameter('user', $this->getUser()->getId());
$query->setParameter('course', $lessonBase->getCourse()->getId());
$query->setParameter('requirement', LessonEnum::YES);
$query->setParameter('orderL', $lessonBase->getOrder());
$query->setParameter('orderLM', $lessonModule->getOrder());
$query->setParameter('lessonStatus', LessonEnum::PUBLISHED);
$query->setParameter('lessonModuleStatus', LessonModuleEnum::PUBLISHED);
$query->addOrderBy('lm.order', 'ASC');
$query->addOrderBy('l.order', 'ASC');
$query->setMaxResults(1);
$lesson = (object)$query->getQuery()->getOneOrNullResult();
if(!empty($lesson->id)){
return $this->findOneBy([ "id" => $lesson->id ]);
}
return;
}
public function getCurrentLesson(Lesson $lessonBase, User $user)
{
$course = $lessonBase->getCourse();
$lessonModule = $lessonBase->getLessonModule();
$query = $this->createQueryBuilder('l');
$query->select('l.id');
$query->innerJoin('EADPlataforma:Course', 'c', 'WITH', 'c.id = l.course');
$query->innerJoin(
'EADPlataforma:LessonModule', 'lm', 'WITH', 'lm.id = l.lessonModule'
);
$query->innerJoin('EADPlataforma:Library', 'lb', 'WITH', 'lb.id = l.library');
$query->andWhere('c.deleted = 0');
$query->andWhere('l.deleted = 0');
$query->andWhere('lm.deleted = 0');
$query->andWhere('lb.deleted = 0');
$query->andWhere('l.controlRequirement = :requirement');
$query->andWhere('l.status = :lessonStatus');
$query->andWhere('lm.status = :lessonModuleStatus');
$query->andWhere('l.course = :course');
$query->andWhere('l.id != :lessonBase');
if($lessonBase->getOrder() == LessonEnum::YES){
$query->andWhere('(
( l.order <= :orderL AND lm.order = :orderLM ) OR ( lm.order < :orderLM )
)');
}else{
$query->andWhere('(
( l.order < :orderL AND lm.order = :orderLM ) OR ( lm.order < :orderLM )
)');
}
$query->setParameter('course', $lessonBase->getCourse()->getId());
$query->setParameter('requirement', LessonEnum::YES);
$query->setParameter('orderL', $lessonBase->getOrder());
$query->setParameter('orderLM', $lessonModule->getOrder());
$query->setParameter('lessonStatus', LessonEnum::PUBLISHED);
$query->setParameter('lessonModuleStatus', LessonModuleEnum::PUBLISHED);
$query->setParameter('lessonBase', $lessonBase->getId());
$query->addOrderBy('lm.order', 'DESC');
$query->addOrderBy('l.order', 'DESC');
$query->setMaxResults(1);
$lesson = (object)$query->getQuery()->getOneOrNullResult();
if(!empty($lesson->id)){
$logId = "{$course->getId()}#{$user->getId()}#{$lesson->id}";
$log = $this->emEadmin->getRepository(LessonLog::class)->find($logId);
if(!$log || ($log && empty($log->getDateConclusion()))){
return $this->findOneBy([ "id" => $lesson->id ]);
}
}
return;
}
public function getCourseLessonsIds(
Course $course,
?LessonModule $lessonModule = null,
?string $searchText = null
)
{
$userPermissionUtil = $this->generalService->getUtil('UserPermissionUtil');
$permission = $userPermissionUtil->getPermission("course", "see");
$user = $userPermissionUtil->getUser();
$lessonModuleId = ($lessonModule ? $lessonModule->getId() : null);
$keyCache = md5(
"getCourseLessonsIds{$course->getId()}-{$user->getId()}-{$lessonModuleId}"
);
if(isset($this->lessonIdsCourse[$keyCache])){
return $this->lessonIdsCourse[$keyCache];
}
$isInTeam = $this->em->getRepository(CourseTeam::class)->userExistInCourseTeam(
$course,
$user
);
$query = $this->createQueryBuilder('l');
$query->select('
l.id,
l.title,
IDENTITY(l.course) AS courseId,
IDENTITY(l.lessonModule) AS moduleId,
lm.title AS moduleTitle
');
$query->innerJoin(
'EADPlataforma:LessonModule', 'lm', 'WITH', 'lm.id = l.lessonModule'
);
if(!empty($searchText)){
$query->andWhere('l.title LIKE :searchText');
$query->setParameter('searchText', "%{$searchText}%");
}
$query->andWhere('l.deleted = 0');
$query->andWhere('lm.deleted = 0');
$query->andWhere('l.course = :courseId');
$query->setParameter('courseId', $course->getId());
if($lessonModule){
$query->andWhere('l.lessonModule = :lessonModuleId');
$query->setParameter('lessonModuleId', $lessonModule->getId());
}
if(
$userPermissionUtil->isLow($permission) ||
($userPermissionUtil->isMiddle($permission) && !$isInTeam)
){
$query->andWhere('l.status = :lessonStatus');
$query->andWhere('lm.status = :lessonModuleStatus');
$query->setParameter('lessonStatus', LessonEnum::PUBLISHED);
$query->setParameter('lessonModuleStatus', LessonModuleEnum::PUBLISHED);
}
$query->addOrderBy('lm.order', 'ASC');
$query->addOrderBy('l.order', 'ASC');
$data = $query->getQuery()->execute();
$this->lessonIdsCourse[$keyCache] = $data;
return $this->lessonIdsCourse[$keyCache];
}
public function getLessonIdBeforeThat(Lesson $lessonBase, bool $complete = false)
{
$lessons = $this->getCourseLessonsIds($lessonBase->getCourse());
foreach ($lessons as $key => $lesson) {
$lesson = (object)$lesson;
if($lesson->id == $lessonBase->getId()){
if($key == 0){
return;
}else{
$obj = (object)$lessons[$key-1];
if($complete){
return $obj;
}
return $obj->id;
}
}
}
return;
}
public function getLessonIdAfterThat(Lesson $lessonBase, bool $complete = false)
{
$lessons = $this->getCourseLessonsIds($lessonBase->getCourse());
$maxPosition = count($lessons) - 1;
foreach ($lessons as $key => $lesson) {
$lesson = (object)$lesson;
if($lesson->id == $lessonBase->getId()){
if($key == $maxPosition){
return;
}else{
$obj = (object)$lessons[$key+1];
if($complete){
return $obj;
}
return $obj->id;
}
}
}
return;
}
public function refreshOrder(
$courseId,
$lessonModuleId,
$oldOrder,
$newOrder,
$isDelete = false
)
{
$this->em->beginTransaction();
try {
$sql = "SELECT l.id
FROM EADPlataforma:Lesson AS l
WHERE l.course = :courseId
AND l.lessonModule = :lessonModuleId
AND l.deleted = :deleted
ORDER BY l.order ASC";
$query = $this->em->createQuery($sql);
$query->setParameter('courseId', $courseId);
$query->setParameter('lessonModuleId', $lessonModuleId);
$query->setParameter('deleted', $isDelete);
$lessons = $query->getResult();
$order = 1;
foreach ($lessons as $lesson) {
$updateSql = "UPDATE EADPlataforma:Lesson AS l
SET l.order = :order
WHERE l.id = :id";
$updateQuery = $this->em->createQuery($updateSql);
$updateQuery->setParameter('order', $order);
$updateQuery->setParameter('id', $lesson['id']);
$updateQuery->execute();
$order++;
}
$maxOrder = count($lessons);
if ($newOrder < 1) {
$newOrder = 1;
} elseif ($newOrder > $maxOrder) {
$newOrder = $maxOrder;
}
if ($oldOrder != $newOrder) {
$sql = ($oldOrder < $newOrder)
? "UPDATE EADPlataforma:Lesson AS l
SET l.order = l.order - 1
WHERE l.order > :oldOrder
AND l.order <= :newOrder
AND l.course = :courseId
AND l.lessonModule = :lessonModuleId
AND l.deleted = :deleted"
: "UPDATE EADPlataforma:Lesson AS l
SET l.order = l.order + 1
WHERE l.order < :oldOrder
AND l.order >= :newOrder
AND l.course = :courseId
AND l.lessonModule = :lessonModuleId
AND l.deleted = :deleted";
$shiftQuery = $this->em->createQuery($sql);
$shiftQuery->setParameter('oldOrder', $oldOrder);
$shiftQuery->setParameter('newOrder', $newOrder);
$shiftQuery->setParameter('courseId', $courseId);
$shiftQuery->setParameter('lessonModuleId', $lessonModuleId);
$shiftQuery->setParameter('deleted', $isDelete);
$shiftQuery->execute();
}
$finalSql = "UPDATE EADPlataforma:Lesson AS l
SET l.order = :newOrder
WHERE l.id = :lessonId";
$finalUpdateQuery = $this->em->createQuery($finalSql);
$finalUpdateQuery->setParameter('newOrder', $newOrder);
$finalUpdateQuery->setParameter('lessonId', $oldOrder);
$finalUpdateQuery->execute();
$this->em->commit();
} catch (\Exception $e) {
$this->em->rollback();
throw $e;
}
}
public function copyLesson(
LessonModule $newModule,
Lesson $lesson,
$isPartial = false,
$isModulePartial = false,
$copyType = null
)
{
$course = $newModule->getCourse();
$courseId = $course->getId();
$newLesson = clone $lesson;
$newLesson->setLessonModule($newModule);
$newLesson->setCourse($course);
if($copyType == LessonEnum::COPY_PUBLISHED){
$newLesson->setStatus(LessonEnum::PUBLISHED);
}else if($copyType == LessonEnum::COPY_DRAFT){
$newLesson->setStatus(LessonEnum::DRAFT);
}
if($isPartial){
$lastOrder = $this->count([
"course" => $courseId,
"lessonModule" => $newModule->getId(),
"deleted" => LessonEnum::ITEM_NO_DELETED
]);
$newLesson->setOrder($lastOrder + 1);
}
$this->em->persist($newLesson);
$this->em->flush();
if($isPartial || $isModulePartial){
$userLessonId = $newLesson->getUser()->getId();
$courseTeam = $this->em->getRepository(CourseTeam::class)->findOneBy([
"course" => $courseId,
"user" => $userLessonId,
"deleted" => LessonEnum::ITEM_NO_DELETED
]);
if(!$courseTeam){
$newCourseTeam = new CourseTeam();
$newCourseTeam->setCourse($course);
$newCourseTeam->setUser($newLesson->getUser());
$this->em->persist($newCourseTeam);
$this->em->flush();
}
}
$files = $this->em->getRepository(LessonXLibrary::class)->findBy([
"lesson"=> $lesson->getId(),
"deleted"=> LessonXLibraryEnum::ITEM_NO_DELETED
]);
if($files){
foreach ($files as $key => $file) {
$newFile = clone $file;
$newFile->setLesson($newLesson);
$this->em->persist($newFile);
$this->em->flush();
}
}
$this->em->getRepository(Exam::class)->copyExamByLesson($lesson, $newLesson);
$this->em->getRepository(Exam::class)->copyQuizByLesson($lesson, $newLesson);
}
public function notifyStudentsLesson(Lesson $lesson, $type)
{
if(!$this->configuration->checkModuleIsAbleOnPlan('notificationFunction')){
return;
}
$today = date('Y-m-d');
$dateLastNotify = $lesson->getDateLastNotify('Y-m-d');
if($today != $dateLastNotify && $lesson->getStatus() == LessonEnum::PUBLISHED){
$course = $lesson->getCourse();
$lessonModule = $lesson->getLessonModule();
if(
$course->getStatus() == CourseEnum::PUBLISHED &&
$lessonModule->getStatus() == LessonModuleEnum::PUBLISHED
){
$taskQueueService = $this->generalService->getService('TaskQueueService');
$enrollmentRepository = $this->em->getRepository(Enrollment::class);
$enrollments = $enrollmentRepository->getEnrollmentsByCourse(
$course->getId(),
EnrollmentEnum::STATUS_ACTIVE
);
foreach ($enrollments as $key => $enrollment) {
if($enrollment->getUser()->getAllowNotifyNewLesson() == LessonEnum::YES){
$taskQueueService->insert($type, $enrollment->getUser(), $lesson->getId());
}
}
$lesson->setDateLastNotify(date('Y-m-d H:i:s'));
$this->em->flush();
}
}
}
public function lessonUpdateOrder($modules)
{
$dqlModule = "UPDATE EADPlataforma:LessonModule AS lm SET lm.order = CASE";
$idModules = "";
$dqlExam = "";
$newModuleId = "";
$whereExam = "";
$caseLesson1 = " l.order = CASE ";
$caseLesson2 = " l.lessonModule = CASE ";
$caseLesson3 = " e.lessonModule = CASE ";
$idsLesson = "";
foreach ($modules as $key => $value) {
$orderNew = $key + 1;
$dqlModule .= " WHEN lm.id = {$value->moduleId} THEN {$orderNew}";
if(empty($idModules)){
$idModules .= "{$value->moduleId}";
}else{
$idModules .= ", {$value->moduleId}";
}
foreach ($value->lessons as $key_lesson => $valLesson) {
if(!empty($valLesson->lessonId)){
$ordemNewLesson = $key_lesson + 1;
$caseLesson1 .= " WHEN l.id = {$valLesson->lessonId} THEN {$ordemNewLesson}";
$caseLesson2 .= " WHEN l.id = {$valLesson->lessonId} THEN {$value->moduleId}";
$caseLesson3 .= " WHEN e.lesson = {$valLesson->lessonId} THEN {$value->moduleId}";
if(empty($idsLesson)){
$idsLesson .= " {$valLesson->lessonId} ";
}else{
$idsLesson .= ", {$valLesson->lessonId} ";
}
}
}
}
$dqlModule .= " ELSE lm.order END WHERE lm.id IN ({$idModules}) ";
$dqlLesson = "UPDATE EADPlataforma:Lesson AS l
SET {$caseLesson1} ELSE l.order END,
{$caseLesson2} ELSE IDENTITY(l.lessonModule) END
WHERE l.id IN ({$idsLesson}) ";
$dqlExam = "UPDATE EADPlataforma:Exam AS e
SET {$caseLesson3} ELSE IDENTITY(e.lessonModule) END
WHERE e.lesson IN ({$idsLesson}) ";
$query = $this->em->createQuery($dqlModule);
$queryLesson = $this->em->createQuery($dqlLesson);
$queryExam = $this->em->createQuery($dqlExam);
$query->execute();
$queryLesson->execute();
$queryExam->execute();
}
public function getLessonPublicNumber(
Course $course,
?LessonModule $lessonModule = null,
?bool $required = false,
?bool $filterModule = false
)
{
$query = $this->createQueryBuilder('l');
$query->select('COUNT(l.id) AS total');
$query->innerJoin(
'EADPlataforma:LessonModule',
'lm',
'WITH',
'lm.id = l.lessonModule AND lm.deleted = :deleted'
);
$query->innerJoin(
'EADPlataforma:Course',
'c',
'WITH',
'c.id = l.course AND c.deleted = :deleted'
);
if($lessonModule){
$query->andWhere('lm.order <= :lessonModuleOrder');
$query->setParameter('lessonModuleOrder', $lessonModule->getOrder());
if($filterModule){
$query->andWhere('lm.id = :lessonModule');
$query->setParameter('lessonModule', $lessonModule->getId());
}
}
if($required){
$query->andWhere('l.controlRequirement = :required');
$query->setParameter('required', LessonEnum::YES);
}
$query->andWhere('l.deleted = :deleted');
$query->andWhere('l.course = :courseId');
$query->andWhere('l.status = :lessonStatus');
$query->andWhere('lm.status = :lessonModuleStatus');
$query->setParameter('courseId', $course->getId());
$query->setParameter('deleted', LessonEnum::ITEM_NO_DELETED);
$query->setParameter('lessonStatus', LessonEnum::PUBLISHED);
$query->setParameter('lessonModuleStatus', LessonModuleEnum::PUBLISHED);
$query->setMaxResults(1);
$result = (object)$query->getQuery()->getOneOrNullResult();
return $result->total;
}
public function countCourseLessons(
Course $course,
int $userId,
?LessonModule $lessonModule = null,
$isHistory = false
)
{
$userPermissionUtil = $this->generalService->getUtil('UserPermissionUtil');
$permission = $userPermissionUtil->getPermission("course", "see");
$user = $userPermissionUtil->getUser();
$isInTeam = $this->em->getRepository(CourseTeam::class)->userExistInCourseTeam(
$course,
$user
);
$sqlDateConclusion = "
SELECT
(
CASE
WHEN ll.complete = :yes THEN ll.date_conclusion
ELSE CURDATE()
END
) AS date_conclusion
FROM lesson_log AS ll
WHERE ll.lesson_id = l.id
AND ll.course_id = l.course_id
AND ll.user_id = :userId
ORDER BY ll.id DESC
LIMIT 1
";
$sqlDateRegisterEnrollement = "
SELECT
e.date_register
FROM enrollment AS e
WHERE e.deleted = :deletedEnrollment
AND e.course_id = l.course_id
AND e.user_id = :userId
ORDER BY e.id DESC
LIMIT 1
";
$sql = "
SELECT
COUNT(l.id) AS total
FROM lesson AS l
INNER JOIN course AS c ON (c.id = l.course_id AND c.deleted = :deletedCourse)
INNER JOIN lesson_module AS lm ON (
lm.id = l.lesson_module_id AND lm.deleted = :deletedModule
)
LEFT JOIN library AS lb ON (lb.id = l.library_id AND lb.deleted = :deletedLibrary)
WHERE l.deleted = :deleted
AND l.course_id = :courseId
/* AND CASO FOSSE CONSIDERADA DATA DE LIBERAÇÃO DA AULA PARA ENCERRAR O ACESSO
(
(
l.control_close_period = 0 OR
l.control_close_period IS NULL
)
OR
(
l.control_close_period > 0
AND l.control_release_type = 0
AND DATEDIFF(CURDATE(), (DATE(
(
CASE
WHEN ({$sqlDateConclusion}) IS NOT NULL THEN ({$sqlDateConclusion})
ELSE CURDATE()
END
)
) + INTERVAL l.control_close_period DAY)) < 0
)
OR
(
l.control_close_period > 0
AND l.control_release_type = 1
AND DATEDIFF(CURDATE(), (DATE(
(l.control_date_release)
) + INTERVAL l.control_close_period DAY)) < 0
)
OR
(
l.control_close_period > 0
AND l.control_release_type = 2
AND l.control_release_after_type = 1
AND DATEDIFF(CURDATE(), (DATE(
({$sqlDateRegisterEnrollement})
) + INTERVAL l.control_close_period DAY)) < 0
)
OR
(
l.control_close_period > 0
AND l.control_release_type = 2
AND l.control_release_after_type = 2
)
)*/
";
if($lessonModule){
$sql .= " AND l.lesson_module_id = :lessonModuleId ";
}
if(
$isHistory ||
$userPermissionUtil->isLow($permission) ||
($userPermissionUtil->isMiddle($permission) && !$isInTeam)
){
$sql .= " AND l.status = :lessonStatus ";
$sql .= " AND lm.status = :lessonModuleStatus ";
}
$stmt = $this->em->getConnection()->prepare($sql);
//$stmt->bindValue(':deletedEnrollment', EnrollmentEnum::ITEM_NO_DELETED, PDO::PARAM_INT);
$stmt->bindValue(':deletedCourse', CourseEnum::ITEM_NO_DELETED, PDO::PARAM_INT);
$stmt->bindValue(':deletedModule', LessonModuleEnum::ITEM_NO_DELETED, PDO::PARAM_INT);
$stmt->bindValue(':deletedLibrary', LibraryEnum::ITEM_NO_DELETED, PDO::PARAM_INT);
$stmt->bindValue(':deleted', LessonEnum::ITEM_NO_DELETED, PDO::PARAM_INT);
$stmt->bindValue(':courseId', $course->getId(), PDO::PARAM_INT);
//$stmt->bindValue(':yes', LessonEnum::YES, PDO::PARAM_INT);
//$stmt->bindValue(':userId', $userId, PDO::PARAM_INT);
if($lessonModule){
$stmt->bindValue(':lessonModuleId', $lessonModule->getId(), PDO::PARAM_INT);
}
if(
$isHistory ||
$userPermissionUtil->isLow($permission) ||
($userPermissionUtil->isMiddle($permission) && !$isInTeam)
){
$stmt->bindValue(':lessonStatus', LessonEnum::PUBLISHED, PDO::PARAM_INT);
$stmt->bindValue(':lessonModuleStatus', LessonModuleEnum::PUBLISHED, PDO::PARAM_INT);
}
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_CLASS);
return $result[0]->total;
}
public function getCourseLessons(
Course $course,
?LessonModule $lessonModule = null,
?array $lessonIds = null,
?string $searchText = null
)
{
$userPermissionUtil = $this->generalService->getUtil('UserPermissionUtil');
$permission = $userPermissionUtil->getPermission("course", "see");
$user = $userPermissionUtil->getUser();
$isInTeam = $this->em->getRepository(CourseTeam::class)->userExistInCourseTeam(
$course,
$user
);
$query = $this->createQueryBuilder('l');
$query->innerJoin(
'EADPlataforma:LessonModule',
'lm',
'WITH',
'lm.id = l.lessonModule AND lm.deleted = 0'
);
$query->innerJoin(
'EADPlataforma:Course',
'c',
'WITH',
'c.id = l.course AND c.deleted = 0'
);
$query->leftJoin(
'EADPlataforma:Library',
'lb',
'WITH',
'lb.id = l.library AND lb.deleted = 0'
);
$query->andWhere('l.deleted = 0');
$query->andWhere('l.course = :courseId');
$query->setParameter('courseId', $course->getId());
if(!empty($searchText)){
$query->andWhere('(l.title LIKE :searchText OR lm.title LIKE :searchText)');
$query->setParameter('searchText', "%{$searchText}%");
}
if($lessonModule){
$query->andWhere('l.lessonModule = :lessonModuleId');
$query->setParameter('lessonModuleId', $lessonModule->getId());
}
if(is_array($lessonIds) && !empty($lessonIds)){
$query->andWhere($query->expr()->in('l.id', $lessonIds));
}
if(
$userPermissionUtil->isLow($permission) ||
($userPermissionUtil->isMiddle($permission) && !$isInTeam)
){
$query->andWhere('l.status = :lessonStatus');
$query->andWhere('lm.status = :lessonModuleStatus');
$query->setParameter('lessonStatus', LessonEnum::PUBLISHED);
$query->setParameter('lessonModuleStatus', LessonModuleEnum::PUBLISHED);
}
$query->addOrderBy('l.order', 'ASC');
$query->addOrderBy('l.lessonModule', 'ASC');
$data = $query->getQuery()->execute();
return $data;
}
public function getFirstLesson(Course $course, ?LessonModule $lessonModule = null)
{
$userPermissionUtil = $this->generalService->getUtil('UserPermissionUtil');
$permission = $userPermissionUtil->getPermission("course", "see");
$user = $userPermissionUtil->getUser();
$courseTeamRepository = $this->em->getRepository(CourseTeam::class);
$isInTeam = $courseTeamRepository->userExistInCourseTeam($course, $user);
$query = $this->createQueryBuilder('l');
$query->innerJoin(
'EADPlataforma:LessonModule',
'lm',
'WITH',
'lm.id = l.lessonModule AND lm.deleted = 0'
);
$query->innerJoin(
'EADPlataforma:Course',
'c',
'WITH',
'c.id = l.course AND c.deleted = 0'
);
$query->andWhere('l.deleted = 0');
$query->andWhere('l.course = :courseId');
$query->setParameter('courseId', $course->getId());
if($lessonModule){
$query->andWhere('l.lessonModule = :lessonModuleId');
$query->setParameter('lessonModuleId', $lessonModule->getId());
}
if(
$userPermissionUtil->isLow($permission) ||
($userPermissionUtil->isMiddle($permission) && !$isInTeam)
){
$query->andWhere('l.status = :lessonStatus');
$query->andWhere('lm.status = :lessonModuleStatus');
$query->setParameter('lessonStatus', LessonEnum::PUBLISHED);
$query->setParameter('lessonModuleStatus', LessonModuleEnum::PUBLISHED);
}
$query->addOrderBy('lm.order', 'ASC');
$query->addOrderBy('l.order', 'ASC');
$query->setMaxResults(1);
return $query->getQuery()->getOneOrNullResult();
}
public function getLastLesson(Course $course, ?LessonModule $lessonModule = null)
{
$userPermissionUtil = $this->generalService->getUtil('UserPermissionUtil');
$permission = $userPermissionUtil->getPermission("course", "see");
$user = $userPermissionUtil->getUser();
$isInTeam = $this->em->getRepository(CourseTeam::class)->userExistInCourseTeam(
$course,
$user
);
$query = $this->createQueryBuilder('l');
$query->innerJoin(
'EADPlataforma:LessonModule',
'lm',
'WITH',
'lm.id = l.lessonModule AND lm.deleted = 0'
);
$query->innerJoin(
'EADPlataforma:Course',
'c',
'WITH',
'c.id = l.course AND c.deleted = 0'
);
$query->andWhere('l.deleted = 0');
$query->andWhere('l.course = :courseId');
$query->setParameter('courseId', $course->getId());
if($lessonModule){
$query->andWhere('l.lessonModule = :lessonModuleId');
$query->setParameter('lessonModuleId', $lessonModule->getId());
}
if(
$userPermissionUtil->isLow($permission) ||
($userPermissionUtil->isMiddle($permission) && !$isInTeam)
){
$query->andWhere('l.status = :lessonStatus');
$query->andWhere('lm.status = :lessonModuleStatus');
$query->setParameter('lessonStatus', LessonEnum::PUBLISHED);
$query->setParameter('lessonModuleStatus', LessonModuleEnum::PUBLISHED);
}
$query->addOrderBy('lm.order', 'DESC');
$query->addOrderBy('l.order', 'DESC');
$query->setMaxResults(1);
return $query->getQuery()->getOneOrNullResult();
}
public function getLessonByLessonModule(LessonModule $lessonModule)
{
$query = $this->createQueryBuilder('l');
$query->leftJoin(
'EADPlataforma:Library',
'li',
'WITH',
'li.id = l.library AND li.deleted = 0'
);
$query->andWhere('l.deleted = 0');
$query->andWhere('l.status = :status');
$query->andWhere('l.course = :courseId');
$query->andWhere('l.lessonModule = :lessonModule');
$query->setParameter('courseId', $lessonModule->getCourse()->getId());
$query->setParameter('lessonModule', $lessonModule->getId());
$query->setParameter('status', LessonEnum::PUBLISHED);
$query->addOrderBy('l.order', 'ASC');
return $query->getQuery()->execute();
}
public function getNextLessonByLessonModule(
int $order,
LessonModule $lessonModule,
int $limit = 3
)
{
$userPermissionUtil = $this->generalService->getUtil('UserPermissionUtil');
$permission = $userPermissionUtil->getPermission("course", "see");
$course = $lessonModule->getCourse();
$user = $userPermissionUtil->getUser();
$isInTeam = $this->em->getRepository(CourseTeam::class)->userExistInCourseTeam(
$course,
$user
);
$query = $this->createQueryBuilder('l');
$query->select('
l.id,
l.order,
l.title,
l.status,
l.controlRequirement,
l.controlReleaseType,
l.controlReleaseAfterType,
l.controlDateRelease,
l.controlReleasePeriod,
l.controlClosePeriod,
lm.id AS lessonModule,
li.type AS libraryType,
li.pagesNumber,
li.duration
');
$query->innerJoin(
'EADPlataforma:LessonModule',
'lm',
'WITH',
'lm.id = l.lessonModule AND lm.deleted = 0'
);
$query->innerJoin(
'EADPlataforma:Course',
'c',
'WITH',
'c.id = l.course AND c.deleted = 0'
);
$query->leftJoin(
'EADPlataforma:Library',
'li',
'WITH',
'li.id = l.library AND li.deleted = 0'
);
if(
$userPermissionUtil->isLow($permission) ||
($userPermissionUtil->isMiddle($permission) && !$isInTeam)
){
$query->andWhere('l.status = :lessonStatus');
$query->andWhere('lm.status = :lessonModuleStatus');
$query->setParameter('lessonStatus', LessonEnum::PUBLISHED);
$query->setParameter('lessonModuleStatus', LessonModuleEnum::PUBLISHED);
}
$query->andWhere('l.deleted = 0');
$query->andWhere('l.course = :courseId');
$query->andWhere('l.lessonModule = :lessonModule');
$query->andWhere('l.order > :order');
$query->setParameter('courseId', $course->getId());
$query->setParameter('lessonModule', $lessonModule->getId());
$query->setParameter('order', $order);
$query->addOrderBy('l.order', 'ASC');
$query->setMaxResults($limit);
return $query->getQuery()->execute();
}
public function getLessonNotView($userId, $courseId, $lessonId = null)
{
$and = '';
if(!empty($lessonId))
{
$and .= " AND l.id = :lessonId";
}
if(empty($courseId) || empty($userId))
{
return [];
}
$dql = "SELECT
l.id,
l.title,
lm.title AS titleModule,
'0' AS totalView,
'' AS lastAccess,
'--' AS timeWatch,
'0' AS completed,
'---' AS dateConclusion
FROM EADPlataforma:Lesson AS l
INNER JOIN EADPlataforma:LessonModule AS lm WITH (lm.id = l.lessonModule AND lm.deleted = 0)
WHERE l.deleted = 0
AND l.course = :courseId
{$and}
AND l.id NOT IN (
SELECT
IDENTITY (ll.lesson)
FROM EADPlataforma:LessonLogOrigin AS ll
WHERE ll.user != 1
AND ll.user = :userId
AND ll.course = :courseId
)
ORDER BY l.order ASC";
$query = $this->em->createQuery($dql);
$query->setParameter('userId', $userId);
$query->setParameter('courseId', $courseId);
if(!empty($lessonId))
{
$query->setParameter('lessonId', $lessonId);
}
$data = $query->execute();
$result = [];
foreach ($data as $key => $value) {
$result[] = [
$value["id"],
$value["title"],
$value["titleModule"],
$value["totalView"],
$value["lastAccess"],
$value["timeWatch"],
$value["completed"],
$value["dateConclusion"]
];
}
return $result;
}
public function isFirstCourseLesson(?Lesson $lesson)
{
if(!$lesson){
return false;
}
$firstLesson = $this->getFirstLesson($lesson->getCourse());
if($firstLesson){
return $firstLesson->getId() == $lesson->getId();
}
return true;
}
public function isFirstModuleLesson(?Lesson $lesson)
{
if(!$lesson){
return false;
}
$firstLesson = $this->getFirstLesson($lesson->getCourse(), $lesson->getLessonModule());
if($firstLesson){
return $firstLesson->getId() == $lesson->getId();
}
return true;
}
public function isLastCourseLesson(?Lesson $lesson)
{
if(!$lesson){
return false;
}
$firstLesson = $this->getLastLesson($lesson->getCourse());
if($firstLesson){
return $firstLesson->getId() == $lesson->getId();
}
return true;
}
public function isLastModuleLesson(?Lesson $lesson)
{
if(!$lesson){
return false;
}
$firstLesson = $this->getLastLesson(
$lesson->getCourse(),
$lesson->getLessonModule()
);
if($firstLesson){
return $firstLesson->getId() == $lesson->getId();
}
return true;
}
public function isLessonVisibleToStudent(
Lesson $lesson,
?bool $ignoreControlFunction = false,
?bool $isStudent = true
): bool
{
$info = $this->checkLessonVisibleToStudent($lesson, $ignoreControlFunction, $isStudent);
return $info->visible;
}
public function checkLessonVisibleToStudent(
Lesson $lesson,
?bool $ignoreControlFunction = false,
?bool $isStudent = true
): object
{
$userPermissionUtil = $this->generalService->getUtil('UserPermissionUtil');
$user = $userPermissionUtil->getUser();
$info = (object)[
"visible" => true,
"message" => "",
];
if(!$user){
$info->visible = false;
return $info;
}
$course = $lesson->getCourse();
$lessonModule = $lesson->getLessonModule();
if($lesson->isDeleted() || $lessonModule->isDeleted() || $course->isDeleted()){
$info->visible = false;
return $info;
}
if(!$isStudent){
$info->visible = true;
return $info;
}
$enrollmentRepository = $this->em->getRepository(Enrollment::class);
$isEnroll = $enrollmentRepository->isValidEnrollmentByUser(
$user->getId(),
$course->getId()
);
$hasLessonControl = $this->configuration->checkModuleIsAbleOnPlan(
'lessonControlFunction'
);
if($lesson->getStatus() == LessonEnum::DRAFT){
$info->visible = false;
return $info;
}
if($lessonModule->getStatus() == LessonModuleEnum::DRAFT){
$info->visible = false;
return $info;
}
if($course->getStatus() == CourseEnum::DRAFT){
$info->visible = false;
return $info;
}
if(!$isEnroll){
$info->visible = false;
return $info;
}
if(!$ignoreControlFunction){
if($lesson->getControlReleaseType() == LessonEnum::FIXED_DATE){
$todaySeconds = strtotime(date('Y-m-d H:i:s'));
if($hasLessonControl){
$controlClosePeriod = $lesson->getControlClosePeriod();
if(!empty($controlClosePeriod)){
$timeLog = strtotime(
"{$lesson->getControlDateRelease()} + {$controlClosePeriod} day"
);
if($todaySeconds > $timeLog){
$info->visible = false;
return $info;
}
}
}
}else{
$lessonLogRepository = $this->emEadmin->getRepository(LessonLog::class);
$logId = "{$course->getId()}#{$user->getId()}#{$lesson->getId()}";
$lessonLog = $lessonLogRepository->find($logId);
//check lesson to user is closed
if($lessonLog){
$todaySeconds = strtotime(date('Y-m-d H:i:s'));
if($hasLessonControl){
$controlClosePeriod = $lesson->getControlClosePeriod();
if(
!empty($controlClosePeriod) &&
$lessonLog->getComplete() == LessonEnum::YES
){
$timeLog = strtotime(
"{$lessonLog->getDateConclusion()} + {$controlClosePeriod} day"
);
if($todaySeconds > $timeLog){
$info->visible = false;
return $info;
}
}
}
}
}
}
return $info;
}
public function getLessonNumberByProduct(Product $product)
{
$query = $this->createQueryBuilder('l');
$query->select("COUNT(l.id) AS total");
$query->innerJoin('EADPlataforma:Course', 'c', 'WITH', 'l.course = c.id');
$query->innerJoin('EADPlataforma:Product', 'p', 'WITH', 'l.course MEMBER OF p.course');
$query->innerJoin('EADPlataforma:LessonModule', 'lm', 'WITH', 'l.lessonModule = lm.id');
$query->andWhere('l.deleted = :deletedLesson');
$query->andWhere('c.deleted = :deletedCourse');
$query->andWhere('lm.deleted = :deletedLessonModule');
$query->andWhere('l.status = :statusLesson');
$query->andWhere('c.status = :statusCourse');
$query->andWhere('lm.status = :statusLessonModule');
$query->andWhere('p.id = :productId');
$query->setParameter('deletedLesson', LessonEnum::ITEM_NO_DELETED);
$query->setParameter('deletedCourse', CourseEnum::ITEM_NO_DELETED);
$query->setParameter('deletedLessonModule', LessonModuleEnum::ITEM_NO_DELETED);
$query->setParameter('statusLesson', LessonEnum::PUBLISHED);
$query->setParameter('statusCourse', CourseEnum::PUBLISHED);
$query->setParameter('statusLessonModule', LessonModuleEnum::PUBLISHED);
$query->setParameter('productId', $product->getId());
$result = (object)$query->getQuery()->getOneOrNullResult();
return $result->total;
}
public function getLessonForExportPresence(Course $course, $lessonModuleId = null){
$query = $this->createQueryBuilder('l');
$query->select('
l.id,
lm.id AS lessonModuleId,
l.order,
lm.title,
l.title AS lessonTitle
');
$query->innerJoin(
'EADPlataforma:LessonModule',
'lm',
'WITH',
'lm.id = l.lessonModule AND lm.deleted = 0'
);
if($lessonModuleId){
$query->andWhere('lm.id = :lessonModuleId');
$query->setParameter('lessonModuleId', $lessonModuleId);
}
$query->andWhere('l.status = :lessonStatus');
$query->andWhere('lm.status = :lessonModuleStatus');
$query->setParameter('lessonStatus', LessonEnum::PUBLISHED);
$query->setParameter('lessonModuleStatus', LessonModuleEnum::PUBLISHED);
$query->andWhere('l.deleted = 0');
$query->andWhere('l.course = :courseId');
$query->setParameter('courseId', $course->getId());
$query->addOrderBy('lm.order', 'ASC');
$query->addOrderBy('lm.id', 'ASC');
$query->addOrderBy('l.order', 'ASC');
$query->addOrderBy('l.id', 'ASC');
return $query->getQuery()->execute();
}
public function restore(Lesson $lesson, $typeItem, $key)
{
$lessonId = $lesson->getId();
$dateNow = date('Y-m-d H:i:s');
$lastOrder = $this->count(
[
"deleted" => LessonEnum::ITEM_NO_DELETED,
"lessonModule" => $lesson->getLessonModule()->getId()
]
) + ($key + 1);
$lesson->setOrder($lastOrder);
$courseRepository = $this->em->getRepository(Course::class);
$lesson->setUserDelete($this->getUser());
$lesson->setDateDelete($dateNow);
$lesson->restore();
$deleted = LessonEnum::ITEM_NO_DELETED;
$typeDelete = LessonEnum::CASCADE;
$this->em->getRepository(Exam::class)->restoreByLesson(
$lessonId,
$deleted,
$typeDelete,
$this->getUser(),
$dateNow
);
$this->em->getRepository(ExamUser::class)->restoreByLesson(
$lessonId,
$deleted,
$typeDelete,
$this->getUser(),
$dateNow
);
$this->em->getRepository(LessonSupport::class)->restoreByLesson(
$lessonId,
$deleted,
$typeDelete,
$this->getUser(),
$dateNow
);
$this->em->getRepository(LessonXLibrary::class)->restoreByLesson(
$lessonId,
$deleted,
$typeDelete,
$this->getUser(),
$dateNow
);
$this->em->getRepository(Trash::class)->deleteTrash($lessonId, $typeItem);
}
public function delete(Lesson $lesson, $typeItem, $permission, $isTrash)
{
$lessonId = $lesson->getId();
$dateNow = date('Y-m-d H:i:s');
$typeDelete = LessonEnum::CASCADE;
$notificationService = $this->generalService->getService('NotificationService');
$userPermissionUtil = $this->generalService->getUtil('UserPermissionUtil');
$lessonXLibrarys = $this->em->getRepository(LessonXLibrary::class)->findBy([
"lesson" => $lesson->getId(),
]);
$libraryRepository = $this->em->getRepository(Library::class);
$libraryModule = $this->configuration->checkModuleIsAbleOnPlan('libraryModule');
if($isTrash == LessonEnum::YES){
$permission = $userPermissionUtil->getPermission("trash", "delete");
}
$isLessonTeacher = $this->isLessonTeacher($lesson, $this->getUser());
if($isLessonTeacher || $userPermissionUtil->isHigh($permission)){
$lesson->setUserDelete($this->getUser());
$lesson->setDateDelete($dateNow);
$lesson->individual();
if($lesson->isOnTrash() || $lesson->isDeleted()){
$lesson->delete();
$deleted = LessonEnum::ITEM_DELETED;
$this->em->getRepository(Trash::class)->deleteTrash($lessonId, $typeItem);
$this->em->flush();
foreach ($lessonXLibrarys as $key => $lessonXLibrary) {
$library = $lessonXLibrary->getLibrary();
if(!$libraryModule && $library){
$library->cascade();
$libraryRepository->deleteContent($library);
}
$lessonXLibrary->delete();
}
$library = $lesson->getLibrary();
if(!$libraryModule && $library){
$library->cascade();
$libraryRepository->deleteContent($library);
}
}
if(!$lesson->isOnTrash() && !$lesson->isDeleted()){
$order = $lesson->getOrder();
$this->refreshOrder(
$lesson->getCourse()->getId(),
$lesson->getLessonModule()->getId(),
$order,
null,
true
);
$notificationService->delete(
NotificationEnum::ORIGIN_LESSON_SUPPORT_LIKE,
$lessonId
);
$notificationService->delete(
NotificationEnum::ORIGIN_LESSON_SUPPORT_ANSWER_LIKE,
$lessonId
);
$notificationService->delete(
NotificationEnum::ORIGIN_LESSON_SUPPORT_NEW,
$lessonId
);
$notificationService->delete(
NotificationEnum::ORIGIN_LESSON_SUPPORT_ANSWER_NEW,
$lessonId
);
$notificationService->delete(
NotificationEnum::ORIGIN_LESSON_NEW,
$lessonId
);
$notificationService->delete(
NotificationEnum::ORIGIN_LESSON_CHANGE,
$lessonId
);
$lesson->trash();
$deleted = LessonEnum::ITEM_ON_TRASH;
$this->em->getRepository(Trash::class)->insertTrash(
$lesson,
$typeItem,
"Aula: {$lesson->getTitle()} | Prof. {$lesson->getUser()->getName()}"
);
}
}
$this->em->getRepository(Exam::class)->deleteByLesson(
$lessonId,
$deleted,
$typeDelete,
$this->getUser(),
$dateNow
);
$this->em->getRepository(ExamUser::class)->deleteByLesson(
$lessonId,
$deleted,
$typeDelete,
$this->getUser(),
$dateNow
);
$this->em->getRepository(LessonSupport::class)->deleteByLesson(
$lessonId,
$deleted,
$typeDelete,
$this->getUser(),
$dateNow
);
$this->em->getRepository(LessonXLibrary::class)->deleteByLesson(
$lessonId,
$deleted,
$typeDelete,
$this->getUser(),
$dateNow
);
}
public function restoreByCourse($courseId, $deleted, $typeDelete){
$typeItem = TrashEnum::LESSON;
$lessons = $this->em->getRepository(Lesson::class)->findBy([
"course" => $courseId,
"deleted" => (1 - $deleted),
"typeDelete" => $typeDelete
]);
foreach ($lessons as $key => $lesson) {
$this->restore($lesson, $typeItem, $key);
}
}
public function deleteByCourse($courseId, $deleted){
$typeItem = TrashEnum::LESSON;
$isTrash = LessonEnum::NO;
if($deleted == LessonEnum::ITEM_ON_TRASH){
$isTrash = LessonEnum::YES;
}
$userPermissionUtil = $this->generalService->getUtil('UserPermissionUtil');
$permission = $userPermissionUtil->getPermission(
"course",
"lesson",
"delete"
);
$lessons = $this->em->getRepository(Lesson::class)->findBy([
"course" => $courseId,
"deleted" => ($deleted - 1)
]);
foreach ($lessons as $key => $lesson) {
$this->delete($lesson, $typeItem, $permission, $isTrash);
$lesson->cascade();
}
}
public function restoreByLessonModule($lessonModuleId, $deleted, $typeDelete){
$typeItem = TrashEnum::LESSON;
$lessons = $this->em->getRepository(Lesson::class)->findBy([
"lessonModule" => $lessonModuleId,
"deleted" => (1 - $deleted),
"typeDelete" => $typeDelete
]);
foreach ($lessons as $key => $lesson) {
$this->restore($lesson, $typeItem, $key);
}
}
public function deleteByLessonModule($lessonModuleId, $deleted){
$typeItem = TrashEnum::LESSON;
$isTrash = LessonEnum::NO;
if($deleted == LessonEnum::ITEM_ON_TRASH){
$isTrash = LessonEnum::YES;
}
$userPermissionUtil = $this->generalService->getUtil('UserPermissionUtil');
$permission = $userPermissionUtil->getPermission(
"course",
"lesson",
"delete"
);
$lessons = $this->em->getRepository(Lesson::class)->findBy([
"lessonModule" => $lessonModuleId,
"deleted" => ($deleted - 1)
]);
foreach ($lessons as $key => $lesson) {
$this->delete($lesson, $typeItem, $permission, $isTrash);
$lesson->cascade();
}
}
public function deleteTrashCron()
{
$sql = "UPDATE EADPlataforma:Lesson AS l SET l.deleted = 2
WHERE l.dateDelete <= :date AND l.deleted = 1 ";
$query = $this->em->createQuery($sql);
$query->setParameter('date', date('Y-m-d H:i:s', strtotime('-90 days')));
$query->execute();
}
}