protected function body()
 {
     if (!$this->userHasPrivileges(User::groupsJoinPrivate, User::groupsJoinPublic, User::groupsRequest)) {
         return false;
     }
     if (!$this->isInputValid(array('id' => 'isIndex'))) {
         return false;
     }
     $groupId = $this->getParams('id');
     /**
      * @var $group \Group
      */
     $group = Repositories::findEntity(Repositories::Group, $groupId);
     // Calculate privileges of the user
     $user = User::instance();
     $canJoinPrivate = User::instance()->hasPrivileges(User::groupsJoinPrivate);
     $groupIsPrivate = $group->getType() == \Group::TYPE_PRIVATE;
     $hasSufficientPrivileges = $groupIsPrivate && ($canJoinPrivate || $user->hasPrivileges(User::groupsRequest)) || !$groupIsPrivate && $user->hasPrivileges(User::groupsJoinPublic);
     if (!$hasSufficientPrivileges) {
         return $this->death(StringID::InsufficientPrivileges);
     }
     $status = $canJoinPrivate || !$groupIsPrivate ? \Subscription::STATUS_SUBSCRIBED : \Subscription::STATUS_REQUESTED;
     // Put into database
     $subscription = new \Subscription();
     $subscription->setGroup($group);
     $subscription->setUser(User::instance()->getEntity());
     $subscription->setStatus($status);
     Repositories::persistAndFlush($subscription);
     return true;
 }
 protected function body()
 {
     $inputs = array('name' => array('isNotEmpty'), 'description' => 'isNotEmpty');
     if (!$this->isInputValid($inputs)) {
         return false;
     }
     $name = $this->getParams('name');
     $description = $this->getParams('description');
     $id = $this->getParams('id');
     $isIdSet = $id !== null && $id !== '';
     $user = User::instance();
     $userId = $user->getId();
     if (!$isIdSet) {
         if (!$this->userHasPrivileges(User::lecturesAdd)) {
             return false;
         }
         $lecture = new \Lecture();
         $lecture->setName($name);
         $lecture->setDescription($description);
         $lecture->setOwner(User::instance()->getEntity());
         Repositories::persistAndFlush($lecture);
     } else {
         if ($isIdSet) {
             $lecture = Repositories::findEntity(Repositories::Lecture, $id);
             if (!$user->hasPrivileges(User::lecturesManageAll) && (!$user->hasPrivileges(User::lecturesManageOwn) || $lecture->getOwner()->getId() != $userId)) {
                 return $this->death(StringID::InsufficientPrivileges);
             }
             $lecture->setDescription($description);
             Repositories::persistAndFlush($lecture);
         }
     }
     return true;
 }
 protected function body()
 {
     if (!$this->userHasPrivileges(User::submissionsCorrect)) {
         return false;
     }
     $canViewAuthors = User::instance()->hasPrivileges(User::submissionsViewAuthors);
     $rated = $this->getParams('rated') ? true : false;
     $all = $this->getParams('all') ? true : false;
     $absolutelyAll = $this->getParams('absolutelyAll') ? true : false;
     $userId = User::instance()->getId();
     if ($absolutelyAll) {
         if (!$this->userHasPrivileges(User::lecturesManageAll, User::groupsManageAll, User::otherAdministration)) {
             return false;
         }
     }
     /**
      * @var $submissions \Submission[]
      */
     // group is a DQL reserved word, so we must use _group
     if ($absolutelyAll) {
         $submissions = Repositories::makeDqlQuery("SELECT submission, user, assignment, problem, _group FROM \\Submission submission JOIN submission.assignment assignment JOIN assignment.problem problem JOIN submission.user user JOIN assignment.group _group WHERE submission.status <> 'deleted'")->getResult();
     } else {
         $submissions = Repositories::makeDqlQuery("SELECT submission, user, assignment, problem, _group FROM \\Submission submission JOIN submission.assignment assignment JOIN assignment.problem problem JOIN submission.user user JOIN assignment.group _group WHERE _group.owner = :submissionCorrector AND (submission.status = 'graded' OR submission.status = 'latest' OR submission.status = 'handsoff') AND _group.deleted = 0")->setParameter('submissionCorrector', $userId)->getResult();
     }
     foreach ($submissions as $submission) {
         if (!$all && !$absolutelyAll) {
             if ($rated && $submission->getStatus() !== \Submission::STATUS_GRADED) {
                 continue;
             }
             if (!$rated && $submission->getStatus() === \Submission::STATUS_GRADED) {
                 continue;
             }
         }
         $descriptionForTeacher = $submission->getInfo();
         if ($submission->getSimilarityStatus() == \Submission::SIMILARITY_STATUS_GUILTY) {
             $descriptionForTeacher = Language::get(StringID::ThisSubmissionIsPlagiarism) . "\n======\n" . $descriptionForTeacher;
         }
         if ($submission->getSimilarityStatus() == \Submission::SIMILARITY_STATUS_INNOCENT) {
             $descriptionForTeacher = $descriptionForTeacher . "\n======\n" . Language::get(StringID::ThisSubmissionIsInnocent);
         }
         if ($submission->getSimilarityStatus() == \Submission::SIMILARITY_STATUS_NEW) {
             $descriptionForTeacher = $descriptionForTeacher . "\n======\n" . Language::get(StringID::ThisHasYetToBeCheckedForPlagiarism);
         }
         if ($submission->getStatus() == \Submission::STATUS_REQUESTING_GRADING) {
             $descriptionForTeacher = Language::get(StringID::GradingRequested) . " " . $descriptionForTeacher;
         }
         $row = [$submission->getId(), $submission->getAssignment()->getProblem()->getName(), $submission->getAssignment()->getGroup()->getName(), $submission->getDate()->format("Y-m-d H:i:s"), $submission->getSuccess(), $descriptionForTeacher, $submission->getRating(), $submission->getExplanation(), $submission->getAssignment()->getReward(), $submission->getAssignment()->getDeadline()->format("Y-m-d H:i:s"), $canViewAuthors ? $submission->getUser()->getId() : 0, $canViewAuthors ? $submission->getUser()->getRealName() : Language::get(StringID::NotAuthorizedForName), $submission->getOutputfile() != '', $submission->getAssignment()->getId()];
         if ($absolutelyAll) {
             $row[] = $canViewAuthors ? $submission->getUser()->getEmail() : Language::get(StringID::NotAuthorizedForName);
             $row[] = $submission->getStatus();
         }
         $this->addRowToOutput($row);
     }
     return true;
 }
Example #4
0
 protected function body()
 {
     if (!$this->isInputSet(array('name', 'pass'))) {
         return false;
     }
     $user = User::instance();
     if (!$user->login($this->getParams('name'), $this->getParams('pass'))) {
         return $this->stop(Language::get(StringID::InvalidLogin));
     }
     $this->setOutput(array('id' => $user->getId(), 'username' => $user->getName(), 'name' => $user->getRealName(), 'email' => $user->getEmail(), 'lastLogin' => $user->getLastAccess(), 'privileges' => $user->unpackPrivileges(), 'timeout' => $user->getTimeout(), User::sendEmailOnSubmissionRatedStudent => $user->getData(User::sendEmailOnSubmissionRatedStudent), User::sendEmailOnSubmissionConfirmedTutor => $user->getData(User::sendEmailOnSubmissionConfirmedTutor), User::sendEmailOnAssignmentAvailableStudent => $user->getData(User::sendEmailOnAssignmentAvailableStudent)));
     return true;
 }
 /**
  * Initializes @ref $storageFolder and @ref $filePrefix.
  */
 protected function __construct()
 {
     if (!session_id()) {
         session_start();
     }
     /// @ref $storageFolder is retrieved from Config.
     $this->storageFolder = Config::get('paths', 'temp');
     /// @ref $filePrefix is set to username if user is logged in.
     $user = User::instance();
     if ($user->isLogged()) {
         $this->filePrefix = $user->getName() . '-';
     }
 }
 protected final function body()
 {
     if (!$this->isInputValid(array('id' => 'isIndex'))) {
         return false;
     }
     $id = $this->getParams('id');
     /** @var \XTest $test */
     $test = Repositories::findEntity(Repositories::Xtest, $id);
     $description = $test->getDescription();
     $questions = $test->getGenerated();
     $lecture = $test->getLecture();
     $user = User::instance();
     if (!$user->hasPrivileges(User::lecturesManageAll) && (!$user->hasPrivileges(User::lecturesManageOwn) || $lecture->getOwner()->getId() != $user->getId())) {
         return $this->death(StringID::InsufficientPrivileges);
     }
     if (!$questions) {
         return $this->stop('the test has not been generated yet', 'cannot create test');
     }
     $questions = explode(',', $questions);
     $selectedQuestions = array();
     $attachmentIds = array();
     foreach ($questions as $questionId) {
         /** @var \Question $qData */
         $qData = Repositories::findEntity(Repositories::Question, $questionId);
         $options = $qData->getOptions();
         $options = $options ? explode($options[0], substr($options, 1)) : array();
         $qAtt = $qData->getAttachments();
         $qAtt = $qAtt ? explode(';', $qAtt) : array();
         array_push($selectedQuestions, array('text' => $qData->getText(), 'type' => $qData->getType(), 'options' => $options, 'attachments' => $qAtt));
         $attachmentIds = array_merge($attachmentIds, $qAtt);
     }
     $attachmentIds = array_unique($attachmentIds);
     $reverseIndex = array_flip($attachmentIds);
     foreach ($selectedQuestions as &$selQ) {
         $translated = array();
         foreach ($selQ['attachments'] as $selA) {
             array_push($translated, $reverseIndex[$selA] + 1);
         }
         $selQ['attachments'] = $translated;
     }
     $attachments = array();
     $folder = Config::get('paths', 'attachments');
     foreach ($attachmentIds as $attachmentId) {
         /** @var \Attachment $aData */
         $aData = Repositories::findEntity(Repositories::Attachment, $attachmentId);
         array_push($attachments, array('id' => $aData->getId(), 'type' => $aData->getType(), 'file' => $folder . $aData->getFile()));
     }
     $this->setContentType('text/html');
     $this->generateTestHtml($description, $selectedQuestions, $attachments);
     return true;
 }
 protected function body()
 {
     if (!$this->isInputValid(array('id' => 'isIndex'))) {
         return false;
     }
     /**
      * @var $lecture \Lecture
      */
     $lecture = Repositories::findEntity(Repositories::Lecture, $this->getParams('id'));
     $user = User::instance();
     if (!$user->hasPrivileges(User::lecturesManageAll) && (!$user->hasPrivileges(User::lecturesManageOwn) || $user->getId() != $lecture->getId())) {
         return $this->death(StringID::InsufficientPrivileges);
     }
     RemovalManager::hideLectureItsProblemsGroupsQuestionsAttachmentsAndXtests($lecture);
     return true;
 }
 protected function body()
 {
     if (!$this->isInputValid(array('id' => 'isIndex'))) {
         return false;
     }
     /**
      * @var $group \Group
      */
     $group = Repositories::findEntity(Repositories::Group, $this->getParams('id'));
     $user = User::instance();
     if (!$user->hasPrivileges(User::groupsManageAll) && (!$user->hasPrivileges(User::groupsManageOwn) || $user->getId() != $group->getOwner()->getId())) {
         return $this->death(StringID::InsufficientPrivileges);
     }
     RemovalManager::hideGroupAndItsAssignments($group);
     return true;
 }
 protected function body()
 {
     if (!$this->isInputSet('id')) {
         return false;
     }
     $id = $this->getParams('id');
     /**
      * @var $subscription \Subscription
      */
     $subscription = Repositories::findEntity(Repositories::Subscription, $id);
     if (User::instance()->getId() !== $subscription->getGroup()->getOwner()->getId()) {
         return $this->death(StringID::InsufficientPrivileges);
     }
     $this->handleRequest($subscription);
     return true;
 }
 protected function body()
 {
     if (!$this->isInputValid(array('id' => 'isIndex'))) {
         return false;
     }
     $id = $this->getParams('id');
     /**
      * @var $subscription \Subscription
      */
     $subscription = Repositories::findEntity(Repositories::Subscription, $id);
     if ($subscription->getUser()->getId() !== User::instance()->getId()) {
         return $this->death(StringID::InsufficientPrivileges);
     }
     Repositories::remove($subscription);
     return true;
 }
 /**
  * Gets submission with supplied ID if it's accessible to user [stopping].
  * @param int $id submission ID
  * @return \Submission submission or false in case of failure
  */
 protected final function findAccessibleSubmissionById($id)
 {
     /**
      * @var $submission \Submission
      */
     $submission = Repositories::findEntity(Repositories::Submission, $id);
     $userId = User::instance()->getId();
     $authorId = $submission->getUser()->getId();
     $ownerId = $submission->getAssignment()->getGroup()->getOwner()->getId();
     if ($authorId !== $userId && $ownerId !== $userId) {
         if (User::instance()->hasPrivileges(User::groupsManageAll, User::lecturesManageAll, User::otherAdministration)) {
             return $submission;
         }
         return $this->death(StringID::InsufficientPrivileges);
     }
     return $submission;
 }
 protected function body()
 {
     if (!$this->userHasPrivileges(User::usersRemove)) {
         return false;
     }
     if (!$this->isInputSet('id')) {
         return false;
     }
     $id = $this->getParams('id');
     if ($id == User::instance()->getId()) {
         return $this->death(StringID::YouCannotRemoveYourself);
     }
     /** @var \User $user */
     $user = Repositories::findEntity(Repositories::User, $id);
     RemovalManager::hideUserAndAllHeOwns($user);
     return true;
 }
 protected function body()
 {
     if (!$this->isInputValid(array('id' => 'isIndex'))) {
         return false;
     }
     /**
      * @var $assignment \Assignment
      */
     $assignment = Repositories::findEntity(Repositories::Assignment, $this->getParams('id'));
     $user = User::instance();
     if (!$user->hasPrivileges(User::groupsManageAll) && (!$user->hasPrivileges(User::groupsManageOwn) || $user->getId() != $assignment->getGroup()->getOwner()->getId())) {
         return $this->death(StringID::InsufficientPrivileges);
     }
     $assignment->setDeleted(true);
     Repositories::persistAndFlush($assignment);
     return true;
 }
 protected function body()
 {
     if (!$this->isInputValid(array('id' => 'isIndex'))) {
         return false;
     }
     $id = $this->getParams('id');
     /**
      * @var $submission \Submission
      */
     $submission = Repositories::findEntity(Repositories::Submission, $id);
     $userId = User::instance()->getId();
     if ($submission->getUser()->getId() != $userId) {
         return $this->death(StringID::HackerError);
     }
     // First, if you handed something off previously, it is no longer handed off
     /**
      * @var $yourSubmissions \Submission[]
      */
     $yourSubmissions = Repositories::getRepository(Repositories::Submission)->findBy(['user' => $userId, 'assignment' => $submission->getAssignment()->getId()]);
     foreach ($yourSubmissions as $previouslyHandedOffSubmission) {
         if ($previouslyHandedOffSubmission->getStatus() == \Submission::STATUS_REQUESTING_GRADING || $previouslyHandedOffSubmission->getStatus() == \Submission::STATUS_LATEST) {
             $previouslyHandedOffSubmission->setStatus(\Submission::STATUS_NORMAL);
             Repositories::persistAndFlush($previouslyHandedOffSubmission);
         }
     }
     // Next, hand off the submission
     $submission->setStatus(\Submission::STATUS_REQUESTING_GRADING);
     Repositories::persistAndFlush($submission);
     $emailText = file_get_contents(Config::get("paths", "newSubmissionEmail"));
     $emailText = str_replace("%{RealName}", User::instance()->getRealName(), $emailText);
     $emailText = str_replace("%{Email}", User::instance()->getEmail(), $emailText);
     $emailText = str_replace("%{Link}", Config::getHttpRoot() . "#correctionAll#submission#" . $submission->getId(), $emailText);
     $lines = explode("\n", $emailText);
     $subject = $lines[0];
     // The first line is subject.
     $text = preg_replace('/^.*\\n/', '', $emailText);
     // Everything except the first line.
     $to = $submission->getAssignment()->getGroup()->getOwner();
     if ($to->getSendEmailOnNewSubmission()) {
         if (!Core::sendEmail($to->getEmail(), $subject, $text)) {
             return $this->death(StringID::MailError);
         }
     }
     return true;
 }
 protected function body()
 {
     if (!$this->userHasPrivileges(User::otherAdministration, User::groupsManageAll, User::lecturesManageAll)) {
         return false;
     }
     $newId = $this->getParams('newId');
     if (!$newId) {
         return true;
     }
     $canViewAuthors = User::instance()->hasPrivileges(User::submissionsViewAuthors);
     /** @var \Similarity[] $similarities */
     $similarities = Repositories::getRepository(Repositories::Similarity)->findBy(['newSubmission' => $newId]);
     foreach ($similarities as $similarity) {
         $row = [$similarity->getId(), $similarity->getOldSubmission()->getId(), $similarity->getSuspicious() ? "yes" : false, $similarity->getScore(), $similarity->getDetails(), $canViewAuthors ? $similarity->getOldSubmission()->getUser()->getRealName() : Language::get(StringID::NotAuthorizedForName), $similarity->getOldSubmission()->getDate()->format("Y-m-d H:i:s"), $similarity->getOldSubmission()->getStatus()];
         $this->addRowToOutput($row);
     }
     return true;
 }
 protected function body()
 {
     if (!$this->userHasPrivileges()) {
         return;
     }
     $query = "SELECT a, p, l, z, g FROM Assignment a JOIN a.problem p LEFT JOIN p.plugin z JOIN p.lecture l JOIN a.group g WITH g.id IN (SELECT IDENTITY(k.group) FROM \\Subscription k WHERE k.user = :id AND a.deleted = false)";
     /**
      * @var $assignments \Assignment[]
      */
     $userId = User::instance()->getId();
     $assignments = Repositories::getEntityManager()->createQuery($query)->setParameter('id', $userId)->getResult();
     foreach ($assignments as $assignment) {
         $submissionGraded = count(Repositories::getRepository(Repositories::Submission)->findBy(['assignment' => $assignment->getId(), 'user' => $userId, 'status' => \Submission::STATUS_GRADED])) > 0;
         $submissionExists = count(Repositories::getRepository(Repositories::Submission)->findBy(['assignment' => $assignment->getId(), 'user' => $userId])) > 0;
         $row = [$assignment->getId(), $assignment->getProblem()->getName(), $assignment->getProblem()->getDescription(), $assignment->getProblem()->getPlugin() ? $assignment->getProblem()->getPlugin()->getDescription() : Language::get(StringID::NoPluginUsed), $assignment->getDeadline()->format("Y-m-d H:i:s"), $assignment->getReward(), $assignment->getProblem()->getLecture()->getName(), $assignment->getProblem()->getLecture()->getDescription(), $assignment->getGroup()->getName(), $assignment->getGroup()->getDescription(), $submissionExists, $submissionGraded];
         $this->addRowToOutput($row);
     }
 }
 protected function body()
 {
     if (!$this->isInputValid(array('id' => 'isIndex'))) {
         return false;
     }
     $id = $this->getParams('id');
     /**
      * @var $problem \Problem
      */
     $problem = Repositories::findEntity(Repositories::Problem, $id);
     $lecture = $problem->getLecture();
     $user = User::instance();
     if (!$user->hasPrivileges(User::lecturesManageAll) && (!$user->hasPrivileges(User::lecturesManageOwn) || $user->getId() != $lecture->getOwner())) {
         return $this->death(StringID::InsufficientPrivileges);
     }
     RemovalManager::hideProblemAndItsAssignments($problem);
     return true;
 }
 /**
  * Runs this script.
  * @return bool Is it successful?
  */
 protected function body()
 {
     if (!$this->isInputSet(array('id'))) {
         return false;
     }
     $id = $this->getParams('id');
     /**
      * @var $submission \Submission
      */
     $submission = Repositories::findEntity(Repositories::Submission, $id);
     if ($submission->getUser()->getId() !== User::instance()->getId()) {
         return $this->death(StringID::InsufficientPrivileges);
     }
     if ($submission->getStatus() === \Submission::STATUS_GRADED) {
         return $this->death(StringID::CannotDeleteGradedSubmissions);
     }
     if ($submission->getStatus() === \Submission::STATUS_REQUESTING_GRADING) {
         return $this->death(StringID::CannotDeleteHandsoffSubmissions);
     }
     $status = $submission->getStatus();
     $submission->setStatus(\Submission::STATUS_DELETED);
     Repositories::persist($submission);
     // Make something else latest
     if ($status === \Submission::STATUS_LATEST) {
         $latestSubmission = null;
         /**
          * @var $submissions \Submission[]
          * @var $latestSubmission \Submission
          */
         $submissions = Repositories::getRepository(Repositories::Submission)->findBy(['status' => \Submission::STATUS_NORMAL, 'assignment' => $submission->getAssignment()->getId(), 'user' => User::instance()->getId()]);
         foreach ($submissions as $olderSolution) {
             if ($latestSubmission === null || $olderSolution->getDate() > $latestSubmission->getDate()) {
                 $latestSubmission = $olderSolution;
             }
         }
         if ($latestSubmission !== null) {
             $latestSubmission->setStatus(\Submission::STATUS_LATEST);
             Repositories::persist($latestSubmission);
         }
     }
     Repositories::flushAll();
     return true;
 }
Example #19
0
 protected function body()
 {
     $inputs = array('lecture' => 'isIndex', 'name' => 'isNotEmpty', 'description' => array());
     if (!$this->isInputValid($inputs)) {
         return false;
     }
     $lectureIndex = $this->getParams('lecture');
     $groupName = $this->getParams('name');
     $groupDescription = $this->getParams('description');
     $public = $this->paramExists('public') ? 'public' : 'private';
     $groupId = $this->getParams('id');
     $editing = $groupId !== null && $groupId !== '';
     $user = User::instance();
     /** @var \Lecture $lecture */
     $lecture = Repositories::findEntity(Repositories::Lecture, $lectureIndex);
     if ($editing) {
         /**
          * @var $group \Group
          */
         $group = Repositories::findEntity(Repositories::Group, $groupId);
         $group->setName($groupName);
         $group->setDescription($groupDescription);
         $group->setType($public);
         Repositories::persistAndFlush($group);
     } else {
         if (!$this->userHasPrivileges(User::groupsAdd)) {
             return $this->death(StringID::InsufficientPrivileges);
         }
         $group = new \Group();
         $group->setDeleted(false);
         $group->setDescription($groupDescription);
         $group->setLecture($lecture);
         $group->setName($groupName);
         $group->setOwner($user->getEntity());
         $group->setType($public);
         Repositories::persistAndFlush($group);
     }
     return true;
 }
    /**
     * Performs the function of this script.
     */
    protected function body()
    {
        if (!$this->userHasPrivileges(User::assignmentsSubmit)) {
            return;
        }
        if (!$this->isInputValid(array('assignmentId' => 'isIndex'))) {
            return;
        }
        $userId = User::instance()->getId();
        $assignmentId = $this->getParams('assignmentId');
        /**
         * @var $assignment \Assignment
         */
        $assignment = Repositories::getEntityManager()->find('Assignment', $assignmentId);
        $query = "SELECT s, a FROM Subscription s, Assignment a WHERE s.group = a.group AND s.user = "******" AND a.id = " . $assignmentId;
        /**
         * @var $result \Subscription[]
         */
        $result = Repositories::getEntityManager()->createQuery($query)->getResult();
        if (count($result) === 0) {
            $this->stop(Language::get(StringID::HackerError));
            return;
        }
        if ($result[0]->getStatus() == \Subscription::STATUS_REQUESTED) {
            $this->stop(Language::get(StringID::SubscriptionNotYetAccepted));
            return;
        }
        $submissionsFolder = Config::get('paths', 'submissions');
        $file = date('Y-m-d_H-i-s_') . $userId . '_' . StringUtils::randomString(10) . '.zip';
        if (!$this->saveUploadedFile('submission', $submissionsFolder . $file)) {
            return;
        }
        // Create submission
        $newSubmission = new \Submission();
        $newSubmission->setAssignment($assignment);
        $newSubmission->setSubmissionFile($file);
        $newSubmission->setUser(User::instance()->getEntity());
        $newSubmission->setDate(new \DateTime());
        // Put into database
        Repositories::persistAndFlush($newSubmission);
        // Launch plugin, or set full success if not connected to any plugin
        if ($assignment->getProblem()->getPlugin() === null) {
            $newSubmission->setSuccess(100);
            $newSubmission->setInfo(Language::get(StringID::NoPluginUsed));
            $previousSubmissions = Repositories::makeDqlQuery("SELECT s FROM \\Submission s WHERE s.user = :sameUser AND s.assignment = :sameAssignment AND s.status != 'graded' AND s.status != 'deleted'")->setParameter('sameUser', User::instance()->getEntity()->getId())->setParameter('sameAssignment', $assignment->getId())->getResult();
            foreach ($previousSubmissions as $previousSubmission) {
                $previousSubmission->setStatus(\Submission::STATUS_NORMAL);
                Repositories::getEntityManager()->persist($previousSubmission);
            }
            $newSubmission->setStatus(\Submission::STATUS_LATEST);
            Repositories::getEntityManager()->persist($newSubmission);
            Repositories::flushAll();
        } else {
            Core::launchPlugin($assignment->getProblem()->getPlugin()->getType(), Config::get('paths', 'plugins') . $assignment->getProblem()->getPlugin()->getMainfile(), $submissionsFolder . $file, false, $newSubmission->getId(), explode(';', $assignment->getProblem()->getConfig()));
        }
        // Run checking for plagiarism
        $similarityJar = Config::get('paths', 'similarity');
        if ($similarityJar != null && is_file($similarityJar)) {
            $arguments = "comparenew";
            // Get config file and autoloader file
            $paths = Config::get('paths');
            $vendorAutoload = $paths['composerAutoload'];
            $java = Config::get('bin', 'java');
            $javaArguments = Config::get('bin', 'javaArguments');
            $pathToCore = Config::get('paths', 'core');
            // This code will be passed, shell-escaped to the PHP CLI
            $launchCode = <<<LAUNCH_CODE
require_once '{$vendorAutoload}';
chdir("{$pathToCore}");
`"{$java}" {$javaArguments} -Dfile.encoding=UTF-8 -jar "{$similarityJar}" {$arguments}`;
LAUNCH_CODE;
            ShellUtils::phpExecInBackground(Config::get('bin', 'phpCli'), $launchCode);
        }
    }
 protected function body()
 {
     // Validate input.
     $inputs = array('group' => 'isIndex', 'problem' => 'isIndex', 'deadline' => 'isDate', 'reward' => 'isNonNegativeInt');
     if (!$this->isInputValid($inputs)) {
         return false;
     }
     // Load input
     $id = $this->getParams('id');
     $group = $this->getParams('group');
     $problem = $this->getParams('problem');
     $deadline = $this->getParams('deadline');
     $reward = $this->getParams('reward');
     // Adjust input
     $deadline = $deadline . ' 23:59:59';
     // Load from database
     /**
      * @var $groupEntity \Group
      * @var $assignmentEntity \Assignment
      * @var $problemEntity \Problem
      */
     $groupEntity = Repositories::getEntityManager()->find('Group', $group);
     $problemEntity = Repositories::getEntityManager()->find('Problem', $problem);
     if ($groupEntity === null || $problemEntity === null) {
         return $this->stop('Group or problem does not exist.', 'Assignment cannot be edited.');
     }
     // Authenticate
     $user = User::instance();
     if (!$user->hasPrivileges(User::groupsManageAll) && (!$user->hasPrivileges(User::groupsManageOwn) || $groupEntity->getOwner()->getId() !== $user->getId())) {
         return $this->stop(Language::get(StringID::InsufficientPrivileges));
     }
     // Already exists?
     if ($id !== null && $id !== '') {
         $assignmentEntity = Repositories::getEntityManager()->find('Assignment', $id);
         $assignmentEntity->setDeadline(\DateTime::createFromFormat("Y-m-d H:i:s", $deadline));
         $assignmentEntity->setReward($reward);
         Repositories::getEntityManager()->persist($assignmentEntity);
         Repositories::getEntityManager()->flush($assignmentEntity);
     } else {
         // Verify integrity
         if ($problemEntity->getLecture()->getId() !== $groupEntity->getLecture()->getId()) {
             return $this->stop('You are adding an assignment for problem belonging to lecture X to a group that belongs to lecture Y. This is not possible.');
         }
         // Create new
         $assignmentEntity = new \Assignment();
         $assignmentEntity->setGroup($groupEntity);
         $assignmentEntity->setProblem($problemEntity);
         $assignmentEntity->setDeadline(\DateTime::createFromFormat("Y-m-d H:i:s", $deadline));
         $assignmentEntity->setReward($reward);
         Repositories::getEntityManager()->persist($assignmentEntity);
         Repositories::getEntityManager()->flush($assignmentEntity);
         // Send e-mail
         /**
          * @var $subscription \Subscription
          */
         $query = Repositories::getEntityManager()->createQuery('SELECT s, u FROM Subscription s JOIN s.user u  WHERE s.group = :group');
         $query->setParameter('group', $groupEntity);
         $subscriptions = $query->getResult();
         foreach ($subscriptions as $subscription) {
             if (!$subscription->getUser()->getSendEmailOnNewAssignment()) {
                 continue;
             }
             $to = $subscription->getUser()->getEmail();
             $email = file_get_contents(Config::get("paths", "newAssignmentEmail"));
             $email = str_replace("%{Problem}", $problemEntity->getName(), $email);
             $email = str_replace("%{Deadline}", $deadline, $email);
             $email = str_replace("%{Group}", $groupEntity->getName(), $email);
             $email = str_replace("%{Link}", Config::getHttpRoot() . "#studentAssignments#" . $assignmentEntity->getId(), $email);
             $email = str_replace("%{Date}", date("Y-m-d H:i:s"), $email);
             $lines = explode("\n", $email);
             $subject = $lines[0];
             // The first line is subject.
             $text = preg_replace('/^.*\\n/', '', $email);
             // Everything except the first line.
             if (!Core::sendEmail($to, trim($subject), $text)) {
                 Core::logError(Error::create(Error::levelWarning, "E-mail could not be sent to {$to}."));
             }
         }
     }
     return true;
 }
Example #22
0
 /**
  * Checks whether user has at least one the given sets of privileges [stopping].
  * @param int $privileges sets of privileges to check against
  * @return bool true if he has
  * @see User::hasPrivileges()
  */
 protected final function userHasPrivileges(...$privileges)
 {
     $reason = "";
     if (!User::instance()->isSessionValid($reason)) {
         return $this->stop(Language::get(StringID::SessionInvalidated));
     }
     if (!User::instance()->hasPrivileges(...$privileges)) {
         return $this->stop(Language::get(StringID::InsufficientPrivileges));
     }
     return true;
 }
Example #23
0
 /**
  * Creates and initializes logger instance if it doesn't exist yet.
  */
 protected static function initLogger()
 {
     if (!self::$logger) {
         $user = User::instance();
         $username = $user->isLogged() ? $user->getName() : '[not logged in]';
         $remoteAddr = $_SERVER['REMOTE_ADDR'] != '::1' ? $_SERVER['REMOTE_ADDR'] : '[localhost]';
         $remoteHost = isset($_SERVER['REMOTE_HOST']) ? $_SERVER['REMOTE_ADDR'] : '[no lookup]';
         self::$logger = Logger::create(Config::get('paths', 'log'))->setMaxFileSize(2097152)->setMaxFileCount(5)->setEntrySeparator("\n\n")->setLineSeparator("\n")->setDatetimeFormat('Y-m-d H:i:s')->setHeader("User " . $username . ", IP " . $remoteAddr . ", host " . $remoteHost . ", request " . self::$request);
     }
 }
Example #24
0
 /**
  * Runs this script.
  * @return bool Is it successful?
  * @throws \Exception Should never occur.
  */
 protected function body()
 {
     $inputs = array('name' => array('isAlphaNumeric', 'hasLength' => array('min_length' => Constants::UsernameMinLength, 'max_length' => Constants::UsernameMaxLength)), 'realname' => array('isNotEmpty', 'isName'), 'email' => 'isEmail', 'pass' => array(), 'repass' => array());
     if (!$this->isInputValid($inputs)) {
         return false;
     }
     // Extract input data
     $username = strtolower($this->getParams('name'));
     $realname = $this->getParams('realname');
     $email = $this->getParams('email');
     $pass = $this->getParams('pass');
     $repass = $this->getParams('repass');
     $id = $this->getParams('id');
     $type = $this->getParams('type');
     $user = null;
     $isIdSet = $id !== null && $id !== '';
     $isTypeSet = $type !== null && $type !== '';
     // Extract database data
     if ($id) {
         $user = Repositories::findEntity(Repositories::User, $id);
     }
     $userExists = $user != null;
     $sameNameUserExists = count(Repositories::getRepository(Repositories::User)->findBy(['name' => $username])) > 0;
     // Custom verification of input data
     if ($pass !== $repass) {
         return $this->death(StringID::InvalidInput);
     }
     if ($userExists) {
         if ((strlen($pass) < Constants::PasswordMinLength || strlen($pass) > Constants::PasswordMaxLength) && $pass !== "") {
             return $this->death(StringID::InvalidInput);
         }
     } else {
         // A new user must have full password
         if (strlen($pass) < Constants::PasswordMinLength || strlen($pass) > Constants::PasswordMaxLength) {
             return $this->death(StringID::InvalidInput);
         }
     }
     $code = '';
     $unhashedPass = $pass;
     $pass = Security::hash($pass, Security::HASHTYPE_PHPASS);
     $canAddUsers = User::instance()->hasPrivileges(User::usersAdd);
     $canEditUsers = User::instance()->hasPrivileges(User::usersManage);
     $isEditingSelf = $id == User::instance()->getId();
     // This must not be a strict comparison.
     /**
      * @var $user \User
      */
     if (!$userExists && !$sameNameUserExists) {
         if ($this->getParams('fromRegistrationForm')) {
             if ($type != Repositories::StudentUserType) {
                 return $this->death(StringID::InsufficientPrivileges);
             }
             $code = md5(uniqid(mt_rand(), true));
             $emailText = file_get_contents(Config::get("paths", "registrationEmail"));
             $emailText = str_replace("%{Username}", $username, $emailText);
             $emailText = str_replace("%{ActivationCode}", $code, $emailText);
             $emailText = str_replace("%{Link}", Config::getHttpRoot() . "#activate", $emailText);
             $lines = explode("\n", $emailText);
             $subject = $lines[0];
             // The first line is subject.
             $text = preg_replace('/^.*\\n/', '', $emailText);
             // Everything except the first line.
             $returnCode = Core::sendEmail($email, $subject, $text);
             if (!$returnCode) {
                 return $this->stop(ErrorCode::mail, 'user registration failed', 'email could not be sent');
             }
         } else {
             if (!$canAddUsers) {
                 return $this->death(StringID::InsufficientPrivileges);
             }
         }
         $user = new \User();
         /** @var \UserType $typeEntity */
         $typeEntity = Repositories::findEntity(Repositories::UserType, $type);
         $user->setType($typeEntity);
         $user->setPass($pass);
         $user->setName($username);
         $user->setEmail($email);
         $user->setActivationCode($code);
         $user->setEncryptionType(Security::HASHTYPE_PHPASS);
         $user->setRealName($realname);
         Repositories::persistAndFlush($user);
     } elseif ($isIdSet) {
         if (!$canEditUsers && ($isTypeSet || !$isEditingSelf)) {
             return $this->stop(ErrorCode::lowPrivileges, 'cannot edit data of users other than yourself');
         }
         $type = $isTypeSet ? $type : $user->getType()->getId();
         /** @var \UserType $typeEntity */
         $typeEntity = Repositories::findEntity(Repositories::UserType, $type);
         if ($unhashedPass) {
             $user->setPass($pass);
             $user->setEncryptionType(Security::HASHTYPE_PHPASS);
         }
         $user->setType($typeEntity);
         $user->setEmail($email);
         $user->setActivationCode('');
         $user->setRealName($realname);
         Repositories::persistAndFlush($user);
     } else {
         return $this->death(StringID::UserNameExists);
     }
     return true;
 }