Part-DB.Part-DB-server/src/Controller/AdminPages/BaseAdminController.php

352 lines
14 KiB
PHP
Raw Normal View History

<?php
2020-02-22 18:14:36 +01:00
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
* Copyright (C) 2019 - 2020 Jan Böhmer (https://github.com/jbtronics)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
2020-01-05 15:46:58 +01:00
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
2019-11-01 13:40:30 +01:00
* Copyright (C) 2019 Jan Böhmer (https://github.com/jbtronics)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
2019-04-28 13:10:11 +02:00
namespace App\Controller\AdminPages;
2020-03-04 21:09:01 +01:00
use App\DataTables\LogDataTable;
use App\Entity\Base\AbstractNamedDBElement;
use App\Entity\Base\AbstractStructuralDBElement;
use App\Entity\UserSystem\User;
use App\Exceptions\AttachmentDownloadException;
use App\Form\AdminPages\ImportType;
use App\Form\AdminPages\MassCreationForm;
use App\Services\Attachments\AttachmentManager;
use App\Services\Attachments\AttachmentSubmitHandler;
use App\Services\EntityExporter;
use App\Services\EntityImporter;
use App\Services\LogSystem\EventCommentHelper;
2020-03-04 21:09:01 +01:00
use App\Services\LogSystem\HistoryHelper;
use App\Services\LogSystem\TimeTravel;
use App\Services\StructuralElementRecursionHelper;
use Doctrine\ORM\EntityManagerInterface;
2020-01-05 22:49:00 +01:00
use InvalidArgumentException;
2020-03-04 21:09:01 +01:00
use Omines\DataTablesBundle\DataTableFactory;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\File\UploadedFile;
2020-02-02 14:05:36 +01:00
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
2020-02-02 14:05:36 +01:00
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Validator\ConstraintViolationList;
use Symfony\Contracts\Translation\TranslatorInterface;
abstract class BaseAdminController extends AbstractController
{
2019-08-20 18:39:57 +02:00
protected $entity_class = '';
protected $form_class = '';
protected $twig_template = '';
protected $route_base = '';
protected $attachment_class = '';
protected $passwordEncoder;
protected $translator;
protected $attachmentHelper;
protected $attachmentSubmitHandler;
protected $commentHelper;
2020-03-04 21:09:01 +01:00
protected $historyHelper;
protected $timeTravel;
protected $dataTableFactory;
public function __construct(TranslatorInterface $translator, UserPasswordEncoderInterface $passwordEncoder,
AttachmentManager $attachmentHelper, AttachmentSubmitHandler $attachmentSubmitHandler,
2020-03-04 21:09:01 +01:00
EventCommentHelper $commentHelper, HistoryHelper $historyHelper, TimeTravel $timeTravel,
DataTableFactory $dataTableFactory)
{
if ('' === $this->entity_class || '' === $this->form_class || '' === $this->twig_template || '' === $this->route_base) {
2020-01-05 22:49:00 +01:00
throw new InvalidArgumentException('You have to override the $entity_class, $form_class, $route_base and $twig_template value in your subclasss!');
}
if ('' === $this->attachment_class) {
2020-01-05 22:49:00 +01:00
throw new InvalidArgumentException('You have to override the $attachment_class value in your subclass!');
}
$this->translator = $translator;
$this->passwordEncoder = $passwordEncoder;
$this->attachmentHelper = $attachmentHelper;
$this->attachmentSubmitHandler = $attachmentSubmitHandler;
$this->commentHelper = $commentHelper;
2020-03-04 21:09:01 +01:00
$this->historyHelper = $historyHelper;
$this->timeTravel = $timeTravel;
$this->dataTableFactory = $dataTableFactory;
}
2020-02-02 14:05:36 +01:00
protected function _edit(AbstractNamedDBElement $entity, Request $request, EntityManagerInterface $em) : Response
{
$this->denyAccessUnlessGranted('read', $entity);
2020-03-04 21:09:01 +01:00
$table = $this->dataTableFactory->createFromType(LogDataTable::class, [
'filter_elements' => $this->historyHelper->getAssociatedElements($entity),
'mode' => 'element_history'
], ['pageLength' => 10])
->handleRequest($request);
if ($table->isCallback()) {
return $table->getResponse();
}
$form = $this->createForm($this->form_class, $entity, ['attachment_class' => $this->attachment_class]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
//Check if we editing a user and if we need to change the password of it
2020-01-05 15:46:58 +01:00
if ($entity instanceof User && ! empty($form['new_password']->getData())) {
$password = $this->passwordEncoder->encodePassword($entity, $form['new_password']->getData());
$entity->setPassword($password);
//By default the user must change the password afterwards
$entity->setNeedPwChange(true);
}
//Upload passed files
$attachments = $form['attachments'];
foreach ($attachments as $attachment) {
2020-01-05 15:46:58 +01:00
/** @var FormInterface $attachment */
$options = [
'secure_attachment' => $attachment['secureFile']->getData(),
'download_url' => $attachment['downloadURL']->getData(),
];
2020-01-05 15:46:58 +01:00
try {
$this->attachmentSubmitHandler->handleFormSubmit($attachment->getData(), $attachment['file']->getData(), $options);
2020-01-05 22:49:00 +01:00
} catch (AttachmentDownloadException $attachmentDownloadException) {
$this->addFlash(
'error',
2020-01-05 22:49:00 +01:00
$this->translator->trans('attachment.download_failed').' '.$attachmentDownloadException->getMessage()
);
}
}
$this->commentHelper->setMessage($form['log_comment']->getData());
$em->persist($entity);
$em->flush();
$this->addFlash('success', 'entity.edit_flash');
//Rebuild form, so it is based on the updated data. Important for the parent field!
//We can not use dynamic form events here, because the parent entity list is build from database!
$form = $this->createForm($this->form_class, $entity, ['attachment_class' => $this->attachment_class]);
2020-01-05 15:46:58 +01:00
} elseif ($form->isSubmitted() && ! $form->isValid()) {
$this->addFlash('error', 'entity.edit_flash.invalid');
}
return $this->render($this->twig_template, [
'entity' => $entity,
'form' => $form->createView(),
'attachment_helper' => $this->attachmentHelper,
2020-02-23 19:45:06 +01:00
'route_base' => $this->route_base,
2020-03-04 21:09:01 +01:00
'datatable' => $table
]);
}
protected function _new(Request $request, EntityManagerInterface $em, EntityImporter $importer)
{
/** @var AbstractStructuralDBElement|User $new_entity */
$new_entity = new $this->entity_class();
$this->denyAccessUnlessGranted('read', $new_entity);
//Basic edit form
$form = $this->createForm($this->form_class, $new_entity, ['attachment_class' => $this->attachment_class]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
2020-01-05 15:46:58 +01:00
if ($new_entity instanceof User && ! empty($form['new_password']->getData())) {
$password = $this->passwordEncoder->encodePassword($new_entity, $form['new_password']->getData());
$new_entity->setPassword($password);
//By default the user must change the password afterwards
$new_entity->setNeedPwChange(true);
}
//Upload passed files
$attachments = $form['attachments'];
foreach ($attachments as $attachment) {
2020-01-05 15:46:58 +01:00
/** @var FormInterface $attachment */
$options = [
'secure_attachment' => $attachment['secureFile']->getData(),
'download_url' => $attachment['downloadURL']->getData(),
];
2020-01-05 15:46:58 +01:00
try {
$this->attachmentSubmitHandler->handleFormSubmit($attachment->getData(), $attachment['file']->getData(), $options);
2020-01-05 22:49:00 +01:00
} catch (AttachmentDownloadException $attachmentDownloadException) {
$this->addFlash(
'error',
2020-01-05 22:49:00 +01:00
$this->translator->trans('attachment.download_failed').' '.$attachmentDownloadException->getMessage()
);
}
}
$this->commentHelper->setMessage($form['log_comment']->getData());
$em->persist($new_entity);
$em->flush();
$this->addFlash('success', 'entity.created_flash');
return $this->redirectToRoute($this->route_base.'_edit', ['id' => $new_entity->getID()]);
2019-09-16 22:04:59 +02:00
}
2020-01-05 15:46:58 +01:00
if ($form->isSubmitted() && ! $form->isValid()) {
$this->addFlash('error', 'entity.created_flash.invalid');
}
//Import form
$import_form = $this->createForm(ImportType::class, ['entity_class' => $this->entity_class]);
$import_form->handleRequest($request);
if ($import_form->isSubmitted() && $import_form->isValid()) {
/** @var UploadedFile $file */
$file = $import_form['file']->getData();
$data = $import_form->getData();
2020-01-05 22:49:00 +01:00
$options = [
'parent' => $data['parent'],
'preserve_children' => $data['preserve_children'],
'format' => $data['format'],
'csv_separator' => $data['csv_separator'],
];
$this->commentHelper->setMessage('Import ' . $file->getClientOriginalName());
$errors = $importer->fileToDBEntities($file, $this->entity_class, $options);
foreach ($errors as $name => $error) {
2020-01-05 15:46:58 +01:00
/** @var ConstraintViolationList $error */
$this->addFlash('error', $name.':'.$error);
}
}
//Mass creation form
$mass_creation_form = $this->createForm(MassCreationForm::class, ['entity_class' => $this->entity_class]);
$mass_creation_form->handleRequest($request);
if ($mass_creation_form->isSubmitted() && $mass_creation_form->isValid()) {
$data = $mass_creation_form->getData();
//Create entries based on input
2019-11-09 16:14:57 +01:00
$errors = [];
$results = $importer->massCreation($data['lines'], $this->entity_class, $data['parent'], $errors);
//Show errors to user:
2019-11-09 16:14:57 +01:00
foreach ($errors as $error) {
$this->addFlash('error', $error['entity']->getFullPath().':'.$error['violations']);
}
2019-11-09 16:14:57 +01:00
//Persist valid entities to DB
foreach ($results as $result) {
$em->persist($result);
}
$em->flush();
}
return $this->render($this->twig_template, [
'entity' => $new_entity,
'form' => $form->createView(),
'import_form' => $import_form->createView(),
'mass_creation_form' => $mass_creation_form->createView(),
'attachment_helper' => $this->attachmentHelper,
2020-02-23 19:45:06 +01:00
'route_base' => $this->route_base,
]);
}
2020-02-02 14:05:36 +01:00
protected function _delete(Request $request, AbstractNamedDBElement $entity, StructuralElementRecursionHelper $recursionHelper) : RedirectResponse
{
$this->denyAccessUnlessGranted('delete', $entity);
if ($this->isCsrfTokenValid('delete'.$entity->getId(), $request->request->get('_token'))) {
$entityManager = $this->getDoctrine()->getManager();
//Check if we need to remove recursively
if ($entity instanceof AbstractStructuralDBElement && $request->get('delete_recursive', false)) {
$recursionHelper->delete($entity, false);
} else {
if ($entity instanceof AbstractStructuralDBElement) {
$parent = $entity->getParent();
//Move all sub entities to the current parent
foreach ($entity->getSubelements() as $subelement) {
$subelement->setParent($parent);
$entityManager->persist($subelement);
}
}
//Remove current element
$entityManager->remove($entity);
}
$this->commentHelper->setMessage($request->request->get('log_comment', null));
//Flush changes
$entityManager->flush();
$this->addFlash('success', 'attachment_type.deleted');
} else {
$this->addFlash('error', 'csfr_invalid');
}
return $this->redirectToRoute($this->route_base.'_new');
}
2020-02-02 14:05:36 +01:00
protected function _exportAll(EntityManagerInterface $em, EntityExporter $exporter, Request $request): Response
{
$entity = new $this->entity_class();
$this->denyAccessUnlessGranted('read', $entity);
$entities = $em->getRepository($this->entity_class)->findAll();
return $exporter->exportEntityFromRequest($entities, $request);
}
2020-02-02 14:05:36 +01:00
protected function _exportEntity(AbstractNamedDBElement $entity, EntityExporter $exporter, Request $request): \Symfony\Component\HttpFoundation\Response
{
$this->denyAccessUnlessGranted('read', $entity);
return $exporter->exportEntityFromRequest($entity, $request);
}
}