Starts the import based on the form

@param \core_kernel_classes_Class $class
@param Form|array $form
@param string|null $userId owner of the resource
@return Report $report
@throws \common_exception_Error
359596
public function import($class, $form, $userId = null)
    {
        $uploadedFile = $this->fetchUploadedFile($form);

        try {
            $service = MediaService::singleton();
            $classUri = $class->getUri();

            $instanceUri = $form instanceof Form
                ? $form->getValue('instanceUri')
                : (isset($form['instanceUri']) ? $form['instanceUri'] : null);

            $fileInfo = $form instanceof Form ? $form->getValue('source') : $form['source'];

            // importing new media
            if (!$instanceUri || $instanceUri === $classUri) {
                //if the file is a zip do a zip import
                if (!\helpers_File::isZipMimeType($fileInfo['type'])) {
                    try {
                        self::isValidSharedStimulus($uploadedFile);

                        $mediaResourceUri = $service->createMediaInstance(
                            $uploadedFile,
                            $classUri,
                            \tao_helpers_Uri::decode($form instanceof Form ? $form->getValue('lang') : $form['lang']),
                            $fileInfo['name'],
                            'application/qti+xml',
                            $userId
                        );

                        if (!$mediaResourceUri) {
                            $report = Report::createFailure(__('Fail to import Shared Stimulus'));
                            $report->setData(['uriResource' => '']);
                        } else {
                            $report = Report::createSuccess(__('Shared Stimulus imported successfully'));
                            $report->add(Report::createSuccess(
                                __('Imported %s', $fileInfo['name']),
                                ['uriResource' => $mediaResourceUri] // 'uriResource' key is needed by javascript in tao/views/templates/form/import.tpl
                            ));
                        }
                    } catch (XmlStorageException $e) {
                        // The shared stimulus is not qti compliant, display error
                        $report = Report::createFailure($e->getMessage());
                        $report->setData(['uriResource' => '']);
                    }
                } else {
                    $report = $this->getZipImporter()->import($class, $form, $userId);
                }
            } else {
                if (!\helpers_File::isZipMimeType($fileInfo['type'])) {
                    self::isValidSharedStimulus($uploadedFile);
                    if (in_array($fileInfo['type'], array('application/xml', 'text/xml'))) {
                        $name = basename($fileInfo['name'], 'xml');
                        $name .= 'xhtml';
                        $filepath = \tao_helpers_File::concat([dirname($fileInfo['name']), $name]);
                        $fileResource = fopen($filepath, 'w');
                        $uploadedFileResource = $uploadedFile->readStream();
                        stream_copy_to_stream($uploadedFileResource, $fileResource);
                        fclose($fileResource);
                        fclose($uploadedFileResource);
                    }

                    if (!$service->editMediaInstance(
                        isset($filepath) ? $filepath : $uploadedFile,
                        $instanceUri,
                        \tao_helpers_Uri::decode($form instanceof Form ? $form->getValue('lang') : $form['lang']),
                        $userId
                    )) {
                        $report = Report::createFailure(__('Fail to edit shared stimulus'));
                    } else {
                        $report = Report::createSuccess(__('Shared Stimulus edited successfully'));
                    }

                    $report->setData(['uriResource' => $instanceUri]);
                } else {
                    $report = $this->getZipImporter()->edit(new \core_kernel_classes_Resource($instanceUri), $form, $userId);
                }
            }

        } catch (\Exception $e) {
            $message = $e instanceof \common_exception_UserReadableException
                ? $e->getUserMessage()
                : __('An error has occurred. Please contact your administrator.');
            $report = Report::createFailure($message);
            $report->setData(['uriResource' => '']);
            $this->logError($e->getMessage());
        }

        $this->getUploadService()->remove($uploadedFile);

        return $report;
    }
230934
public function formAction(Request $request, $userId)
    {
        $user = $this->get('open_orchestra_user.repository.user')->find($userId);

        if ($user instanceof UserInterface) {
            $this->denyAccessUnlessGranted(ContributionActionInterface::EDIT, $user);
            $user = $this->refreshLanguagesByAliases($user);

            return $this->renderForm($request, $user, false);
        }

        throw new UserNotFoundHttpException();
    }
42313
public function startImport(array &$form, FormStateInterface $form_state) {
        // Выполняет стандартную валидацию полей формы и добавляет примечания об ошибках.
        ConfigFormBase::validateForm($form, $form_state);

        if (!$form_state->getValue('validate_error')) {
            $config = $this->config('site_geo.import');

            $fid = $config->get('fid');
            $skip_first_line = $config->get('skip_first_line');
            $delimiter = $config->get('delimiter');
            $enclosure = $config->get('enclosure');
            $chunk_size = $config->get('chunk_size');
            $plugin_id = $form_state->getValue('import_plugin');

            if ($plugin_id != "") {
                $import = new SiteGeoCSVBatchImport($plugin_id, $fid, $skip_first_line, $delimiter, $enclosure, $chunk_size);
                $import->setBatch();
            }
        }
    }
956399
public function buildForm(array $form, FormStateInterface $form_state, $token = null)
    {
        if ($token === null) {
            return [];
        }

        /* @var Token $token */
        $token = $this->tokenManager->loadToken($token);
        if ($token === null) {
            drupal_set_message(
                $this->t('You have tried to use a one-time login link that has either been used or is no longer valid. Please request a new one using the form below.'), 'error');
            return [];
        }

        $currentUser = $this->currentUser();
        $userStorage = $this->entityManager->getStorage('user');

        if ($currentUser->id()) {
            // The existing user is already logged in.
            if ($currentUser->id() == $token->uid) {
                drupal_set_message($this->t('You are logged in as %user. <a href="!user_edit">Change your password.</a>', [
                    '%user' => $currentUser->getAccountName(),
                    '!user_edit' => url('user/password'),
                ]));
            }
            // A different user is already logged in on the computer.
            else {
                /* @var UserInterface $user */
                $tokenUser = $userStorage->load($token->uid);

                drupal_set_message($this->t('Another user (%other_user) is already logged into the site on this computer, but you tried to use a one-time link for user %resetting_user. Please <a href="!logout">logout</a> and try using the link again.', [
                    '%other_user' => $currentUser->getAccountName(),
                    '%resetting_user' => $tokenUser->getAccountName(),
                    '!logout' => url('user/logout'),
                ]), 'warning');
            }

            drupal_goto();
        }
        else {
            /* @var UserInterface $user */
            $user = $userStorage->load($token->uid);

            if ($user->isBlocked() && $user->getLastLoginTime() > 0) {
                drupal_access_denied();
                drupal_exit();
            }

            if ($token->isValid()) {
                $form_state->setTemporaryValue('token', $token);
                $form_state->setTemporaryValue('user', $user);

                $form['#form_horizontal'] = true;

                $form['password'] = [
                    '#type' => 'password_confirm',
                    '#size' => 20,
                    '#required' => true,
                    '#description' => $this->t("!count characters at least. Mix letters, digits and special characters for a better password.", ['!count' => UCMS_USER_PWD_MIN_LENGTH]),
                ];

                $form['actions'] = [
                    '#type' => 'actions',
                    'submit' => [
                        '#type' => 'submit',
                        '#value' => $this->t('Save my password'),
                    ],
                ];
            }
            else {
                drupal_set_message(
                    $this->t('You have tried to use a one-time login link that has either been used or is no longer valid. Please request a new one using the form below.'), 'error');
                drupal_goto('user/password');
            }
        }

        return $form;
    }
913430
public function inviteAction(Request $request, $userClass)
    {
        $form = $this->get('form.factory')->createNamedBuilder('', InviteType::class, null, [
            'roles'           => $this->getParameter('bengor_user.' . $userClass . '_default_roles'),
            'csrf_protection' => false,
        ])->getForm();

        $form->handleRequest($request);
        if ($form->isValid()) {
            try {
                $this->get('bengor_user.' . $userClass . '.api_command_bus')->handle(
                    $form->getData()
                );

                return new JsonResponse([
                    'user_id' => $form->getData()->id(),
                    'email'   => $form->getData()->email(),
                    'role'    => $form->getData()->roles(),
                ]);
            } catch (UserAlreadyExistException $exception) {
                return new JsonResponse(
                    sprintf(
                        'The %s email is already invited',
                        $form->getData()->email()
                    ),
                    409
                );
            }
        }

        return new JsonResponse(FormErrorSerializer::errors($form), 400);
    }
964546
public static function message_processor_config_form($userid, $name, $formvalues) {
        global $USER, $CFG;

        // Check if messaging is enabled.
        if (empty($CFG->messaging)) {
            throw new moodle_exception('disabled', 'message');
        }

        $params = self::validate_parameters(
            self::message_processor_config_form_parameters(),
            array(
                'userid' => $userid,
                'name' => $name,
                'formvalues' => $formvalues,
            )
        );

        $user = self::validate_preferences_permissions($params['userid']);

        $processor = get_message_processor($params['name']);
        $preferences = [];
        $form = new stdClass();

        foreach ($params['formvalues'] as $formvalue) {
            // Curly braces to ensure interpretation is consistent between
            // php 5 and php 7.
            $form->{$formvalue['name']} = $formvalue['value'];
        }

        $processor->process_form($form, $preferences);

        if (!empty($preferences)) {
            set_user_preferences($preferences, $params['userid']);
        }
    }
360023
public function create(ApiClientInterface $client, UserInterface $user = null)
    {
        $tokenClass = $this->tokenClass;

        return $tokenClass::create($client, $user);
    }
643454
protected function createInstance(
        InputInterface $input,
        OutputInterface $output,
        Form $form = null
    ) {
        if (!isset($form)) {
            $form = new Form();
        }

        return $form
            ->setInput($input)
            ->setOutput($output)
            ->setHelperSet($this->getHelperSet());
    }
127244
public function importPreviewAction(Request $request, User $loggedUser, $format, $previewId)
    {
        $this->checkPortfolioToolAccess();

        $temporaryImportFilePathToSearch = sprintf('%s-%s.%s.import', strtolower($loggedUser->getUsername()), $previewId, $format);

        $finder = new Finder();
        $files = $finder->files()->in($this->container->get('claroline.config.platform_config_handler')->getParameter('tmp_dir'))
            ->depth('0')->name($temporaryImportFilePathToSearch);
        $filesCount = $files->count();
        $errorMessage = null;

        if (0 === $filesCount) {
            $errorMessage = 'portfolio_import_error_import_file_not_found_message';
        } elseif (1 < $filesCount) {
            $errorMessage = 'portfolio_import_error_import_too_many_file_message';
        }

        if (null !== $errorMessage) {
            $this->getSessionFlashbag()->add('error', $this->getTranslator()->trans($errorMessage, [], 'icap_portfolio'));

            return $this->redirect($this->generateUrl('icap_portfolio_import', ['format' => $format]));
        }

        if ($request->isMethod('POST')) {
            try {
                foreach ($files as $file) {
                    $importManager = $this->getImportManager();

                    $portfolio = $importManager->doImport($file->getContents(), $loggedUser, $format);
                }

                if ($request->isXmlHttpRequest()) {
                    return new JsonResponse([]);
                } else {
                    $this->getSessionFlashbag()
                        ->add('success', $this->getTranslator()
                            ->trans('portfolio_import_success_message', [], 'icap_portfolio'));

                    return $this->redirect($this->generateUrl('icap_portfolio_index'));
                }
            } catch (\Exception $exception) {
                $this->getSessionFlashbag()
                    ->add('error', $this->getTranslator()
                        ->trans('portfolio_import_error_message', [], 'icap_portfolio'));

                throw $exception;
            }
        }

        foreach ($files as $file) {
            $portfolio = $this->getImportManager()->simulateImport($file->getContents(), $loggedUser, $format);
        }

        return [
            'format' => $format,
            'previewId' => $previewId,
            'portfolio' => $portfolio,
        ];
    }
638687
public function write($userdata, $splash, $session, $sessionId, $expiry)
    {

        $ini = new Ini();
        $store = $session->folder . DIRECTORY_SEPARATOR;

        if (!$ini->is($store)) {
            if (!$ini->create($store)) {
                throw new \Exception("Could not create the $store folder. Please create this manually and check it hass writable permissions");
                return false;
            }
        }

        //We need to know the array;
        if (!is_array($splash)) return false;

        $sfile = $store . $sessionId . ".ini";


        //We create the session file;
        if (!($sini = $ini->create($sfile))) {
            throw new \Exception("Could not create the session file");
            return false;
        }
        //Temporarily chmode the file;
        $ini->chmod($sfile, 0755);

        $splash['expiry'] = $expiry;
        $splash['active'] = time();
        $splash['key'] = $sessionId;
        $splash['registry'] = static::quote("'" . $userdata . "'");


        //Now write to file
        if (!$ini->write($sfile, $ini->toIniString($splash))) {
            throw new \Exception("Could not write out to the configuration file");
            return false;
        }

        return true;
    }
1096046
public static function create_contact_request(int $userid, int $requesteduserid) : \stdClass {
        global $DB, $PAGE;

        $request = new \stdClass();
        $request->userid = $userid;
        $request->requesteduserid = $requesteduserid;
        $request->timecreated = time();

        $request->id = $DB->insert_record('message_contact_requests', $request);

        // Send a notification.
        $userfrom = \core_user::get_user($userid);
        $userfromfullname = fullname($userfrom);
        $userto = \core_user::get_user($requesteduserid);
        $url = new \moodle_url('/message/pendingcontactrequests.php');

        $subject = get_string('messagecontactrequestsnotificationsubject', 'core_message', $userfromfullname);
        $fullmessage = get_string('messagecontactrequestsnotification', 'core_message', $userfromfullname);

        $message = new \core\message\message();
        $message->courseid = SITEID;
        $message->component = 'moodle';
        $message->name = 'messagecontactrequests';
        $message->notification = 1;
        $message->userfrom = $userfrom;
        $message->userto = $userto;
        $message->subject = $subject;
        $message->fullmessage = text_to_html($fullmessage);
        $message->fullmessageformat = FORMAT_HTML;
        $message->fullmessagehtml = $fullmessage;
        $message->smallmessage = '';
        $message->contexturl = $url->out(false);
        $userpicture = new \user_picture($userfrom);
        $userpicture->includetoken = $userto->id; // Generate an out-of-session token for the user receiving the message.
        $message->customdata = [
            'notificationiconurl' => $userpicture->get_url($PAGE)->out(false),
            'actionbuttons' => [
                'accept' => get_string_manager()->get_string('accept', 'moodle', null, $userto->lang),
                'reject' => get_string_manager()->get_string('reject', 'moodle', null, $userto->lang),
            ],
        ];

        message_send($message);

        return $request;
    }
1199026
public function buildForm(array $form, FormStateInterface $form_state, $course_esid = NULL) {
    $this->course_esid = (int) $course_esid;
    if ($this->course_esid) {
      $step = (object) $this->databaseCourses->loadStep($this->course_esid);
      $this->step = $step;
      $this->course_id = $step->course_id;
      $this->course_sid = $step->course_sid;
      $this->course_eid = $step->course_eid;
    }
    return parent::buildForm($form, $form_state);
  }
1070484
public function populateResourceWithForm(Resource $resource, FormInterface $form)
    {
        $formData = $form->getData();

        $resource->setData(
            array(
                'username' => $formData['username'],
                'email'    => $formData['email']
            )
        );
    }
463143
protected function initializeRequest(RequestAbstract $form, Request $current)
    {
        $files = $current->files->all();

        $files = is_array($files) ? array_filter($files) : $files;

        $form->initialize(
            $current->query->all(), $current->request->all(), $current->attributes->all(),
            $current->cookies->all(), $files, $current->server->all(), $current->getContent()
        );

        $form->setContainer($this->app);
    }
977912
public function load() {

        if (!$this->hasRequestParameter('uri')) {
            throw new common_exception_MissingParameter('uri', __METHOD__);
        }
        if (!$this->hasRequestParameter('stylesheetUri')) {
            throw new common_exception_MissingParameter('stylesheetUri', __METHOD__);
        }
        if (!$this->hasRequestParameter('lang')) {
            throw new common_exception_MissingParameter('lang', __METHOD__);
        }
        
        $item = new \core_kernel_classes_Resource($this->getRequestParameter('uri'));
        $lang = $this->getRequestParameter('lang');
        $styleSheet = $this->getRequestParameter('stylesheetUri');
        if (!\tao_helpers_File::securityCheck($styleSheet, true)) {
            throw new \common_exception_Error('invalid stylesheet path "'.$styleSheet.'"');
        }



        $cssArray = CssHelper::loadCssFile($item, $lang, $styleSheet);
        echo json_encode($cssArray);
    }
109175
public static function user_competency_start_review($userid, $competencyid) {
        global $USER;
        static::require_enabled();

        $context = context_user::instance($userid);
        $uc = user_competency::get_record(array('userid' => $userid, 'competencyid' => $competencyid));
        if (!$uc || !$uc->can_read()) {
            throw new required_capability_exception($context, 'moodle/competency:usercompetencyview', 'nopermissions', '');
        } else if ($uc->get('status') != user_competency::STATUS_WAITING_FOR_REVIEW) {
            throw new coding_exception('The competency review can not be started at this stage.');
        } else if (!$uc->can_review()) {
            throw new required_capability_exception($context, 'moodle/competency:usercompetencyreview', 'nopermissions', '');
        }

        $uc->set('status', user_competency::STATUS_IN_REVIEW);
        $uc->set('reviewerid', $USER->id);
        $result = $uc->update();
        if ($result) {
            \core\event\competency_user_competency_review_started::create_from_user_competency($uc)->trigger();
        }
        return $result;
    }
1266154
public function get_form_elements_for_user($grade, MoodleQuickForm $mform, stdClass $data, $userid) {
        global $PAGE;

        $attempt = -1;
        if ($grade) {
            $attempt = $grade->attemptnumber;
        }

        $renderer = $PAGE->get_renderer('assignfeedback_editpdf');

        $widget = $this->get_widget($userid, $grade, false);

        $html = $renderer->render($widget);
        $mform->addElement('static', 'editpdf', get_string('editpdf', 'assignfeedback_editpdf'), $html);
        $mform->addHelpButton('editpdf', 'editpdf', 'assignfeedback_editpdf');
        $mform->addElement('hidden', 'editpdf_source_userid', $userid);
        $mform->setType('editpdf_source_userid', PARAM_INT);
        $mform->setConstant('editpdf_source_userid', $userid);
    }