diff options
author | Thomas Mueller <thomas.mueller@tmit.eu> | 2013-02-13 01:18:01 +0100 |
---|---|---|
committer | Thomas Mueller <thomas.mueller@tmit.eu> | 2013-02-13 01:18:01 +0100 |
commit | bc43dd704fc89188faadb42d313a41f8b2929c0c (patch) | |
tree | e3d55e4b2cff99d4bdae91475a7249381c846ba9 /apps/user_ldap | |
parent | 14e3d77d64a83704d224ca91b5736ec2e94ee01b (diff) | |
parent | 68fa0b7dcc4a45e4f44b754626440091608ccc85 (diff) | |
download | nextcloud-server-bc43dd704fc89188faadb42d313a41f8b2929c0c.tar.gz nextcloud-server-bc43dd704fc89188faadb42d313a41f8b2929c0c.zip |
Merge branch 'master' into fixing-1424-master
Conflicts:
settings/js/users.js
Diffstat (limited to 'apps/user_ldap')
-rw-r--r-- | apps/user_ldap/l10n/de_DE.php | 1 | ||||
-rw-r--r-- | apps/user_ldap/l10n/es_AR.php | 12 | ||||
-rw-r--r-- | apps/user_ldap/l10n/eu.php | 26 | ||||
-rw-r--r-- | apps/user_ldap/l10n/hi.php | 3 | ||||
-rw-r--r-- | apps/user_ldap/l10n/ko.php | 11 | ||||
-rw-r--r-- | apps/user_ldap/l10n/nl.php | 1 | ||||
-rw-r--r-- | apps/user_ldap/l10n/ru.php | 12 | ||||
-rw-r--r-- | apps/user_ldap/lib/access.php | 121 |
8 files changed, 167 insertions, 20 deletions
diff --git a/apps/user_ldap/l10n/de_DE.php b/apps/user_ldap/l10n/de_DE.php index 7d3847f8a89..69faf5dc45d 100644 --- a/apps/user_ldap/l10n/de_DE.php +++ b/apps/user_ldap/l10n/de_DE.php @@ -43,6 +43,7 @@ "Disable Main Server" => "Hauptserver deaktivieren", "When switched on, ownCloud will only connect to the replica server." => "Wenn eingeschaltet wird sich ownCloud nur mit dem Replilat-Server verbinden.", "Use TLS" => "Nutze TLS", +"Do not use it additionally for LDAPS connections, it will fail." => "Benutze es nicht zusätzlich für LDAPS Verbindungen, es wird scheitern.", "Case insensitve LDAP server (Windows)" => "LDAP-Server (Windows: Groß- und Kleinschreibung bleibt unbeachtet)", "Turn off SSL certificate validation." => "Schalten Sie die SSL-Zertifikatsprüfung aus.", "If connection only works with this option, import the LDAP server's SSL certificate in your ownCloud server." => "Falls die Verbindung es erfordert, muss das SSL-Zertifikat des LDAP-Server importiert werden.", diff --git a/apps/user_ldap/l10n/es_AR.php b/apps/user_ldap/l10n/es_AR.php index a87444a270c..b0e7ec12b21 100644 --- a/apps/user_ldap/l10n/es_AR.php +++ b/apps/user_ldap/l10n/es_AR.php @@ -1,7 +1,10 @@ <?php $TRANSLATIONS = array( "Failed to delete the server configuration" => "Fallo al borrar la configuración del servidor", "The configuration is valid and the connection could be established!" => "La configuración es valida y la conexión pudo ser establecida.", +"The configuration is valid, but the Bind failed. Please check the server settings and credentials." => "La configuración es válida, pero el enlace falló. Por favor, comprobá la configuración del servidor y las credenciales.", +"The configuration is invalid. Please look in the ownCloud log for further details." => "La configuración no es válida. Por favor, buscá en el log de ownCloud más detalles.", "Deletion failed" => "Error al borrar", +"Take over settings from recent server configuration?" => "Tomar los valores de la anterior configuración de servidor?", "Keep settings?" => "¿Mantener preferencias?", "Cannot add server configuration" => "No se pudo añadir la configuración del servidor", "Connection test succeeded" => "El este de conexión ha sido completado satisfactoriamente", @@ -32,9 +35,15 @@ "without any placeholder, e.g. \"objectClass=posixGroup\"." => "Sin ninguna plantilla, p. ej.: \"objectClass=posixGroup\".", "Connection Settings" => "Configuración de Conección", "Configuration Active" => "Configuración activa", +"When unchecked, this configuration will be skipped." => "Si no está seleccionada, esta configuración será omitida.", "Port" => "Puerto", +"Backup (Replica) Host" => "Host para copia de seguridad (réplica)", +"Give an optional backup host. It must be a replica of the main LDAP/AD server." => "Dar un servidor de copia de seguridad opcional. Debe ser una réplica del servidor principal LDAP/AD.", +"Backup (Replica) Port" => "Puerto para copia de seguridad (réplica)", "Disable Main Server" => "Deshabilitar el Servidor Principal", +"When switched on, ownCloud will only connect to the replica server." => "Al comenzar, ownCloud se conectará únicamente al servidor réplica", "Use TLS" => "Usar TLS", +"Do not use it additionally for LDAPS connections, it will fail." => "No usar adicionalmente para conexiones LDAPS, las mismas fallarán", "Case insensitve LDAP server (Windows)" => "Servidor de LDAP sensible a mayúsculas/minúsculas (Windows)", "Turn off SSL certificate validation." => "Desactivar la validación por certificado SSL.", "If connection only works with this option, import the LDAP server's SSL certificate in your ownCloud server." => "Si la conexión sólo funciona con esta opción, importá el certificado SSL del servidor LDAP en tu servidor ownCloud.", @@ -45,10 +54,13 @@ "The LDAP attribute to use to generate the user`s ownCloud name." => "El atributo LDAP a usar para generar el nombre de usuario de ownCloud.", "Base User Tree" => "Árbol base de usuario", "One User Base DN per line" => "Una DN base de usuario por línea", +"User Search Attributes" => "Atributos de la búsqueda de usuario", +"Optional; one attribute per line" => "Opcional; un atributo por linea", "Group Display Name Field" => "Campo de nombre de grupo a mostrar", "The LDAP attribute to use to generate the groups`s ownCloud name." => "El atributo LDAP a usar para generar el nombre de los grupos de ownCloud.", "Base Group Tree" => "Árbol base de grupo", "One Group Base DN per line" => "Una DN base de grupo por línea", +"Group Search Attributes" => "Atributos de búsqueda de grupo", "Group-Member association" => "Asociación Grupo-Miembro", "Special Attributes" => "Atributos Especiales", "in bytes" => "en bytes", diff --git a/apps/user_ldap/l10n/eu.php b/apps/user_ldap/l10n/eu.php index 97c23f86480..7ab4d00e756 100644 --- a/apps/user_ldap/l10n/eu.php +++ b/apps/user_ldap/l10n/eu.php @@ -1,7 +1,19 @@ <?php $TRANSLATIONS = array( +"Failed to delete the server configuration" => "Zerbitzariaren konfigurazioa ezabatzeak huts egin du", +"The configuration is valid and the connection could be established!" => "Konfigurazioa egokia da eta konexioa ezarri daiteke!", +"The configuration is valid, but the Bind failed. Please check the server settings and credentials." => "Konfigurazioa ongi dago, baina Bind-ek huts egin du. Mesedez egiaztatu zerbitzariaren ezarpenak eta kredentzialak.", +"The configuration is invalid. Please look in the ownCloud log for further details." => "Konfigurazioa ez dago ongi. Mesedez ikusi ownCloud-en egunerokoa informazio gehiago eskuratzeko.", "Deletion failed" => "Ezabaketak huts egin du", +"Keep settings?" => "Mantendu ezarpenak?", +"Cannot add server configuration" => "Ezin da zerbitzariaren konfigurazioa gehitu", +"Connection test succeeded" => "Konexio froga ongi burutu da", +"Connection test failed" => "Konexio frogak huts egin du", +"Do you really want to delete the current Server Configuration?" => "Ziur zaude Zerbitzariaren Konfigurazioa ezabatu nahi duzula?", +"Confirm Deletion" => "Baieztatu Ezabatzea", "<b>Warning:</b> Apps user_ldap and user_webdavauth are incompatible. You may experience unexpected behaviour. Please ask your system administrator to disable one of them." => "<b>Abisua:</b> user_ldap eta user_webdavauth aplikazioak bateraezinak dira. Portaera berezia izan dezakezu. Mesedez eskatu zure sistema kudeatzaileari bietako bat desgaitzeko.", "<b>Warning:</b> The PHP LDAP module is not installed, the backend will not work. Please ask your system administrator to install it." => "<b>Abisua:</b> PHPk behar duen LDAP modulua ez dago instalaturik, motorrak ez du funtzionatuko. Mesedez eskatu zure sistema kudeatzaileari instala dezan.", +"Server configuration" => "Zerbitzariaren konfigurazioa", +"Add Server Configuration" => "Gehitu Zerbitzariaren Konfigurazioa", "Host" => "Hostalaria", "You can omit the protocol, except you require SSL. Then start with ldaps://" => "Protokoloa ez da beharrezkoa, SSL behar baldin ez baduzu. Honela bada hasi ldaps://", "Base DN" => "Oinarrizko DN", @@ -20,22 +32,36 @@ "Group Filter" => "Taldeen iragazkia", "Defines the filter to apply, when retrieving groups." => "Taldeak jasotzen direnean ezarriko den iragazkia zehazten du.", "without any placeholder, e.g. \"objectClass=posixGroup\"." => "txantiloirik gabe, adb. \"objectClass=posixGroup\".", +"Connection Settings" => "Konexio Ezarpenak", +"Configuration Active" => "Konfigurazio Aktiboa", +"When unchecked, this configuration will be skipped." => "Markatuta ez dagoenean, konfigurazio hau ez da kontutan hartuko.", "Port" => "Portua", +"Backup (Replica) Host" => "Babeskopia (Replica) Ostalaria", +"Give an optional backup host. It must be a replica of the main LDAP/AD server." => "Eman babeskopia ostalari gehigarri bat. LDAP/AD zerbitzari nagusiaren replica bat izan behar da.", +"Backup (Replica) Port" => "Babeskopia (Replica) Ataka", +"Disable Main Server" => "Desgaitu Zerbitzari Nagusia", +"When switched on, ownCloud will only connect to the replica server." => "Markatuta dagoenean, ownCloud bakarrik replica zerbitzarira konektatuko da.", "Use TLS" => "Erabili TLS", +"Do not use it additionally for LDAPS connections, it will fail." => "Ez erabili LDAPS konexioetarako, huts egingo du.", "Case insensitve LDAP server (Windows)" => "Maiuskulak eta minuskulak ezberditzen ez dituen LDAP zerbitzaria (windows)", "Turn off SSL certificate validation." => "Ezgaitu SSL ziurtagirien egiaztapena.", "If connection only works with this option, import the LDAP server's SSL certificate in your ownCloud server." => "Konexioa aukera hau ezinbestekoa badu, inportatu LDAP zerbitzariaren SSL ziurtagiria zure ownCloud zerbitzarian.", "Not recommended, use for testing only." => "Ez da aholkatzen, erabili bakarrik frogak egiteko.", "in seconds. A change empties the cache." => "segundutan. Aldaketak katxea husten du.", +"Directory Settings" => "Karpetaren Ezarpenak", "User Display Name Field" => "Erabiltzaileen bistaratzeko izena duen eremua", "The LDAP attribute to use to generate the user`s ownCloud name." => "ownCloud erabiltzailearen izena sortzeko erabiliko den LDAP atributua", "Base User Tree" => "Oinarrizko Erabiltzaile Zuhaitza", "One User Base DN per line" => "Erabiltzaile DN Oinarri bat lerroko", +"User Search Attributes" => "Erabili Bilaketa Atributuak ", +"Optional; one attribute per line" => "Aukerakoa; atributu bat lerro bakoitzeko", "Group Display Name Field" => "Taldeen bistaratzeko izena duen eremua", "The LDAP attribute to use to generate the groups`s ownCloud name." => "ownCloud taldearen izena sortzeko erabiliko den LDAP atributua", "Base Group Tree" => "Oinarrizko Talde Zuhaitza", "One Group Base DN per line" => "Talde DN Oinarri bat lerroko", +"Group Search Attributes" => "Taldekatu Bilaketa Atributuak ", "Group-Member association" => "Talde-Kide elkarketak", +"Special Attributes" => "Atributu Bereziak", "in bytes" => "bytetan", "Leave empty for user name (default). Otherwise, specify an LDAP/AD attribute." => "Utzi hutsik erabiltzaile izenarako (lehentsia). Bestela zehaztu LDAP/AD atributua.", "Help" => "Laguntza" diff --git a/apps/user_ldap/l10n/hi.php b/apps/user_ldap/l10n/hi.php new file mode 100644 index 00000000000..60d4ea98e84 --- /dev/null +++ b/apps/user_ldap/l10n/hi.php @@ -0,0 +1,3 @@ +<?php $TRANSLATIONS = array( +"Help" => "सहयोग" +); diff --git a/apps/user_ldap/l10n/ko.php b/apps/user_ldap/l10n/ko.php index 419e2d0a690..8aa9fe74b3d 100644 --- a/apps/user_ldap/l10n/ko.php +++ b/apps/user_ldap/l10n/ko.php @@ -1,5 +1,8 @@ <?php $TRANSLATIONS = array( "Deletion failed" => "삭제 실패", +"Keep settings?" => "설정을 유지합니까?", +"Connection test succeeded" => "연결 시험 성공", +"Connection test failed" => "연결 시험 실패", "<b>Warning:</b> Apps user_ldap and user_webdavauth are incompatible. You may experience unexpected behaviour. Please ask your system administrator to disable one of them." => "<b>경고:</b> user_ldap 앱과 user_webdavauth 앱은 호환되지 않습니다. 오동작을 일으킬 수 있으므로, 시스템 관리자에게 요청하여 둘 중 하나만 사용하도록 하십시오.", "<b>Warning:</b> The PHP LDAP module is not installed, the backend will not work. Please ask your system administrator to install it." => "<b>경고:</b> PHP LDAP 모듈이 비활성화되어 있거나 설치되어 있지 않습니다. 백엔드를 사용할 수 없습니다. 시스템 관리자에게 설치를 요청하십시오.", "Host" => "호스트", @@ -20,21 +23,29 @@ "Group Filter" => "그룹 필터", "Defines the filter to apply, when retrieving groups." => "그룹을 검색할 때 적용할 필터를 정의합니다.", "without any placeholder, e.g. \"objectClass=posixGroup\"." => "자리 비움자를 사용할 수 없습니다. 예제: \"objectClass=posixGroup\"", +"Connection Settings" => "연결 설정", +"Configuration Active" => "구성 활성화", "Port" => "포트", +"Backup (Replica) Host" => "백업 (복제) 포트", +"Backup (Replica) Port" => "백업 (복제) 포트", +"Disable Main Server" => "주 서버 비활성화", "Use TLS" => "TLS 사용", "Case insensitve LDAP server (Windows)" => "서버에서 대소문자를 구분하지 않음 (Windows)", "Turn off SSL certificate validation." => "SSL 인증서 유효성 검사를 해제합니다.", "If connection only works with this option, import the LDAP server's SSL certificate in your ownCloud server." => "이 옵션을 사용해야 연결할 수 있는 경우에는 LDAP 서버의 SSL 인증서를 ownCloud로 가져올 수 있습니다.", "Not recommended, use for testing only." => "추천하지 않음, 테스트로만 사용하십시오.", "in seconds. A change empties the cache." => "초. 항목 변경 시 캐시가 갱신됩니다.", +"Directory Settings" => "디렉토리 설정", "User Display Name Field" => "사용자의 표시 이름 필드", "The LDAP attribute to use to generate the user`s ownCloud name." => "LDAP 속성은 사용자의 ownCloud 이름을 생성하기 위해 사용합니다.", "Base User Tree" => "기본 사용자 트리", "One User Base DN per line" => "사용자 DN을 한 줄에 하나씩 입력하십시오", +"User Search Attributes" => "사용자 검색 속성", "Group Display Name Field" => "그룹의 표시 이름 필드", "The LDAP attribute to use to generate the groups`s ownCloud name." => "LDAP 속성은 그룹의 ownCloud 이름을 생성하기 위해 사용합니다.", "Base Group Tree" => "기본 그룹 트리", "One Group Base DN per line" => "그룹 기본 DN을 한 줄에 하나씩 입력하십시오", +"Group Search Attributes" => "그룹 검색 속성", "Group-Member association" => "그룹-회원 연결", "in bytes" => "바이트", "Leave empty for user name (default). Otherwise, specify an LDAP/AD attribute." => "사용자 이름을 사용하려면 비워 두십시오(기본값). 기타 경우 LDAP/AD 속성을 지정하십시오.", diff --git a/apps/user_ldap/l10n/nl.php b/apps/user_ldap/l10n/nl.php index 6879a4c4b94..0eda263aa11 100644 --- a/apps/user_ldap/l10n/nl.php +++ b/apps/user_ldap/l10n/nl.php @@ -43,6 +43,7 @@ "Disable Main Server" => "Deactiveren hoofdserver", "When switched on, ownCloud will only connect to the replica server." => "Wanneer ingeschakeld, zal ownCloud allen verbinden met de replicaserver.", "Use TLS" => "Gebruik TLS", +"Do not use it additionally for LDAPS connections, it will fail." => "Gebruik het niet voor LDAPS verbindingen, dat gaat niet lukken.", "Case insensitve LDAP server (Windows)" => "Niet-hoofdlettergevoelige LDAP server (Windows)", "Turn off SSL certificate validation." => "Schakel SSL certificaat validatie uit.", "If connection only works with this option, import the LDAP server's SSL certificate in your ownCloud server." => "Als de connectie alleen werkt met deze optie, importeer dan het LDAP server SSL certificaat naar je ownCloud server.", diff --git a/apps/user_ldap/l10n/ru.php b/apps/user_ldap/l10n/ru.php index 4c4b9708667..c66530174a9 100644 --- a/apps/user_ldap/l10n/ru.php +++ b/apps/user_ldap/l10n/ru.php @@ -1,6 +1,7 @@ <?php $TRANSLATIONS = array( "Failed to delete the server configuration" => "Не удалось удалить конфигурацию сервера", "The configuration is valid and the connection could be established!" => "Конфигурация правильная и подключение может быть установлено!", +"The configuration is valid, but the Bind failed. Please check the server settings and credentials." => "Конфигурация верна, но операция подключения завершилась неудачно. Пожалуйста, проверьте настройки сервера и учетные данные.", "The configuration is invalid. Please look in the ownCloud log for further details." => "Конфигурация не верна. Пожалуйста, посмотрите в журнале ownCloud детали.", "Deletion failed" => "Удаление не удалось", "Take over settings from recent server configuration?" => "Принять настройки из последней конфигурации сервера?", @@ -11,11 +12,13 @@ "Do you really want to delete the current Server Configuration?" => "Вы действительно хотите удалить существующую конфигурацию сервера?", "Confirm Deletion" => "Подтверждение удаления", "<b>Warning:</b> Apps user_ldap and user_webdavauth are incompatible. You may experience unexpected behaviour. Please ask your system administrator to disable one of them." => "<b>Внимание:</b>Приложения user_ldap и user_webdavauth несовместимы. Вы можете столкнуться с неожиданным поведением. Пожалуйста, обратитесь к системному администратору, чтобы отключить одно из них.", +"<b>Warning:</b> The PHP LDAP module is not installed, the backend will not work. Please ask your system administrator to install it." => "<b>Внимание:</b> Модуль LDAP для PHP не установлен, бэкенд не будет работать. Пожалуйста, попросите вашего системного администратора его установить. ", "Server configuration" => "Конфигурация сервера", "Add Server Configuration" => "Добавить конфигурацию сервера", "Host" => "Сервер", "You can omit the protocol, except you require SSL. Then start with ldaps://" => "Можно опустить протокол, за исключением того, когда вам требуется SSL. Тогда начните с ldaps :/ /", "Base DN" => "Базовый DN", +"One Base DN per line" => "По одному базовому DN в строке.", "You can specify Base DN for users and groups in the Advanced tab" => "Вы можете задать Base DN для пользователей и групп на вкладке \"Расширенное\"", "User DN" => "DN пользователя", "The DN of the client user with which the bind shall be done, e.g. uid=agent,dc=example,dc=com. For anonymous access, leave DN and Password empty." => "DN-клиента пользователя, с которым связывают должно быть заполнено, например, uid=агент, dc=пример, dc=com. Для анонимного доступа, оставьте DN и пароль пустыми.", @@ -32,9 +35,15 @@ "without any placeholder, e.g. \"objectClass=posixGroup\"." => "без заполнения, например \"objectClass=posixGroup\".", "Connection Settings" => "Настройки подключения", "Configuration Active" => "Конфигурация активна", +"When unchecked, this configuration will be skipped." => "Когда галочка снята, эта конфигурация будет пропущена.", "Port" => "Порт", +"Backup (Replica) Host" => "Адрес резервного сервера", +"Give an optional backup host. It must be a replica of the main LDAP/AD server." => "Укажите дополнительный резервный сервер. Он должен быть репликой главного LDAP/AD сервера.", +"Backup (Replica) Port" => "Порт резервного сервера", "Disable Main Server" => "Отключение главного сервера", +"When switched on, ownCloud will only connect to the replica server." => "Когда включено, ownCloud будет соединяться только с резервным сервером.", "Use TLS" => "Использовать TLS", +"Do not use it additionally for LDAPS connections, it will fail." => "Не используйте совместно с безопасными подключениями (LDAPS), это не сработает.", "Case insensitve LDAP server (Windows)" => "Нечувствительный к регистру сервер LDAP (Windows)", "Turn off SSL certificate validation." => "Отключить проверку сертификата SSL.", "If connection only works with this option, import the LDAP server's SSL certificate in your ownCloud server." => "Если соединение работает только с этой опцией, импортируйте на ваш сервер ownCloud сертификат SSL сервера LDAP.", @@ -44,11 +53,14 @@ "User Display Name Field" => "Поле отображаемого имени пользователя", "The LDAP attribute to use to generate the user`s ownCloud name." => "Атрибут LDAP для генерации имени пользователя ownCloud.", "Base User Tree" => "База пользовательского дерева", +"One User Base DN per line" => "По одной базовому DN пользователей в строке.", "User Search Attributes" => "Поисковые атрибуты пользователя", "Optional; one attribute per line" => "Опционально; один атрибут на линию", "Group Display Name Field" => "Поле отображаемого имени группы", "The LDAP attribute to use to generate the groups`s ownCloud name." => "Атрибут LDAP для генерации имени группы ownCloud.", "Base Group Tree" => "База группового дерева", +"One Group Base DN per line" => "По одной базовому DN групп в строке.", +"Group Search Attributes" => "Атрибуты поиска для группы", "Group-Member association" => "Ассоциация Группа-Участник", "Special Attributes" => "Специальные атрибуты", "in bytes" => "в байтах", diff --git a/apps/user_ldap/lib/access.php b/apps/user_ldap/lib/access.php index 68cbe4a5e75..057ae17c308 100644 --- a/apps/user_ldap/lib/access.php +++ b/apps/user_ldap/lib/access.php @@ -4,7 +4,7 @@ * ownCloud – LDAP Access * * @author Arthur Schiwon - * @copyright 2012 Arthur Schiwon blizzz@owncloud.com + * @copyright 2012, 2013 Arthur Schiwon blizzz@owncloud.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE @@ -293,6 +293,10 @@ abstract class Access { $query->execute(array($dn, $uuid)); return $component; } + } else { + //If the UUID can't be detected something is foul. + \OCP\Util::writeLog('user_ldap', 'Cannot determine UUID for '.$dn.'. Skipping.', \OCP\Util::INFO); + return false; } if(is_null($ldapname)) { @@ -303,21 +307,24 @@ abstract class Access { } $ldapname = $ldapname[0]; } - $ldapname = $this->sanitizeUsername($ldapname); + $intname = $isUser ? $this->sanitizeUsername($uuid) : $this->sanitizeUsername($ldapname); //a new user/group! Add it only if it doesn't conflict with other backend's users or existing groups - if(($isUser && !\OCP\User::userExists($ldapname, 'OCA\\user_ldap\\USER_LDAP')) || (!$isUser && !\OC_Group::groupExists($ldapname))) { - if($this->mapComponent($dn, $ldapname, $isUser)) { - return $ldapname; + //disabling Cache is required to avoid that the new user is cached as not-existing in fooExists check + $originalTTL = $this->connection->ldapCacheTTL; + $this->connection->setConfiguration(array('ldapCacheTTL' => 0)); + if(($isUser && !\OCP\User::userExists($intname)) + || (!$isUser && !\OC_Group::groupExists($intname))) { + if($this->mapComponent($dn, $intname, $isUser)) { + $this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL)); + return $intname; } } + $this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL)); - //doh! There is a conflict. We need to distinguish between users/groups. Adding indexes is an idea, but not much of a help for the user. The DN is ugly, but for now the only reasonable way. But we transform it to a readable format and remove the first part to only give the path where this object is located. - $oc_name = $this->alternateOwnCloudName($ldapname, $dn); - if(($isUser && !\OCP\User::userExists($oc_name)) || (!$isUser && !\OC_Group::groupExists($oc_name))) { - if($this->mapComponent($dn, $oc_name, $isUser)) { - return $oc_name; - } + $altname = $this->createAltInternalOwnCloudName($intname, $isUser); + if($this->mapComponent($dn, $altname, $isUser)) { + return $altname; } //if everything else did not help.. @@ -400,18 +407,92 @@ abstract class Access { } /** - * @brief creates a hopefully unique name for owncloud based on the display name and the dn of the LDAP object + * @brief creates a unique name for internal ownCloud use for users. Don't call it directly. * @param $name the display name of the object - * @param $dn the dn of the object - * @returns string with with the name to use in ownCloud + * @returns string with with the name to use in ownCloud or false if unsuccessful * - * creates a hopefully unique name for owncloud based on the display name and the dn of the LDAP object + * Instead of using this method directly, call + * createAltInternalOwnCloudName($name, true) */ - private function alternateOwnCloudName($name, $dn) { - $ufn = ldap_dn2ufn($dn); - $name = $name . '@' . trim(\OCP\Util::mb_substr_replace($ufn, '', 0, mb_strpos($ufn, ',', 0, 'UTF-8'), 'UTF-8')); - $name = $this->sanitizeUsername($name); - return $name; + private function _createAltInternalOwnCloudNameForUsers($name) { + $attempts = 0; + //while loop is just a precaution. If a name is not generated within + //20 attempts, something else is very wrong. Avoids infinite loop. + while($attempts < 20){ + $altName = $name . '_' . uniqid(); + if(\OCP\User::userExists($altName)) { + return $altName; + } + $attempts++; + } + return false; + } + + /** + * @brief creates a unique name for internal ownCloud use for groups. Don't call it directly. + * @param $name the display name of the object + * @returns string with with the name to use in ownCloud or false if unsuccessful. + * + * Instead of using this method directly, call + * createAltInternalOwnCloudName($name, false) + * + * Group names are also used as display names, so we do a sequential + * numbering, e.g. Developers_42 when there are 41 other groups called + * "Developers" + */ + private function _createAltInternalOwnCloudNameForGroups($name) { + $query = \OCP\DB::prepare(' + SELECT `owncloud_name` + FROM `'.$this->getMapTable(false).'` + WHERE `owncloud_name` LIKE ? + '); + + $usedNames = array(); + $res = $query->execute(array($name.'_%')); + while($row = $res->fetchRow()) { + $usedNames[] = $row['owncloud_name']; + } + if(!($usedNames) || count($usedNames) == 0) { + $lastNo = 1; //will become name_2 + } else { + natsort($usedNames); + $lastname = array_pop($usedNames); + $lastNo = intval(substr($lastname, strrpos($lastname, '_') + 1)); + } + $altName = $name.'_'.strval($lastNo+1); + unset($usedNames); + + $attempts = 1; + while($attempts < 21){ + //Pro forma check to be really sure it is unique + //while loop is just a precaution. If a name is not generated within + //20 attempts, something else is very wrong. Avoids infinite loop. + if(!\OC_Group::groupExists($altName)) { + return $altName; + } + $altName = $name . '_' . $lastNo + $attempts; + $attempts++; + } + return false; + } + + /** + * @brief creates a unique name for internal ownCloud use. + * @param $name the display name of the object + * @param $isUser boolean, whether name should be created for a user (true) or a group (false) + * @returns string with with the name to use in ownCloud or false if unsuccessful + */ + private function createAltInternalOwnCloudName($name, $isUser) { + $originalTTL = $this->connection->ldapCacheTTL; + $this->connection->setConfiguration(array('ldapCacheTTL' => 0)); + if($isUser) { + $altName = $this->_createAltInternalOwnCloudNameForUsers($name); + } else { + $altName = $this->_createAltInternalOwnCloudNameForGroups($name); + } + $this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL)); + + return $altName; } /** |