Prepares renderable submission component

@param stdClass $record required by {@see workshop_submission}
@param bool $showauthor show the author-related information
@return workshop_submission
435310
public function prepare_submission(stdClass $record, $showauthor = false) {

        $submission         = new workshop_submission($this, $record, $showauthor);
        $submission->url    = $this->submission_url($record->id);

        return $submission;
    }
969720
protected function requestAuthor()
    {
        if (!empty($this->getComposerData()->authors)) {
            return $this->selectAuthors();
        }

        $nameQuestion = new Question('Please enter your name: ');
        $emailQuestion = new Question('Please enter your e-mail address: ');
        $this->getOutput()->writeln('');
        $this->getOutput()->writeln(
            '<info>Cannot determine the developer name ' .
            'from project\'s composer.json file.</info>'
        );
        $this->getOutput()->writeln(
            "<comment>To automatically set the developer's " .
            "name and e-mail and avoid entering it on every generate:* " .
            "commands set the authors entry on your project's " .
            "composer.json file.</comment>"
        );
        $authorName = $this->getQuestionHelper()->ask(
            $this->getInput(),
            $this->getOutput(),
            $nameQuestion
        );
        $authorEmail = $this->getQuestionHelper()->ask(
            $this->getInput(),
            $this->getOutput(),
            $emailQuestion
        );
        return compact('authorName', 'authorEmail');
    }
893563
public function get_author_from_stdclass(stdClass $record) : author_entity {
        return new author_entity(
            $record->id,
            $record->picture,
            $record->firstname,
            $record->lastname,
            fullname($record),
            $record->email,
            $record->middlename,
            $record->firstnamephonetic,
            $record->lastnamephonetic,
            $record->alternatename,
            $record->imagealt
        );
    }
517341
public function create(array $data, MembershipInterface $author, ModelInterface $category): PodiumResponse
    {
        /* @var $forumForm CategorisedFormInterface */
        $forumForm = $this->getForm();

        $forumForm->setAuthor($author);
        $forumForm->setCategory($category);

        if (!$forumForm->loadData($data)) {
            return PodiumResponse::error();
        }

        return $forumForm->create();
    }
1291830
protected function processRecord($record, $columnMap, &$results, $preview = false)
    {
        $class = $this->objectClass;

        // find existing object, or create new one
        $existingObj = $this->findExistingObject($record, $columnMap);
        /** @var DataObject $obj */
        $obj = ($existingObj) ? $existingObj : new $class();
        $schema = DataObject::getSchema();

        // first run: find/create any relations and store them on the object
        // we can't combine runs, as other columns might rely on the relation being present
        foreach ($record as $fieldName => $val) {
            // don't bother querying of value is not set
            if ($this->isNullValue($val)) {
                continue;
            }

            // checking for existing relations
            if (isset($this->relationCallbacks[$fieldName])) {
                // trigger custom search method for finding a relation based on the given value
                // and write it back to the relation (or create a new object)
                $relationName = $this->relationCallbacks[$fieldName]['relationname'];
                /** @var DataObject $relationObj */
                $relationObj = null;
                if ($this->hasMethod($this->relationCallbacks[$fieldName]['callback'])) {
                    $relationObj = $this->{$this->relationCallbacks[$fieldName]['callback']}($obj, $val, $record);
                } elseif ($obj->hasMethod($this->relationCallbacks[$fieldName]['callback'])) {
                    $relationObj = $obj->{$this->relationCallbacks[$fieldName]['callback']}($val, $record);
                }
                if (!$relationObj || !$relationObj->exists()) {
                    $relationClass = $schema->hasOneComponent(get_class($obj), $relationName);
                    $relationObj = new $relationClass();
                    //write if we aren't previewing
                    if (!$preview) {
                        $relationObj->write();
                    }
                }
                $obj->{"{$relationName}ID"} = $relationObj->ID;
                //write if we are not previewing
                if (!$preview) {
                    $obj->write();
                    $obj->flushCache(); // avoid relation caching confusion
                }
            } elseif (strpos($fieldName, '.') !== false) {
                // we have a relation column with dot notation
                list($relationName, $columnName) = explode('.', $fieldName);
                // always gives us an component (either empty or existing)
                $relationObj = $obj->getComponent($relationName);
                if (!$preview) {
                    $relationObj->write();
                }
                $obj->{"{$relationName}ID"} = $relationObj->ID;

                //write if we are not previewing
                if (!$preview) {
                    $obj->write();
                    $obj->flushCache(); // avoid relation caching confusion
                }
            }
        }

        // second run: save data

        foreach ($record as $fieldName => $val) {
            // break out of the loop if we are previewing
            if ($preview) {
                break;
            }

            // look up the mapping to see if this needs to map to callback
            $mapped = $this->columnMap && isset($this->columnMap[$fieldName]);

            if ($mapped && strpos($this->columnMap[$fieldName], '->') === 0) {
                $funcName = substr($this->columnMap[$fieldName], 2);

                $this->$funcName($obj, $val, $record);
            } elseif ($obj->hasMethod("import{$fieldName}")) {
                $obj->{"import{$fieldName}"}($val, $record);
            } else {
                $obj->update(array($fieldName => $val));
            }
        }

        // write record
        if (!$preview) {
            $obj->write();
        }

        // @todo better message support
        $message = '';

        // save to results
        if ($existingObj) {
            $results->addUpdated($obj, $message);
        } else {
            $results->addCreated($obj, $message);
        }

        $objID = $obj->ID;

        $obj->destroy();

        // memory usage
        unset($existingObj, $obj);

        return $objID;
    }
412306
public function get_feedbackauthor_form($actionurl, stdclass $submission, $options=array()) {
        global $CFG;
        require_once(__DIR__ . '/feedbackauthor_form.php');

        $current = new stdclass();
        $current->submissionid          = $submission->id;
        $current->published             = $submission->published;
        $current->grade                 = $this->real_grade($submission->grade);
        $current->gradeover             = $this->real_grade($submission->gradeover);
        $current->feedbackauthor        = $submission->feedbackauthor;
        $current->feedbackauthorformat  = $submission->feedbackauthorformat;
        if (is_null($current->grade)) {
            $current->grade = get_string('nullgrade', 'workshop');
        }
        if (!isset($options['editable'])) {
            $editable = true;   // by default
        } else {
            $editable = (bool)$options['editable'];
        }

        // prepare wysiwyg editor
        $current = file_prepare_standard_editor($current, 'feedbackauthor', array());

        return new workshop_feedbackauthor_form($actionurl,
                array('workshop' => $this, 'current' => $current, 'editoropts' => array(), 'options' => $options),
                'post', '', null, $editable);
    }
893920
protected function processRecord($record, $columnMap, &$results, $preview = false)
    {
        if (!is_array($record) || empty($record) || !array_filter($record)) {
            $results->addSkipped("Empty/invalid record data.");
            return;
        }
        //map incoming record according to the standardisation mapping (columnMap)
        $record = $this->columnMapRecord($record);
        //skip if required data is not present
        if (!$this->hasRequiredData($record)) {
            $results->addSkipped("Required data is missing.");
            return;
        }
        $modelClass = $this->objectClass;
        $placeholder = new $modelClass();

        //populate placeholder object with transformed data
        foreach ($this->mappableFields_cache as $field => $label) {
            //skip empty fields
            if (!isset($record[$field]) || empty($record[$field])) {
                continue;
            }
            $this->transformField($placeholder, $field, $record[$field]);
        }
        //find existing duplicate of placeholder data
        $obj = null;
        $existing = null;
        if (!$placeholder->ID && !empty($this->duplicateChecks)) {
            $data = $placeholder->getQueriedDatabaseFields();
            //don't match on ID, ClassName or RecordClassName
            unset($data['ID'], $data['ClassName'], $data['RecordClassName']);
            $existing = $this->findExistingObject($data);
        }
        if ($existing) {
            $obj = $existing;
            $obj->update($data);
        } else {
            // new record
            if (!$this->addNewRecords) {
                $results->addSkipped('New record not added');
                return;
            }
            $obj = $placeholder;
        }

        //callback access to every object
        if (is_callable($this->recordCallback)) {
            $callback  = $this->recordCallback;
            $callback($obj, $record);
        }

        $changed = $existing && $obj->isChanged();
        //try/catch for potential write() ValidationException
        try {
            // write obj record
            $obj->write();

            //publish pages
            if ($this->publishPages && $obj instanceof SiteTree) {
                $obj->publish('Stage', 'Live');
            }

            // save to results
            if ($existing) {
                if ($changed) {
                    $results->addUpdated($obj);
                } else {
                    $results->addSkipped("No data was changed.");
                }
            } else {
                $results->addCreated($obj);
            }
        } catch (ValidationException $e) {
            $results->addSkipped($e->getMessage());
        }

        $objID = $obj->ID;
        // reduce memory usage
        $obj->destroy();
        unset($existingObj);
        unset($obj);
        
        return $objID;
    }
1140170
public function write($showDebug = false, $forceInsert = false, $forceWrite = false, $writeComponents = false)
    {
        //throw new Exception("{$this->ClassName} can not be written back to the database.");
        // NOTE: we need to fail silently on writes because writing is part of the cloud upload process
        if ($this->storeRecord) {
            $this->storeRecord->write($showDebug, $forceInsert, $forceWrite, $writeComponents);
        }
    }
454431
boolean documentAuthor(String author) {
    if (!lazyInitDocumentation()) {
      return true;
    }

    if (documentation.authors == null) {
      documentation.authors = new ArrayList<>();
    }

    documentation.authors.add(author);
    return true;
  }
851298
public function create(array $data, MembershipInterface $author): PodiumResponse
    {
        /* @var $categoryForm AuthoredFormInterface */
        $categoryForm = $this->getForm();

        $categoryForm->setAuthor($author);

        if (!$categoryForm->loadData($data)) {
            return PodiumResponse::error();
        }

        return $categoryForm->create();
    }
1098789
private ApacheHttpRequest<GenericRecord> buildWriteRequest(BufferedRecord<GenericRecord> record) {
    if (record == null) {
      return null;
    }

    ApacheHttpRequest<GenericRecord> request = new ApacheHttpRequest<>();
    HttpOperation httpOperation = HttpUtils.toHttpOperation(record.getRecord());

    // Set uri
    URI uri = HttpUtils.buildURI(urlTemplate, httpOperation.getKeys(), httpOperation.getQueryParams());
    if (uri == null) {
      return null;
    }

    RequestBuilder builder = RequestBuilder.create(verb.toUpperCase());
    builder.setUri(uri);

    // Set headers
    Map<String, String> headers = httpOperation.getHeaders();
    if (headers != null && headers.size() != 0) {
      for (Map.Entry<String, String> header : headers.entrySet()) {
        builder.setHeader(header.getKey(), header.getValue());
      }
    }

    // Add payload
    int bytesWritten = addPayload(builder, httpOperation.getBody());
    if (bytesWritten == -1) {
      throw new RuntimeException("Fail to write payload into request");
    }

    request.setRawRequest(build(builder));
    request.markRecord(record, bytesWritten);
    return request;
  }
568542
protected function open( Record $record = null )
    {
        if ($this->isOpen) {
            return;
        }

        $this->recordCount = 0;
        $this->isOpen      = true;

        $this->writer->open();
        $this->writeHeader( $record );
    }
632426
public function create($entity, $record = null, $child = null)
    {
        if (!$record && !$child && ($entityObject = Entity::fromYamlFile($entity))) {
            $form = new Form($entityObject, null, Session::get('errors'));

            return $form->view();
        } elseif (($parentEntity = Entity::fromYamlFile($entity)) && ($entityObject = Entity::fromYamlFile($child))) {
            // Get parent's record
            $parentRecord = $parentEntity->class::findOrFail($record);

            $form = new Form($entityObject, null, Session::get('errors'), $parentEntity, $parentRecord);

            return $form->view();
        } else {
            abort(404);
        }
    }
285401
protected function prepareContentData($record)
    {
        $dataArray = array(
            'token'       => $this->token,
            'channel'     => $this->channel,
            'username'    => $this->username,
            'text'        => '',
            'attachments' => array(),
        );

        if ($this->formatter) {
            $message = $this->formatter->format($record);
        } else {
            $message = $record['message'];
        }

        if ($this->useAttachment) {
            $attachment = array(
                'fallback' => $message,
                'color'    => $this->getAttachmentColor($record['level']),
                'fields'   => array(),
            );

            if ($this->useShortAttachment) {
                $attachment['title'] = $record['level_name'];
                $attachment['text'] = $message;
            } else {
                $attachment['title'] = 'Message';
                $attachment['text'] = $message;
                $attachment['fields'][] = array(
                    'title' => 'Level',
                    'value' => $record['level_name'],
                    'short' => true,
                );
            }

            if ($this->includeContextAndExtra) {
                if (!empty($record['extra'])) {
                    if ($this->useShortAttachment) {
                        $attachment['fields'][] = array(
                            'title' => "Extra",
                            'value' => $this->stringify($record['extra']),
                            'short' => $this->useShortAttachment,
                        );
                    } else {
                        // Add all extra fields as individual fields in attachment
                        foreach ($record['extra'] as $var => $val) {
                            $attachment['fields'][] = array(
                                'title' => $var,
                                'value' => $val,
                                'short' => $this->useShortAttachment,
                            );
                        }
                    }
                }

                if (!empty($record['context'])) {
                    if ($this->useShortAttachment) {
                        $attachment['fields'][] = array(
                            'title' => "Context",
                            'value' => $this->stringify($record['context']),
                            'short' => $this->useShortAttachment,
                        );
                    } else {
                        // Add all context fields as individual fields in attachment
                        foreach ($record['context'] as $var => $val) {
                            $attachment['fields'][] = array(
                                'title' => $var,
                                'value' => $val,
                                'short' => $this->useShortAttachment,
                            );
                        }
                    }
                }
            }

            $dataArray['attachments'] = json_encode(array($attachment));
        } else {
            $dataArray['text'] = $message;
        }

        if ($this->iconEmoji) {
            $dataArray['icon_emoji'] = ":{$this->iconEmoji}:";
        }

        return $dataArray;
    }
980394
protected function addVersionedButtons(DataObject $record, FieldList $actions)
    {
        // Save & Publish action
        if ($record->canPublish()) {
            // "publish", as with "save", it supports an alternate state to show when action is needed.
            $publish = FormAction::create(
                'doPublish',
                _t(__CLASS__ . '.BUTTONPUBLISH', 'Publish')
            )
                ->setUseButtonTag(true)
                ->addExtraClass('btn btn-primary font-icon-rocket');

            // Insert after save
            if ($actions->fieldByName('action_doSave')) {
                $actions->insertAfter('action_doSave', $publish);
            } else {
                $actions->push($publish);
            }
        }

        // Unpublish action
        if ($record->isInDB() && $record->canUnpublish()) {
            /** @var DataObject|Versioned|RecursivePublishable $liveRecord */
            $liveRecord = Versioned::get_by_stage($record->baseClass(), Versioned::LIVE)
                ->byID($record->ID);
            if ($liveRecord) {
                $liveOwners = $liveRecord->findOwners(false)->count();
                $actions->push(
                    FormAction::create(
                        'doUnpublish',
                        _t(__CLASS__ . '.BUTTONUNPUBLISH', 'Unpublish')
                    )
                        ->setUseButtonTag(true)
                        ->setDescription(_t(
                            __CLASS__ . '.BUTTONUNPUBLISHDESC',
                            'Remove this record from the published site'
                        ))
                        ->addExtraClass('btn-secondary')
                        ->setAttribute('data-owners', $liveOwners)
                );
            }
        }

        // Archive action
        if ($record->isInDB() && $record->canArchive()) {
            // Replace "delete" action
            $actions->removeByName('action_doDelete');

            // "archive"
            $actions->push(
                FormAction::create('doArchive', _t(__CLASS__ . '.ARCHIVE', 'Archive'))
                    ->setUseButtonTag(true)
                    ->setDescription(_t(
                        __CLASS__ . '.BUTTONARCHIVEDESC',
                        'Unpublish and send to archive'
                    ))
                    ->addExtraClass('btn-secondary action--archive font-icon-box')
            );
        }
    }
926940
public function export_for_template(renderer_base $output) {
        global $DB;

        $usercompetencycourse = api::get_user_competency_in_course($this->courseid, $this->userid, $this->competencyid);
        $competency = $usercompetencycourse->get_competency();
        if (empty($usercompetencycourse) || empty($competency)) {
            throw new \invalid_parameter_exception('Invalid params. The competency does not belong to the course.');
        }

        $relatedcompetencies = api::list_related_competencies($competency->get('id'));
        $user = $DB->get_record('user', array('id' => $this->userid));
        $evidence = api::list_evidence_in_course($this->userid, $this->courseid, $this->competencyid);
        $course = $DB->get_record('course', array('id' => $this->courseid));

        $params = array(
            'competency' => $competency,
            'usercompetencycourse' => $usercompetencycourse,
            'evidence' => $evidence,
            'user' => $user,
            'course' => $course,
            'scale' => $competency->get_scale(),
            'relatedcompetencies' => $relatedcompetencies
        );
        $exporter = new user_competency_summary_in_course_exporter(null, $params);
        $data = $exporter->export($output);

        return $data;
    }
484173
public function get_assign_submission_status_renderable($user, $showlinks) {
        global $PAGE;

        $instance = $this->get_instance();
        $flags = $this->get_user_flags($user->id, false);
        $submission = $this->get_user_submission($user->id, false);

        $teamsubmission = null;
        $submissiongroup = null;
        $notsubmitted = array();
        if ($instance->teamsubmission) {
            $teamsubmission = $this->get_group_submission($user->id, 0, false);
            $submissiongroup = $this->get_submission_group($user->id);
            $groupid = 0;
            if ($submissiongroup) {
                $groupid = $submissiongroup->id;
            }
            $notsubmitted = $this->get_submission_group_members_who_have_not_submitted($groupid, false);
        }

        $showedit = $showlinks &&
                    ($this->is_any_submission_plugin_enabled()) &&
                    $this->can_edit_submission($user->id);

        $submissionlocked = ($flags && $flags->locked);

        // Grading criteria preview.
        $gradingmanager = get_grading_manager($this->context, 'mod_assign', 'submissions');
        $gradingcontrollerpreview = '';
        if ($gradingmethod = $gradingmanager->get_active_method()) {
            $controller = $gradingmanager->get_controller($gradingmethod);
            if ($controller->is_form_defined()) {
                $gradingcontrollerpreview = $controller->render_preview($PAGE);
            }
        }

        $showsubmit = ($showlinks && $this->submissions_open($user->id));
        $showsubmit = ($showsubmit && $this->show_submit_button($submission, $teamsubmission, $user->id));

        $extensionduedate = null;
        if ($flags) {
            $extensionduedate = $flags->extensionduedate;
        }
        $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_context());

        $gradingstatus = $this->get_grading_status($user->id);
        $usergroups = $this->get_all_groups($user->id);
        $submissionstatus = new assign_submission_status($instance->allowsubmissionsfromdate,
                                                          $instance->alwaysshowdescription,
                                                          $submission,
                                                          $instance->teamsubmission,
                                                          $teamsubmission,
                                                          $submissiongroup,
                                                          $notsubmitted,
                                                          $this->is_any_submission_plugin_enabled(),
                                                          $submissionlocked,
                                                          $this->is_graded($user->id),
                                                          $instance->duedate,
                                                          $instance->cutoffdate,
                                                          $this->get_submission_plugins(),
                                                          $this->get_return_action(),
                                                          $this->get_return_params(),
                                                          $this->get_course_module()->id,
                                                          $this->get_course()->id,
                                                          assign_submission_status::STUDENT_VIEW,
                                                          $showedit,
                                                          $showsubmit,
                                                          $viewfullnames,
                                                          $extensionduedate,
                                                          $this->get_context(),
                                                          $this->is_blind_marking(),
                                                          $gradingcontrollerpreview,
                                                          $instance->attemptreopenmethod,
                                                          $instance->maxattempts,
                                                          $gradingstatus,
                                                          $instance->preventsubmissionnotingroup,
                                                          $usergroups);
        return $submissionstatus;
    }