Allocate submissions as requested by user

@return workshop_allocation_result
178886
public function init() {
        global $PAGE;

        $mode = optional_param('mode', 'display', PARAM_ALPHA);
        $perpage = optional_param('perpage', null, PARAM_INT);

        if ($perpage and $perpage > 0 and $perpage <= 1000) {
            require_sesskey();
            set_user_preference('workshopallocation_manual_perpage', $perpage);
            redirect($PAGE->url);
        }

        $result = new workshop_allocation_result($this);

        switch ($mode) {
        case 'new':
            if (!confirm_sesskey()) {
                throw new moodle_exception('confirmsesskeybad');
            }
            $reviewerid = required_param('by', PARAM_INT);
            $authorid   = required_param('of', PARAM_INT);
            $m          = array();  // message object to be passed to the next page
            $submission = $this->workshop->get_submission_by_author($authorid);
            if (!$submission) {
                // nothing submitted by the given user
                $m[] = self::MSG_NOSUBMISSION;
                $m[] = $authorid;

            } else {
                // ok, we have the submission
                $res = $this->workshop->add_allocation($submission, $reviewerid);
                if ($res == workshop::ALLOCATION_EXISTS) {
                    $m[] = self::MSG_EXISTS;
                    $m[] = $submission->authorid;
                    $m[] = $reviewerid;
                } else {
                    $m[] = self::MSG_ADDED;
                    $m[] = $submission->authorid;
                    $m[] = $reviewerid;
                }
            }
            $m = implode('-', $m);  // serialize message object to be passed via URL
            redirect($PAGE->url->out(false, array('m' => $m)));
            break;
        case 'del':
            if (!confirm_sesskey()) {
                throw new moodle_exception('confirmsesskeybad');
            }
            $assessmentid   = required_param('what', PARAM_INT);
            $confirmed      = optional_param('confirm', 0, PARAM_INT);
            $assessment     = $this->workshop->get_assessment_by_id($assessmentid);
            if ($assessment) {
                if (!$confirmed) {
                    $m[] = self::MSG_CONFIRM_DEL;
                    $m[] = $assessment->id;
                    $m[] = $assessment->authorid;
                    $m[] = $assessment->reviewerid;
                    if (is_null($assessment->grade)) {
                        $m[] = 0;
                    } else {
                        $m[] = 1;
                    }
                } else {
                    if($this->workshop->delete_assessment($assessment->id)) {
                        $m[] = self::MSG_DELETED;
                        $m[] = $assessment->authorid;
                        $m[] = $assessment->reviewerid;
                    } else {
                        $m[] = self::MSG_DELETE_ERROR;
                        $m[] = $assessment->authorid;
                        $m[] = $assessment->reviewerid;
                    }
                }
                $m = implode('-', $m);  // serialize message object to be passed via URL
                redirect($PAGE->url->out(false, array('m' => $m)));
            }
            break;
        }

        $result->set_status(workshop_allocation_result::STATUS_VOID);
        return $result;
    }
667966
protected function render_workshop_allocation_result(workshop_allocation_result $result) {
        global $CFG;

        $status = $result->get_status();

        if (is_null($status) or $status == workshop_allocation_result::STATUS_VOID) {
            debugging('Attempt to render workshop_allocation_result with empty status', DEBUG_DEVELOPER);
            return '';
        }

        switch ($status) {
        case workshop_allocation_result::STATUS_FAILED:
            if ($message = $result->get_message()) {
                $message = new workshop_message($message, workshop_message::TYPE_ERROR);
            } else {
                $message = new workshop_message(get_string('allocationerror', 'workshop'), workshop_message::TYPE_ERROR);
            }
            break;

        case workshop_allocation_result::STATUS_CONFIGURED:
            if ($message = $result->get_message()) {
                $message = new workshop_message($message, workshop_message::TYPE_INFO);
            } else {
                $message = new workshop_message(get_string('allocationconfigured', 'workshop'), workshop_message::TYPE_INFO);
            }
            break;

        case workshop_allocation_result::STATUS_EXECUTED:
            if ($message = $result->get_message()) {
                $message = new workshop_message($message, workshop_message::TYPE_OK);
            } else {
                $message = new workshop_message(get_string('allocationdone', 'workshop'), workshop_message::TYPE_OK);
            }
            break;

        default:
            throw new coding_exception('Unknown allocation result status', $status);
        }

        // start with the message
        $o = $this->render($message);

        // display the details about the process if available
        $logs = $result->get_logs();
        if (is_array($logs) and !empty($logs)) {
            $o .= html_writer::start_tag('ul', array('class' => 'allocation-init-results'));
            foreach ($logs as $log) {
                if ($log->type == 'debug' and !$CFG->debugdeveloper) {
                    // display allocation debugging messages for developers only
                    continue;
                }
                $class = $log->type;
                if ($log->indent) {
                    $class .= ' indent';
                }
                $o .= html_writer::tag('li', $log->message, array('class' => $class)).PHP_EOL;
            }
            $o .= html_writer::end_tag('ul');
        }

        return $o;
    }
1035348
public static function installed_allocators() {
        $installed = core_component::get_plugin_list('workshopallocation');
        $forms = array();
        foreach ($installed as $allocation => $allocationpath) {
            if (file_exists($allocationpath . '/lib.php')) {
                $forms[$allocation] = get_string('pluginname', 'workshopallocation_' . $allocation);
            }
        }
        // usability - make sure that manual allocation appears the first
        if (isset($forms['manual'])) {
            $m = array('manual' => $forms['manual']);
            unset($forms['manual']);
            $forms = array_merge($m, $forms);
        }
        return $forms;
    }
1315869
public static function save_submission_parameters() {
        global $CFG;
        $instance = new assign(null, null, null);
        $pluginsubmissionparams = array();

        foreach ($instance->get_submission_plugins() as $plugin) {
            if ($plugin->is_visible()) {
                $pluginparams = $plugin->get_external_parameters();
                if (!empty($pluginparams)) {
                    $pluginsubmissionparams = array_merge($pluginsubmissionparams, $pluginparams);
                }
            }
        }

        return new external_function_parameters(
            array(
                'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
                'plugindata' => new external_single_structure(
                    $pluginsubmissionparams
                )
            )
        );
    }
1013663
private function setLimit()
    {
        if (isset($this->requestParams['start']) && -1 != $this->requestParams['length']) {
            $this->qb->setFirstResult($this->requestParams['start'])->setMaxResults($this->requestParams['length']);
        }

        return $this;
    }
1317503
public function populate_submissions_and_grades() {
        global $DB;

        if (empty($this->get_userids())) {
            throw new \coding_exception('Please use set_userids() before calling this method.');
        }

        list($sql, $params) = $DB->get_in_or_equal($this->get_userids(), SQL_PARAMS_NAMED);
        $params['assign'] = $this->get_assign()->get_instance()->id;
        $this->submissions = $DB->get_records_select('assign_submission', "assignment = :assign AND userid $sql", $params);
        $this->grades = $DB->get_records_select('assign_grades', "assignment = :assign AND userid $sql", $params);
    }
1211109
def allocate(self):
        """"""
        disk_path = self.provider_image

        self._hypervisor = libvirt.open(
            self.configuration.get('hypervisor', 'vbox:///session'))

        self._domain = domain_create(self._hypervisor, self.identifier,
                                     self.configuration['domain'], disk_path)
11695
private function GrantCreateLayout()
    {
        $groups = $this->GetGroups();
        foreach ($groups as $group)
        {
            if ($group->GetCreateLayouts())
            {
                return GrantResult::Allowed();
            }
        }
        return GrantResult::NoAccess();
    }
267745
protected function createAssignment()
    {
        $url = config('forge-publish.url') . config('forge-publish.store_assignment_uri');
        try {
            $response = $this->http->post($url, [
                'form_params' => [
                    'name' => $this->assignmentName,
                    'repository_uri' => $this->repository_uri,
                    'repository_type' => $this->repository_type,
                    'forge_site' => $this->forge_site,
                    'forge_server' => $this->forge_server
                ],
                'headers' => [
                    'X-Requested-With' => 'XMLHttpRequest',
                    'Authorization' => 'Bearer ' . fp_env('ACACHA_FORGE_ACCESS_TOKEN')
                ]
            ]);
        } catch (\Exception $e) {
            $this->error('And error occurs connecting to the api url: ' . $url);
            $this->error('Status code: ' . $e->getResponse()->getStatusCode() . ' | Reason : ' . $e->getResponse()->getReasonPhrase());
            return;
        }
        $assignment = json_decode((string) $response->getBody());
        $this->addValueToEnv('ACACHA_FORGE_ASSIGNMENT', $assignment->id);
        return $assignment;
    }
50825
public function get_assign_perpage() {
        $perpage = (int) get_user_preferences('assign_perpage', 10);
        $adminconfig = $this->get_admin_config();
        $maxperpage = -1;
        if (isset($adminconfig->maxperpage)) {
            $maxperpage = $adminconfig->maxperpage;
        }
        if (isset($maxperpage) &&
            $maxperpage != -1 &&
            ($perpage == -1 || $perpage > $maxperpage)) {
            $perpage = $maxperpage;
        }
        return $perpage;
    }
467824
public static function get_workshop_access_information($workshopid) {
        global $USER;

        $params = self::validate_parameters(self::get_workshop_access_information_parameters(), array('workshopid' => $workshopid));

        list($workshop, $course, $cm, $context) = self::validate_workshop($params['workshopid']);

        $result = array();
        // Return all the available capabilities.
        $capabilities = load_capability_def('mod_workshop');
        foreach ($capabilities as $capname => $capdata) {
            // Get fields like cansubmit so it is consistent with the access_information function implemented in other modules.
            $field = 'can' . str_replace('mod/workshop:', '', $capname);
            $result[$field] = has_capability($capname, $context);
        }

        // Now, specific features access information.
        $result['creatingsubmissionallowed'] = $workshop->creating_submission_allowed($USER->id);
        $result['modifyingsubmissionallowed'] = $workshop->modifying_submission_allowed($USER->id);
        $result['assessingallowed'] = $workshop->assessing_allowed($USER->id);
        $result['assessingexamplesallowed'] = $workshop->assessing_examples_allowed();
        if (is_null($result['assessingexamplesallowed'])) {
            $result['assessingexamplesallowed'] = false;
        }
        $result['examplesassessedbeforesubmission'] = $workshop->check_examples_assessed_before_submission($USER->id);
        list($result['examplesassessedbeforeassessment'], $code) = $workshop->check_examples_assessed_before_assessment($USER->id);

        $result['warnings'] = array();
        return $result;
    }
1122433
protected function process_assign_submission($data) {
        global $DB;

        if (!$this->includesubmission) {
            return;
        }

        $data = (object)$data;
        $oldid = $data->id;

        $data->assignment = $this->get_new_parentid('assign');

        if ($data->userid > 0) {
            $data->userid = $this->get_mappingid('user', $data->userid);
        }
        if (!empty($data->groupid)) {
            $data->groupid = $this->get_mappingid('group', $data->groupid);
            if (!$data->groupid) {
                // If the group does not exist, then the submission cannot be viewed and restoring can
                // violate the unique index on the submission table.
                return;
            }
        } else {
            $data->groupid = 0;
        }

        // We will correct this in set_latest_submission_field() once all submissions are restored.
        $data->latest = 0;

        $newitemid = $DB->insert_record('assign_submission', $data);

        // Note - the old contextid is required in order to be able to restore files stored in
        // sub plugin file areas attached to the submissionid.
        $this->set_mapping('submission', $oldid, $newitemid, false, null, $this->task->get_old_contextid());
    }
12875
function getUnstartedSubmissions($project) {
		$submissions = array ();
		$creatingSubmissions = $this->submissionService->findCreatingSubmissionsByProjectShortCode($project->shortCode)->return;
		foreach ($creatingSubmissions as &$creatingSubmission){
			$sub = new Submission();
			$sub->ticket = $creatingSubmission->ticket;
			$sub->name = $creatingSubmission->submissionInfo->name;
			array_push($submissions , $sub);
		}
		return $submissions;
	}
896478
public function allocator_instance($method) {
        global $CFG;    // because we require other libs here

        $allocationlib = __DIR__ . '/allocation/' . $method . '/lib.php';
        if (is_readable($allocationlib)) {
            require_once($allocationlib);
        } else {
            throw new coding_exception('Unable to find the allocation library ' . $allocationlib);
        }
        $classname = 'workshop_' . $method . '_allocator';
        return new $classname($this);
    }
1123784
public static function get_workshop_access_information_returns() {

        $structure = array(
            'creatingsubmissionallowed' => new external_value(PARAM_BOOL,
                'Is the given user allowed to create their submission?'),
            'modifyingsubmissionallowed' => new external_value(PARAM_BOOL,
                'Is the user allowed to modify his existing submission?'),
            'assessingallowed' => new external_value(PARAM_BOOL,
                'Is the user allowed to create/edit his assessments?'),
            'assessingexamplesallowed' => new external_value(PARAM_BOOL,
                'Are reviewers allowed to create/edit their assessments of the example submissions?.'),
            'examplesassessedbeforesubmission' => new external_value(PARAM_BOOL,
                'Whether the given user has assessed all his required examples before submission
                (always true if there are not examples to assess or not configured to check before submission).'),
            'examplesassessedbeforeassessment' => new external_value(PARAM_BOOL,
                'Whether the given user has assessed all his required examples before assessment
                (always true if there are not examples to assessor not configured to check before assessment).'),
            'warnings' => new external_warnings()
        );

        $capabilities = load_capability_def('mod_workshop');
        foreach ($capabilities as $capname => $capdata) {
            // Get fields like cansubmit so it is consistent with the access_information function implemented in other modules.
            $field = 'can' . str_replace('mod/workshop:', '', $capname);
            $structure[$field] = new external_value(PARAM_BOOL, 'Whether the user has the capability ' . $capname . ' allowed.');
        }

        return new external_single_structure($structure);
    }
710857
public function definition() {
        global $OUTPUT;

        $mform = $this->_form;
        $workshop = $this->_customdata['workshop'];
        $current = $this->_customdata['current'];

        if (!empty($workshop->submissionend)) {
            $strtimeexpected = workshop::timestamp_formats($workshop->submissionend);
        }

        if (!empty($current->timeallocated)) {
            $strtimeexecuted = workshop::timestamp_formats($current->timeallocated);
        }

        $mform->addElement('header', 'scheduledallocationsettings', get_string('scheduledallocationsettings', 'workshopallocation_scheduled'));
        $mform->addHelpButton('scheduledallocationsettings', 'scheduledallocationsettings', 'workshopallocation_scheduled');

        $mform->addElement('checkbox', 'enablescheduled', get_string('enablescheduled', 'workshopallocation_scheduled'), get_string('enablescheduledinfo', 'workshopallocation_scheduled'), 1);

        $mform->addElement('header', 'scheduledallocationinfo', get_string('currentstatus', 'workshopallocation_scheduled'));

        if ($current === false) {
            $mform->addElement('static', 'infostatus', get_string('currentstatusexecution', 'workshopallocation_scheduled'),
                get_string('resultdisabled', 'workshopallocation_scheduled').' '. $OUTPUT->pix_icon('i/invalid', ''));

        } else {
            if (!empty($current->timeallocated)) {
                $mform->addElement('static', 'infostatus', get_string('currentstatusexecution', 'workshopallocation_scheduled'),
                    get_string('currentstatusexecution1', 'workshopallocation_scheduled', $strtimeexecuted).' '.
                    $OUTPUT->pix_icon('i/valid', ''));

                if ($current->resultstatus == workshop_allocation_result::STATUS_EXECUTED) {
                    $strstatus = get_string('resultexecuted', 'workshopallocation_scheduled').' '.
                        $OUTPUT->pix_icon('i/valid', '');

                } else if ($current->resultstatus == workshop_allocation_result::STATUS_FAILED) {
                    $strstatus = get_string('resultfailed', 'workshopallocation_scheduled').' '.
                        $OUTPUT->pix_icon('i/invalid', '');

                } else {
                    $strstatus = get_string('resultvoid', 'workshopallocation_scheduled').' '.
                        $OUTPUT->pix_icon('i/invalid', '');

                }

                if (!empty($current->resultmessage)) {
                    $strstatus .= html_writer::empty_tag('br').$current->resultmessage; // yes, this is ugly. better solution suggestions are welcome.
                }
                $mform->addElement('static', 'inforesult', get_string('currentstatusresult', 'workshopallocation_scheduled'), $strstatus);

                if ($current->timeallocated < $workshop->submissionend) {
                    $mform->addElement('static', 'infoexpected', get_string('currentstatusnext', 'workshopallocation_scheduled'),
                        get_string('currentstatusexecution2', 'workshopallocation_scheduled', $strtimeexpected).' '.
                        $OUTPUT->pix_icon('i/caution', ''));
                    $mform->addHelpButton('infoexpected', 'currentstatusnext', 'workshopallocation_scheduled');
                } else {
                    $mform->addElement('checkbox', 'reenablescheduled', get_string('currentstatusreset', 'workshopallocation_scheduled'),
                       get_string('currentstatusresetinfo', 'workshopallocation_scheduled'));
                    $mform->addHelpButton('reenablescheduled', 'currentstatusreset', 'workshopallocation_scheduled');
                }

            } else if (empty($current->enabled)) {
                $mform->addElement('static', 'infostatus', get_string('currentstatusexecution', 'workshopallocation_scheduled'),
                    get_string('resultdisabled', 'workshopallocation_scheduled').' '.
                        $OUTPUT->pix_icon('i/invalid', ''));

            } else if ($workshop->phase != workshop::PHASE_SUBMISSION) {
                $mform->addElement('static', 'infostatus', get_string('currentstatusexecution', 'workshopallocation_scheduled'),
                    get_string('resultfailed', 'workshopallocation_scheduled').' '.
                    $OUTPUT->pix_icon('i/invalid', '') .
                    html_writer::empty_tag('br').
                    get_string('resultfailedphase', 'workshopallocation_scheduled'));

            } else if (empty($workshop->submissionend)) {
                $mform->addElement('static', 'infostatus', get_string('currentstatusexecution', 'workshopallocation_scheduled'),
                    get_string('resultfailed', 'workshopallocation_scheduled').' '.
                    $OUTPUT->pix_icon('i/invalid', '') .
                    html_writer::empty_tag('br').
                    get_string('resultfaileddeadline', 'workshopallocation_scheduled'));

            } else if ($workshop->submissionend < time()) {
                // next cron will execute it
                $mform->addElement('static', 'infostatus', get_string('currentstatusexecution', 'workshopallocation_scheduled'),
                    get_string('currentstatusexecution4', 'workshopallocation_scheduled').' '.
                    $OUTPUT->pix_icon('i/caution', ''));

            } else {
                $mform->addElement('static', 'infostatus', get_string('currentstatusexecution', 'workshopallocation_scheduled'),
                    get_string('currentstatusexecution3', 'workshopallocation_scheduled', $strtimeexpected).' '.
                    $OUTPUT->pix_icon('i/caution', ''));
            }
        }

        parent::definition();

        $mform->addHelpButton('randomallocationsettings', 'randomallocationsettings', 'workshopallocation_scheduled');
    }
1099906
public static function get_submission_status_returns() {
        return new external_single_structure(
            array(
                'gradingsummary' => new external_single_structure(
                    array(
                        'participantcount' => new external_value(PARAM_INT, 'Number of users who can submit.'),
                        'submissiondraftscount' => new external_value(PARAM_INT, 'Number of submissions in draft status.'),
                        'submissiondraftscount' => new external_value(PARAM_INT, 'Number of submissions in draft status.'),
                        'submissionsenabled' => new external_value(PARAM_BOOL, 'Whether submissions are enabled or not.'),
                        'submissionssubmittedcount' => new external_value(PARAM_INT, 'Number of submissions in submitted status.'),
                        'submissionsneedgradingcount' => new external_value(PARAM_INT, 'Number of submissions that need grading.'),
                        'warnofungroupedusers' => new external_value(PARAM_BOOL, 'Whether we need to warn people that there
                                                                        are users without groups.'),
                    ), 'Grading information.', VALUE_OPTIONAL
                ),
                'lastattempt' => new external_single_structure(
                    array(
                        'submission' => self::get_submission_structure(VALUE_OPTIONAL),
                        'teamsubmission' => self::get_submission_structure(VALUE_OPTIONAL),
                        'submissiongroup' => new external_value(PARAM_INT, 'The submission group id (for group submissions only).',
                                                                VALUE_OPTIONAL),
                        'submissiongroupmemberswhoneedtosubmit' => new external_multiple_structure(
                            new external_value(PARAM_INT, 'USER id.'),
                            'List of users who still need to submit (for group submissions only).',
                            VALUE_OPTIONAL
                        ),
                        'submissionsenabled' => new external_value(PARAM_BOOL, 'Whether submissions are enabled or not.'),
                        'locked' => new external_value(PARAM_BOOL, 'Whether new submissions are locked.'),
                        'graded' => new external_value(PARAM_BOOL, 'Whether the submission is graded.'),
                        'canedit' => new external_value(PARAM_BOOL, 'Whether the user can edit the current submission.'),
                        'caneditowner' => new external_value(PARAM_BOOL, 'Whether the owner of the submission can edit it.'),
                        'cansubmit' => new external_value(PARAM_BOOL, 'Whether the user can submit.'),
                        'extensionduedate' => new external_value(PARAM_INT, 'Extension due date.'),
                        'blindmarking' => new external_value(PARAM_BOOL, 'Whether blind marking is enabled.'),
                        'gradingstatus' => new external_value(PARAM_ALPHANUMEXT, 'Grading status.'),
                        'usergroups' => new external_multiple_structure(
                            new external_value(PARAM_INT, 'Group id.'), 'User groups in the course.'
                        ),
                    ), 'Last attempt information.', VALUE_OPTIONAL
                ),
                'feedback' => new external_single_structure(
                    array(
                        'grade' => self::get_grade_structure(VALUE_OPTIONAL),
                        'gradefordisplay' => new external_value(PARAM_RAW, 'Grade rendered into a format suitable for display.'),
                        'gradeddate' => new external_value(PARAM_INT, 'The date the user was graded.'),
                        'plugins' => new external_multiple_structure(self::get_plugin_structure(), 'Plugins info.', VALUE_OPTIONAL),
                    ), 'Feedback for the last attempt.', VALUE_OPTIONAL
                ),
                'previousattempts' => new external_multiple_structure(
                    new external_single_structure(
                        array(
                            'attemptnumber' => new external_value(PARAM_INT, 'Attempt number.'),
                            'submission' => self::get_submission_structure(VALUE_OPTIONAL),
                            'grade' => self::get_grade_structure(VALUE_OPTIONAL),
                            'feedbackplugins' => new external_multiple_structure(self::get_plugin_structure(), 'Feedback info.',
                                                                                    VALUE_OPTIONAL),
                        )
                    ), 'List all the previous attempts did by the user.', VALUE_OPTIONAL
                ),
                'warnings' => new external_warnings(),
            )
        );
    }