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
204 changes: 165 additions & 39 deletions Classes/EventListener/Backend/DefaultUploadFolder.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,17 @@
namespace BeechIt\DefaultUploadFolder\EventListener\Backend;

use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Core\Page\PageRenderer;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\File\ExtendedFileUtility;
use TYPO3\CMS\Core\Resource\Event\AfterDefaultUploadFolderWasResolvedEvent;
use TYPO3\CMS\Core\Resource\Exception\FolderDoesNotExistException;
use TYPO3\CMS\Core\Resource\Exception\InsufficientFolderAccessPermissionsException;
use TYPO3\CMS\Core\Resource\Folder;
use TYPO3\CMS\Core\Resource\FolderInterface;
use TYPO3\CMS\Core\Resource\ResourceFactory;
use TYPO3\CMS\Core\Utility\File\ExtendedFileUtility;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Resource\Enum\DuplicationBehavior;


class DefaultUploadFolder
{
Expand All @@ -34,15 +37,15 @@ public function __invoke(AfterDefaultUploadFolderWasResolvedEvent $event): void
$userTsConfig = $GLOBALS['BE_USER']->getTsConfig();
$subFolder = '';
if ($table !== null && $field !== null) {
$subFolder = $this->getDefaultUploadFolderForTableAndField($table, $field, $pageTs, $userTsConfig);
$subFolder = $this->getDefaultUploadFolderForTableAndField($table, $field, $pageTs, $userTsConfig, (int)$pid);
}

if (trim($subFolder) === '' && $field !== null) {
$subFolder = $this->getDefaultUploadFolderForTable($table, $pageTs, $userTsConfig);
$subFolder = $this->getDefaultUploadFolderForTable($table, $pageTs, $userTsConfig, (int)$pid);
}

if (trim($subFolder) === '') {
$subFolder = $this->getDefaultUploadFolderForAllTables($pageTs, $userTsConfig);
$subFolder = $this->getDefaultUploadFolderForAllTables($pageTs, $userTsConfig, (int)$pid);
}

// Folder by combined identifier
Expand All @@ -65,8 +68,74 @@ public function __invoke(AfterDefaultUploadFolderWasResolvedEvent $event): void
if ($uploadFolder instanceof FolderInterface) {
$event->setUploadFolder($uploadFolder);
}

$this->showUploadFolderInfo($table, $field, $subFolder, (int)$pid);
}

/**
* Zeigt Informationen zum aktuellen Upload-Ordner an
*
* @param string|null $table
* @param string|null $field
* @param string $uploadFolder
* @param int $pid
*/
protected function showUploadFolderInfo(?string $table, ?string $field, string $uploadFolder, int $pid): void
{


// Prüfen, ob die notwendigen Daten vorhanden sind
if (!$table || !$field || !$uploadFolder) {
return;
}


// Prüfe die Gültigkeit des Ordners und bereite Informationen vor
$uploadFolderPath = $uploadFolder;
$isValidPath = true;
$errorMessage = '';

if (preg_match('/^(\d+):(.*)$/', $uploadFolder, $matches)) {


$storageUid = (int)$matches[1];
$folderPath = $matches[2];

try {
// Versuche den Storage zu laden
$storage = GeneralUtility::makeInstance(ResourceFactory::class)->getStorageObject($storageUid);

if (!$storage->isOnline()) {
$isValidPath = false;
$errorMessage = 'Storage ist falsch oder nicht erreichbar';
} else {
$configuration = $storage->getConfiguration();
$basePath = $configuration['basePath'] ?? '';

if ($basePath) {
$uploadFolderPath = $basePath . $folderPath;
}
}
} catch (\Exception $e) {
$isValidPath = false;
$errorMessage = 'Storage mit ID ' . $storageUid . ' existiert nicht';
}
}

// JavaScript-Code einfügen, um die Information im Formular anzuzeigen
$pageRenderer = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Page\PageRenderer::class);

$js = '
if (!window.uploadFolderInfo) window.uploadFolderInfo = {};
window.uploadFolderInfo[' . json_encode($field) . '] = ' . json_encode($uploadFolderPath) . ';
';

$pageRenderer->addJsInlineCode('uploadFolderData_' . $field, $js, false, false, true);
$pageRenderer->addJsFile('EXT:default_upload_folder/Resources/Public/JavaScript/PathInfo.js');

}


/**
* Create upload folder
*
Expand Down Expand Up @@ -106,10 +175,13 @@ private function createUploadFolder($combinedFolderIdentifier): ?Folder
],
];


$fileProcessor = GeneralUtility::makeInstance(ExtendedFileUtility::class);
$fileProcessor->setExistingFilesConflictMode(DuplicationBehavior::RENAME);
$fileProcessor->setActionPermissions();
$fileProcessor->start($data);
$fileProcessor->processData();

return GeneralUtility::makeInstance(ResourceFactory::class)->getFolderObjectFromCombinedIdentifier(
$combinedFolderIdentifier
);
Expand All @@ -122,22 +194,24 @@ private function createUploadFolder($combinedFolderIdentifier): ?Folder
* @param string $field
* @param array $defaultPageTs
* @param array $userTsConfig
* @param int $pid
* @return string
*/
protected function getDefaultUploadFolderForTableAndField(
string $table,
string $field,
array $defaultPageTs,
array $userTsConfig
array $userTsConfig,
int $pid
): string
{
$subFolder = $defaultPageTs[self::DEFAULT_UPLOAD_FOLDERS][$table . '.'][$field] ?? '';
$dateFormatConfig = $defaultPageTs[self::DEFAULT_UPLOAD_FOLDERS][$table . '.'][$field . '.'] ?? [];
$subFolder = $this->checkAndConvertForDateFormat($subFolder, $dateFormatConfig);
$config = $defaultPageTs[self::DEFAULT_UPLOAD_FOLDERS][$table . '.'][$field . '.'] ?? [];
$subFolder = $this->checkAndConvertForVariable($subFolder, $config, $pid);
if (empty($subFolder)) {
$subFolder = $userTsConfig[self::DEFAULT_UPLOAD_FOLDERS][$table . '.'][$field] ?? '';
$dateFormatConfig = $userTsConfig[self::DEFAULT_UPLOAD_FOLDERS][$table . '.'][$field . '.'] ?? [];
$subFolder = $this->checkAndConvertForDateFormat($subFolder, $dateFormatConfig);
$config = $userTsConfig[self::DEFAULT_UPLOAD_FOLDERS][$table . '.'][$field . '.'] ?? [];
$subFolder = $this->checkAndConvertForVariable($subFolder, $config, $pid);
}
return $subFolder;
}
Expand All @@ -148,22 +222,24 @@ protected function getDefaultUploadFolderForTableAndField(
* @param string $table
* @param array $defaultPageTs
* @param array $userTsConfig
* @param int $pid
* @return string
*/
protected function getDefaultUploadFolderForTable(
string $table,
array $defaultPageTs,
array $userTsConfig
array $userTsConfig,
int $pid
): string
{
$subFolder = $defaultPageTs[self::DEFAULT_UPLOAD_FOLDERS][$table] ?? '';

$dateFormatConfig = $defaultPageTs[self::DEFAULT_UPLOAD_FOLDERS][$table . '.'] ?? [];
$subFolder = $this->checkAndConvertForDateFormat($subFolder, $dateFormatConfig);
$config = $defaultPageTs[self::DEFAULT_UPLOAD_FOLDERS][$table . '.'] ?? [];
$subFolder = $this->checkAndConvertForVariable($subFolder, $config, $pid);
if (empty($subFolder)) {
$subFolder = $userTsConfig[self::DEFAULT_UPLOAD_FOLDERS][$table] ?? '';
$dateFormatConfig = $userTsConfig[self::DEFAULT_UPLOAD_FOLDERS][$table . '.'] ?? [];
$subFolder = $this->checkAndConvertForDateFormat($subFolder, $dateFormatConfig);
$config = $userTsConfig[self::DEFAULT_UPLOAD_FOLDERS][$table . '.'] ?? [];
$subFolder = $this->checkAndConvertForVariable($subFolder, $config, $pid);
}
return $subFolder;
}
Expand All @@ -173,53 +249,103 @@ protected function getDefaultUploadFolderForTable(
*
* @param array $defaultPageTs
* @param array $userTsConfig
* @param int $pid
* @return string
*/
protected function getDefaultUploadFolderForAllTables(
array $defaultPageTs,
array $userTsConfig
array $userTsConfig,
int $pid
): string
{
$subFolder = $defaultPageTs[self::DEFAULT_UPLOAD_FOLDERS][self::DEFAULT_FOR_ALL_TABLES] ?? '';

$dateFormatConfig = $defaultPageTs[self::DEFAULT_UPLOAD_FOLDERS][self::DEFAULT_FOR_ALL_TABLES . '.'] ?? [];
$subFolder = $this->checkAndConvertForDateFormat($subFolder, $dateFormatConfig);
$config = $defaultPageTs[self::DEFAULT_UPLOAD_FOLDERS][self::DEFAULT_FOR_ALL_TABLES . '.'] ?? [];
$subFolder = $this->checkAndConvertForVariable($subFolder, $config, $pid);
if (empty($subFolder)) {
$subFolder = $userTsConfig[self::DEFAULT_UPLOAD_FOLDERS][self::DEFAULT_FOR_ALL_TABLES] ?? '';

$dateFormatConfig = $userTsConfig[self::DEFAULT_UPLOAD_FOLDERS][self::DEFAULT_FOR_ALL_TABLES . '.'] ?? [];
$subFolder = $this->checkAndConvertForDateFormat($subFolder, $dateFormatConfig);
$config = $userTsConfig[self::DEFAULT_UPLOAD_FOLDERS][self::DEFAULT_FOR_ALL_TABLES . '.'] ?? [];
$subFolder = $this->checkAndConvertForVariable($subFolder, $config, $pid);
}
return $subFolder;
}

protected function slugify(string $string): string
{
$string = trim($string);
$string = mb_strtolower($string, 'UTF-8');

// Umlaute ersetzen
$umlaute = ['ä' => 'ae', 'ö' => 'oe', 'ü' => 'ue', 'ß' => 'ss'];
$string = strtr($string, $umlaute);

// Sonderzeichen entfernen
$string = preg_replace('/[^a-z0-9\s\-]/', '', $string);

// Leerzeichen und Doppelte Dashes zu einem
$string = preg_replace('/[\s\-]+/', '-', $string);

return trim($string, '-');
}


/**
* Check and convert for date format
* Check and convert for variables
*
* @param $subFolder
* @param $dateFormatConfig
* @return string $subFolder
* @param $config
* @param $pid
* @return string
*/
protected function checkAndConvertForDateFormat($subFolder, $dateFormatConfig): string
protected function checkAndConvertForVariable($subFolder, $config, int $pid): string
{



if (trim($subFolder) === '') {
return $subFolder;
}
if (!isset($dateFormatConfig['dateformat']) || (int)$dateFormatConfig['dateformat'] !== 1) {
return $subFolder;

// Handle date variables
//Exmaple: 1:user_upload/news/{y}/{m}/
if (isset($config['dateformat']) && (int)$config['dateformat'] === 1) {
$datePlaceholders = [
'{Y}', '{y}',
'{m}', '{n}',
'{j}', '{d}',
'{W}', '{w}',
];
$dateReplacements = [
date('Y'), date('y'),
date('m'), date('n'),
date('j'), date('d'),
date('W'), date('w'),
];
$subFolder = str_replace($datePlaceholders, $dateReplacements, $subFolder);
}
$strReplace = [
'{Y}', '{y}',
'{m}', '{n}',
'{j}', '{d}',
'{W}', '{w}',
];
$replaceWith = [
date('Y'), date('y'),
date('m'), date('n'),
date('j'), date('d'),
date('W'), date('w'),
];
return str_replace($strReplace, $replaceWith, $subFolder);

// Handle page related variables
// Example: 1:user_upload/{title}/images/
if (!empty($config['variableformat']) && (int)$config['variableformat'] === 1) {

$fields = ['title', 'nav_title', 'subtitle'];
$page = BackendUtility::getRecord('pages', $pid, implode(',', $fields)) ?: [];

foreach ($fields as $field) {
$subFolder = str_replace(
'{' . $field . '}',
$this->slugify($page[$field] ?? ''),
$subFolder
);
}
}

// Prüfen: Enthält der Subfolder noch Platzhalter {xyz} ?
if (preg_match('/\{[^}]+\}/', $subFolder)) {
return '';
}

return $subFolder;
}
}
4 changes: 4 additions & 0 deletions Configuration/PageTs/defaultUploadFolders.tsconfig
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,8 @@ default_upload_folders {
# You can set a default year/month/day folder within the set default folder
tx_news_domain_model_news.dateformat = 1
tx_news_domain_model_news = 1:news/{Y}/{n}/{d}

# You can use page variables like {title}, {subtitle} or {nav_title} to create dynamic folders
tt_content.assets.variableformat = 1
tt_content.assets = 1:user_upload/{title}/
}