1<?php 2 3/** 4 * webtrees: online genealogy 5 * Copyright (C) 2019 webtrees development team 6 * This program is free software: you can redistribute it and/or modify 7 * it under the terms of the GNU General Public License as published by 8 * the Free Software Foundation, either version 3 of the License, or 9 * (at your option) any later version. 10 * This program is distributed in the hope that it will be useful, 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 * GNU General Public License for more details. 14 * You should have received a copy of the GNU General Public License 15 * along with this program. If not, see <http://www.gnu.org/licenses/>. 16 */ 17 18declare(strict_types=1); 19 20namespace Fisharebest\Webtrees\Http\RequestHandlers; 21 22use Fig\Http\Message\StatusCodeInterface; 23use Fisharebest\Webtrees\FlashMessages; 24use Fisharebest\Webtrees\I18N; 25use InvalidArgumentException; 26use League\Flysystem\FilesystemInterface; 27use Psr\Http\Message\ResponseInterface; 28use Psr\Http\Message\ServerRequestInterface; 29use Psr\Http\Server\RequestHandlerInterface; 30use Throwable; 31 32use function assert; 33use function e; 34use function is_string; 35use function response; 36 37/** 38 * Delete a file. 39 */ 40class DeletePath implements RequestHandlerInterface, StatusCodeInterface 41{ 42 /** @var FilesystemInterface */ 43 private $filesystem; 44 45 /** 46 * @param FilesystemInterface $filesystem 47 */ 48 public function __construct(FilesystemInterface $filesystem) 49 { 50 $this->filesystem = $filesystem; 51 } 52 53 /** 54 * @param ServerRequestInterface $request 55 * 56 * @return ResponseInterface 57 */ 58 public function handle(ServerRequestInterface $request): ResponseInterface 59 { 60 $path = $request->getQueryParams()['path']; 61 assert(is_string($path), new InvalidArgumentException()); 62 63 if ($this->filesystem->has($path)) { 64 $metadata = $this->filesystem->getMetadata($path); 65 66 switch ($metadata['type']) { 67 case 'file': 68 try { 69 $this->filesystem->delete($path); 70 FlashMessages::addMessage(I18N::translate('The file %s has been deleted.', e($path)), 'success'); 71 } catch (Throwable $ex) { 72 FlashMessages::addMessage(I18N::translate('The file %s could not be deleted.', e($path)), 'danger'); 73 } 74 break; 75 76 case 'dir': 77 try { 78 $this->filesystem->deleteDir($path); 79 FlashMessages::addMessage(I18N::translate('The folder %s has been deleted.', e($path)), 'success'); 80 } catch (Throwable $ex) { 81 FlashMessages::addMessage(I18N::translate('The folder %s could not be deleted.', e($path)), 'danger'); 82 } 83 break; 84 } 85 } else { 86 FlashMessages::addMessage(I18N::translate('The file %s could not be deleted.', e($path)), 'danger'); 87 } 88 89 return response('', StatusCodeInterface::STATUS_NO_CONTENT); 90 } 91} 92