Skip to content

Commit

Permalink
Merge pull request #18 from KLXM/skerbis-patch-wolf
Browse files Browse the repository at this point in the history
api und meta per Session aktivieren / deaktivieren
  • Loading branch information
skerbis authored Jan 9, 2025
2 parents 99800da + fa08dfc commit 34e7da1
Show file tree
Hide file tree
Showing 4 changed files with 144 additions and 43 deletions.
88 changes: 88 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,94 @@ data-filepond-types="application/vnd.oasis.opendocument.text, application/vnd.oa
data-filepond-types="application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-powerpoint, application/vnd.openxmlformats-officedocument.presentationml.presentation, application/vnd.oasis.opendocument.text, application/vnd.oasis.opendocument.spreadsheet, application/vnd.oasis.opendocument.presentation, application/pdf"
```

## Session-Konfiguration für individuelle Änderungen

> Hinweis: Bei Verwendung von Yform/Yorm vor Yform/YOrm ausführen.
Im Frontend sollte die Session gestartet werden

```
rex_login::startSession();
```
Wenn die Werte nicht mehr gebraucht werden, sollten sie zurückgesetzt werden.


### API-Token übergeben
```php
rex_set_session('filepond_token', rex_config::get('filepond_uploader', 'api_token'));

```
Hiermit kann der API-Token übergeben werden. Damit ist es möglich auch ußerhalb von YCOM im Frontend Datei-Uploads zu erlauben.

### Meta-Abfrage deaktivieren

```php
rex_set_session('filepond_no_meta', true);
```
Hiermit lässt sich die Meta-Abfrage deaktivieren. Bool: true/false

### Modulbeispiel

```php
<?php
rex_login::startSession();
// Session-Token für API-Zugriff setzen (für Frontend)
rex_set_session('filepond_token', rex_config::get('filepond_uploader', 'api_token'));

// Optional: Meta-Eingabe deaktivieren
rex_set_session('filepond_no_meta', true);

// Filepond Assets einbinden , besser im Template ablegen
if (rex::isFrontend()) {
echo filepond_helper::getStyles();
echo filepond_helper::getScripts();
}
?>

<form class="uploadform" method="post" enctype="multipart/form-data">
<input
type="hidden"
name="REX_INPUT_MEDIALIST[1]"
value="REX_MEDIALIST[1]"
data-widget="filepond"
data-filepond-cat="1"
data-filepond-types="image/*,video/*,application/pdf"
data-filepond-maxfiles="3"
data-filepond-maxsize="10"
data-filepond-lang="de_de"
data-filepond-skip-meta="<?= rex_session('filepond_no_meta', 'boolean', false) ? 'true' : 'false' ?>"
>
</form>

```

## Intitialisierung im Frontend und Tipps

```js
document.addEventListener('DOMContentLoaded', function() {
// Dieser Code wird ausgeführt, nachdem das HTML vollständig geladen wurde.
initFilePond();
});

```

Falls das Panel nicht schön gestaltet dargestellt wird, hilft es diesen Stil anzupassen

Hier ein hässliches Beispiel:

```
.filepond--panel-root {
border: 1px solid var(--fp-border);
background-color: #eedede;
min-height: 150px;
}
```




## Bildoptimierung

Bilder werden automatisch optimiert, wenn sie die konfigurierte maximale Pixelgröße überschreiten:
Expand Down
38 changes: 28 additions & 10 deletions assets/filepond_widget.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
(function() {
const initFilePond = () => {
console.log('initFilePond function called');
// Translations
const translations = {
de_de: {
Expand Down Expand Up @@ -35,12 +36,25 @@
FilePondPluginImagePreview
);

document.querySelectorAll('input[data-widget="filepond"]').forEach(input => {
// Funktion zum Ermitteln des Basepaths
const getBasePath = () => {
const baseElement = document.querySelector('base');
if (baseElement && baseElement.href) {
return baseElement.href.replace(/\/$/, ''); // Entferne optionalen trailing slash
}
// Fallback, wenn kein <base>-Tag vorhanden ist
return window.location.origin;
};
const basePath = getBasePath();
console.log('Basepath ermittelt:', basePath);

document.querySelectorAll('input[data-widget="filepond"]').forEach(input => {
console.log('FilePond input element found:', input);
const lang = input.dataset.filepondLang || document.documentElement.lang || 'de_de';
const t = translations[lang] || translations['de_de'];

const initialValue = input.value.trim();
const skipMeta = input.dataset.filepondSkipMeta === 'true';
const skipMeta = input.dataset.filepondSkipMeta === 'true';

input.style.display = 'none';

Expand Down Expand Up @@ -195,12 +209,11 @@
allowReorder: true,
maxFiles: parseInt(input.dataset.filepondMaxfiles) || null,
server: {
url: 'index.php',
url: basePath, // Verwende den Basepath
process: async (fieldName, file, metadata, load, error, progress, abort, transfer, options) => {
try {
let fileMetadata = {};

// Meta-Dialog nur anzeigen wenn nicht übersprungen
if (!skipMeta) {
fileMetadata = await createMetadataDialog(file);
} else {
Expand All @@ -219,7 +232,7 @@
formData.append('category_id', input.dataset.filepondCat || '0');
formData.append('metadata', JSON.stringify(fileMetadata));

const response = await fetch('index.php', {
const response = await fetch(basePath, { // Verwende den Basepath
method: 'POST',
headers: {
'X-Requested-With': 'XMLHttpRequest'
Expand Down Expand Up @@ -256,17 +269,23 @@
}
},
load: (source, load, error, progress, abort, headers) => {
const url = '/media/' + source.replace(/^"|"$/g, '');
const url = '/media/' + source.replace(/^"|"$/g, '');
console.log('FilePond load url:', url);

fetch(url)
.then(response => {
console.log('FilePond load response:', response);
if (!response.ok) {
throw new Error('HTTP error! status: ' + response.status);
}
return response.blob();
})
.then(load)
.then(blob => {
console.log('FilePond load blob:', blob);
load(blob);
})
.catch(e => {
console.error('FilePond load error:', e);
error(e.message);
});

Expand Down Expand Up @@ -322,7 +341,6 @@

// JQUERY REDAXO BACKEND
if (typeof jQuery !== 'undefined') {
jQuery(document).on('rex:ready', initFilePond);
jQuery(document).on('rex:ready', initFilePond);
}
}
})();

57 changes: 24 additions & 33 deletions lib/api/api_filepond.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ public function execute()

$apiToken = rex_config::get('filepond_uploader', 'api_token');
$requestToken = rex_request('api_token', 'string', null);
$isValidToken = $requestToken && hash_equals($apiToken, $requestToken);
$sessionToken = rex_session('filepond_token', 'string', '');

$isValidToken = ($requestToken && hash_equals($apiToken, $requestToken)) ||
($sessionToken && hash_equals($apiToken, $sessionToken));

if (!$isValidToken && !$isYComUser) {
throw new rex_api_exception('Unauthorized access - requires valid API token or YCom login');
Expand Down Expand Up @@ -107,16 +110,19 @@ protected function handleUpload($categoryId)

// Process image if it's not a GIF
if (strpos($file['type'], 'image/') === 0 && $file['type'] !== 'image/gif') {
// error_log('FILEPOND: Starting image processing for: ' . $file['type'] . ' - ' . $file['name']);
$this->processImage($file['tmp_name']);
} else {
// error_log('FILEPOND: Skipping image processing - file type: ' . $file['type']);
}

$originalName = $file['name'];
$filename = rex_string::normalize(pathinfo($originalName, PATHINFO_FILENAME));

$metadata = json_decode(rex_post('metadata', 'string', '{}'), true);
// Prüfe ob Metadaten übersprungen werden sollen
$skipMeta = rex_session('filepond_no_meta', 'boolean', false);
$metadata = [];

if (!$skipMeta) {
$metadata = json_decode(rex_post('metadata', 'string', '{}'), true);
}

if (!isset($categoryId) || $categoryId < 0) {
$categoryId = rex_config::get('filepond_uploader', 'category_id', 0);
Expand All @@ -129,20 +135,22 @@ protected function handleUpload($categoryId)
'name' => $originalName,
'tmp_name' => $file['tmp_name'],
'type' => $file['type'],
'size' => filesize($file['tmp_name']) // Update filesize after potential resize
'size' => filesize($file['tmp_name'])
]
];

try {
$result = rex_media_service::addMedia($data, true);
if ($result['ok']) {
$sql = rex_sql::factory();
$sql->setTable(rex::getTable('media'));
$sql->setWhere(['filename' => $result['filename']]);
$sql->setValue('title', $metadata['title'] ?? '');
$sql->setValue('med_alt', $metadata['alt'] ?? '');
$sql->setValue('med_copyright', $metadata['copyright'] ?? '');
$sql->update();
if (!$skipMeta) {
$sql = rex_sql::factory();
$sql->setTable(rex::getTable('media'));
$sql->setWhere(['filename' => $result['filename']]);
$sql->setValue('title', $metadata['title'] ?? '');
$sql->setValue('med_alt', $metadata['alt'] ?? '');
$sql->setValue('med_copyright', $metadata['copyright'] ?? '');
$sql->update();
}

return $result['filename'];
}
Expand All @@ -155,24 +163,19 @@ protected function handleUpload($categoryId)

protected function processImage($tmpFile)
{
// error_log('FILEPOND: Processing image: ' . $tmpFile);
$maxPixel = rex_config::get('filepond_uploader', 'max_pixel', 1200);

$imageInfo = getimagesize($tmpFile);
if (!$imageInfo) {
// error_log('FILEPOND: Could not get image size for file: ' . $tmpFile);
return;
}

list($width, $height, $type) = $imageInfo;
// error_log("FILEPOND: Image dimensions: {$width}x{$height}, type: {$type}");

// Return if image is smaller than max dimensions
if ($width <= $maxPixel && $height <= $maxPixel) {
// error_log('FILEPOND: Image is already small enough, skipping resize');
if ($width <= $maxPixel && $height <= $maxPixel) {
return;
}
// error_log('FILEPOND: Image needs resizing');

// Calculate new dimensions
$ratio = $width / $height;
Expand All @@ -188,25 +191,20 @@ protected function processImage($tmpFile)
$srcImage = null;
switch ($type) {
case IMAGETYPE_JPEG:
// error_log('FILEPOND: Processing as JPEG');
$srcImage = imagecreatefromjpeg($tmpFile);
break;
case IMAGETYPE_PNG:
// error_log('FILEPOND: Processing as PNG');
$srcImage = imagecreatefrompng($tmpFile);
break;
default:
// error_log('FILEPOND: Unsupported image type: ' . $type);
return;
}

if (!$srcImage) {
// error_log('FILEPOND: Could not create image resource');
return;
}

$dstImage = imagecreatetruecolor($newWidth, $newHeight);
// error_log("FILEPOND: Creating new image with dimensions: {$newWidth}x{$newHeight}");

// Preserve transparency for PNG images
if ($type === IMAGETYPE_PNG) {
Expand All @@ -231,19 +229,12 @@ protected function processImage($tmpFile)
);

// Save image
$success = false;
if ($type === IMAGETYPE_JPEG) {
$success = imagejpeg($dstImage, $tmpFile, 90);
imagejpeg($dstImage, $tmpFile, 90);
} elseif ($type === IMAGETYPE_PNG) {
$success = imagepng($dstImage, $tmpFile, 9);
imagepng($dstImage, $tmpFile, 9);
}

/*if ($success) {
error_log('FILEPOND: Successfully saved resized image');
} else {
error_log('FILEPOND: Failed to save resized image');
}*/

// Free memory
imagedestroy($srcImage);
imagedestroy($dstImage);
Expand Down
4 changes: 4 additions & 0 deletions ytemplates/bootstrap/value.filepond.tpl.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@

$currentUser = rex::getUser();
$langCode = $currentUser ? $currentUser->getLanguage() : rex_config::get('filepond_uploader', 'lang', 'en_gb');

// Prüfe ob Metadaten übersprungen werden sollen
$skipMeta = rex_session('filepond_no_meta', 'boolean', false);
?>
<div class="<?= $class_group ?>" id="<?= $this->getHTMLId() ?>">
<label class="control-label" for="<?= $this->getFieldId() ?>"><?= $this->getLabel() ?></label>
Expand All @@ -42,6 +45,7 @@
data-filepond-types="<?= $this->getElement('allowed_types') ?: rex_config::get('filepond_uploader', 'allowed_types', 'image/*') ?>"
data-filepond-maxsize="<?= $this->getElement('allowed_filesize') ?: rex_config::get('filepond_uploader', 'max_filesize', 10) ?>"
data-filepond-lang="<?= $langCode ?>"
data-filepond-skip-meta="<?= $skipMeta ? 'true' : 'false' ?>"
/>

<?php if ($notice = $this->getElement('notice')): ?>
Expand Down

0 comments on commit 34e7da1

Please sign in to comment.