Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions islandora_workbench_integration.permissions.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
rename files:
title: 'Rename files'
description: 'Rename files.'
restrict access: true
16 changes: 16 additions & 0 deletions islandora_workbench_integration.routing.yml
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,19 @@ islandora_workbench_integration.file_hash:
_permission: 'administer site configuration'
options:
_auth: ['basic_auth','jwt_auth','cookie']

islandora_workbench_integration.workbench_rename_file:
path: '/islandora_workbench_integration/rename/{file}'
defaults:
_controller: '\Drupal\islandora_workbench_integration\Controller\IslandoraWorkbenchIntegrationFileRenameController::main'
_title: 'Rename file'
_access: TRUE
requirements:
_permission: 'rename files'
methods: [GET, POST]
options:
_admin_route: TRUE
_auth: ['basic_auth']
parameters:
file:
type: entity:file
188 changes: 188 additions & 0 deletions src/Controller/IslandoraWorkbenchIntegrationFileRenameController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
<?php

namespace Drupal\islandora_workbench_integration\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\File\FileSystemInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\File\Event\FileUploadSanitizeNameEvent;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Psr\Log\LoggerInterface;

/**
* Controller for file rename operations.
*/
class IslandoraWorkbenchIntegrationFileRenameController extends ControllerBase {
/**
* FileSystem service.
*
* @var \Drupal\Core\File\FileSystemInterface
*/
protected $fileSystem;

/**
* EventDispatcher service.
*
* @var \Symfony\Component\EventDispatcher\EventDispatcher
*/
protected $eventDispatcher;

/**
* Logger service.
*
* @var \Psr\Log\LoggerInterface
*/
protected $logger;

/**
* Constructor to inject the Symfony Filesystem service.
*/
public function __construct(FileSystemInterface $fileSystem, EventDispatcherInterface $event_dispatcher, LoggerInterface $logger) {
$this->fileSystem = $fileSystem;
$this->eventDispatcher = $event_dispatcher;
$this->logger = $logger;
}

/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('file_system'),
$container->get('event_dispatcher'),
$container->get('logger.factory')->get('islandora_workbench_integration')
);
}

/**
* Renames a file while keeping the extension unchanged.
*
* Expects a URL parameter for the file ID (fid) and a JSON payload with:
* - new_filename: The new base file name (without extension).
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The incoming request.
* @param Drupal\file\Entity\File $file
* The file ID from the URL.
*
* @return \Symfony\Component\HttpFoundation\JsonResponse
* The JSON response.
*/
public function main(Request $request, $file) {
// Decode JSON payload.
$data = json_decode($request->getContent(), TRUE);

// Validate that new_filename is provided.
if (empty($data['new_filename'])) {
return new JsonResponse(['error' => 'Missing new_filename parameter']);
}

if (!$file) {
return new JsonResponse(["Error 404" => 'No file found']);
}

$filename_new = $data['new_filename'];
$msg = $this->validate($file, $filename_new);
if ($msg != 'OK') {
return new JsonResponse(['Error' => $msg]);
}

if ($filename_new != $file->getFilename()) {
$original_filename = $file->getFilename();
$filepath_new = $this->getRenamedFilePath($file, $filename_new);
rename($file->getFileUri(), $filepath_new);
// Update file entity.
$file->setFilename($filename_new);
$file->setFileUri($filepath_new);
$file->save();

// Log the file rename operation.
$this->logger->info(
'File renamed from @original to @new', [
'@original' => $original_filename,
'@new' => $filename_new,
]
);

return new JsonResponse(
[
'message' => 'File renamed successfully',
'original_filename' => $original_filename,
'new_filename' => $filename_new,
]
);
}
}

/**
* Check if the file name is valid.
*
* @param Drupal\file\Entity\File $file
* File that needs to be renamed.
* @param string $new_filename
* File Name of the new file.
*
* @return string
* Error Message if not valid else OK.
*/
public function validate($file, $new_filename) {
$pathinfo = pathinfo($file->getFileUri());
$source_file_uri = $file->getFileUri();

if (!file_exists($source_file_uri)) {
// Show an error if no file on disc.
return 'No file with name' . $file->getFilename() . 'exists at' . $source_file_uri;
}

$new_basename = $new_filename;

if ($new_basename !== $file->getFilename()) {
// File renamed.
if ($new_basename !== basename($new_basename)
|| strpos($new_basename, '\\') !== FALSE
) {
// If filename contains a slash or a backslash.
return 'Value must be a filename with no path information';
}
else {
// Dispatching a event to use default filename validation.
$event = new FileUploadSanitizeNameEvent($new_basename, $pathinfo['extension']);
$this->eventDispatcher->dispatch($event);

if ($event->isSecurityRename()) {
// If new filename contains forbidden characters.
return ('File name is invalid');
}
}

$new_file_path = $this->getRenamedFilePath($file, $new_basename);
if (file_exists($new_file_path)) {
// File with given name already on disc.
return ('File with this name already exists in the directory.');
}
}

return 'OK';
}

/**
* Get Renamed File Path.
*
* @param Drupal\file\Entity\File $file
* File that needs to be renamed.
* @param string $new_filename
* File Name of the new file.
*
* @return string
* File name after rename.
*/
protected function getRenamedFilePath($file, $new_filename) {
$pathinfo = pathinfo($file->getFileUri());
$old_filename = $pathinfo['filename'] . '.' . $pathinfo['extension'];
// Path after renaming.
return str_replace($old_filename, $new_filename, $file->getFileUri());
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
<?php

namespace Drupal\Tests\islandora_workbench_integration\Functional;

use Drupal\Tests\BrowserTestBase;
use Drupal\file\Entity\File;

/**
* Tests the file rename controller.
*
* @group islandora_workbench_integration
*/
class IslandoraWorkbenchIntegrationFileRenameControllerTest extends BrowserTestBase {

/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';

/**
* {@inheritdoc}
*/
protected static $modules = ['islandora_workbench_integration', 'file'];

/**
* Test file entity.
*
* @var \Drupal\file\Entity\File
*/
protected $testFile;

/**
* User with rename files permission.
*
* @var \Drupal\user\UserInterface
*/
protected $privilegedUser;

/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();

// Create a user with 'rename files' permission.
$this->privilegedUser = $this->drupalCreateUser(['rename files']);

// Create a test file.
$file_system = \Drupal::service('file_system');
$temp_file = $file_system->tempnam('temporary://', 'test');
file_put_contents($temp_file, 'Test file content');

$this->testFile = File::create([
'uri' => $temp_file,
'filename' => 'test_file.txt',
'status' => 1,
]);
$this->testFile->save();
}

/**
* Test that the route exists and responds.
*/
public function testRouteExists() {
$this->drupalLogin($this->privilegedUser);

// Just test that the route responds (even if with an error).
$this->drupalGet('/islandora_workbench_integration/rename/' . $this->testFile->id());

// Accept any response that's not 404 (route not found).
$status_code = $this->getSession()->getStatusCode();
$this->assertNotEquals(404, $status_code, 'Route should exist and not return 404');
}

/**
* Test unauthenticated access.
*/
public function testUnauthenticatedAccess() {
// Don't login - test unauthenticated access.
$this->drupalGet('/islandora_workbench_integration/rename/' . $this->testFile->id());

// Should be denied access without authentication.
$status_code = $this->getSession()->getStatusCode();
$this->assertContains($status_code, [401, 403], 'Unauthenticated access should be denied');
}

/**
* {@inheritdoc}
*/
protected function tearDown(): void {
// Clean up test files.
if ($this->testFile) {
$this->testFile->delete();
}
parent::tearDown();
}

}