コード例 #1
0
 protected function body()
 {
     if (!$this->isInputSet(array('email'))) {
         return false;
     }
     $email = $this->getParams('email');
     $users = Repositories::getRepository(Repositories::User)->findBy(['email' => $email]);
     foreach ($users as $user) {
         /**
          * @var $user \User
          */
         // Generate reset link.
         $resetLink = StringUtils::randomString(60);
         $now = new \DateTime();
         $expiryDate = $now->add(new \DateInterval('P1D'));
         // Add in in the database (replacing any older reset links in the process)
         $user->setResetLink($resetLink);
         $user->setResetLinkExpiry($expiryDate);
         Repositories::persistAndFlush($user);
         // Send the e-mail
         $body = "A Password Reset Link was requested for your e-mail address on XMLCheck.\n\nYour name: " . $user->getRealName() . "\nYour login: "******"\n\nClick this link to reset your password: \n\n" . Config::get('roots', 'http') . "#resetPassword#" . $resetLink . "\n\nThe link will be valid for the next 24 hours, until " . $expiryDate->format("Y-m-d H:i:s") . ".";
         if (!Core::sendEmail($user->getEmail(), "[XMLCheck] Password Reset Link for '" . $user->getRealName() . "'", $body)) {
             return $this->death(StringID::MailError);
         }
     }
     $this->addOutput('count', count($users));
     return true;
 }
コード例 #2
0
 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;
 }
コード例 #3
0
<?php

use asm\core\Config, asm\core\Core, asm\utils\ErrorHandler, asm\core\UiResponse, asm\core\Error;
/**
 * @file
 * Handles core requests coming from UI.
 *
 * 1. Starts session.
 * 2. Starts the Composer autoloader.
 * 3. Loads configuration from the config.ini and internal.ini files.
 * 4. Activates the custom error handler.
 * 5. Calls Core::handleUiRequest with data from user.
 */
// Session is used to keep track of logged in user, and is used for file uploads.
session_start();
// Load up the Composer-generated autoloader. All PHP classes are loaded using this autoloader.
require_once __DIR__ . "/../vendor/autoload.php";
// Load configuration from the "config.ini" file.
Config::init(__DIR__ . '/config.ini', __DIR__ . '/internal.ini');
// If ever an exception occurs or a PHP error occurs, log it and send it to the user.
ErrorHandler::register();
ErrorHandler::bind(['asm\\core\\Core', 'logException']);
ErrorHandler::bind(function (Exception $e) {
    Core::sendUiResponse(UiResponse::create([], [Error::create(Error::levelFatal, $e->getMessage() . "[details: code " . $e->getCode() . ", file " . $e->getFile() . ", line " . $e->getLine() . ", trace: \n" . $e->getTraceAsString() . "]", \asm\core\lang\Language::get(\asm\core\lang\StringID::ServerSideRuntimeError))]));
});
// Process the AJAX request.
// Usually, the Javascript part of XML Check sends a POST request but in some special cases, a GET request is needed.
Core::handleUiRequest(empty($_POST) ? $_GET : $_POST, $_FILES);
コード例 #4
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;
 }
コード例 #5
0
 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;
 }
コード例 #6
0
 /**
  * Outputs supplied data along with stored errors to UI.
  * @param array $data data to output
  */
 protected final function outputData($data = array())
 {
     Core::sendUiResponse(UiResponse::create($data, $this->getErrors()));
 }
コード例 #7
0
    /**
     * 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);
        }
    }