Merge pull request #3 from mschilli87/jaykruse20

Nextcloud addon index.php
This commit is contained in:
Nextgen-Networks 2026-02-19 16:28:49 +01:00 committed by GitHub
commit 669e0c17bd
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -4,8 +4,9 @@ class NextcloudPlugin extends \RainLoop\Plugins\AbstractPlugin
{ {
const const
NAME = 'Nextcloud', NAME = 'Nextcloud',
VERSION = '2.38.1', // Keep upstream metadata if you prefer; this is not functional.
RELEASE = '2024-10-08', VERSION = '2.38.2',
RELEASE = '2026-02-06',
CATEGORY = 'Integrations', CATEGORY = 'Integrations',
DESCRIPTION = 'Integrate with Nextcloud v20+', DESCRIPTION = 'Integrate with Nextcloud v20+',
REQUIRED = '2.38.0'; REQUIRED = '2.38.0';
@ -43,7 +44,6 @@ class NextcloudPlugin extends \RainLoop\Plugins\AbstractPlugin
$this->addHook('sieve.before-login', 'beforeLogin'); $this->addHook('sieve.before-login', 'beforeLogin');
} else { } else {
\SnappyMail\Log::debug('Nextcloud', 'NOT integrated'); \SnappyMail\Log::debug('Nextcloud', 'NOT integrated');
// \OC::$server->getConfig()->getAppValue('snappymail', 'snappymail-no-embed');
$this->addHook('main.content-security-policy', 'ContentSecurityPolicy'); $this->addHook('main.content-security-policy', 'ContentSecurityPolicy');
} }
} }
@ -72,13 +72,7 @@ class NextcloudPlugin extends \RainLoop\Plugins\AbstractPlugin
public function loginCredentials(string &$sEmail, string &$sLogin, ?string &$sPassword = null) : void public function loginCredentials(string &$sEmail, string &$sLogin, ?string &$sPassword = null) : void
{ {
/** // left intentionally as upstream (commented in upstream)
* This has an issue.
* When user changes email address, all settings are gone as the new
* _data_/_default_/storage/{domain}/{local-part} is used
*/
// $ocUser = \OC::$server->getUserSession()->getUser();
// $sEmail = $ocUser->getEMailAddress() ?: $ocUser->getPrimaryEMailAddress() ?: $sEmail;
} }
public function loginCredentials2(string &$sEmail, ?string &$sPassword = null) : void public function loginCredentials2(string &$sEmail, ?string &$sPassword = null) : void
@ -89,83 +83,145 @@ class NextcloudPlugin extends \RainLoop\Plugins\AbstractPlugin
public function beforeLogin(\RainLoop\Model\Account $oAccount, \MailSo\Net\NetClient $oClient, \MailSo\Net\ConnectSettings $oSettings) : void public function beforeLogin(\RainLoop\Model\Account $oAccount, \MailSo\Net\NetClient $oClient, \MailSo\Net\ConnectSettings $oSettings) : void
{ {
// Only login with OIDC access token if
// it is enabled in config, the user is currently logged in with OIDC,
// the current snappymail account is the OIDC account and no account defined explicitly
if ($oAccount instanceof \RainLoop\Model\MainAccount if ($oAccount instanceof \RainLoop\Model\MainAccount
&& \OCA\SnappyMail\Util\SnappyMailHelper::isOIDCLogin() && \OCA\SnappyMail\Util\SnappyMailHelper::isOIDCLogin()
// && $oClient->supportsAuthType('OAUTHBEARER') // v2.28
&& \str_starts_with($oSettings->passphrase, 'oidc_login|') && \str_starts_with($oSettings->passphrase, 'oidc_login|')
) { ) {
// $oSettings->passphrase = \OC::$server->getSession()->get('snappymail-passphrase'); $oSettings->passphrase = (string) \OC::$server->getSession()->get('oidc_access_token');
$oSettings->passphrase = \OC::$server->getSession()->get('oidc_access_token');
\array_unshift($oSettings->SASLMechanisms, 'OAUTHBEARER'); \array_unshift($oSettings->SASLMechanisms, 'OAUTHBEARER');
} }
} }
/* /**
\OC::$server->getCalendarManager(); * Attach a Nextcloud file into SnappyMail temp storage (for composing).
\OC::$server->getLDAPProvider();
*/ */
public function NextcloudAttachFile() : array public function NextcloudAttachFile() : array
{ {
$aResult = [ $aResult = [
'success' => false, 'success' => false,
'tempName' => '' 'tempName' => ''
]; ];
$sFile = $this->jsonParam('file', '');
$oFiles = \OCP\Files::getStorage('files'); $sFile = (string) $this->jsonParam('file', '');
if ($oFiles && $oFiles->is_file($sFile) && $fp = $oFiles->fopen($sFile, 'rb')) {
try {
$oActions = \RainLoop\Api::Actions(); $oActions = \RainLoop\Api::Actions();
$oAccount = $oActions->getAccountFromToken(); $oAccount = $oActions->getAccountFromToken();
if ($oAccount) { if (!$oAccount) {
$sSavedName = 'nextcloud-file-' . \sha1($sFile . \microtime()); $aResult['error'] = 'no-account';
if (!$oActions->FilesProvider()->PutFile($oAccount, $sSavedName, $fp)) { return $this->jsonResponse(__FUNCTION__, $aResult);
}
$user = \OC::$server->getUserSession()->getUser();
if (!$user) {
$aResult['error'] = 'no-user';
return $this->jsonResponse(__FUNCTION__, $aResult);
}
/** @var \OCP\Files\IRootFolder $root */
$root = \OC::$server->get(\OCP\Files\IRootFolder::class);
$userFolder = $root->getUserFolder($user->getUID());
// SnappyMail sends "/Documents/app.svg" style paths; userFolder expects relative.
$relPath = \ltrim($sFile, '/');
if ($relPath === '') {
$aResult['error'] = 'empty-path';
return $this->jsonResponse(__FUNCTION__, $aResult);
}
$node = $userFolder->get($relPath);
if (!($node instanceof \OCP\Files\File)) {
$aResult['error'] = 'not-a-file';
return $this->jsonResponse(__FUNCTION__, $aResult);
}
$fp = $node->fopen('rb');
if (!$fp) {
$aResult['error'] = 'open-failed';
return $this->jsonResponse(__FUNCTION__, $aResult);
}
$sSavedName = 'nextcloud-file-' . \sha1($sFile . \microtime(true));
$ok = $oActions->FilesProvider()->PutFile($oAccount, $sSavedName, $fp);
@\fclose($fp);
if (!$ok) {
$aResult['error'] = 'failed'; $aResult['error'] = 'failed';
} else { } else {
$aResult['tempName'] = $sSavedName; $aResult['tempName'] = $sSavedName;
$aResult['success'] = true; $aResult['success'] = true;
} }
} catch (\Throwable $e) {
$aResult['error'] = 'exception';
$aResult['errorMessage'] = $e->getMessage();
} }
}
return $this->jsonResponse(__FUNCTION__, $aResult); return $this->jsonResponse(__FUNCTION__, $aResult);
} }
/**
* Save an .eml message from SnappyMail into Nextcloud Files.
*/
public function NextcloudSaveMsg() : array public function NextcloudSaveMsg() : array
{ {
$sSaveFolder = \ltrim($this->jsonParam('folder', ''), '/'); $sSaveFolder = \ltrim((string) $this->jsonParam('folder', ''), '/');
// $aValues = \RainLoop\Api::Actions()->decodeRawKey($this->jsonParam('msgHash', ''));
$msgHash = $this->jsonParam('msgHash', ''); $msgHash = (string) $this->jsonParam('msgHash', '');
$aValues = \json_decode(\MailSo\Base\Utils::UrlSafeBase64Decode($msgHash), true); $aValues = \json_decode(\MailSo\Base\Utils::UrlSafeBase64Decode($msgHash), true);
$aResult = [ $aResult = [
'folder' => '', 'folder' => '',
'filename' => '', 'filename' => '',
'success' => false 'success' => false,
]; ];
if ($sSaveFolder && !empty($aValues['folder']) && !empty($aValues['uid'])) {
if (!empty($aValues['folder']) && !empty($aValues['uid'])) {
$oActions = \RainLoop\Api::Actions(); $oActions = \RainLoop\Api::Actions();
$oMailClient = $oActions->MailClient(); $oMailClient = $oActions->MailClient();
if (!$oMailClient->IsLoggined()) { if (!$oMailClient->IsLoggined()) {
$oAccount = $oActions->getAccountFromToken(); $oAccount = $oActions->getAccountFromToken();
$oAccount->ImapConnectAndLogin($oActions->Plugins(), $oMailClient->ImapClient(), $oActions->Config()); $oAccount->ImapConnectAndLogin($oActions->Plugins(), $oMailClient->ImapClient(), $oActions->Config());
} }
// Default folder
$sSaveFolder = $sSaveFolder ?: 'Emails'; $sSaveFolder = $sSaveFolder ?: 'Emails';
$oFiles = \OCP\Files::getStorage('files'); $sSaveFolder = \trim($sSaveFolder, '/');
if ($oFiles) {
$oFiles->is_dir($sSaveFolder) || $oFiles->mkdir($sSaveFolder);
}
$aResult['folder'] = $sSaveFolder;
$aResult['filename'] = \MailSo\Base\Utils::SecureFileName(
\mb_substr($this->jsonParam('filename', '') ?: \date('YmdHis'), 0, 100)
) . '.' . \md5($msgHash) . '.eml';
// Use Nextcloud Files API (per-user)
$userFolder = \OC::$server->getUserFolder();
// Create folder path (supports nested folders)
$folderNode = $this->ensureFolderPath($userFolder, $sSaveFolder);
$filenameBase = (string) ($this->jsonParam('filename', '') ?: \date('YmdHis'));
$safeBase = \MailSo\Base\Utils::SecureFileName(\mb_substr($filenameBase, 0, 100));
$filename = $safeBase . '.' . \md5($msgHash) . '.eml';
$aResult['folder'] = $sSaveFolder;
$aResult['filename'] = $filename;
$oMailClient->MessageMimeStream( $oMailClient->MessageMimeStream(
function ($rResource) use ($oFiles, $aResult) { function ($rResource) use (&$aResult, $folderNode, $filename) {
if (\is_resource($rResource)) { if (!\is_resource($rResource)) {
$aResult['success'] = $oFiles->file_put_contents("{$aResult['folder']}/{$aResult['filename']}", $rResource); return;
}
// If exists, overwrite by deleting and recreating (keeps behavior deterministic)
if ($folderNode->nodeExists($filename)) {
$existing = $folderNode->get($filename);
if ($existing instanceof \OCP\Files\File) {
$existing->delete();
}
}
$fileNode = $folderNode->newFile($filename);
$out = $fileNode->fopen('w');
if (\is_resource($out)) {
\stream_copy_to_stream($rResource, $out);
\fclose($out);
$aResult['success'] = true;
} }
}, },
(string) $aValues['folder'], (string) $aValues['folder'],
@ -177,58 +233,96 @@ class NextcloudPlugin extends \RainLoop\Plugins\AbstractPlugin
return $this->jsonResponse(__FUNCTION__, $aResult); return $this->jsonResponse(__FUNCTION__, $aResult);
} }
/**
* Save message attachments from SnappyMail into Nextcloud Files.
* (Used by SnappyMail "save attachments to nextcloud" actions.)
*/
public function DoAttachmentsActions(\SnappyMail\AttachmentsAction $data) public function DoAttachmentsActions(\SnappyMail\AttachmentsAction $data)
{ {
if (static::isLoggedIn() && 'nextcloud' === $data->action) { if (!static::isLoggedIn() || 'nextcloud' !== $data->action) {
$oFiles = \OCP\Files::getStorage('files'); return;
if ($oFiles && \method_exists($oFiles, 'file_put_contents')) { }
$sSaveFolder = \ltrim($this->jsonParam('NcFolder', ''), '/');
try {
// Target folder in Nextcloud
$sSaveFolder = \ltrim((string) $this->jsonParam('NcFolder', ''), '/');
$sSaveFolder = $sSaveFolder ?: 'Attachments'; $sSaveFolder = $sSaveFolder ?: 'Attachments';
$oFiles->is_dir($sSaveFolder) || $oFiles->mkdir($sSaveFolder); $sSaveFolder = \trim($sSaveFolder, '/');
$userFolder = \OC::$server->getUserFolder();
$folderNode = $this->ensureFolderPath($userFolder, $sSaveFolder);
$data->result = true; $data->result = true;
foreach ($data->items as $aItem) { foreach ($data->items as $aItem) {
$sSavedFileName = empty($aItem['fileName']) ? 'file.dat' : $aItem['fileName']; $sSavedFileName = empty($aItem['fileName']) ? 'file.dat' : (string) $aItem['fileName'];
$sSavedFileName = \MailSo\Base\Utils::SecureFileName(\mb_substr($sSavedFileName, 0, 180));
$finalName = $this->uniqueNameInFolder($folderNode, $sSavedFileName);
// Create file node
$fileNode = $folderNode->newFile($finalName);
$out = $fileNode->fopen('w');
if (!\is_resource($out)) {
$data->result = false;
continue;
}
$wrote = false;
if (!empty($aItem['data'])) { if (!empty($aItem['data'])) {
$sSavedFileNameFull = static::SmartFileExists($sSaveFolder.'/'.$sSavedFileName, $oFiles); // Raw data string
if (!$oFiles->file_put_contents($sSavedFileNameFull, $aItem['data'])) { $bytes = \fwrite($out, (string) $aItem['data']);
$data->result = false; $wrote = ($bytes !== false);
}
} else if (!empty($aItem['fileHash'])) { } else if (!empty($aItem['fileHash'])) {
$fFile = $data->filesProvider->GetFile($data->account, $aItem['fileHash'], 'rb'); // Stream from SnappyMail temp storage
$fFile = $data->filesProvider->GetFile($data->account, (string) $aItem['fileHash'], 'rb');
if (\is_resource($fFile)) { if (\is_resource($fFile)) {
$sSavedFileNameFull = static::SmartFileExists($sSaveFolder.'/'.$sSavedFileName, $oFiles); \stream_copy_to_stream($fFile, $out);
if (!$oFiles->file_put_contents($sSavedFileNameFull, $fFile)) { \fclose($fFile);
$wrote = true;
}
}
\fclose($out);
if (!$wrote) {
// Clean up the empty file
try { $fileNode->delete(); } catch (\Throwable $e) {}
$data->result = false; $data->result = false;
} }
if (\is_resource($fFile)) {
\fclose($fFile);
}
}
}
}
} }
} catch (\Throwable $e) {
$data->result = false;
} }
} }
public function FilterAppData($bAdmin, &$aResult) : void public function FilterAppData($bAdmin, &$aResult) : void
{ {
if (!$bAdmin && \is_array($aResult)) { if ($bAdmin || !\is_array($aResult)) {
return;
}
$ocUser = \OC::$server->getUserSession()->getUser(); $ocUser = \OC::$server->getUserSession()->getUser();
if (!$ocUser) {
return;
}
$sUID = $ocUser->getUID(); $sUID = $ocUser->getUID();
$oUrlGen = \OC::$server->getURLGenerator(); $oUrlGen = \OC::$server->getURLGenerator();
$sWebDAV = $oUrlGen->getAbsoluteURL($oUrlGen->linkTo('', 'remote.php') . '/dav'); $sWebDAV = $oUrlGen->getAbsoluteURL($oUrlGen->linkTo('', 'remote.php') . '/dav');
// $sWebDAV = \OCP\Util::linkToRemote('dav');
$aResult['Nextcloud'] = [ $aResult['Nextcloud'] = [
'UID' => $sUID, 'UID' => $sUID,
'WebDAV' => $sWebDAV, 'WebDAV' => $sWebDAV,
'CalDAV' => $this->Config()->Get('plugin', 'calendar', false) 'CalDAV' => $this->Config()->Get('plugin', 'calendar', false)
// 'WebDAV_files' => $sWebDAV . '/files/' . $sUID
]; ];
if (empty($aResult['Auth'])) { if (empty($aResult['Auth'])) {
$config = \OC::$server->getConfig(); $config = \OC::$server->getConfig();
$sEmail = ''; $sEmail = '';
// Only store the user's password in the current session if they have
// enabled auto-login using Nextcloud username or email address.
if ($config->getAppValue('snappymail', 'snappymail-autologin', false)) { if ($config->getAppValue('snappymail', 'snappymail-autologin', false)) {
$sEmail = $sUID; $sEmail = $sUID;
} else if ($config->getAppValue('snappymail', 'snappymail-autologin-with-email', false)) { } else if ($config->getAppValue('snappymail', 'snappymail-autologin-with-email', false)) {
@ -236,31 +330,21 @@ class NextcloudPlugin extends \RainLoop\Plugins\AbstractPlugin
} else { } else {
\SnappyMail\Log::debug('Nextcloud', 'snappymail-autologin is off'); \SnappyMail\Log::debug('Nextcloud', 'snappymail-autologin is off');
} }
// If the user has set credentials for SnappyMail in their personal
// settings, override everything before and use those instead. // User-set SnappyMail credentials override
$sCustomEmail = $config->getUserValue($sUID, 'snappymail', 'snappymail-email', ''); $sCustomEmail = $config->getUserValue($sUID, 'snappymail', 'snappymail-email', '');
if ($sCustomEmail) { if ($sCustomEmail) {
$sEmail = $sCustomEmail; $sEmail = $sCustomEmail;
} }
if (!$sEmail) { if (!$sEmail) {
$sEmail = $ocUser->getEMailAddress(); $sEmail = $ocUser->getEMailAddress();
// ?: $ocUser->getPrimaryEMailAddress();
} }
/*
if ($config->getAppValue('snappymail', 'snappymail-autologin-oidc', false)) {
if (\OC::$server->getSession()->get('is_oidc')) {
$sEmail = "{$sUID}@nextcloud";
$aResult['DevPassword'] = \OC::$server->getSession()->get('oidc_access_token');
} else {
\SnappyMail\Log::debug('Nextcloud', 'Not an OIDC login');
}
} else {
\SnappyMail\Log::debug('Nextcloud', 'OIDC is off');
}
*/
$aResult['DevEmail'] = $sEmail ?: ''; $aResult['DevEmail'] = $sEmail ?: '';
} else if (!empty($aResult['ContactsSync'])) { } else if (!empty($aResult['ContactsSync'])) {
$bSave = false; $bSave = false;
if (empty($aResult['ContactsSync']['Url'])) { if (empty($aResult['ContactsSync']['Url'])) {
$aResult['ContactsSync']['Url'] = "{$sWebDAV}/addressbooks/users/{$sUID}/contacts/"; $aResult['ContactsSync']['Url'] = "{$sWebDAV}/addressbooks/users/{$sUID}/contacts/";
$bSave = true; $bSave = true;
@ -269,29 +353,31 @@ class NextcloudPlugin extends \RainLoop\Plugins\AbstractPlugin
$aResult['ContactsSync']['User'] = $sUID; $aResult['ContactsSync']['User'] = $sUID;
$bSave = true; $bSave = true;
} }
$pass = \OC::$server->getSession()['snappymail-passphrase'];
if ($pass/* && empty($aResult['ContactsSync']['Password'])*/) { // FIX: do not array-access the session; use ->get()
$pass = (string) \OC::$server->getSession()->get('snappymail-passphrase');
if ($pass) {
$pass = \SnappyMail\Crypt::DecryptUrlSafe($pass, $sUID); $pass = \SnappyMail\Crypt::DecryptUrlSafe($pass, $sUID);
if ($pass) { if ($pass) {
$aResult['ContactsSync']['Password'] = $pass; $aResult['ContactsSync']['Password'] = $pass;
$bSave = true; $bSave = true;
} }
} }
if ($bSave) { if ($bSave) {
$oActions = \RainLoop\Api::Actions(); $oActions = \RainLoop\Api::Actions();
$oActions->setContactsSyncData( $oActions->setContactsSyncData(
$oActions->getAccountFromToken(), $oActions->getAccountFromToken(),
array( [
'Mode' => $aResult['ContactsSync']['Mode'], 'Mode' => $aResult['ContactsSync']['Mode'],
'User' => $aResult['ContactsSync']['User'], 'User' => $aResult['ContactsSync']['User'],
'Password' => $aResult['ContactsSync']['Password'], 'Password' => $aResult['ContactsSync']['Password'],
'Url' => $aResult['ContactsSync']['Url'] 'Url' => $aResult['ContactsSync']['Url']
) ]
); );
} }
} }
} }
}
public function FilterLanguage(&$sLanguage, $bAdmin) : void public function FilterLanguage(&$sLanguage, $bAdmin) : void
{ {
@ -301,116 +387,124 @@ class NextcloudPlugin extends \RainLoop\Plugins\AbstractPlugin
$userLang = \OC::$server->getConfig()->getUserValue($userId, 'core', 'lang', 'en'); $userLang = \OC::$server->getConfig()->getUserValue($userId, 'core', 'lang', 'en');
$userLang = \strtr($userLang, '_', '-'); $userLang = \strtr($userLang, '_', '-');
$sLanguage = $this->determineLocale($userLang, $aResultLang); $sLanguage = $this->determineLocale($userLang, $aResultLang);
// Check if $sLanguage is null
if (!$sLanguage) { if (!$sLanguage) {
$sLanguage = 'en'; // Assign 'en' if $sLanguage is null $sLanguage = 'en';
} }
} }
} }
/**
* Determine locale from user language.
*
* @param string $langCode The name of the input.
* @param array $languagesArray The value of the array.
*
* @return string return locale
*/
private function determineLocale(string $langCode, array $languagesArray) : ?string private function determineLocale(string $langCode, array $languagesArray) : ?string
{ {
// Direct check for the language code if (\in_array($langCode, $languagesArray, true)) {
if (\in_array($langCode, $languagesArray)) {
return $langCode; return $langCode;
} }
// Check without country code
if (\str_contains($langCode, '-')) { if (\str_contains($langCode, '-')) {
$langCode = \explode('-', $langCode)[0]; $langCode = \explode('-', $langCode)[0];
if (\in_array($langCode, $languagesArray)) { if (\in_array($langCode, $languagesArray, true)) {
return $langCode; return $langCode;
} }
} }
// Check with uppercase country code
$langCodeWithUpperCase = $langCode . '-' . \strtoupper($langCode); $langCodeWithUpperCase = $langCode . '-' . \strtoupper($langCode);
if (\in_array($langCodeWithUpperCase, $languagesArray)) { if (\in_array($langCodeWithUpperCase, $languagesArray, true)) {
return $langCodeWithUpperCase; return $langCodeWithUpperCase;
} }
// If no match is found
return null; return null;
} }
/**
* @param mixed $mResult
*/
public function MainFabrica(string $sName, &$mResult) public function MainFabrica(string $sName, &$mResult)
{ {
if (static::isLoggedIn()) { if (!static::isLoggedIn()) {
return;
}
if ('suggestions' === $sName && $this->Config()->Get('plugin', 'suggestions', true)) { if ('suggestions' === $sName && $this->Config()->Get('plugin', 'suggestions', true)) {
if (!\is_array($mResult)) { if (!\is_array($mResult)) {
$mResult = array(); $mResult = [];
} }
include_once __DIR__ . '/NextcloudContactsSuggestions.php'; include_once __DIR__ . '/NextcloudContactsSuggestions.php';
$mResult[] = new NextcloudContactsSuggestions( $mResult[] = new NextcloudContactsSuggestions(
$this->Config()->Get('plugin', 'ignoreSystemAddressbook', true) $this->Config()->Get('plugin', 'ignoreSystemAddressbook', true)
); );
} }
/*
if ($this->Config()->Get('plugin', 'storage', false) && ('storage' === $sName || 'storage-local' === $sName)) { // storage hook left as upstream (commented)
require_once __DIR__ . '/storage.php';
$oDriver = new \NextcloudStorage(APP_PRIVATE_DATA.'storage', $sName === 'storage-local');
}
*/
}
} }
protected function configMapping() : array protected function configMapping() : array
{ {
return array( return [
\RainLoop\Plugins\Property::NewInstance('suggestions')->SetLabel('Suggestions') \RainLoop\Plugins\Property::NewInstance('suggestions')->SetLabel('Suggestions')
->SetType(\RainLoop\Enumerations\PluginPropertyType::BOOL) ->SetType(\RainLoop\Enumerations\PluginPropertyType::BOOL)
->SetDefaultValue(true), ->SetDefaultValue(true),
\RainLoop\Plugins\Property::NewInstance('ignoreSystemAddressbook')->SetLabel('Ignore system addressbook') \RainLoop\Plugins\Property::NewInstance('ignoreSystemAddressbook')->SetLabel('Ignore system addressbook')
->SetType(\RainLoop\Enumerations\PluginPropertyType::BOOL) ->SetType(\RainLoop\Enumerations\PluginPropertyType::BOOL)
->SetDefaultValue(true), ->SetDefaultValue(true),
/*
\RainLoop\Plugins\Property::NewInstance('storage')->SetLabel('Use Nextcloud user ID in config storage path')
->SetType(\RainLoop\Enumerations\PluginPropertyType::BOOL)
->SetDefaultValue(false)
*/
\RainLoop\Plugins\Property::NewInstance('calendar')->SetLabel('Enable "Put ICS in calendar"') \RainLoop\Plugins\Property::NewInstance('calendar')->SetLabel('Enable "Put ICS in calendar"')
->SetType(\RainLoop\Enumerations\PluginPropertyType::BOOL) ->SetType(\RainLoop\Enumerations\PluginPropertyType::BOOL)
->SetDefaultValue(false) ->SetDefaultValue(false)
); ];
} }
private static function SmartFileExists(string $sFilePath, $oFiles) : string /**
* Ensure a (possibly nested) folder path exists under the given base folder.
*/
private function ensureFolderPath(\OCP\Files\Folder $baseFolder, string $path) : \OCP\Files\Folder
{ {
$sFilePath = \str_replace('\\', '/', \trim($sFilePath)); $path = \trim($path, '/');
if ($path === '') {
if (!$oFiles->file_exists($sFilePath)) { return $baseFolder;
return $sFilePath;
} }
$aFileInfo = \pathinfo($sFilePath); $folderNode = $baseFolder;
foreach (\array_filter(\explode('/', $path), 'strlen') as $part) {
$part = (string) $part;
if ($folderNode->nodeExists($part)) {
$node = $folderNode->get($part);
if ($node instanceof \OCP\Files\Folder) {
$folderNode = $node;
} else {
// name collision: file exists where folder needed; create a suffixed folder
$folderNode = $folderNode->newFolder($part . '-folder');
}
} else {
$folderNode = $folderNode->newFolder($part);
}
}
$iIndex = 0; return $folderNode;
}
while (true) { /**
++$iIndex; * Return a unique filename inside a Nextcloud folder (keeps original extension).
$sFilePathNew = $aFileInfo['dirname'].'/'. */
\preg_replace('/\(\d{1,2}\)$/', '', $aFileInfo['filename']). private function uniqueNameInFolder(\OCP\Files\Folder $folderNode, string $fileName) : string
' ('.$iIndex.')'. {
(empty($aFileInfo['extension']) ? '' : '.'.$aFileInfo['extension']) $fileName = \trim($fileName);
; if ($fileName === '') {
if (!$oFiles->file_exists($sFilePathNew)) { $fileName = 'file.dat';
return $sFilePathNew;
} }
if (10 < $iIndex) {
break; if (!$folderNode->nodeExists($fileName)) {
return $fileName;
}
$info = \pathinfo($fileName);
$base = $info['filename'] ?? 'file';
$ext = isset($info['extension']) && $info['extension'] !== '' ? ('.' . $info['extension']) : '';
for ($i = 1; $i <= 50; $i++) {
$try = $base . ' (' . $i . ')' . $ext;
if (!$folderNode->nodeExists($try)) {
return $try;
} }
} }
return $sFilePath;
// fallback
return $fileName;
} }
} }