@EXT\Route("/import/submit", name="claro_admin_import_users")
@EXT\Method("POST")
@EXT\Template("ClarolineCoreBundle:Administration/Users:importForm.html.twig")

@return Response
962699
public function importAction()
    {

        $form = $this->formFactory->create(new ImportUserType(true));
        $form->handleRequest($this->request);
        $mode = $form->get('mode')->getData();

        if ($mode === 'update') {
            $form = $this->formFactory->create(new ImportUserType(true, 1));
            $form->handleRequest($this->request);
        }

        if ($form->isValid()) {
            $file = $form->get('file')->getData();
            $sendMail = $form->get('sendMail')->getData();
            $data = file_get_contents($file);
            $data = $this->container->get('claroline.utilities.misc')->formatCsvOutput($data);
            $lines = str_getcsv($data, PHP_EOL);
            $users = array();
            $toUpdate = array();
            $sessionFlashBag = $this->session->getFlashBag();

            foreach ($lines as $line) {

                if ($mode === 'update') {
                    $datas = str_getcsv($line, ';');
                    $username = $datas[2];
                    $email = $datas[4];
                    $existingUser = $this->userManager->getUserByUsernameOrMail(
                        $username,
                        $email
                    );

                    if (is_null($existingUser)) {
                        $users[] = $datas;
                    } else {
                        $toUpdate[] = $datas;
                    }
                } else {
                    $users[] = str_getcsv($line, ';');
                }
            }

            $roleUser = $this->roleManager->getRoleByName('ROLE_USER');
            $max = $roleUser->getMaxUsers();
            $total = $this->userManager->countUsersByRoleIncludingGroup($roleUser);

            if ($total + count($users) > $max) {

                return array('form' => $form->createView(), 'error' => 'role_user unavailable');
            }

            $additionalRoles = $form->get('roles')->getData();

            foreach ($additionalRoles as $additionalRole) {
                $max = $additionalRole->getMaxUsers();
                $total = $this->userManager->countUsersByRoleIncludingGroup($additionalRole);

                if ($total + count($users) > $max) {

                    return array(
                        'form' => $form->createView(),
                        'error' => $additionalRole->getName() . ' unavailable'
                    );
                }
            }

            if (count($toUpdate) > 0) {
                $updatedNames = $this->userManager->updateImportedUsers(
                    $toUpdate,
                    $additionalRoles->toArray()
                );

                foreach ($updatedNames as $name) {
                    $msg =  '<' . $name . '> ';
                    $msg .= $this->translator->trans(
                        'has_been_updated',
                        array(),
                        'platform'
                    );
                    $sessionFlashBag->add('success', $msg);
                }
            }
            $createdNames = $this->userManager->importUsers(
                $users,
                $sendMail,
                null,
                $additionalRoles
            );

            foreach ($createdNames as $name) {
                $msg =  '<' . $name . '> ';
                $msg .= $this->translator->trans(
                    'has_been_created',
                    array(),
                    'platform'
                );
                $sessionFlashBag->add('success', $msg);
            }

            return new RedirectResponse($this->router->generate('claro_admin_users_index'));
        }

        return array('form' => $form->createView());
    }
608910
public function indexAction()
    {
        if($this->identity()) {
            return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
        }
        
        $user = new User;
        $form = $this->getUserFormHelper()->createUserForm($user, 'SignUp');
        if($this->getRequest()->isPost()) {
            $form->setValidationGroup('username', 'email', 'firstName', 'lastName', 'password', 'passwordVerify', 'question', 'answer', 'csrf', 'captcha');
            $form->setData($this->getRequest()->getPost());    
            if($form->isValid()) {
                $entityManager = $this->getEntityManager();
                $user->setState($entityManager->find('CsnUser\Entity\State', 1));
                $user->setRole($entityManager->find('CsnUser\Entity\Role', 2));
                $user->setEmailConfirmed(false);
                $user->setLanguage($entityManager->find('CsnUser\Entity\Language', 1));
                $user->setRegistrationDate(new \DateTime());
                $user->setRegistrationToken(md5(uniqid(mt_rand(), true)));
                $user->setPassword(UserCredentialsService::encryptPassword($user->getPassword()));
                
    		    try {
    		        $fullLink = $this->getBaseUrl() . $this->url()->fromRoute('user-register', array('action' => 'confirm-email', 'id' => $user->getRegistrationToken()));
    		        $this->sendEmail(
    		            $user->getEmail(),
    		            $this->getTranslatorHelper()->translate('Please, confirm your registration!'),
    		            sprintf($this->getTranslatorHelper()->translate('Please, click the link to confirm your registration => %s'), $fullLink)
    		        );
    		        $entityManager->persist($user);
                    $entityManager->flush();

                    $viewModel = new ViewModel(array(
                        'email' => $user->getEmail(),
                        'navMenu' => $this->getOptions()->getNavMenu()
                    ));
                    $viewModel->setTemplate('csn-user/registration/registration-success');
                    return $viewModel;
    		    } catch (\Exception $e) {
                    return $this->getServiceLocator()->get('csnuser_error_view')->createErrorView(
    				    $this->getTranslatorHelper()->translate('Something went wrong when trying to send activation email! Please, try again later.'),
    					$e,
    					$this->getOptions()->getDisplayExceptions(),
    					$this->getOptions()->getNavMenu()
    				);
    			}
            }
        }   

        $viewModel = new ViewModel(array(
            'form' => $form,
            'navMenu' => $this->getOptions()->getNavMenu()
        ));
        $viewModel->setTemplate('csn-user/registration/registration');
        return $viewModel;
    }
466105
public function importAction()
    {
        $success = null;
        $request = $this->getRequest();
        $data    = $request->getPost();
        $form    = $this->getServiceLocator()
                        ->get( 'Form' )
                        ->create( 'Grid\Paragraph\ChangeLayout\Import', array(
                            'returnUri' => $request->getQuery( 'returnUri' ),
                        ) );

        $form->setAttribute(
            'action',
            $this->url()
                 ->fromRoute( 'Grid\Paragraph\ChangeLayout\Import', array(
                     'locale'       => (string) $this->locale(),
                     'paragraphId'  => $this->paragraphId,
                     'returnUri'    => $request->getQuery( 'returnUri' ),
                 ) )
        );

        if ( $request->isPost() )
        {
            $form->setData( $data );

            if ( $form->isValid() )
            {
                $data       = $form->getData();
                $beforeId   = $this->getLayoutId();
                $clonedId   = $this->getParagraphModel()
                                   ->cloneFrom( $data['importId'], '_central' );
                $success    = $this->saveLayout( $clonedId );

                $this->getServiceLocator()
                     ->get( 'Grid\Menu\Model\Menu\Model' )
                     ->interleaveParagraphs( $clonedId, $beforeId );
            }
            else
            {
                $success    = false;
            }
        }

        if ( true === $success )
        {
            $this->messenger()
                 ->add( 'paragraph.action.importLayout.success',
                        'paragraph', Message::LEVEL_INFO );
        }

        if ( false === $success )
        {
            $this->messenger()
                 ->add( 'paragraph.action.importLayout.failed',
                        'paragraph', Message::LEVEL_ERROR );
        }

        if ( null !== $success )
        {
            return $this->redirect()
                        ->toUrl( $form->get( 'returnUri' )
                                      ->getValue() );
        }

        $view = new ViewModel( array(
            'form' => $form,
        ) );
        return $view->setTerminal( true );
    }
499543
public function register(Request $request): Response
    {
        $contentTypeIdentifier = $this->getConfigResolver()->getParameter('user.content_type_identifier', 'ngsite');
        $contentType = $this->getRepository()->getContentTypeService()->loadContentTypeByIdentifier($contentTypeIdentifier);
        $languages = $this->getConfigResolver()->getParameter('languages');
        $userCreateStruct = $this->userService->newUserCreateStruct(
            null,
            null,
            null,
            $languages[0],
            $contentType
        );

        $userCreateStruct->enabled = (bool) $this->getConfigResolver()->getParameter('user.auto_enable', 'ngsite');
        $userCreateStruct->alwaysAvailable = (bool) $contentType->defaultAlwaysAvailable;

        $data = new DataWrapper($userCreateStruct, $userCreateStruct->contentType);

        $formBuilder = $this->formFactory->createBuilder(
            CreateUserType::class,
            $data,
            [
                'translation_domain' => 'ngsite_user',
            ]
        );

        $form = $formBuilder->getForm();
        $form->handleRequest($request);

        if (!$form->isValid()) {
            return $this->render(
                $this->getConfigResolver()->getParameter('template.user.register', 'ngsite'),
                [
                    'form' => $form->createView(),
                ]
            );
        }

        $users = $this->userService->loadUsersByEmail($form->getData()->payload->email);

        if (!empty($users)) {
            return $this->render(
                $this->getConfigResolver()->getParameter('template.user.register', 'ngsite'),
                [
                    'form' => $form->createView(),
                    'error' => 'email_in_use',
                ]
            );
        }

        try {
            $this->userService->loadUserByLogin($form->getData()->payload->login);

            return $this->render(
                $this->getConfigResolver()->getParameter('template.user.register', 'ngsite'),
                [
                    'form' => $form->createView(),
                    'error' => 'username_taken',
                ]
            );
        } catch (NotFoundException $e) {
            // do nothing
        }

        $userGroupId = $this->getConfigResolver()->getParameter('user.user_group_content_id', 'ngsite');

        $preUserRegisterEvent = new UserEvents\PreRegisterEvent($data->payload);
        $this->eventDispatcher->dispatch(SiteEvents::USER_PRE_REGISTER, $preUserRegisterEvent);
        $data->payload = $preUserRegisterEvent->getUserCreateStruct();

        /** @var \eZ\Publish\API\Repository\Values\User\User $newUser */
        $newUser = $this->getRepository()->sudo(
            static function (Repository $repository) use ($data, $userGroupId): User {
                $userGroup = $repository->getUserService()->loadUserGroup($userGroupId);

                return $repository->getUserService()->createUser(
                    $data->payload,
                    [$userGroup]
                );
            }
        );

        $userRegisterEvent = new UserEvents\PostRegisterEvent($newUser);
        $this->eventDispatcher->dispatch(SiteEvents::USER_POST_REGISTER, $userRegisterEvent);

        if ($newUser->enabled) {
            return $this->render(
                $this->getConfigResolver()->getParameter('template.user.register_success', 'ngsite')
            );
        }

        if ($this->getConfigResolver()->getParameter('user.require_admin_activation', 'ngsite')) {
            return $this->render(
                $this->getConfigResolver()->getParameter('template.user.activate_admin_activation_pending', 'ngsite')
            );
        }

        return $this->render(
            $this->getConfigResolver()->getParameter('template.user.activate_sent', 'ngsite')
        );
    }
743303
public function updateAction()
    {
        // Check current user authorization
        if (null !== $response = $this->checkAuth(AdminResources::MODULE, Team::getModuleCode(),
                AccessManager::UPDATE)
        ) {
            return $response;
        }

        // Load object if exist
        if (null !== $object = $this->getExistingObject()) {
            // Hydrate the form abd pass it to the parser
            $changeForm = $this->hydrateObjectForm($object);

            // Pass it to the parser
            $this->getParserContext()->addForm($changeForm);
        }

        // Render the edition template.
        return $this->getEditRenderTemplate();
    }
204553
public function importAction()
    {
        $form = $this->getServiceLocator()->get('playgroundgame_import_form');
        $form->setAttribute('action', $this->adminUrl()->fromRoute('playgroundgame/import'));
        $form->setAttribute('method', 'post');
        
        if ($this->getRequest()->isPost()) {
            $data = array_replace_recursive(
                $this->getRequest()->getPost()->toArray(),
                $this->getRequest()->getFiles()->toArray()
            );
            
            if (! empty($data['import_file']['tmp_name'])) {
                ErrorHandler::start();
                $game = unserialize(file_get_contents($data['import_file']['tmp_name']));
                $game->setId(null);
                if ($data['slug']) {
                    $game->setIdentifier($data['slug']);
                }
                $duplicate = $this->getAdminGameService()->getGameMapper()->findByIdentifier($game->getIdentifier());
                if (!$duplicate) {
                    $this->getAdminGameService()->getGameMapper()->insert($game);
                }

                ErrorHandler::stop(true);
            }
            
            return $this->redirect()->toUrl($this->adminUrl()->fromRoute('playgroundgame/list'));
        }
        
        return array(
            'form' => $form,
        );
    }
960875
public function actionImport()
    {
        $filename = Architect::$configPath . DIRECTORY_SEPARATOR . Craft::$app->request->getQueryParam('file');
        $fileContents = '';
        if (is_file($filename)) {
            $fileContents = file_get_contents($filename);
        }
        return $this->renderTemplate('architect/import', [ 'importData' => $fileContents, 'invalidJSON' => false ]);
    }
657010
public function indexAction()
    {
        return $this->render('LiipTranslationBundle:Import:index.html.twig', array(
            'upload_form' => $this->createForm(new FileImportType())->createView(),
            'translations' => $this->getSessionImporter()->getCurrentTranslations(),
        ));
    }
820299
public function actionCanEdit(): Response
    {
        $this->requireAcceptsJson();
        $this->requirePostRequest();

        $assetId = Craft::$app->getRequest()->getRequiredBodyParam('assetId');
        $asset = Asset::find()->id($assetId)->one();

        if (!$asset) {
            return $this->asJson([
                'success' => false
            ]);
        }

        /** @var Volume $volume */
        $volume = $asset->getVolume();
        $user = Craft::$app->getUser()->getIdentity();

        return $this->asJson([
            'success' => (
                $user->can('saveAssetInVolume:' . $volume->uid) &&
                $user->can('deleteFilesAndFoldersInVolume:' . $volume->uid)
            ),
        ]);
    }
1123244
public function formAction()
    {
        $isNew     = 'new' == $this->params('mode');
        $form      = $this->formManager->get('Auth/Group', array('mode' => $this->params('mode')));
        $repository = $this->repositories->get('Auth/Group');
        
        if ($isNew) {
            $group = new \Auth\Entity\Group();
        } else {
            if ($this->getRequest()->isPost()) {
                $data = $this->params()->fromPost('data');
                $id   = isset($data['id']) ? $data['id'] : false;
            } else {
                $id   = $this->params()->fromQuery('id', false);
            }
            if (!$id) {
                throw new \RuntimeException('No id.');
            }
            $group = $repository->find($id);
        }
        
        $form->bind($group);
        if ($this->getRequest()->isPost()) {
            $form->setData($_POST);
            $isOk      = $form->isValid();
            $isUsersOk = !empty($group->users);
             
            if ($isOk) {
                // We have to check here, if there are any users provided
                // as InputFilter does not allow "required" to be set on fieldsets.
                if ($isUsersOk) {
                    if ($isNew) {
                        $user    = $this->auth()->getUser();
                        $group->setOwner($user);
                        $groups  = $user->getGroups();
                        $message = /*@translate*/ 'Group created';
                        $groups->add($group);
                    } else {
                        $message = /*@translate*/ 'Group updated';
                    }
                    
                    $this->notification()->success($message);
                    return $this->redirect()->toRoute('lang/my-groups');
                }
            }
            if (!$isUsersOk) {
                $form->get('data')->get('users')->setNoUsersError(true);
            }
            $this->notification()->error(/*@translate*/ 'Changes not saved.');
        }
        
        return array(
            'form' => $form,
            'isNew' => $isNew,
        );
    }
42277
protected function createComponentUserForm(): Form
	{
		$form = $this->formFactory->create();
		$form->setAjaxRequest();

		$form->addProtection();

		$form->addText('username', 'cms.user.username')
			->setDisabled()
			->setDefaultValue($this->profile->username);
		$form->addText('roles', 'cms.permissions.roles')
			->setDisabled()
			->setDefaultValue(implode(', ', $this->profile->roleTitles));
		$form->addText('firstName', 'cms.user.firstName')
			->setDefaultValue($this->profile->firstName);
		$form->addText('surname', 'cms.user.surname')
			->setDefaultValue($this->profile->surname);
		$form->addText('email', 'cms.user.email')
			->setDefaultValue($this->profile->email)
			->setRequired()
			->addRule(Form::EMAIL);
		$form->addPhone('phone', 'cms.user.phone')
			->setDefaultValue($this->profile->phone);

		$language = $form->addSelectUntranslated('language', 'cms.user.language', $this->localeService->allowed, 'form.none');
		$locale = $this->localeService->get($this->profile->language);
		if ($locale) {
			$language->setDefaultValue($locale->id);
		}

		$form->addSubmit('save', 'form.save');

		$form->onError[] = function (Form $form) {
			if ($this->isAjax()) {
				$this->redrawControl('userForm');
			}
		};

		$form->onSuccess[] = [$this, 'userFormSucceeded'];

		return $form;
	}
855026
public function index()
    {
        $importer = $this->getCurrentImporter();

        $this->propagate($importer);

        $formContainer = new tao_actions_form_Import(
            $importer,
            $this->getAvailableImportHandlers(),
            $this->getCurrentClass()
        );
        $importForm = $formContainer->getForm();

        if ($importForm->isSubmited() && $importForm->isValid()) {
            /** @var QueueDispatcher $queueDispatcher */
            $queueDispatcher = $this->getServiceLocator()->get(QueueDispatcher::SERVICE_ID);

            $task = $queueDispatcher->createTask(
                new ImportByHandler(),
                [
                    ImportByHandler::PARAM_IMPORT_HANDLER => get_class($importer),
                    ImportByHandler::PARAM_FORM_VALUES => $importer instanceof TaskParameterProviderInterface ? $importer->getTaskParameters($importForm) : [],
                    ImportByHandler::PARAM_PARENT_CLASS => $this->getCurrentClass()->getUri(),
                    ImportByHandler::PARAM_OWNER => \common_session_SessionManager::getSession()->getUser()->getIdentifier(),
                ],
                __('Import a %s into "%s"', $importer->getLabel(), $this->getCurrentClass()->getLabel()));

            return $this->returnTaskJson($task);
        }

        $context = Context::getInstance();
        $this->setData('import_extension', $context->getExtensionName());
        $this->setData('import_module', $context->getModuleName());
        $this->setData('import_action', $context->getActionName());

        $this->setData('myForm', $importForm->render());
        $this->setData('formTitle', __('Import '));
        $this->setView('form/import.tpl', 'tao');
    }
586424
public function AddForm() {
        $sng=singleton('Snippet');
        $fields=$sng->getCMSFields();
        $validator=$sng->getCMSValidator();
        
        $actions=new FieldList(
                                FormAction::create('doAdd', _t('CodeBank.CREATE', '_Create'))->addExtraClass('ss-ui-action-constructive')->setAttribute('data-icon', 'accept')->setUseButtonTag(true)
                            );
        
        $form=CMSForm::create($this, 'AddForm', $fields, $actions)->setHTMLID('Form_AddForm');
        $form->setValidator($validator);
        $form->disableDefaultAction();
        $form->addExtraClass('cms-add-form cms-edit-form');
        $form->setResponseNegotiator($this->getResponseNegotiator());
        $form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
        $form->addExtraClass('center '.$this->BaseCSSClasses());
        $form->setAttribute('data-pjax-fragment', 'CurrentForm');
        
        
        //Handle Language id in url
        if($this->request->getVar('LanguageID')) {
            $langField=$form->Fields()->dataFieldByName('LanguageID');
            if($langField && $langField->Value()=='') {
                $langField->setValue(intval(str_replace('language-', '', $this->request->getVar('LanguageID'))));
            }
        }
        
        
        //Handle folder id in url (or post)
        if($this->request->getVar('FolderID')) {
            $folder=SnippetFolder::get()->byID(intval($this->request->getVar('FolderID')));
            if(!empty($folder) && $folder!==false && $folder->ID!=0) {
                $langField=$form->Fields()->dataFieldByName('LanguageID')->setValue($folder->ParentID);
                $form->Fields()->replaceField('LanguageID', $langField->performReadonlyTransformation());
                $form->Fields()->push(new HiddenField('FolderID', 'FolderID', $folder->ID));
            }
        }else if($this->request->postVar('FolderID')) {
            $folder=SnippetFolder::get()->byID(intval($this->request->postVar('FolderID')));
            if(!empty($folder) && $folder!==false && $folder->ID!=0) {
                $langField=$form->Fields()->dataFieldByName('LanguageID')->setValue($folder->ParentID);
                $form->Fields()->replaceField('LanguageID', $langField->performReadonlyTransformation());
                $form->Fields()->push(new HiddenField('FolderID', 'FolderID', $folder->ID));
            }
        }
        
        
        $this->extend('updateAddForm', $form);
        
        
        //Display message telling user to run dev/build because the version numbers are out of sync
        if(CB_VERSION!='@@VERSION@@' && CodeBankConfig::CurrentConfig()->Version!=CB_VERSION.' '.CB_BUILD_DATE) {
            $form->insertBefore(new LiteralField('<p class="message error">'._t('CodeBank.UPDATE_NEEDED', '_A database upgrade is required please run {startlink}dev/build{endlink}.', array('startlink'=>'<a href="dev/build?flush=all">', 'endlink'=>'</a>')).'</p>'), 'LanguageID');
        }else if($this->hasOldTables()) {
            $form->insertBefore(new LiteralField('<p class="message warning">'._t('CodeBank.MIGRATION_AVAILABLE', '_It appears you are upgrading from Code Bank 2.2.x, your old data can be migrated {startlink}click here to begin{endlink}, though it is recommended you backup your database first.', array('startlink'=>'<a href="dev/tasks/CodeBankLegacyMigrate">', 'endlink'=>'</a>')).'</p>'), 'LanguageID');
        }
        
        $form->Actions()->push(new LiteralField('CodeBankVersion', '<p class="codeBankVersion">Code Bank: '.$this->getVersion().'</p>'));
        
        
        Requirements::javascript(CB_DIR.'/javascript/CodeBank.EditForm.js');
        
        return $form;
    }
828557
public function form()
    {
        $userModel = config('admin.database.users_model');
        $permissionModel = config('admin.database.permissions_model');
        $roleModel = config('admin.database.roles_model');

        $form = new Form(new $userModel());

        $form->display('id', 'ID');

        if (request()->isMethod('POST')) {
            $userTable = config('admin.database.users_table');
            $userNameRules = "required|unique:{$userTable}";
        } else {
            $userNameRules = 'required';
        }

        $form->text('username', trans('admin.username'))->rules($userNameRules);
        $form->text('name', trans('admin.name'))->rules('required');
        $form->image('avatar', trans('admin.avatar'));
        $form->password('password', trans('admin.password'))->rules('required|confirmed');
        $form->password('password_confirmation', trans('admin.password_confirmation'))->rules('required')
            ->default(function ($form) {
                return $form->model()->password;
            });

        $form->ignore(['password_confirmation']);

        $form->multipleSelect('roles', trans('admin.roles'))->options($roleModel::all()->pluck('name', 'id'));
        $form->multipleSelect('permissions', trans('admin.permissions'))->options($permissionModel::all()->pluck('name', 'id'));

        $form->display('created_at', trans('admin.created_at'));
        $form->display('updated_at', trans('admin.updated_at'));

        $form->saving(function (Form $form) {
            if ($form->password && $form->model()->password != $form->password) {
                $form->password = bcrypt($form->password);
            }
        });

        return $form;
    }
1054025
protected function createComponentEditForm(): Form
	{
		$form = $this->formFactory->create();
		$form->addProtection();

		$form->addText('username', 'cms.user.username')
			->setDefaultValue($this->currentUser->username)
			->setRequired();
		$form->addText('firstName', 'cms.user.firstName')
			->setDefaultValue($this->currentUser->firstName);
		$form->addText('surname', 'cms.user.surname')
			->setDefaultValue($this->currentUser->surname);
		$form->addText('email', 'cms.user.email')
			->setDefaultValue($this->currentUser->email)
			->setRequired()
			->addRule(Form::EMAIL);
		$form->addPhone('phone', 'cms.user.phone')
			->setDefaultValue($this->currentUser->phone);

		$language = $form->addSelectUntranslated('language', 'cms.user.language', $this->localeService->allowed, 'form.none');
		if (!empty($this->currentUser->language)) {
			$locale = $this->localeService->get($this->currentUser->language);
			if ($locale) {
				$language->setDefaultValue($locale->id);
			}
		}

		$roles = $form->addMultiSelectUntranslated('roles', 'cms.permissions.roles', $this->orm->aclRoles->fetchPairs($this->user->isAllowed('dockbar.settings.permissions.superadmin', 'view')))
			->setRequired();
		try {
			$roles->setDefaultValue($this->currentUser->roles->getRawValue());
		} catch (InvalidArgumentException $ex) {

		}

		$form->addSubmit('save', 'form.save');
		$form->addLink('back', 'form.back', $this->getBacklink());

		$form->onSuccess[] = [$this, 'editFormSucceeded'];

		return $form;
	}
1102560
static public function formSubmit() {

		// --------------------------------------------------------------------------------------------------------
		// Sanity check

		if ( false === static::isFormSubmission() || false === current_user_can( 'edit_posts' ) ) {
			// Don't do anything in this function, bail.
			return;
		}

		// --------------------------------------------------------------------------------------------------------
		// Determine at what stage of the import we are and do something about it

		$redirect_url = get_admin_url( get_current_blog_id(), '/tools.php?page=pb_import' );

		// Revoke
		if ( ! empty( $_GET['revoke'] ) && check_admin_referer( 'pb-revoke-import' ) ) {
			self::_revokeCurrentImport();
			\Pressbooks\Redirect\location( $redirect_url );
		}

		if ( isset( $_GET['import'] ) && ! empty( $_POST['import_type'] ) && check_admin_referer( 'pb-import' ) ) {
			self::setImportOptions(); // STEP 1
		}

		// Default, back to form
		\Pressbooks\Redirect\location( $redirect_url );
	}
981639
public function actionExport() {
        // Initialize export array.
        $data = [
            'siteGroups' => [],
            'sites' => [],
            'routes' => [],
            'fieldGroups' => [],
            'volumes' => [],
            'transforms' => [],
            'tagGroups' => [],
            'categoryGroups' => [],
            'sections' => [],
            'fields' => [],
            'entryTypes' => [],
            'globalSets' => [],
            'userGroups' => [],
            'users' => [],
        ];
        // The list of exportable items.
        $exportList = [
            'sites' => [
                'bodyParam' => 'siteSelection',
                'postProcess' => [
                    'groupId' => 'siteGroups'
                ],
            ],
            'sections' => [
                'bodyParam' => 'sectionSelection',
                'postProcess' => [
                    'entryTypes' => 'entryTypes'
                ],
            ],
            'routes' => [
                'bodyParam' => 'routeSelection',
            ],
            'volumes' => [
                'bodyParam' => 'volumeSelection',
            ],
            'transforms' => [
                'bodyParam' => 'assetTransformSelection',
            ],
            'tagGroups' => [
                'bodyParam' => 'tagSelection',
            ],
            'categoryGroups' => [
                'bodyParam' => 'categorySelection',
            ],
            'fields' => [
                'bodyParam' => 'fieldSelection',
                'postProcess' => [
                    'groupId' => 'fieldGroups'
                ],
            ],
            'globalSets' => [
                'bodyParam' => 'globalSelection',
            ],
            'userGroups' => [
                'bodyParam' => 'userGroupSelection',
            ],
            'users' => [
                'bodyParam' => 'userSelection',
            ]
        ];

        foreach ($exportList as $processorName => $processorInfo) {
            $exportIds = Craft::$app->request->getBodyParam($processorInfo['bodyParam']);
            if ($exportIds) {
                foreach ($exportIds as $exportId) {
                    if ($processorName === 'routes') {
                        $exportObj = Architect::$processors->$processorName->exportByUid($exportId);
                    } else {
                        $exportObj = Architect::$processors->$processorName->exportById($exportId);
                    }

                    if (isset($processorInfo['postProcess'])) {
                        foreach ($processorInfo['postProcess'] as $postProcessKey => $postProcessorName) {
                            switch ($postProcessKey) {
                                case 'groupId':
                                    $groupName = Architect::$processors->$postProcessorName->exportById($exportObj[$postProcessKey]);
                                    if (\in_array($groupName, $data[$postProcessorName], false) === false) {
                                        $data[$postProcessorName][] = $groupName;
                                    }
                                    unset($exportObj[$postProcessKey]);
                                    break;
                                case 'entryTypes':
                                    if (isset($exportObj[$postProcessKey]) && \is_array($exportObj[$postProcessKey])) {
                                        $data[$postProcessorName] = array_merge($data[$postProcessorName], $exportObj[$postProcessKey]);
                                        unset($exportObj[$postProcessKey]);
                                    }
                                    break;
                            }
                        }
                    }

                    $data[$processorName][] = $exportObj;
                }
            }
        }

        foreach ($data as $key => $value) {
            if (\count($value) <= 0) {
                unset($data[$key]);
            }
        }

        $this->renderTemplate('architect/export_results', [ 'dump' => json_encode($data, JSON_PRETTY_PRINT) ]);
    }