Example #1
0
 /**
  * Returns the web address of the running application.
  *
  * For example, this might return http://xmlcheck.projekty.ms.mff.cuni.cz/
  * @return string the web address of the running instance of XMLCheck
  * @throws Exception when Config::init was not called before
  */
 public static function getHttpRoot()
 {
     if (!self::$instance) {
         throw new Exception("Configuration is not initialized");
     }
     return self::$instance->_get("roots", "http");
 }
 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;
 }
 protected function body()
 {
     if (!$this->userHasPrivileges(User::pluginsAdd)) {
         return false;
     }
     $inputs = array('name' => array('isName', 'isNotEmpty'));
     if (!$this->isInputValid($inputs)) {
         return false;
     }
     $name = $this->getParams('name');
     $existingPluginsWithSameName = Repositories::getRepository(Repositories::Plugin)->findBy(['name' => $name]);
     if (count($existingPluginsWithSameName) > 0) {
         return $this->death(StringID::PluginNameAlreadyExists);
     }
     $pluginFile = $this->getUploadedFile('plugin');
     if (!$pluginFile) {
         return false;
     }
     $pluginFolder = Config::get('paths', 'plugins') . $name;
     if (file_exists($pluginFolder)) {
         return $this->death(StringID::PluginFolderAlreadyExists);
     }
     if (!Filesystem::createDir($pluginFolder)) {
         return $this->death(StringID::FileSystemError);
     }
     if (!Compression::unzip($pluginFile, $pluginFolder)) {
         $this->death(StringID::UnzipUnsuccessful);
         goto cleanup_error;
     }
     $manifestFile = $pluginFolder . DIRECTORY_SEPARATOR . 'manifest.xml';
     $manifest = null;
     if (!($manifest = $this->parsePluginManifest($manifestFile))) {
         $this->death(StringID::BadlyFormedPlugin);
         goto cleanup_error;
     }
     if (!file_exists($pluginFolder . DIRECTORY_SEPARATOR . $manifest['mainFile'])) {
         $this->death(StringID::BadlyFormedPlugin);
         goto cleanup_error;
     }
     $plugin = new \Plugin();
     $plugin->setIdentifier($manifest['identifier']);
     $plugin->setDescription($manifest['description']);
     $plugin->setConfig($manifest['arguments']);
     $plugin->setMainfile($name . '/' . $manifest['mainFile']);
     $plugin->setName($name);
     $plugin->setType($manifest['type']);
     Repositories::persistAndFlush($plugin);
     Filesystem::removeFile($pluginFile);
     return true;
     cleanup_error:
     Filesystem::removeDir($pluginFolder);
     Filesystem::removeFile($pluginFile);
     return false;
 }
 public function launch($file, array $arguments, &$output)
 {
     /// Supplied file path must point to JAR archive with defined main class.
     if (!file_exists($file)) {
         return 'File ' . $file . ' doesn\'t exist or cannot be read';
     }
     $java = Config::get('bin', 'java');
     $arguments = ShellUtils::makeShellArguments($arguments);
     $output = `"{$java}" -Dfile.encoding=UTF-8 -jar "{$file}" {$arguments}`;
     return false;
 }
 protected function body()
 {
     $inputs = array('lecture' => 'isIndex', 'name' => array('isName', 'isNotEmpty'), 'type' => array('isEnum' => array('text', 'code', 'image')));
     if (!$this->isInputValid($inputs)) {
         return false;
     }
     $lectureId = $this->getParams('lecture');
     /** @var \Lecture $lecture */
     $lecture = Repositories::findEntity(Repositories::Lecture, $lectureId);
     $name = $this->getParams('name');
     $type = $this->getParams('type');
     $id = $this->getParams('id');
     $isIdSet = $id !== null && $id !== '';
     $originalName = $this->getUploadedFileName('file');
     if (!$originalName) {
         return false;
     }
     $extensionStart = strrpos($originalName, '.');
     $extension = $extensionStart === false ? '' : substr($originalName, strrpos($originalName, '.'));
     $attachmentFolder = Config::get('paths', 'attachments');
     $filename = $id . '_' . $name . $extension;
     if (!$this->checkTestGenerationPrivileges($lecture)) {
         return $this->death(StringID::InsufficientPrivileges);
     }
     /**
      * @var $attachment \Attachment
      */
     $attachment = null;
     if (!$this->saveUploadedFile('file', $attachmentFolder . $filename)) {
         return $this->death(StringID::InsufficientPrivileges);
     }
     /** @var \Attachment[] $attachmentsWithThisName */
     $attachmentsWithThisName = Repositories::getRepository(Repositories::Attachment)->findBy(['lecture' => $lectureId, 'name' => $name]);
     if ($isIdSet) {
         $attachment = Repositories::findEntity(Repositories::Attachment, $id);
         if (count($attachmentsWithThisName) > 0) {
             if ($attachmentsWithThisName[0]->getId() !== $attachment->getId()) {
                 return $this->death(StringID::AttachmentExists);
             }
         }
     } else {
         if (count($attachmentsWithThisName) > 0) {
             return $this->death(StringID::AttachmentExists);
         }
         $attachment = new \Attachment();
     }
     $attachment->setType($type);
     $attachment->setLecture($lecture);
     $attachment->setName($name);
     $attachment->setFile($filename);
     Repositories::persistAndFlush($attachment);
     return true;
 }
 protected function body()
 {
     $plugins = Repositories::getRepository(Repositories::Plugin)->findAll();
     $errors = [];
     foreach ($plugins as $plugin) {
         /** @var $plugin \Plugin */
         $dbPhpFile = $plugin->getMainfile();
         $dbDescription = $plugin->getDescription();
         $dbIdentifier = $plugin->getIdentifier();
         $pluginDirectory = $this->getMainDirectory($dbPhpFile);
         if ($pluginDirectory === false) {
             $errors[] = $plugin->getName() . ": " . Language::get(StringID::ReloadManifests_InvalidFolder);
             continue;
         }
         $manifestFile = Filesystem::combinePaths(Config::get('paths', 'plugins'), $pluginDirectory, "manifest.xml");
         $xml = new \DOMDocument();
         $success = $xml->load(realpath($manifestFile));
         if ($success === false) {
             $errors[] = $plugin->getName() . ": " . Language::get(StringID::ReloadManifests_MalformedXmlOrFileMissing);
             continue;
         }
         $fileDescription = $xml->getElementsByTagName('description')->item(0);
         $fileArguments = $xml->getElementsByTagName('argument');
         $fileIdentifier = $xml->getElementsByTagName('identifier')->item(0);
         $fileArgumentsArray = [];
         for ($i = 0; $i < $fileArguments->length; $i++) {
             $fileArgumentsArray[] = trim($fileArguments->item($i)->nodeValue);
         }
         $fileArgumentsString = implode(';', $fileArgumentsArray);
         if ($dbDescription !== trim($fileDescription->nodeValue)) {
             $errors[] = $plugin->getName() . ": " . Language::get(StringID::ReloadManifests_DescriptionMismatch);
             $plugin->setDescription(trim($fileDescription->nodeValue));
             Repositories::persist($plugin);
         }
         if ($dbIdentifier !== trim($fileIdentifier->nodeValue)) {
             $errors[] = $plugin->getName() . ": " . Language::get(StringID::ReloadManifests_IdentifierMismatch);
             $plugin->setIdentifier(trim($fileIdentifier->nodeValue));
             Repositories::persist($plugin);
         }
         if ($plugin->getConfig() !== $fileArgumentsString) {
             $errors[] = $plugin->getName() . ": " . Language::get(StringID::ReloadManifests_ArgumentsMismatch);
             $plugin->setConfig($fileArgumentsString);
             Repositories::persist($plugin);
         }
     }
     Repositories::flushAll();
     if (count($errors) === 0) {
         $this->addOutput("text", Language::get(StringID::ReloadManifests_DatabaseCorrespondsToManifests));
     } else {
         $this->addOutput("text", implode('<br>', $errors));
     }
     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 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->isInputValid(array('id' => 'isIndex'))) {
         return false;
     }
     $id = $this->getParams('id');
     /**
      * @var $attachment \Attachment
      */
     $attachment = Repositories::findEntity(Repositories::Attachment, $id);
     $file = $attachment->getFile();
     $lecture = $attachment->getLecture();
     if (!$this->authorizedToManageLecture($lecture)) {
         return $this->death(StringID::InsufficientPrivileges);
     }
     $this->doNotAttach();
     $this->setOutput(Config::get('paths', 'attachments') . $file);
     return true;
 }
 protected function body()
 {
     if (!$this->isInputValid(array('id' => 'isIndex'))) {
         return false;
     }
     $id = $this->getParams('id');
     /**
      * @var $attachment \Attachment
      */
     $attachment = Repositories::findEntity(Repositories::Attachment, $id);
     if (!$this->authorizedToManageLecture($attachment->getLecture())) {
         return false;
     }
     $folder = Config::get('paths', 'attachments');
     $file = $attachment->getFile();
     RemovalManager::deleteAttachmentById($id);
     Filesystem::removeFile($folder . $file);
     return true;
 }
 protected function body()
 {
     if (!$this->userHasPrivileges(User::pluginsRemove)) {
         return false;
     }
     if (!$this->isInputValid(array('id' => 'isIndex'))) {
         return false;
     }
     $id = $this->getParams('id');
     /**
      * @var $plugin \Plugin
      */
     $plugin = Repositories::findEntity(Repositories::Plugin, $id);
     $pluginFolder = Filesystem::combinePaths(Config::get('paths', 'plugins'), $plugin->getName());
     if (!Filesystem::removeDir($pluginFolder)) {
         return $this->death(StringID::FileSystemError);
     }
     RemovalManager::deletePluginById($id);
     return true;
 }
 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;
 }
 /**
  * Connects to the database using configuration from the config files and saves the entity manager in a private
  * static local variable. This function is called the first time getEntityManager is called.
  *
  * As a prerequisite, you must call Config::init() before calling this method.
  * @throws \Doctrine\DBAL\DBALException When the database connection fails.
  * @throws \Doctrine\ORM\ORMException When there is an error in the entity classes.
  * @throws \Exception When there is a different error.
  */
 private static function connectToDatabase()
 {
     $isDevMode = true;
     $connection = array('driver' => 'pdo_mysql', 'user' => Config::get('database', 'user'), 'password' => Config::get('database', 'pass'), 'dbname' => Config::get('database', 'db'), 'host' => Config::get('database', 'host'), 'charset' => 'utf8');
     $paths = array(__DIR__ . "/../doctrine");
     $config = Setup::createConfiguration($isDevMode);
     $driver = new AnnotationDriver(new AnnotationReader(), $paths);
     AnnotationRegistry::registerLoader('class_exists');
     $config->setMetadataDriverImpl($driver);
     $entityManager = EntityManager::create($connection, $config);
     $platform = $entityManager->getConnection()->getDatabasePlatform();
     $platform->registerDoctrineTypeMapping('enum', 'string');
     self::$entityManager = $entityManager;
 }
Example #14
0
 public function isSessionValid(&$reason)
 {
     if ($this->data !== null) {
         if ($this->data['timeout'] < time()) {
             $this->logout();
             $reason = "You have been inactive for a long time. <b>Logout, then log in again.</b>";
             return false;
         } elseif (!array_key_exists("applicationVersion", $this->data) || $this->data['applicationVersion'] !== implode('.', Config::get('version'))) {
             // User is using an out-of-date application version. He must logout and login again.
             $this->logout();
             $reason = "Application was upgraded to a new version. <b>Logout, refresh the page, then log in again.</b>";
             return false;
         }
         return true;
     }
     // The user is not logged in at all, but this is not because the session is invalid.
     $reason = "You are no longer logged in. Perhaps you were inactive for too long or the server was upgraded. <b>Logout, refresh the page, then log in again.</b>";
     return false;
 }
<?php

require_once __DIR__ . "/../../vendor/autoload.php";
\asm\core\Config::init(__DIR__ . "/../config.ini", __DIR__ . "/../internal.ini");
return \Doctrine\ORM\Tools\Console\ConsoleRunner::createHelperSet(\asm\core\Repositories::getEntityManager());
 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>';
     }
 }
Example #17
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);
    /**
     * 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);
        }
    }
Example #19
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);
     }
 }
<?php

namespace asm\unittests;

use asm\core\Config;
use asm\utils\Filesystem;
$xmlcheckRoot = "../../www";
require_once $xmlcheckRoot . "/vendor/autoload.php";
Config::init(Filesystem::combinePaths($xmlcheckRoot, "core/config.ini"), Filesystem::combinePaths($xmlcheckRoot, "core/internal.ini"));
class CheckerRunner
{
    public static $xmlCheckRoot = "../../www";
    public static $testCasesRoot = "../plugins/cases";
    /**
     * @param $checker mixed A class with a run() method
     * @param $zipFile string The path to the zip file with the test case
     * @param $arguments array Configuration of the plugin
     * @return \asm\plugin\PluginResponse
     */
    public static function runChecker($checker, $zipFile, $arguments)
    {
        $testResult = $checker->run(array_merge([$zipFile], $arguments));
        return $testResult;
    }
    /**
     * @param $testCase PHPUnit_Framework_TestCase
     * @param $result \asm\plugin\PluginResponse
     * @param $fulfillment int
     * @param $details string
     */
    public static function assert($testCase, $filename, $result, $fulfillment = null, $details = "")
 /**
  * Deletes test with supplied ID (with input & output files).
  * @param int $id test ID
  * @return array error properties provided by removalError() or retrievalError(),
  * or false in case of success
  */
 public static function deleteTestById($id)
 {
     /**
      * @var $test \PluginTest
      */
     $test = Repositories::findEntity(Repositories::PluginTest, $id);
     $testFolder = Config::get('paths', 'tests');
     // Delete input solution file
     if (is_file(Filesystem::combinePaths($testFolder, $test->getInput()))) {
         Filesystem::removeFile(Filesystem::combinePaths($testFolder, $test->getInput()));
     }
     // Delete plugin test output
     if (is_file(Filesystem::combinePaths($testFolder, $test->getOutput()))) {
         Filesystem::removeFile(Filesystem::combinePaths($testFolder, $test->getOutput()));
     }
     Repositories::remove($test);
     return false;
 }
Example #22
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;
 }
 public function testNonExistingThrowsException()
 {
     $this->setExpectedException("\\Exception");
     \asm\core\Config::init("myconfig2.ini");
 }