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;
 }
Example #2
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;
 }
 protected function generateAttachmentHtml($data)
 {
     echo '<span class="attachmentLabel">[attachment: ', $data['type'], ']</span>';
     switch ($data['type']) {
         case 'code':
             echo '<pre class="attachment">', htmlspecialchars($this->getAttachmentContents($data['file'])), '</pre>';
             break;
         case 'image':
             $httpRoot = Config::getHttpRoot();
             echo '<img class="attachment" src="', $httpRoot, '/core/request.php', '?action=DownloadAttachment&id=', $data['id'], '"/>';
             break;
         default:
             echo '<span class="attachment">', $this->getAttachmentContents($data['file']), '</span>';
     }
 }
 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;
 }