aboutsummaryrefslogtreecommitdiffstats
path: root/apps/user_ldap
diff options
context:
space:
mode:
Diffstat (limited to 'apps/user_ldap')
-rw-r--r--apps/user_ldap/ajax/deleteConfiguration.php4
-rw-r--r--apps/user_ldap/ajax/getNewServerConfigPrefix.php4
-rw-r--r--apps/user_ldap/l10n/gl.js1
-rw-r--r--apps/user_ldap/l10n/gl.json1
-rw-r--r--apps/user_ldap/l10n/ru.js19
-rw-r--r--apps/user_ldap/l10n/ru.json19
-rw-r--r--apps/user_ldap/lib/Command/Search.php3
-rw-r--r--apps/user_ldap/lib/Command/SetConfig.php4
-rw-r--r--apps/user_ldap/lib/Connection.php4
-rw-r--r--apps/user_ldap/lib/Helper.php96
-rw-r--r--apps/user_ldap/lib/Jobs/CleanUp.php2
-rw-r--r--apps/user_ldap/lib/Settings/Admin.php4
-rw-r--r--apps/user_ldap/tests/AccessTest.php3
-rw-r--r--apps/user_ldap/tests/HelperTest.php81
-rw-r--r--apps/user_ldap/tests/Integration/AbstractIntegrationTest.php3
-rw-r--r--apps/user_ldap/tests/LDAPProviderTest.php5
16 files changed, 170 insertions, 83 deletions
diff --git a/apps/user_ldap/ajax/deleteConfiguration.php b/apps/user_ldap/ajax/deleteConfiguration.php
index f09295355ac..68bce69f982 100644
--- a/apps/user_ldap/ajax/deleteConfiguration.php
+++ b/apps/user_ldap/ajax/deleteConfiguration.php
@@ -1,8 +1,6 @@
<?php
use OCA\User_LDAP\Helper;
-use OCP\IConfig;
-use OCP\IDBConnection;
use OCP\Server;
use OCP\Util;
@@ -17,7 +15,7 @@ use OCP\Util;
\OC_JSON::callCheck();
$prefix = (string)$_POST['ldap_serverconfig_chooser'];
-$helper = new Helper(Server::get(IConfig::class), Server::get(IDBConnection::class));
+$helper = Server::get(Helper::class);
if ($helper->deleteServerConfiguration($prefix)) {
\OC_JSON::success();
} else {
diff --git a/apps/user_ldap/ajax/getNewServerConfigPrefix.php b/apps/user_ldap/ajax/getNewServerConfigPrefix.php
index e8746a7c1b1..e5ba6375c73 100644
--- a/apps/user_ldap/ajax/getNewServerConfigPrefix.php
+++ b/apps/user_ldap/ajax/getNewServerConfigPrefix.php
@@ -2,8 +2,6 @@
use OCA\User_LDAP\Configuration;
use OCA\User_LDAP\Helper;
-use OCP\IConfig;
-use OCP\IDBConnection;
use OCP\Server;
/**
@@ -16,7 +14,7 @@ use OCP\Server;
\OC_JSON::checkAppEnabled('user_ldap');
\OC_JSON::callCheck();
-$helper = new Helper(Server::get(IConfig::class), Server::get(IDBConnection::class));
+$helper = Server::get(Helper::class);
$serverConnections = $helper->getServerConfigurationPrefixes();
sort($serverConnections);
$lk = array_pop($serverConnections);
diff --git a/apps/user_ldap/l10n/gl.js b/apps/user_ldap/l10n/gl.js
index d97ec49e13c..a39e92ab1f8 100644
--- a/apps/user_ldap/l10n/gl.js
+++ b/apps/user_ldap/l10n/gl.js
@@ -61,6 +61,7 @@ OC.L10N.register(
"No LDAP base DN was given" : "Non se indicou un DN base de LDAP",
"User base DN is not a subnode of global base DN" : "O DN base do usuario non é un subnodo do DN base global",
"Group base DN is not a subnode of global base DN" : "O DN base de grupo non é un subnodo do DN base global",
+ "Login filter does not contain %s placeholder." : "O filtro de inicio de sesión non contén o marcador de substitución %s.",
"Please login with the new password" : "Acceda co novo contrasinal",
"LDAP User backend" : "Infraestrutura do usuario LDAP",
"Your password will expire tomorrow." : "O seu contrasinal caduca mañá.",
diff --git a/apps/user_ldap/l10n/gl.json b/apps/user_ldap/l10n/gl.json
index 952066b7994..58b0658ebf0 100644
--- a/apps/user_ldap/l10n/gl.json
+++ b/apps/user_ldap/l10n/gl.json
@@ -59,6 +59,7 @@
"No LDAP base DN was given" : "Non se indicou un DN base de LDAP",
"User base DN is not a subnode of global base DN" : "O DN base do usuario non é un subnodo do DN base global",
"Group base DN is not a subnode of global base DN" : "O DN base de grupo non é un subnodo do DN base global",
+ "Login filter does not contain %s placeholder." : "O filtro de inicio de sesión non contén o marcador de substitución %s.",
"Please login with the new password" : "Acceda co novo contrasinal",
"LDAP User backend" : "Infraestrutura do usuario LDAP",
"Your password will expire tomorrow." : "O seu contrasinal caduca mañá.",
diff --git a/apps/user_ldap/l10n/ru.js b/apps/user_ldap/l10n/ru.js
index 2868b79aa5f..30ab9ad0e15 100644
--- a/apps/user_ldap/l10n/ru.js
+++ b/apps/user_ldap/l10n/ru.js
@@ -11,6 +11,7 @@ OC.L10N.register(
"No configuration specified" : "Конфигурация не указана",
"No data specified" : "Нет данных",
"Invalid data specified" : "Указаны некорректные данные",
+ "Could not set configuration %1$s to %2$s" : "Не удалось задать конфигурацию %1$s для %2$s",
"Action does not exist" : "Действие не существует",
"Renewing …" : "Обновление…",
"Very weak password" : "Очень слабый пароль",
@@ -25,12 +26,12 @@ OC.L10N.register(
"Configuration OK" : "Конфигурация в порядке",
"Select groups" : "Выберите группы",
"Select object classes" : "Выберите объектные классы",
- "Please check the credentials, they seem to be wrong." : "Пожалуйста проверьте учетный данные, возможно они не верны.",
+ "Please check the credentials, they seem to be wrong." : "Пожалуйста, проверьте учётные данные — возможно, они указаны неверно.",
"Please specify the port, it could not be auto-detected." : "Пожалуйста укажите порт, он не может быть определен автоматически.",
"Base DN could not be auto-detected, please revise credentials, host and port." : "База поиска не может быть определена автоматически, пожалуйста перепроверьте учетные данные, адрес и порт.",
"Could not detect Base DN, please enter it manually." : "Невозможно обнаружить Base DN, пожалуйста, задайте вручную.",
"{nthServer}. Server" : "Сервер {nthServer}.",
- "No object found in the given Base DN. Please revise." : "Не найдено объектов в Base DN. Пожалуйста перепроверьте.",
+ "No object found in the given Base DN. Please revise." : "В указанной базовой DN не найден ни один объект. Пожалуйста, перепроверьте.",
"More than 1,000 directory entries available." : "В каталоге доступно более 1,000 записей.",
"_{objectsFound} entry available within the provided Base DN_::_{objectsFound} entries available within the provided Base DN_" : ["{objectsFound} элемент доступен в предоставленном базовом DN","{objectsFound} элементов доступно в предоставленном базовом DN","{objectsFound} элементов доступно в предоставленном базовом DN","{objectsFound} элементов доступно в предоставленном базовом DN"],
"An error occurred. Please check the Base DN, as well as connection settings and credentials." : "Произошла ошибка. Пожалуйста проверьте базу поиска DN, а также настройки подключения и учетные данные.",
@@ -53,6 +54,14 @@ OC.L10N.register(
"The \"%uid\" placeholder is missing. It will be replaced with the login name when querying LDAP/AD." : "Заполнитель \"%uid\" отсутствует. Он будет заменён именем пользователя при запросе LDAP/AD.",
"Please provide a login name to test against" : "Пожалуйста, укажите логин для проверки",
"The group box was disabled, because the LDAP/AD server does not support memberOf." : "Блок группы был отключен, поскольку сервер LDAP/AD не поддерживает memberOf.",
+ "Password change rejected. Hint: %s" : "Изменение пароля отклонено. Подсказка: %s",
+ "Mandatory field \"%s\" left empty" : "Обязательное поле «%s» оставлено пустым",
+ "A password is given, but not an LDAP agent" : "Пароль задан, но не указан LDAP-агент",
+ "No password is given for the user agent" : "Пароль для LDAP-агента не задан",
+ "No LDAP base DN was given" : "Не указана базовая DN LDAP",
+ "User base DN is not a subnode of global base DN" : "Базовая DN пользователей не является подузлом глобальной базовой DN",
+ "Group base DN is not a subnode of global base DN" : " Базовая DN групп не является подузлом глобальной базовой DN",
+ "Login filter does not contain %s placeholder." : "Фильтр входа не содержит плейсхолдер %s.",
"Please login with the new password" : "Войдите в систему со своим новым паролем",
"LDAP User backend" : "Механизм учета пользователей LDAP",
"Your password will expire tomorrow." : "Завтра истекает срок действия пароля.",
@@ -60,6 +69,10 @@ OC.L10N.register(
"_Your password will expire within %n day._::_Your password will expire within %n days._" : ["Срок действия пароля истекает через %n день.","Срок действия пароля истекает через %n дня.","Срок действия пароля истекает через %n дней.","Срок действия пароля истекает через %n день."],
"LDAP/AD integration" : "LDAP/AD интеграция",
"LDAP Connection" : "Подключение по протоколу LDAP",
+ "_Binding failed for this LDAP configuration: %s_::_Binding failed for %n LDAP configurations: %s_" : ["Не удалось выполнить привязку для этой конфигурации LDAP: %s","Не удалось выполнить привязку для %n конфигураций LDAP: %s","Не удалось выполнить привязку для %n конфигураций LDAP: %s","Не удалось выполнить привязку для %n конфигураций LDAP: %s"],
+ "_Searching failed for this LDAP configuration: %s_::_Searching failed for %n LDAP configurations: %s_" : ["Ошибка поиска в этой конфигурации LDAP: %s","Ошибка поиска в %n конфигурациях LDAP: %s","Ошибка поиска в %n конфигурациях LDAP: %s","Ошибка поиска в %n конфигурациях LDAP: %s"],
+ "_There is an inactive LDAP configuration: %s_::_There are %n inactive LDAP configurations: %s_" : ["Найдена неактивная конфигурация LDAP: %s","Найдено %n неактивных конфигурации LDAP: %s","Найдено %n неактивных конфигураций LDAP: %s","Найдено %n неактивных конфигураций LDAP: %s"],
+ "_Binding and searching works on the configured LDAP connection (%s)_::_Binding and searching works on all of the %n configured LDAP connections (%s)_" : [" Привязка и поиск работают в настроенном LDAP-соединении (%s)"," Привязка и поиск работают во всех %n настроенных LDAP-соединениях (%s)"," Привязка и поиск работают во всех %n настроенных LDAP-соединениях (%s)"," Привязка и поиск работают во всех %n настроенных LDAP-соединениях (%s)"],
"Invalid LDAP UUIDs" : "Недопустимые UUID LDAP",
"None found" : "Ничего не найдено",
"Invalid UUIDs of LDAP accounts or groups have been found. Please review your \"Override UUID detection\" settings in the Expert part of the LDAP configuration and use \"occ ldap:update-uuid\" to update them." : "Обнаружены недопустимые идентификаторы UUID учетных записей или групп LDAP. Пожалуйста, ознакомьтесь с вашими настройками \"Переопределение обнаружения UUID\" в экспертной части конфигурации LDAP и используйте \"occ ldap:update-uuid\", чтобы обновить их.",
@@ -208,6 +221,8 @@ OC.L10N.register(
"User profile Biography will be set from the specified attribute" : "Биография в профиле пользователя будет установлена из указанного атрибута",
"Birthdate Field" : "Поле Даты рождения",
"User profile Date of birth will be set from the specified attribute" : "Дата рождения профиля пользователя будет установлена на основе указанного атрибута",
+ "Pronouns Field" : " Поле местоимений",
+ "User profile Pronouns will be set from the specified attribute" : "Местоимения в профиле пользователя будут заданы из указанного атрибута",
"Internal Username" : "Внутреннее имя пользователя",
"By default the internal username will be created from the UUID attribute. It makes sure that the username is unique and characters do not need to be converted. The internal username has the restriction that only these characters are allowed: [a-zA-Z0-9_.@-]. Other characters are replaced with their ASCII correspondence or simply omitted. On collisions a number will be added/increased. The internal username is used to identify a user internally. It is also the default name for the user home folder. It is also a part of remote URLs, for instance for all DAV services. With this setting, the default behavior can be overridden. Changes will have effect only on newly mapped (added) LDAP users. Leave it empty for default behavior." : "По умолчанию внутреннее имя пользователя будет создано на основе атрибута UUID. Это гарантирует, что имя пользователя будет уникальным и символы не нужно будет преобразовывать. Внутреннее имя пользователя имеет ограничение – разрешены только эти символы: [a-zA-Z0-9_.@-]. Другие символы заменяются их ASCII-кодами или просто опускаются. При совпадениях число будет добавлено/увеличено. Внутреннее имя пользователя используется для внутренней идентификации пользователя. Оно также является именем по умолчанию для домашней папки пользователя. Оно также является частью удалённых URL-адресов, например, для всех служб DAV. С помощью этого параметра можно переопределить поведение по умолчанию. Изменения будут иметь силу только для новых сопоставленных (добавленных) пользователей LDAP. Оставьте этот параметр пустым для поведения по умолчанию.",
"Internal Username Attribute:" : "Атрибут для внутреннего имени:",
diff --git a/apps/user_ldap/l10n/ru.json b/apps/user_ldap/l10n/ru.json
index 683b486066b..eea51dcf3a7 100644
--- a/apps/user_ldap/l10n/ru.json
+++ b/apps/user_ldap/l10n/ru.json
@@ -9,6 +9,7 @@
"No configuration specified" : "Конфигурация не указана",
"No data specified" : "Нет данных",
"Invalid data specified" : "Указаны некорректные данные",
+ "Could not set configuration %1$s to %2$s" : "Не удалось задать конфигурацию %1$s для %2$s",
"Action does not exist" : "Действие не существует",
"Renewing …" : "Обновление…",
"Very weak password" : "Очень слабый пароль",
@@ -23,12 +24,12 @@
"Configuration OK" : "Конфигурация в порядке",
"Select groups" : "Выберите группы",
"Select object classes" : "Выберите объектные классы",
- "Please check the credentials, they seem to be wrong." : "Пожалуйста проверьте учетный данные, возможно они не верны.",
+ "Please check the credentials, they seem to be wrong." : "Пожалуйста, проверьте учётные данные — возможно, они указаны неверно.",
"Please specify the port, it could not be auto-detected." : "Пожалуйста укажите порт, он не может быть определен автоматически.",
"Base DN could not be auto-detected, please revise credentials, host and port." : "База поиска не может быть определена автоматически, пожалуйста перепроверьте учетные данные, адрес и порт.",
"Could not detect Base DN, please enter it manually." : "Невозможно обнаружить Base DN, пожалуйста, задайте вручную.",
"{nthServer}. Server" : "Сервер {nthServer}.",
- "No object found in the given Base DN. Please revise." : "Не найдено объектов в Base DN. Пожалуйста перепроверьте.",
+ "No object found in the given Base DN. Please revise." : "В указанной базовой DN не найден ни один объект. Пожалуйста, перепроверьте.",
"More than 1,000 directory entries available." : "В каталоге доступно более 1,000 записей.",
"_{objectsFound} entry available within the provided Base DN_::_{objectsFound} entries available within the provided Base DN_" : ["{objectsFound} элемент доступен в предоставленном базовом DN","{objectsFound} элементов доступно в предоставленном базовом DN","{objectsFound} элементов доступно в предоставленном базовом DN","{objectsFound} элементов доступно в предоставленном базовом DN"],
"An error occurred. Please check the Base DN, as well as connection settings and credentials." : "Произошла ошибка. Пожалуйста проверьте базу поиска DN, а также настройки подключения и учетные данные.",
@@ -51,6 +52,14 @@
"The \"%uid\" placeholder is missing. It will be replaced with the login name when querying LDAP/AD." : "Заполнитель \"%uid\" отсутствует. Он будет заменён именем пользователя при запросе LDAP/AD.",
"Please provide a login name to test against" : "Пожалуйста, укажите логин для проверки",
"The group box was disabled, because the LDAP/AD server does not support memberOf." : "Блок группы был отключен, поскольку сервер LDAP/AD не поддерживает memberOf.",
+ "Password change rejected. Hint: %s" : "Изменение пароля отклонено. Подсказка: %s",
+ "Mandatory field \"%s\" left empty" : "Обязательное поле «%s» оставлено пустым",
+ "A password is given, but not an LDAP agent" : "Пароль задан, но не указан LDAP-агент",
+ "No password is given for the user agent" : "Пароль для LDAP-агента не задан",
+ "No LDAP base DN was given" : "Не указана базовая DN LDAP",
+ "User base DN is not a subnode of global base DN" : "Базовая DN пользователей не является подузлом глобальной базовой DN",
+ "Group base DN is not a subnode of global base DN" : " Базовая DN групп не является подузлом глобальной базовой DN",
+ "Login filter does not contain %s placeholder." : "Фильтр входа не содержит плейсхолдер %s.",
"Please login with the new password" : "Войдите в систему со своим новым паролем",
"LDAP User backend" : "Механизм учета пользователей LDAP",
"Your password will expire tomorrow." : "Завтра истекает срок действия пароля.",
@@ -58,6 +67,10 @@
"_Your password will expire within %n day._::_Your password will expire within %n days._" : ["Срок действия пароля истекает через %n день.","Срок действия пароля истекает через %n дня.","Срок действия пароля истекает через %n дней.","Срок действия пароля истекает через %n день."],
"LDAP/AD integration" : "LDAP/AD интеграция",
"LDAP Connection" : "Подключение по протоколу LDAP",
+ "_Binding failed for this LDAP configuration: %s_::_Binding failed for %n LDAP configurations: %s_" : ["Не удалось выполнить привязку для этой конфигурации LDAP: %s","Не удалось выполнить привязку для %n конфигураций LDAP: %s","Не удалось выполнить привязку для %n конфигураций LDAP: %s","Не удалось выполнить привязку для %n конфигураций LDAP: %s"],
+ "_Searching failed for this LDAP configuration: %s_::_Searching failed for %n LDAP configurations: %s_" : ["Ошибка поиска в этой конфигурации LDAP: %s","Ошибка поиска в %n конфигурациях LDAP: %s","Ошибка поиска в %n конфигурациях LDAP: %s","Ошибка поиска в %n конфигурациях LDAP: %s"],
+ "_There is an inactive LDAP configuration: %s_::_There are %n inactive LDAP configurations: %s_" : ["Найдена неактивная конфигурация LDAP: %s","Найдено %n неактивных конфигурации LDAP: %s","Найдено %n неактивных конфигураций LDAP: %s","Найдено %n неактивных конфигураций LDAP: %s"],
+ "_Binding and searching works on the configured LDAP connection (%s)_::_Binding and searching works on all of the %n configured LDAP connections (%s)_" : [" Привязка и поиск работают в настроенном LDAP-соединении (%s)"," Привязка и поиск работают во всех %n настроенных LDAP-соединениях (%s)"," Привязка и поиск работают во всех %n настроенных LDAP-соединениях (%s)"," Привязка и поиск работают во всех %n настроенных LDAP-соединениях (%s)"],
"Invalid LDAP UUIDs" : "Недопустимые UUID LDAP",
"None found" : "Ничего не найдено",
"Invalid UUIDs of LDAP accounts or groups have been found. Please review your \"Override UUID detection\" settings in the Expert part of the LDAP configuration and use \"occ ldap:update-uuid\" to update them." : "Обнаружены недопустимые идентификаторы UUID учетных записей или групп LDAP. Пожалуйста, ознакомьтесь с вашими настройками \"Переопределение обнаружения UUID\" в экспертной части конфигурации LDAP и используйте \"occ ldap:update-uuid\", чтобы обновить их.",
@@ -206,6 +219,8 @@
"User profile Biography will be set from the specified attribute" : "Биография в профиле пользователя будет установлена из указанного атрибута",
"Birthdate Field" : "Поле Даты рождения",
"User profile Date of birth will be set from the specified attribute" : "Дата рождения профиля пользователя будет установлена на основе указанного атрибута",
+ "Pronouns Field" : " Поле местоимений",
+ "User profile Pronouns will be set from the specified attribute" : "Местоимения в профиле пользователя будут заданы из указанного атрибута",
"Internal Username" : "Внутреннее имя пользователя",
"By default the internal username will be created from the UUID attribute. It makes sure that the username is unique and characters do not need to be converted. The internal username has the restriction that only these characters are allowed: [a-zA-Z0-9_.@-]. Other characters are replaced with their ASCII correspondence or simply omitted. On collisions a number will be added/increased. The internal username is used to identify a user internally. It is also the default name for the user home folder. It is also a part of remote URLs, for instance for all DAV services. With this setting, the default behavior can be overridden. Changes will have effect only on newly mapped (added) LDAP users. Leave it empty for default behavior." : "По умолчанию внутреннее имя пользователя будет создано на основе атрибута UUID. Это гарантирует, что имя пользователя будет уникальным и символы не нужно будет преобразовывать. Внутреннее имя пользователя имеет ограничение – разрешены только эти символы: [a-zA-Z0-9_.@-]. Другие символы заменяются их ASCII-кодами или просто опускаются. При совпадениях число будет добавлено/увеличено. Внутреннее имя пользователя используется для внутренней идентификации пользователя. Оно также является именем по умолчанию для домашней папки пользователя. Оно также является частью удалённых URL-адресов, например, для всех служб DAV. С помощью этого параметра можно переопределить поведение по умолчанию. Изменения будут иметь силу только для новых сопоставленных (добавленных) пользователей LDAP. Оставьте этот параметр пустым для поведения по умолчанию.",
"Internal Username Attribute:" : "Атрибут для внутреннего имени:",
diff --git a/apps/user_ldap/lib/Command/Search.php b/apps/user_ldap/lib/Command/Search.php
index ad13c94c84a..85906b20e9a 100644
--- a/apps/user_ldap/lib/Command/Search.php
+++ b/apps/user_ldap/lib/Command/Search.php
@@ -12,7 +12,6 @@ use OCA\User_LDAP\Helper;
use OCA\User_LDAP\LDAP;
use OCA\User_LDAP\User_Proxy;
use OCP\IConfig;
-use OCP\IDBConnection;
use OCP\Server;
use Symfony\Component\Console\Command\Command;
@@ -83,7 +82,7 @@ class Search extends Command {
}
protected function execute(InputInterface $input, OutputInterface $output): int {
- $helper = new Helper($this->ocConfig, Server::get(IDBConnection::class));
+ $helper = Server::get(Helper::class);
$configPrefixes = $helper->getServerConfigurationPrefixes(true);
$ldapWrapper = new LDAP();
diff --git a/apps/user_ldap/lib/Command/SetConfig.php b/apps/user_ldap/lib/Command/SetConfig.php
index 5a0b65a2c3e..7e9efcf34d0 100644
--- a/apps/user_ldap/lib/Command/SetConfig.php
+++ b/apps/user_ldap/lib/Command/SetConfig.php
@@ -11,8 +11,6 @@ use OCA\User_LDAP\Configuration;
use OCA\User_LDAP\ConnectionFactory;
use OCA\User_LDAP\Helper;
use OCA\User_LDAP\LDAP;
-use OCP\IConfig;
-use OCP\IDBConnection;
use OCP\Server;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
@@ -43,7 +41,7 @@ class SetConfig extends Command {
}
protected function execute(InputInterface $input, OutputInterface $output): int {
- $helper = new Helper(Server::get(IConfig::class), Server::get(IDBConnection::class));
+ $helper = Server::get(Helper::class);
$availableConfigs = $helper->getServerConfigurationPrefixes();
$configID = $input->getArgument('configID');
if (!in_array($configID, $availableConfigs)) {
diff --git a/apps/user_ldap/lib/Connection.php b/apps/user_ldap/lib/Connection.php
index 78a5f93d29e..b25a2e72b2b 100644
--- a/apps/user_ldap/lib/Connection.php
+++ b/apps/user_ldap/lib/Connection.php
@@ -11,8 +11,6 @@ use OC\ServerNotAvailableException;
use OCA\User_LDAP\Exceptions\ConfigurationIssueException;
use OCP\ICache;
use OCP\ICacheFactory;
-use OCP\IConfig;
-use OCP\IDBConnection;
use OCP\IL10N;
use OCP\Server;
use OCP\Util;
@@ -156,7 +154,7 @@ class Connection extends LDAPUtility {
if ($memcache->isAvailable()) {
$this->cache = $memcache->createDistributed();
}
- $helper = new Helper(Server::get(IConfig::class), Server::get(IDBConnection::class));
+ $helper = Server::get(Helper::class);
$this->doNotValidate = !in_array($this->configPrefix,
$helper->getServerConfigurationPrefixes());
$this->logger = Server::get(LoggerInterface::class);
diff --git a/apps/user_ldap/lib/Helper.php b/apps/user_ldap/lib/Helper.php
index 27c19e6c4f5..d3abf04fd1e 100644
--- a/apps/user_ldap/lib/Helper.php
+++ b/apps/user_ldap/lib/Helper.php
@@ -9,7 +9,7 @@ namespace OCA\User_LDAP;
use OCP\Cache\CappedMemoryCache;
use OCP\DB\QueryBuilder\IQueryBuilder;
-use OCP\IConfig;
+use OCP\IAppConfig;
use OCP\IDBConnection;
use OCP\Server;
@@ -18,7 +18,7 @@ class Helper {
protected CappedMemoryCache $sanitizeDnCache;
public function __construct(
- private IConfig $config,
+ private IAppConfig $appConfig,
private IDBConnection $connection,
) {
$this->sanitizeDnCache = new CappedMemoryCache(10000);
@@ -45,21 +45,37 @@ class Helper {
* except the default (first) server shall be connected to.
*
*/
- public function getServerConfigurationPrefixes($activeConfigurations = false): array {
+ public function getServerConfigurationPrefixes(bool $activeConfigurations = false): array {
+ $all = $this->getAllServerConfigurationPrefixes();
+ if (!$activeConfigurations) {
+ return $all;
+ }
+ return array_values(array_filter(
+ $all,
+ fn (string $prefix): bool => ($this->appConfig->getValueString('user_ldap', $prefix . 'ldap_configuration_active') === '1')
+ ));
+ }
+
+ protected function getAllServerConfigurationPrefixes(): array {
+ $unfilled = ['UNFILLED'];
+ $prefixes = $this->appConfig->getValueArray('user_ldap', 'configuration_prefixes', $unfilled);
+ if ($prefixes !== $unfilled) {
+ return $prefixes;
+ }
+
+ /* Fallback to browsing key for migration from Nextcloud<32 */
$referenceConfigkey = 'ldap_configuration_active';
$keys = $this->getServersConfig($referenceConfigkey);
$prefixes = [];
foreach ($keys as $key) {
- if ($activeConfigurations && $this->config->getAppValue('user_ldap', $key, '0') !== '1') {
- continue;
- }
-
$len = strlen($key) - strlen($referenceConfigkey);
$prefixes[] = substr($key, 0, $len);
}
- asort($prefixes);
+ sort($prefixes);
+
+ $this->appConfig->setValueArray('user_ldap', 'configuration_prefixes', $prefixes);
return $prefixes;
}
@@ -68,46 +84,45 @@ class Helper {
*
* determines the host for every configured connection
*
- * @return array an array with configprefix as keys
+ * @return array<string,string> an array with configprefix as keys
*
*/
- public function getServerConfigurationHosts() {
- $referenceConfigkey = 'ldap_host';
-
- $keys = $this->getServersConfig($referenceConfigkey);
+ public function getServerConfigurationHosts(): array {
+ $prefixes = $this->getServerConfigurationPrefixes();
+ $referenceConfigkey = 'ldap_host';
$result = [];
- foreach ($keys as $key) {
- $len = strlen($key) - strlen($referenceConfigkey);
- $prefix = substr($key, 0, $len);
- $result[$prefix] = $this->config->getAppValue('user_ldap', $key);
+ foreach ($prefixes as $prefix) {
+ $result[$prefix] = $this->appConfig->getValueString('user_ldap', $prefix . $referenceConfigkey);
}
return $result;
}
/**
- * return the next available configuration prefix
- *
- * @return string
+ * return the next available configuration prefix and register it as used
*/
- public function getNextServerConfigurationPrefix() {
- $serverConnections = $this->getServerConfigurationPrefixes();
-
- if (count($serverConnections) === 0) {
- return 's01';
+ public function getNextServerConfigurationPrefix(): string {
+ $prefixes = $this->getServerConfigurationPrefixes();
+
+ if (count($prefixes) === 0) {
+ $prefix = 's01';
+ } else {
+ sort($prefixes);
+ $lastKey = array_pop($prefixes);
+ $lastNumber = (int)str_replace('s', '', $lastKey);
+ $prefix = 's' . str_pad((string)($lastNumber + 1), 2, '0', STR_PAD_LEFT);
}
- sort($serverConnections);
- $lastKey = array_pop($serverConnections);
- $lastNumber = (int)str_replace('s', '', $lastKey);
- return 's' . str_pad((string)($lastNumber + 1), 2, '0', STR_PAD_LEFT);
+ $prefixes[] = $prefix;
+ $this->appConfig->setValueArray('user_ldap', 'configuration_prefixes', $prefixes);
+ return $prefix;
}
private function getServersConfig(string $value): array {
$regex = '/' . $value . '$/S';
- $keys = $this->config->getAppKeys('user_ldap');
+ $keys = $this->appConfig->getKeys('user_ldap');
$result = [];
foreach ($keys as $key) {
if (preg_match($regex, $key) === 1) {
@@ -125,7 +140,9 @@ class Helper {
* @return bool true on success, false otherwise
*/
public function deleteServerConfiguration($prefix) {
- if (!in_array($prefix, self::getServerConfigurationPrefixes())) {
+ $prefixes = $this->getServerConfigurationPrefixes();
+ $index = array_search($prefix, $prefixes);
+ if ($index === false) {
return false;
}
@@ -144,7 +161,11 @@ class Helper {
$query->andWhere($query->expr()->notLike('configkey', $query->createNamedParameter('s%')));
}
- $deletedRows = $query->execute();
+ $deletedRows = $query->executeStatement();
+
+ unset($prefixes[$index]);
+ $this->appConfig->setValueArray('user_ldap', 'configuration_prefixes', array_values($prefixes));
+
return $deletedRows !== 0;
}
@@ -152,10 +173,13 @@ class Helper {
* checks whether there is one or more disabled LDAP configurations
*/
public function haveDisabledConfigurations(): bool {
- $all = $this->getServerConfigurationPrefixes(false);
- $active = $this->getServerConfigurationPrefixes(true);
-
- return count($all) !== count($active) || count($all) === 0;
+ $all = $this->getServerConfigurationPrefixes();
+ foreach ($all as $prefix) {
+ if ($this->appConfig->getValueString('user_ldap', $prefix . 'ldap_configuration_active') !== '1') {
+ return true;
+ }
+ }
+ return false;
}
/**
diff --git a/apps/user_ldap/lib/Jobs/CleanUp.php b/apps/user_ldap/lib/Jobs/CleanUp.php
index 7cfc473c950..a1309c0c463 100644
--- a/apps/user_ldap/lib/Jobs/CleanUp.php
+++ b/apps/user_ldap/lib/Jobs/CleanUp.php
@@ -67,7 +67,7 @@ class CleanUp extends TimedJob {
if (isset($arguments['helper'])) {
$this->ldapHelper = $arguments['helper'];
} else {
- $this->ldapHelper = new Helper(Server::get(IConfig::class), Server::get(IDBConnection::class));
+ $this->ldapHelper = Server::get(Helper::class);
}
if (isset($arguments['ocConfig'])) {
diff --git a/apps/user_ldap/lib/Settings/Admin.php b/apps/user_ldap/lib/Settings/Admin.php
index 014210ca8f0..49868eb68c7 100644
--- a/apps/user_ldap/lib/Settings/Admin.php
+++ b/apps/user_ldap/lib/Settings/Admin.php
@@ -8,8 +8,6 @@ namespace OCA\User_LDAP\Settings;
use OCA\User_LDAP\Configuration;
use OCA\User_LDAP\Helper;
use OCP\AppFramework\Http\TemplateResponse;
-use OCP\IConfig;
-use OCP\IDBConnection;
use OCP\IL10N;
use OCP\Server;
use OCP\Settings\IDelegatedSettings;
@@ -26,7 +24,7 @@ class Admin implements IDelegatedSettings {
* @return TemplateResponse
*/
public function getForm() {
- $helper = new Helper(Server::get(IConfig::class), Server::get(IDBConnection::class));
+ $helper = Server::get(Helper::class);
$prefixes = $helper->getServerConfigurationPrefixes();
if (count($prefixes) === 0) {
$newPrefix = $helper->getNextServerConfigurationPrefix();
diff --git a/apps/user_ldap/tests/AccessTest.php b/apps/user_ldap/tests/AccessTest.php
index 86ce2aff854..eafaeb76403 100644
--- a/apps/user_ldap/tests/AccessTest.php
+++ b/apps/user_ldap/tests/AccessTest.php
@@ -25,7 +25,6 @@ use OCP\HintException;
use OCP\IAppConfig;
use OCP\IAvatarManager;
use OCP\IConfig;
-use OCP\IDBConnection;
use OCP\Image;
use OCP\IUserManager;
use OCP\Notification\IManager as INotificationManager;
@@ -110,7 +109,7 @@ class AccessTest extends TestCase {
$this->createMock(INotificationManager::class),
$this->shareManager])
->getMock();
- $helper = new Helper(Server::get(IConfig::class), Server::get(IDBConnection::class));
+ $helper = Server::get(Helper::class);
return [$lw, $connector, $um, $helper];
}
diff --git a/apps/user_ldap/tests/HelperTest.php b/apps/user_ldap/tests/HelperTest.php
index 470b67c5531..adea600d900 100644
--- a/apps/user_ldap/tests/HelperTest.php
+++ b/apps/user_ldap/tests/HelperTest.php
@@ -8,7 +8,7 @@ declare(strict_types=1);
namespace OCA\User_LDAP\Tests;
use OCA\User_LDAP\Helper;
-use OCP\IConfig;
+use OCP\IAppConfig;
use OCP\IDBConnection;
use OCP\Server;
use PHPUnit\Framework\MockObject\MockObject;
@@ -17,45 +17,53 @@ use PHPUnit\Framework\MockObject\MockObject;
* @group DB
*/
class HelperTest extends \Test\TestCase {
- private IConfig&MockObject $config;
+ private IAppConfig&MockObject $appConfig;
private Helper $helper;
protected function setUp(): void {
parent::setUp();
- $this->config = $this->createMock(IConfig::class);
- $this->helper = new Helper($this->config, Server::get(IDBConnection::class));
+ $this->appConfig = $this->createMock(IAppConfig::class);
+ $this->helper = new Helper(
+ $this->appConfig,
+ Server::get(IDBConnection::class)
+ );
}
public function testGetServerConfigurationPrefixes(): void {
- $this->config->method('getAppKeys')
- ->with($this->equalTo('user_ldap'))
+ $this->appConfig->method('getKeys')
+ ->with('user_ldap')
->willReturn([
'foo',
'ldap_configuration_active',
's1ldap_configuration_active',
]);
+ $this->appConfig->method('getValueArray')
+ ->with('user_ldap', 'configuration_prefixes')
+ -> willReturnArgument(2);
+
$result = $this->helper->getServerConfigurationPrefixes(false);
$this->assertEquals(['', 's1'], $result);
}
public function testGetServerConfigurationPrefixesActive(): void {
- $this->config->method('getAppKeys')
- ->with($this->equalTo('user_ldap'))
+ $this->appConfig->method('getKeys')
+ ->with('user_ldap')
->willReturn([
'foo',
'ldap_configuration_active',
's1ldap_configuration_active',
]);
- $this->config->method('getAppValue')
+ $this->appConfig->method('getValueArray')
+ ->with('user_ldap', 'configuration_prefixes')
+ -> willReturnArgument(2);
+
+ $this->appConfig->method('getValueString')
->willReturnCallback(function ($app, $key, $default) {
- if ($app !== 'user_ldap') {
- $this->fail('wrong app');
- }
if ($key === 's1ldap_configuration_active') {
return '1';
}
@@ -67,21 +75,58 @@ class HelperTest extends \Test\TestCase {
$this->assertEquals(['s1'], $result);
}
- public function testGetServerConfigurationHost(): void {
- $this->config->method('getAppKeys')
- ->with($this->equalTo('user_ldap'))
+ public function testGetServerConfigurationHostFromAppKeys(): void {
+ $this->appConfig->method('getKeys')
+ ->with('user_ldap')
->willReturn([
'foo',
'ldap_host',
's1ldap_host',
's02ldap_host',
+ 'ldap_configuration_active',
+ 's1ldap_configuration_active',
+ 's02ldap_configuration_active',
]);
- $this->config->method('getAppValue')
+ $this->appConfig->method('getValueArray')
+ ->with('user_ldap', 'configuration_prefixes')
+ -> willReturnArgument(2);
+
+ $this->appConfig->method('getValueString')
->willReturnCallback(function ($app, $key, $default) {
- if ($app !== 'user_ldap') {
- $this->fail('wrong app');
+ if ($key === 'ldap_host') {
+ return 'example.com';
}
+ if ($key === 's1ldap_host') {
+ return 'foo.bar.com';
+ }
+ return $default;
+ });
+
+ $result = $this->helper->getServerConfigurationHosts();
+
+ $this->assertEquals([
+ '' => 'example.com',
+ 's1' => 'foo.bar.com',
+ 's02' => '',
+ ], $result);
+ }
+
+ public function testGetServerConfigurationHost(): void {
+ $this->appConfig
+ ->expects(self::never())
+ ->method('getKeys');
+
+ $this->appConfig->method('getValueArray')
+ ->with('user_ldap', 'configuration_prefixes')
+ -> willReturn([
+ '',
+ 's1',
+ 's02',
+ ]);
+
+ $this->appConfig->method('getValueString')
+ ->willReturnCallback(function ($app, $key, $default) {
if ($key === 'ldap_host') {
return 'example.com';
}
diff --git a/apps/user_ldap/tests/Integration/AbstractIntegrationTest.php b/apps/user_ldap/tests/Integration/AbstractIntegrationTest.php
index be8d7702cd1..00f8be18586 100644
--- a/apps/user_ldap/tests/Integration/AbstractIntegrationTest.php
+++ b/apps/user_ldap/tests/Integration/AbstractIntegrationTest.php
@@ -16,7 +16,6 @@ use OCA\User_LDAP\User\Manager;
use OCA\User_LDAP\UserPluginManager;
use OCP\IAvatarManager;
use OCP\IConfig;
-use OCP\IDBConnection;
use OCP\Image;
use OCP\IUserManager;
use OCP\Server;
@@ -125,7 +124,7 @@ abstract class AbstractIntegrationTest {
* initializes the test Helper
*/
protected function initHelper() {
- $this->helper = new Helper(Server::get(IConfig::class), Server::get(IDBConnection::class));
+ $this->helper = Server::get(Helper::class);
}
/**
diff --git a/apps/user_ldap/tests/LDAPProviderTest.php b/apps/user_ldap/tests/LDAPProviderTest.php
index a4da4a91948..57323e374aa 100644
--- a/apps/user_ldap/tests/LDAPProviderTest.php
+++ b/apps/user_ldap/tests/LDAPProviderTest.php
@@ -21,7 +21,6 @@ use OCA\User_LDAP\User_LDAP;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\ICacheFactory;
use OCP\IConfig;
-use OCP\IDBConnection;
use OCP\IServerContainer;
use OCP\Server;
use Psr\Log\LoggerInterface;
@@ -199,7 +198,7 @@ class LDAPProviderTest extends \Test\TestCase {
$server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
- $helper = new Helper(Server::get(IConfig::class), Server::get(IDBConnection::class));
+ $helper = Server::get(Helper::class);
$ldapProvider = $this->getLDAPProvider($server);
$this->assertEquals(
@@ -212,7 +211,7 @@ class LDAPProviderTest extends \Test\TestCase {
$server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
- $helper = new Helper(Server::get(IConfig::class), Server::get(IDBConnection::class));
+ $helper = Server::get(Helper::class);
$ldapProvider = $this->getLDAPProvider($server);
$this->assertEquals(