@@ -37,13 +37,13 @@ discard block |
||
37 | 37 | $l = \OC::$server->getL10N('user_ldap'); |
38 | 38 | |
39 | 39 | if (!isset($_POST['action'])) { |
40 | - \OC_JSON::error(['message' => $l->t('No action specified')]); |
|
40 | + \OC_JSON::error(['message' => $l->t('No action specified')]); |
|
41 | 41 | } |
42 | 42 | $action = (string)$_POST['action']; |
43 | 43 | |
44 | 44 | |
45 | 45 | if (!isset($_POST['ldap_serverconfig_chooser'])) { |
46 | - \OC_JSON::error(['message' => $l->t('No configuration specified')]); |
|
46 | + \OC_JSON::error(['message' => $l->t('No configuration specified')]); |
|
47 | 47 | } |
48 | 48 | $prefix = (string)$_POST['ldap_serverconfig_chooser']; |
49 | 49 | |
@@ -56,97 +56,97 @@ discard block |
||
56 | 56 | $con->setIgnoreValidation(true); |
57 | 57 | |
58 | 58 | $userManager = new \OCA\User_LDAP\User\Manager( |
59 | - \OC::$server->getConfig(), |
|
60 | - new \OCA\User_LDAP\FilesystemHelper(), |
|
61 | - new \OCA\User_LDAP\LogWrapper(), |
|
62 | - \OC::$server->getAvatarManager(), |
|
63 | - new \OCP\Image(), |
|
64 | - \OC::$server->getUserManager(), |
|
65 | - \OC::$server->getNotificationManager(), |
|
66 | - \OC::$server->get(\OCP\Share\IManager::class) |
|
59 | + \OC::$server->getConfig(), |
|
60 | + new \OCA\User_LDAP\FilesystemHelper(), |
|
61 | + new \OCA\User_LDAP\LogWrapper(), |
|
62 | + \OC::$server->getAvatarManager(), |
|
63 | + new \OCP\Image(), |
|
64 | + \OC::$server->getUserManager(), |
|
65 | + \OC::$server->getNotificationManager(), |
|
66 | + \OC::$server->get(\OCP\Share\IManager::class) |
|
67 | 67 | ); |
68 | 68 | |
69 | 69 | $access = new \OCA\User_LDAP\Access( |
70 | - $con, |
|
71 | - $ldapWrapper, |
|
72 | - $userManager, |
|
73 | - new \OCA\User_LDAP\Helper(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection()), |
|
74 | - \OC::$server->getConfig(), |
|
75 | - \OC::$server->getUserManager() |
|
70 | + $con, |
|
71 | + $ldapWrapper, |
|
72 | + $userManager, |
|
73 | + new \OCA\User_LDAP\Helper(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection()), |
|
74 | + \OC::$server->getConfig(), |
|
75 | + \OC::$server->getUserManager() |
|
76 | 76 | ); |
77 | 77 | |
78 | 78 | $wizard = new \OCA\User_LDAP\Wizard($configuration, $ldapWrapper, $access); |
79 | 79 | |
80 | 80 | switch ($action) { |
81 | - case 'guessPortAndTLS': |
|
82 | - case 'guessBaseDN': |
|
83 | - case 'detectEmailAttribute': |
|
84 | - case 'detectUserDisplayNameAttribute': |
|
85 | - case 'determineGroupMemberAssoc': |
|
86 | - case 'determineUserObjectClasses': |
|
87 | - case 'determineGroupObjectClasses': |
|
88 | - case 'determineGroupsForUsers': |
|
89 | - case 'determineGroupsForGroups': |
|
90 | - case 'determineAttributes': |
|
91 | - case 'getUserListFilter': |
|
92 | - case 'getUserLoginFilter': |
|
93 | - case 'getGroupFilter': |
|
94 | - case 'countUsers': |
|
95 | - case 'countGroups': |
|
96 | - case 'countInBaseDN': |
|
97 | - try { |
|
98 | - $result = $wizard->$action(); |
|
99 | - if ($result !== false) { |
|
100 | - \OC_JSON::success($result->getResultArray()); |
|
101 | - exit; |
|
102 | - } |
|
103 | - } catch (\Exception $e) { |
|
104 | - \OC_JSON::error(['message' => $e->getMessage(), 'code' => $e->getCode()]); |
|
105 | - exit; |
|
106 | - } |
|
107 | - \OC_JSON::error(); |
|
108 | - exit; |
|
109 | - break; |
|
81 | + case 'guessPortAndTLS': |
|
82 | + case 'guessBaseDN': |
|
83 | + case 'detectEmailAttribute': |
|
84 | + case 'detectUserDisplayNameAttribute': |
|
85 | + case 'determineGroupMemberAssoc': |
|
86 | + case 'determineUserObjectClasses': |
|
87 | + case 'determineGroupObjectClasses': |
|
88 | + case 'determineGroupsForUsers': |
|
89 | + case 'determineGroupsForGroups': |
|
90 | + case 'determineAttributes': |
|
91 | + case 'getUserListFilter': |
|
92 | + case 'getUserLoginFilter': |
|
93 | + case 'getGroupFilter': |
|
94 | + case 'countUsers': |
|
95 | + case 'countGroups': |
|
96 | + case 'countInBaseDN': |
|
97 | + try { |
|
98 | + $result = $wizard->$action(); |
|
99 | + if ($result !== false) { |
|
100 | + \OC_JSON::success($result->getResultArray()); |
|
101 | + exit; |
|
102 | + } |
|
103 | + } catch (\Exception $e) { |
|
104 | + \OC_JSON::error(['message' => $e->getMessage(), 'code' => $e->getCode()]); |
|
105 | + exit; |
|
106 | + } |
|
107 | + \OC_JSON::error(); |
|
108 | + exit; |
|
109 | + break; |
|
110 | 110 | |
111 | - case 'testLoginName': { |
|
112 | - try { |
|
113 | - $loginName = $_POST['ldap_test_loginname']; |
|
114 | - $result = $wizard->$action($loginName); |
|
115 | - if ($result !== false) { |
|
116 | - \OC_JSON::success($result->getResultArray()); |
|
117 | - exit; |
|
118 | - } |
|
119 | - } catch (\Exception $e) { |
|
120 | - \OC_JSON::error(['message' => $e->getMessage()]); |
|
121 | - exit; |
|
122 | - } |
|
123 | - \OC_JSON::error(); |
|
124 | - exit; |
|
125 | - break; |
|
126 | - } |
|
111 | + case 'testLoginName': { |
|
112 | + try { |
|
113 | + $loginName = $_POST['ldap_test_loginname']; |
|
114 | + $result = $wizard->$action($loginName); |
|
115 | + if ($result !== false) { |
|
116 | + \OC_JSON::success($result->getResultArray()); |
|
117 | + exit; |
|
118 | + } |
|
119 | + } catch (\Exception $e) { |
|
120 | + \OC_JSON::error(['message' => $e->getMessage()]); |
|
121 | + exit; |
|
122 | + } |
|
123 | + \OC_JSON::error(); |
|
124 | + exit; |
|
125 | + break; |
|
126 | + } |
|
127 | 127 | |
128 | - case 'save': |
|
129 | - $key = isset($_POST['cfgkey']) ? $_POST['cfgkey'] : false; |
|
130 | - $val = isset($_POST['cfgval']) ? $_POST['cfgval'] : null; |
|
131 | - if ($key === false || is_null($val)) { |
|
132 | - \OC_JSON::error(['message' => $l->t('No data specified')]); |
|
133 | - exit; |
|
134 | - } |
|
135 | - $cfg = [$key => $val]; |
|
136 | - $setParameters = []; |
|
137 | - $configuration->setConfiguration($cfg, $setParameters); |
|
138 | - if (!in_array($key, $setParameters)) { |
|
139 | - \OC_JSON::error(['message' => $l->t($key. |
|
140 | - ' Could not set configuration %s', $setParameters[0])]); |
|
141 | - exit; |
|
142 | - } |
|
143 | - $configuration->saveConfiguration(); |
|
144 | - //clear the cache on save |
|
145 | - $connection = new \OCA\User_LDAP\Connection($ldapWrapper, $prefix); |
|
146 | - $connection->clearCache(); |
|
147 | - \OC_JSON::success(); |
|
148 | - break; |
|
149 | - default: |
|
150 | - \OC_JSON::error(['message' => $l->t('Action does not exist')]); |
|
151 | - break; |
|
128 | + case 'save': |
|
129 | + $key = isset($_POST['cfgkey']) ? $_POST['cfgkey'] : false; |
|
130 | + $val = isset($_POST['cfgval']) ? $_POST['cfgval'] : null; |
|
131 | + if ($key === false || is_null($val)) { |
|
132 | + \OC_JSON::error(['message' => $l->t('No data specified')]); |
|
133 | + exit; |
|
134 | + } |
|
135 | + $cfg = [$key => $val]; |
|
136 | + $setParameters = []; |
|
137 | + $configuration->setConfiguration($cfg, $setParameters); |
|
138 | + if (!in_array($key, $setParameters)) { |
|
139 | + \OC_JSON::error(['message' => $l->t($key. |
|
140 | + ' Could not set configuration %s', $setParameters[0])]); |
|
141 | + exit; |
|
142 | + } |
|
143 | + $configuration->saveConfiguration(); |
|
144 | + //clear the cache on save |
|
145 | + $connection = new \OCA\User_LDAP\Connection($ldapWrapper, $prefix); |
|
146 | + $connection->clearCache(); |
|
147 | + \OC_JSON::success(); |
|
148 | + break; |
|
149 | + default: |
|
150 | + \OC_JSON::error(['message' => $l->t('Action does not exist')]); |
|
151 | + break; |
|
152 | 152 | } |
@@ -34,8 +34,8 @@ |
||
34 | 34 | $prefix = (string)$_POST['ldap_serverconfig_chooser']; |
35 | 35 | $helper = new \OCA\User_LDAP\Helper(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection()); |
36 | 36 | if ($helper->deleteServerConfiguration($prefix)) { |
37 | - \OC_JSON::success(); |
|
37 | + \OC_JSON::success(); |
|
38 | 38 | } else { |
39 | - $l = \OC::$server->getL10N('user_ldap'); |
|
40 | - \OC_JSON::error(['message' => $l->t('Failed to delete the server configuration')]); |
|
39 | + $l = \OC::$server->getL10N('user_ldap'); |
|
40 | + \OC_JSON::error(['message' => $l->t('Failed to delete the server configuration')]); |
|
41 | 41 | } |
@@ -31,7 +31,7 @@ |
||
31 | 31 | \OC_JSON::checkAppEnabled('user_ldap'); |
32 | 32 | \OC_JSON::callCheck(); |
33 | 33 | |
34 | -$prefix = (string)$_POST['ldap_serverconfig_chooser']; |
|
34 | +$prefix = (string) $_POST['ldap_serverconfig_chooser']; |
|
35 | 35 | $helper = new \OCA\User_LDAP\Helper(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection()); |
36 | 36 | if ($helper->deleteServerConfiguration($prefix)) { |
37 | 37 | \OC_JSON::success(); |
@@ -26,7 +26,7 @@ |
||
26 | 26 | $config = \OC::$server->getConfig(); |
27 | 27 | $state = $config->getSystemValue('ldapIgnoreNamingRules', 'doSet'); |
28 | 28 | if ($state === 'doSet') { |
29 | - \OC::$server->getConfig()->setSystemValue('ldapIgnoreNamingRules', false); |
|
29 | + \OC::$server->getConfig()->setSystemValue('ldapIgnoreNamingRules', false); |
|
30 | 30 | } |
31 | 31 | |
32 | 32 | $helper = new \OCA\User_LDAP\Helper($config, \OC::$server->getDatabaseConnection()); |
@@ -34,69 +34,69 @@ |
||
34 | 34 | use OCP\Template; |
35 | 35 | |
36 | 36 | class Admin implements ISettings { |
37 | - /** @var IL10N */ |
|
38 | - private $l; |
|
37 | + /** @var IL10N */ |
|
38 | + private $l; |
|
39 | 39 | |
40 | - /** |
|
41 | - * @param IL10N $l |
|
42 | - */ |
|
43 | - public function __construct(IL10N $l) { |
|
44 | - $this->l = $l; |
|
45 | - } |
|
40 | + /** |
|
41 | + * @param IL10N $l |
|
42 | + */ |
|
43 | + public function __construct(IL10N $l) { |
|
44 | + $this->l = $l; |
|
45 | + } |
|
46 | 46 | |
47 | - /** |
|
48 | - * @return TemplateResponse |
|
49 | - */ |
|
50 | - public function getForm() { |
|
51 | - $helper = new Helper(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection()); |
|
52 | - $prefixes = $helper->getServerConfigurationPrefixes(); |
|
53 | - if (count($prefixes) === 0) { |
|
54 | - $newPrefix = $helper->getNextServerConfigurationPrefix(); |
|
55 | - $config = new Configuration($newPrefix, false); |
|
56 | - $config->setConfiguration($config->getDefaults()); |
|
57 | - $config->saveConfiguration(); |
|
58 | - $prefixes[] = $newPrefix; |
|
59 | - } |
|
47 | + /** |
|
48 | + * @return TemplateResponse |
|
49 | + */ |
|
50 | + public function getForm() { |
|
51 | + $helper = new Helper(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection()); |
|
52 | + $prefixes = $helper->getServerConfigurationPrefixes(); |
|
53 | + if (count($prefixes) === 0) { |
|
54 | + $newPrefix = $helper->getNextServerConfigurationPrefix(); |
|
55 | + $config = new Configuration($newPrefix, false); |
|
56 | + $config->setConfiguration($config->getDefaults()); |
|
57 | + $config->saveConfiguration(); |
|
58 | + $prefixes[] = $newPrefix; |
|
59 | + } |
|
60 | 60 | |
61 | - $hosts = $helper->getServerConfigurationHosts(); |
|
61 | + $hosts = $helper->getServerConfigurationHosts(); |
|
62 | 62 | |
63 | - $wControls = new Template('user_ldap', 'part.wizardcontrols'); |
|
64 | - $wControls = $wControls->fetchPage(); |
|
65 | - $sControls = new Template('user_ldap', 'part.settingcontrols'); |
|
66 | - $sControls = $sControls->fetchPage(); |
|
63 | + $wControls = new Template('user_ldap', 'part.wizardcontrols'); |
|
64 | + $wControls = $wControls->fetchPage(); |
|
65 | + $sControls = new Template('user_ldap', 'part.settingcontrols'); |
|
66 | + $sControls = $sControls->fetchPage(); |
|
67 | 67 | |
68 | - $parameters['serverConfigurationPrefixes'] = $prefixes; |
|
69 | - $parameters['serverConfigurationHosts'] = $hosts; |
|
70 | - $parameters['settingControls'] = $sControls; |
|
71 | - $parameters['wizardControls'] = $wControls; |
|
68 | + $parameters['serverConfigurationPrefixes'] = $prefixes; |
|
69 | + $parameters['serverConfigurationHosts'] = $hosts; |
|
70 | + $parameters['settingControls'] = $sControls; |
|
71 | + $parameters['wizardControls'] = $wControls; |
|
72 | 72 | |
73 | - // assign default values |
|
74 | - if (!isset($config)) { |
|
75 | - $config = new Configuration('', false); |
|
76 | - } |
|
77 | - $defaults = $config->getDefaults(); |
|
78 | - foreach ($defaults as $key => $default) { |
|
79 | - $parameters[$key.'_default'] = $default; |
|
80 | - } |
|
73 | + // assign default values |
|
74 | + if (!isset($config)) { |
|
75 | + $config = new Configuration('', false); |
|
76 | + } |
|
77 | + $defaults = $config->getDefaults(); |
|
78 | + foreach ($defaults as $key => $default) { |
|
79 | + $parameters[$key.'_default'] = $default; |
|
80 | + } |
|
81 | 81 | |
82 | - return new TemplateResponse('user_ldap', 'settings', $parameters); |
|
83 | - } |
|
82 | + return new TemplateResponse('user_ldap', 'settings', $parameters); |
|
83 | + } |
|
84 | 84 | |
85 | - /** |
|
86 | - * @return string the section ID, e.g. 'sharing' |
|
87 | - */ |
|
88 | - public function getSection() { |
|
89 | - return 'ldap'; |
|
90 | - } |
|
85 | + /** |
|
86 | + * @return string the section ID, e.g. 'sharing' |
|
87 | + */ |
|
88 | + public function getSection() { |
|
89 | + return 'ldap'; |
|
90 | + } |
|
91 | 91 | |
92 | - /** |
|
93 | - * @return int whether the form should be rather on the top or bottom of |
|
94 | - * the admin section. The forms are arranged in ascending order of the |
|
95 | - * priority values. It is required to return a value between 0 and 100. |
|
96 | - * |
|
97 | - * E.g.: 70 |
|
98 | - */ |
|
99 | - public function getPriority() { |
|
100 | - return 5; |
|
101 | - } |
|
92 | + /** |
|
93 | + * @return int whether the form should be rather on the top or bottom of |
|
94 | + * the admin section. The forms are arranged in ascending order of the |
|
95 | + * priority values. It is required to return a value between 0 and 100. |
|
96 | + * |
|
97 | + * E.g.: 70 |
|
98 | + */ |
|
99 | + public function getPriority() { |
|
100 | + return 5; |
|
101 | + } |
|
102 | 102 | } |
@@ -75,615 +75,615 @@ |
||
75 | 75 | * @property string ldapMatchingRuleInChainState |
76 | 76 | */ |
77 | 77 | class Connection extends LDAPUtility { |
78 | - private $ldapConnectionRes = null; |
|
79 | - private $configPrefix; |
|
80 | - private $configID; |
|
81 | - private $configured = false; |
|
82 | - //whether connection should be kept on __destruct |
|
83 | - private $dontDestruct = false; |
|
84 | - |
|
85 | - /** |
|
86 | - * @var bool runtime flag that indicates whether supported primary groups are available |
|
87 | - */ |
|
88 | - public $hasPrimaryGroups = true; |
|
89 | - |
|
90 | - /** |
|
91 | - * @var bool runtime flag that indicates whether supported POSIX gidNumber are available |
|
92 | - */ |
|
93 | - public $hasGidNumber = true; |
|
94 | - |
|
95 | - //cache handler |
|
96 | - protected $cache; |
|
97 | - |
|
98 | - /** @var Configuration settings handler **/ |
|
99 | - protected $configuration; |
|
100 | - |
|
101 | - protected $doNotValidate = false; |
|
102 | - |
|
103 | - protected $ignoreValidation = false; |
|
104 | - |
|
105 | - protected $bindResult = []; |
|
106 | - |
|
107 | - /** |
|
108 | - * Constructor |
|
109 | - * @param ILDAPWrapper $ldap |
|
110 | - * @param string $configPrefix a string with the prefix for the configkey column (appconfig table) |
|
111 | - * @param string|null $configID a string with the value for the appid column (appconfig table) or null for on-the-fly connections |
|
112 | - */ |
|
113 | - public function __construct(ILDAPWrapper $ldap, $configPrefix = '', $configID = 'user_ldap') { |
|
114 | - parent::__construct($ldap); |
|
115 | - $this->configPrefix = $configPrefix; |
|
116 | - $this->configID = $configID; |
|
117 | - $this->configuration = new Configuration($configPrefix, |
|
118 | - !is_null($configID)); |
|
119 | - $memcache = \OC::$server->getMemCacheFactory(); |
|
120 | - if ($memcache->isAvailable()) { |
|
121 | - $this->cache = $memcache->createDistributed(); |
|
122 | - } |
|
123 | - $helper = new Helper(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection()); |
|
124 | - $this->doNotValidate = !in_array($this->configPrefix, |
|
125 | - $helper->getServerConfigurationPrefixes()); |
|
126 | - } |
|
127 | - |
|
128 | - public function __destruct() { |
|
129 | - if (!$this->dontDestruct && $this->ldap->isResource($this->ldapConnectionRes)) { |
|
130 | - @$this->ldap->unbind($this->ldapConnectionRes); |
|
131 | - $this->bindResult = []; |
|
132 | - } |
|
133 | - } |
|
134 | - |
|
135 | - /** |
|
136 | - * defines behaviour when the instance is cloned |
|
137 | - */ |
|
138 | - public function __clone() { |
|
139 | - $this->configuration = new Configuration($this->configPrefix, |
|
140 | - !is_null($this->configID)); |
|
141 | - if (count($this->bindResult) !== 0 && $this->bindResult['result'] === true) { |
|
142 | - $this->bindResult = []; |
|
143 | - } |
|
144 | - $this->ldapConnectionRes = null; |
|
145 | - $this->dontDestruct = true; |
|
146 | - } |
|
147 | - |
|
148 | - public function __get(string $name) { |
|
149 | - if (!$this->configured) { |
|
150 | - $this->readConfiguration(); |
|
151 | - } |
|
152 | - |
|
153 | - return $this->configuration->$name; |
|
154 | - } |
|
155 | - |
|
156 | - /** |
|
157 | - * @param string $name |
|
158 | - * @param mixed $value |
|
159 | - */ |
|
160 | - public function __set($name, $value) { |
|
161 | - $this->doNotValidate = false; |
|
162 | - $before = $this->configuration->$name; |
|
163 | - $this->configuration->$name = $value; |
|
164 | - $after = $this->configuration->$name; |
|
165 | - if ($before !== $after) { |
|
166 | - if ($this->configID !== '' && $this->configID !== null) { |
|
167 | - $this->configuration->saveConfiguration(); |
|
168 | - } |
|
169 | - $this->validateConfiguration(); |
|
170 | - } |
|
171 | - } |
|
172 | - |
|
173 | - /** |
|
174 | - * @param string $rule |
|
175 | - * @return array |
|
176 | - * @throws \RuntimeException |
|
177 | - */ |
|
178 | - public function resolveRule($rule) { |
|
179 | - return $this->configuration->resolveRule($rule); |
|
180 | - } |
|
181 | - |
|
182 | - /** |
|
183 | - * sets whether the result of the configuration validation shall |
|
184 | - * be ignored when establishing the connection. Used by the Wizard |
|
185 | - * in early configuration state. |
|
186 | - * @param bool $state |
|
187 | - */ |
|
188 | - public function setIgnoreValidation($state) { |
|
189 | - $this->ignoreValidation = (bool)$state; |
|
190 | - } |
|
191 | - |
|
192 | - /** |
|
193 | - * initializes the LDAP backend |
|
194 | - * @param bool $force read the config settings no matter what |
|
195 | - */ |
|
196 | - public function init($force = false) { |
|
197 | - $this->readConfiguration($force); |
|
198 | - $this->establishConnection(); |
|
199 | - } |
|
200 | - |
|
201 | - /** |
|
202 | - * Returns the LDAP handler |
|
203 | - */ |
|
204 | - public function getConnectionResource() { |
|
205 | - if (!$this->ldapConnectionRes) { |
|
206 | - $this->init(); |
|
207 | - } elseif (!$this->ldap->isResource($this->ldapConnectionRes)) { |
|
208 | - $this->ldapConnectionRes = null; |
|
209 | - $this->establishConnection(); |
|
210 | - } |
|
211 | - if (is_null($this->ldapConnectionRes)) { |
|
212 | - \OCP\Util::writeLog('user_ldap', 'No LDAP Connection to server ' . $this->configuration->ldapHost, ILogger::ERROR); |
|
213 | - throw new ServerNotAvailableException('Connection to LDAP server could not be established'); |
|
214 | - } |
|
215 | - return $this->ldapConnectionRes; |
|
216 | - } |
|
217 | - |
|
218 | - /** |
|
219 | - * resets the connection resource |
|
220 | - */ |
|
221 | - public function resetConnectionResource() { |
|
222 | - if (!is_null($this->ldapConnectionRes)) { |
|
223 | - @$this->ldap->unbind($this->ldapConnectionRes); |
|
224 | - $this->ldapConnectionRes = null; |
|
225 | - $this->bindResult = []; |
|
226 | - } |
|
227 | - } |
|
228 | - |
|
229 | - /** |
|
230 | - * @param string|null $key |
|
231 | - * @return string |
|
232 | - */ |
|
233 | - private function getCacheKey($key) { |
|
234 | - $prefix = 'LDAP-'.$this->configID.'-'.$this->configPrefix.'-'; |
|
235 | - if (is_null($key)) { |
|
236 | - return $prefix; |
|
237 | - } |
|
238 | - return $prefix.hash('sha256', $key); |
|
239 | - } |
|
240 | - |
|
241 | - /** |
|
242 | - * @param string $key |
|
243 | - * @return mixed|null |
|
244 | - */ |
|
245 | - public function getFromCache($key) { |
|
246 | - if (!$this->configured) { |
|
247 | - $this->readConfiguration(); |
|
248 | - } |
|
249 | - if (is_null($this->cache) || !$this->configuration->ldapCacheTTL) { |
|
250 | - return null; |
|
251 | - } |
|
252 | - $key = $this->getCacheKey($key); |
|
253 | - |
|
254 | - return json_decode(base64_decode($this->cache->get($key)), true); |
|
255 | - } |
|
256 | - |
|
257 | - /** |
|
258 | - * @param string $key |
|
259 | - * @param mixed $value |
|
260 | - * |
|
261 | - * @return string |
|
262 | - */ |
|
263 | - public function writeToCache($key, $value) { |
|
264 | - if (!$this->configured) { |
|
265 | - $this->readConfiguration(); |
|
266 | - } |
|
267 | - if (is_null($this->cache) |
|
268 | - || !$this->configuration->ldapCacheTTL |
|
269 | - || !$this->configuration->ldapConfigurationActive) { |
|
270 | - return null; |
|
271 | - } |
|
272 | - $key = $this->getCacheKey($key); |
|
273 | - $value = base64_encode(json_encode($value)); |
|
274 | - $this->cache->set($key, $value, $this->configuration->ldapCacheTTL); |
|
275 | - } |
|
276 | - |
|
277 | - public function clearCache() { |
|
278 | - if (!is_null($this->cache)) { |
|
279 | - $this->cache->clear($this->getCacheKey(null)); |
|
280 | - } |
|
281 | - } |
|
282 | - |
|
283 | - /** |
|
284 | - * Caches the general LDAP configuration. |
|
285 | - * @param bool $force optional. true, if the re-read should be forced. defaults |
|
286 | - * to false. |
|
287 | - * @return null |
|
288 | - */ |
|
289 | - private function readConfiguration($force = false) { |
|
290 | - if ((!$this->configured || $force) && !is_null($this->configID)) { |
|
291 | - $this->configuration->readConfiguration(); |
|
292 | - $this->configured = $this->validateConfiguration(); |
|
293 | - } |
|
294 | - } |
|
295 | - |
|
296 | - /** |
|
297 | - * set LDAP configuration with values delivered by an array, not read from configuration |
|
298 | - * @param array $config array that holds the config parameters in an associated array |
|
299 | - * @param array &$setParameters optional; array where the set fields will be given to |
|
300 | - * @return boolean true if config validates, false otherwise. Check with $setParameters for detailed success on single parameters |
|
301 | - */ |
|
302 | - public function setConfiguration($config, &$setParameters = null) { |
|
303 | - if (is_null($setParameters)) { |
|
304 | - $setParameters = []; |
|
305 | - } |
|
306 | - $this->doNotValidate = false; |
|
307 | - $this->configuration->setConfiguration($config, $setParameters); |
|
308 | - if (count($setParameters) > 0) { |
|
309 | - $this->configured = $this->validateConfiguration(); |
|
310 | - } |
|
311 | - |
|
312 | - |
|
313 | - return $this->configured; |
|
314 | - } |
|
315 | - |
|
316 | - /** |
|
317 | - * saves the current Configuration in the database and empties the |
|
318 | - * cache |
|
319 | - * @return null |
|
320 | - */ |
|
321 | - public function saveConfiguration() { |
|
322 | - $this->configuration->saveConfiguration(); |
|
323 | - $this->clearCache(); |
|
324 | - } |
|
325 | - |
|
326 | - /** |
|
327 | - * get the current LDAP configuration |
|
328 | - * @return array |
|
329 | - */ |
|
330 | - public function getConfiguration() { |
|
331 | - $this->readConfiguration(); |
|
332 | - $config = $this->configuration->getConfiguration(); |
|
333 | - $cta = $this->configuration->getConfigTranslationArray(); |
|
334 | - $result = []; |
|
335 | - foreach ($cta as $dbkey => $configkey) { |
|
336 | - switch ($configkey) { |
|
337 | - case 'homeFolderNamingRule': |
|
338 | - if (strpos($config[$configkey], 'attr:') === 0) { |
|
339 | - $result[$dbkey] = substr($config[$configkey], 5); |
|
340 | - } else { |
|
341 | - $result[$dbkey] = ''; |
|
342 | - } |
|
343 | - break; |
|
344 | - case 'ldapBase': |
|
345 | - case 'ldapBaseUsers': |
|
346 | - case 'ldapBaseGroups': |
|
347 | - case 'ldapAttributesForUserSearch': |
|
348 | - case 'ldapAttributesForGroupSearch': |
|
349 | - if (is_array($config[$configkey])) { |
|
350 | - $result[$dbkey] = implode("\n", $config[$configkey]); |
|
351 | - break; |
|
352 | - } //else follows default |
|
353 | - // no break |
|
354 | - default: |
|
355 | - $result[$dbkey] = $config[$configkey]; |
|
356 | - } |
|
357 | - } |
|
358 | - return $result; |
|
359 | - } |
|
360 | - |
|
361 | - private function doSoftValidation() { |
|
362 | - //if User or Group Base are not set, take over Base DN setting |
|
363 | - foreach (['ldapBaseUsers', 'ldapBaseGroups'] as $keyBase) { |
|
364 | - $val = $this->configuration->$keyBase; |
|
365 | - if (empty($val)) { |
|
366 | - $this->configuration->$keyBase = $this->configuration->ldapBase; |
|
367 | - } |
|
368 | - } |
|
369 | - |
|
370 | - foreach (['ldapExpertUUIDUserAttr' => 'ldapUuidUserAttribute', |
|
371 | - 'ldapExpertUUIDGroupAttr' => 'ldapUuidGroupAttribute'] |
|
372 | - as $expertSetting => $effectiveSetting) { |
|
373 | - $uuidOverride = $this->configuration->$expertSetting; |
|
374 | - if (!empty($uuidOverride)) { |
|
375 | - $this->configuration->$effectiveSetting = $uuidOverride; |
|
376 | - } else { |
|
377 | - $uuidAttributes = Access::UUID_ATTRIBUTES; |
|
378 | - array_unshift($uuidAttributes, 'auto'); |
|
379 | - if (!in_array($this->configuration->$effectiveSetting, |
|
380 | - $uuidAttributes) |
|
381 | - && (!is_null($this->configID))) { |
|
382 | - $this->configuration->$effectiveSetting = 'auto'; |
|
383 | - $this->configuration->saveConfiguration(); |
|
384 | - \OCP\Util::writeLog('user_ldap', |
|
385 | - 'Illegal value for the '. |
|
386 | - $effectiveSetting.', '.'reset to '. |
|
387 | - 'autodetect.', ILogger::INFO); |
|
388 | - } |
|
389 | - } |
|
390 | - } |
|
391 | - |
|
392 | - $backupPort = (int)$this->configuration->ldapBackupPort; |
|
393 | - if ($backupPort <= 0) { |
|
394 | - $this->configuration->backupPort = $this->configuration->ldapPort; |
|
395 | - } |
|
396 | - |
|
397 | - //make sure empty search attributes are saved as simple, empty array |
|
398 | - $saKeys = ['ldapAttributesForUserSearch', |
|
399 | - 'ldapAttributesForGroupSearch']; |
|
400 | - foreach ($saKeys as $key) { |
|
401 | - $val = $this->configuration->$key; |
|
402 | - if (is_array($val) && count($val) === 1 && empty($val[0])) { |
|
403 | - $this->configuration->$key = []; |
|
404 | - } |
|
405 | - } |
|
406 | - |
|
407 | - if ((stripos($this->configuration->ldapHost, 'ldaps://') === 0) |
|
408 | - && $this->configuration->ldapTLS) { |
|
409 | - $this->configuration->ldapTLS = false; |
|
410 | - \OCP\Util::writeLog( |
|
411 | - 'user_ldap', |
|
412 | - 'LDAPS (already using secure connection) and TLS do not work together. Switched off TLS.', |
|
413 | - ILogger::INFO |
|
414 | - ); |
|
415 | - } |
|
416 | - } |
|
417 | - |
|
418 | - /** |
|
419 | - * @return bool |
|
420 | - */ |
|
421 | - private function doCriticalValidation() { |
|
422 | - $configurationOK = true; |
|
423 | - $errorStr = 'Configuration Error (prefix '. |
|
424 | - (string)$this->configPrefix .'): '; |
|
425 | - |
|
426 | - //options that shall not be empty |
|
427 | - $options = ['ldapHost', 'ldapPort', 'ldapUserDisplayName', |
|
428 | - 'ldapGroupDisplayName', 'ldapLoginFilter']; |
|
429 | - foreach ($options as $key) { |
|
430 | - $val = $this->configuration->$key; |
|
431 | - if (empty($val)) { |
|
432 | - switch ($key) { |
|
433 | - case 'ldapHost': |
|
434 | - $subj = 'LDAP Host'; |
|
435 | - break; |
|
436 | - case 'ldapPort': |
|
437 | - $subj = 'LDAP Port'; |
|
438 | - break; |
|
439 | - case 'ldapUserDisplayName': |
|
440 | - $subj = 'LDAP User Display Name'; |
|
441 | - break; |
|
442 | - case 'ldapGroupDisplayName': |
|
443 | - $subj = 'LDAP Group Display Name'; |
|
444 | - break; |
|
445 | - case 'ldapLoginFilter': |
|
446 | - $subj = 'LDAP Login Filter'; |
|
447 | - break; |
|
448 | - default: |
|
449 | - $subj = $key; |
|
450 | - break; |
|
451 | - } |
|
452 | - $configurationOK = false; |
|
453 | - \OCP\Util::writeLog( |
|
454 | - 'user_ldap', |
|
455 | - $errorStr.'No '.$subj.' given!', |
|
456 | - ILogger::WARN |
|
457 | - ); |
|
458 | - } |
|
459 | - } |
|
460 | - |
|
461 | - //combinations |
|
462 | - $agent = $this->configuration->ldapAgentName; |
|
463 | - $pwd = $this->configuration->ldapAgentPassword; |
|
464 | - if ( |
|
465 | - ($agent === '' && $pwd !== '') |
|
466 | - || ($agent !== '' && $pwd === '') |
|
467 | - ) { |
|
468 | - \OCP\Util::writeLog( |
|
469 | - 'user_ldap', |
|
470 | - $errorStr.'either no password is given for the user ' . |
|
471 | - 'agent or a password is given, but not an LDAP agent.', |
|
472 | - ILogger::WARN); |
|
473 | - $configurationOK = false; |
|
474 | - } |
|
475 | - |
|
476 | - $base = $this->configuration->ldapBase; |
|
477 | - $baseUsers = $this->configuration->ldapBaseUsers; |
|
478 | - $baseGroups = $this->configuration->ldapBaseGroups; |
|
479 | - |
|
480 | - if (empty($base) && empty($baseUsers) && empty($baseGroups)) { |
|
481 | - \OCP\Util::writeLog( |
|
482 | - 'user_ldap', |
|
483 | - $errorStr.'Not a single Base DN given.', |
|
484 | - ILogger::WARN |
|
485 | - ); |
|
486 | - $configurationOK = false; |
|
487 | - } |
|
488 | - |
|
489 | - if (mb_strpos($this->configuration->ldapLoginFilter, '%uid', 0, 'UTF-8') |
|
490 | - === false) { |
|
491 | - \OCP\Util::writeLog( |
|
492 | - 'user_ldap', |
|
493 | - $errorStr.'login filter does not contain %uid place holder.', |
|
494 | - ILogger::WARN |
|
495 | - ); |
|
496 | - $configurationOK = false; |
|
497 | - } |
|
498 | - |
|
499 | - return $configurationOK; |
|
500 | - } |
|
501 | - |
|
502 | - /** |
|
503 | - * Validates the user specified configuration |
|
504 | - * @return bool true if configuration seems OK, false otherwise |
|
505 | - */ |
|
506 | - private function validateConfiguration() { |
|
507 | - if ($this->doNotValidate) { |
|
508 | - //don't do a validation if it is a new configuration with pure |
|
509 | - //default values. Will be allowed on changes via __set or |
|
510 | - //setConfiguration |
|
511 | - return false; |
|
512 | - } |
|
513 | - |
|
514 | - // first step: "soft" checks: settings that are not really |
|
515 | - // necessary, but advisable. If left empty, give an info message |
|
516 | - $this->doSoftValidation(); |
|
517 | - |
|
518 | - //second step: critical checks. If left empty or filled wrong, mark as |
|
519 | - //not configured and give a warning. |
|
520 | - return $this->doCriticalValidation(); |
|
521 | - } |
|
522 | - |
|
523 | - |
|
524 | - /** |
|
525 | - * Connects and Binds to LDAP |
|
526 | - * |
|
527 | - * @throws ServerNotAvailableException |
|
528 | - */ |
|
529 | - private function establishConnection() { |
|
530 | - if (!$this->configuration->ldapConfigurationActive) { |
|
531 | - return null; |
|
532 | - } |
|
533 | - static $phpLDAPinstalled = true; |
|
534 | - if (!$phpLDAPinstalled) { |
|
535 | - return false; |
|
536 | - } |
|
537 | - if (!$this->ignoreValidation && !$this->configured) { |
|
538 | - \OCP\Util::writeLog( |
|
539 | - 'user_ldap', |
|
540 | - 'Configuration is invalid, cannot connect', |
|
541 | - ILogger::WARN |
|
542 | - ); |
|
543 | - return false; |
|
544 | - } |
|
545 | - if (!$this->ldapConnectionRes) { |
|
546 | - if (!$this->ldap->areLDAPFunctionsAvailable()) { |
|
547 | - $phpLDAPinstalled = false; |
|
548 | - \OCP\Util::writeLog( |
|
549 | - 'user_ldap', |
|
550 | - 'function ldap_connect is not available. Make sure that the PHP ldap module is installed.', |
|
551 | - ILogger::ERROR |
|
552 | - ); |
|
553 | - |
|
554 | - return false; |
|
555 | - } |
|
556 | - if ($this->configuration->turnOffCertCheck) { |
|
557 | - if (putenv('LDAPTLS_REQCERT=never')) { |
|
558 | - \OCP\Util::writeLog('user_ldap', |
|
559 | - 'Turned off SSL certificate validation successfully.', |
|
560 | - ILogger::DEBUG); |
|
561 | - } else { |
|
562 | - \OCP\Util::writeLog( |
|
563 | - 'user_ldap', |
|
564 | - 'Could not turn off SSL certificate validation.', |
|
565 | - ILogger::WARN |
|
566 | - ); |
|
567 | - } |
|
568 | - } |
|
569 | - |
|
570 | - $isOverrideMainServer = ($this->configuration->ldapOverrideMainServer |
|
571 | - || $this->getFromCache('overrideMainServer')); |
|
572 | - $isBackupHost = (trim($this->configuration->ldapBackupHost) !== ""); |
|
573 | - $bindStatus = false; |
|
574 | - try { |
|
575 | - if (!$isOverrideMainServer) { |
|
576 | - $this->doConnect($this->configuration->ldapHost, |
|
577 | - $this->configuration->ldapPort); |
|
578 | - return $this->bind(); |
|
579 | - } |
|
580 | - } catch (ServerNotAvailableException $e) { |
|
581 | - if (!$isBackupHost) { |
|
582 | - throw $e; |
|
583 | - } |
|
584 | - } |
|
585 | - |
|
586 | - //if LDAP server is not reachable, try the Backup (Replica!) Server |
|
587 | - if ($isBackupHost || $isOverrideMainServer) { |
|
588 | - $this->doConnect($this->configuration->ldapBackupHost, |
|
589 | - $this->configuration->ldapBackupPort); |
|
590 | - $this->bindResult = []; |
|
591 | - $bindStatus = $this->bind(); |
|
592 | - $error = $this->ldap->isResource($this->ldapConnectionRes) ? |
|
593 | - $this->ldap->errno($this->ldapConnectionRes) : -1; |
|
594 | - if ($bindStatus && $error === 0 && !$this->getFromCache('overrideMainServer')) { |
|
595 | - //when bind to backup server succeeded and failed to main server, |
|
596 | - //skip contacting him until next cache refresh |
|
597 | - $this->writeToCache('overrideMainServer', true); |
|
598 | - } |
|
599 | - } |
|
600 | - |
|
601 | - return $bindStatus; |
|
602 | - } |
|
603 | - return null; |
|
604 | - } |
|
605 | - |
|
606 | - /** |
|
607 | - * @param string $host |
|
608 | - * @param string $port |
|
609 | - * @return bool |
|
610 | - * @throws \OC\ServerNotAvailableException |
|
611 | - */ |
|
612 | - private function doConnect($host, $port) { |
|
613 | - if ($host === '') { |
|
614 | - return false; |
|
615 | - } |
|
616 | - |
|
617 | - $this->ldapConnectionRes = $this->ldap->connect($host, $port); |
|
618 | - |
|
619 | - if (!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_PROTOCOL_VERSION, 3)) { |
|
620 | - throw new ServerNotAvailableException('Could not set required LDAP Protocol version.'); |
|
621 | - } |
|
622 | - |
|
623 | - if (!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_REFERRALS, 0)) { |
|
624 | - throw new ServerNotAvailableException('Could not disable LDAP referrals.'); |
|
625 | - } |
|
626 | - |
|
627 | - if ($this->configuration->ldapTLS) { |
|
628 | - if (!$this->ldap->startTls($this->ldapConnectionRes)) { |
|
629 | - throw new ServerNotAvailableException('Start TLS failed, when connecting to LDAP host ' . $host . '.'); |
|
630 | - } |
|
631 | - } |
|
632 | - |
|
633 | - return true; |
|
634 | - } |
|
635 | - |
|
636 | - /** |
|
637 | - * Binds to LDAP |
|
638 | - */ |
|
639 | - public function bind() { |
|
640 | - if (!$this->configuration->ldapConfigurationActive) { |
|
641 | - return false; |
|
642 | - } |
|
643 | - $cr = $this->ldapConnectionRes; |
|
644 | - if (!$this->ldap->isResource($cr)) { |
|
645 | - $cr = $this->getConnectionResource(); |
|
646 | - } |
|
647 | - |
|
648 | - if ( |
|
649 | - count($this->bindResult) !== 0 |
|
650 | - && $this->bindResult['dn'] === $this->configuration->ldapAgentName |
|
651 | - && \OC::$server->getHasher()->verify( |
|
652 | - $this->configPrefix . $this->configuration->ldapAgentPassword, |
|
653 | - $this->bindResult['hash'] |
|
654 | - ) |
|
655 | - ) { |
|
656 | - // don't attempt to bind again with the same data as before |
|
657 | - // bind might have been invoked via getConnectionResource(), |
|
658 | - // but we need results specifically for e.g. user login |
|
659 | - return $this->bindResult['result']; |
|
660 | - } |
|
661 | - |
|
662 | - $ldapLogin = @$this->ldap->bind($cr, |
|
663 | - $this->configuration->ldapAgentName, |
|
664 | - $this->configuration->ldapAgentPassword); |
|
665 | - |
|
666 | - $this->bindResult = [ |
|
667 | - 'dn' => $this->configuration->ldapAgentName, |
|
668 | - 'hash' => \OC::$server->getHasher()->hash($this->configPrefix . $this->configuration->ldapAgentPassword), |
|
669 | - 'result' => $ldapLogin, |
|
670 | - ]; |
|
671 | - |
|
672 | - if (!$ldapLogin) { |
|
673 | - $errno = $this->ldap->errno($cr); |
|
674 | - |
|
675 | - \OCP\Util::writeLog('user_ldap', |
|
676 | - 'Bind failed: ' . $errno . ': ' . $this->ldap->error($cr), |
|
677 | - ILogger::WARN); |
|
678 | - |
|
679 | - // Set to failure mode, if LDAP error code is not LDAP_SUCCESS or LDAP_INVALID_CREDENTIALS |
|
680 | - // or (needed for Apple Open Directory:) LDAP_INSUFFICIENT_ACCESS |
|
681 | - if ($errno !== 0 && $errno !== 49 && $errno !== 50) { |
|
682 | - $this->ldapConnectionRes = null; |
|
683 | - } |
|
684 | - |
|
685 | - return false; |
|
686 | - } |
|
687 | - return true; |
|
688 | - } |
|
78 | + private $ldapConnectionRes = null; |
|
79 | + private $configPrefix; |
|
80 | + private $configID; |
|
81 | + private $configured = false; |
|
82 | + //whether connection should be kept on __destruct |
|
83 | + private $dontDestruct = false; |
|
84 | + |
|
85 | + /** |
|
86 | + * @var bool runtime flag that indicates whether supported primary groups are available |
|
87 | + */ |
|
88 | + public $hasPrimaryGroups = true; |
|
89 | + |
|
90 | + /** |
|
91 | + * @var bool runtime flag that indicates whether supported POSIX gidNumber are available |
|
92 | + */ |
|
93 | + public $hasGidNumber = true; |
|
94 | + |
|
95 | + //cache handler |
|
96 | + protected $cache; |
|
97 | + |
|
98 | + /** @var Configuration settings handler **/ |
|
99 | + protected $configuration; |
|
100 | + |
|
101 | + protected $doNotValidate = false; |
|
102 | + |
|
103 | + protected $ignoreValidation = false; |
|
104 | + |
|
105 | + protected $bindResult = []; |
|
106 | + |
|
107 | + /** |
|
108 | + * Constructor |
|
109 | + * @param ILDAPWrapper $ldap |
|
110 | + * @param string $configPrefix a string with the prefix for the configkey column (appconfig table) |
|
111 | + * @param string|null $configID a string with the value for the appid column (appconfig table) or null for on-the-fly connections |
|
112 | + */ |
|
113 | + public function __construct(ILDAPWrapper $ldap, $configPrefix = '', $configID = 'user_ldap') { |
|
114 | + parent::__construct($ldap); |
|
115 | + $this->configPrefix = $configPrefix; |
|
116 | + $this->configID = $configID; |
|
117 | + $this->configuration = new Configuration($configPrefix, |
|
118 | + !is_null($configID)); |
|
119 | + $memcache = \OC::$server->getMemCacheFactory(); |
|
120 | + if ($memcache->isAvailable()) { |
|
121 | + $this->cache = $memcache->createDistributed(); |
|
122 | + } |
|
123 | + $helper = new Helper(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection()); |
|
124 | + $this->doNotValidate = !in_array($this->configPrefix, |
|
125 | + $helper->getServerConfigurationPrefixes()); |
|
126 | + } |
|
127 | + |
|
128 | + public function __destruct() { |
|
129 | + if (!$this->dontDestruct && $this->ldap->isResource($this->ldapConnectionRes)) { |
|
130 | + @$this->ldap->unbind($this->ldapConnectionRes); |
|
131 | + $this->bindResult = []; |
|
132 | + } |
|
133 | + } |
|
134 | + |
|
135 | + /** |
|
136 | + * defines behaviour when the instance is cloned |
|
137 | + */ |
|
138 | + public function __clone() { |
|
139 | + $this->configuration = new Configuration($this->configPrefix, |
|
140 | + !is_null($this->configID)); |
|
141 | + if (count($this->bindResult) !== 0 && $this->bindResult['result'] === true) { |
|
142 | + $this->bindResult = []; |
|
143 | + } |
|
144 | + $this->ldapConnectionRes = null; |
|
145 | + $this->dontDestruct = true; |
|
146 | + } |
|
147 | + |
|
148 | + public function __get(string $name) { |
|
149 | + if (!$this->configured) { |
|
150 | + $this->readConfiguration(); |
|
151 | + } |
|
152 | + |
|
153 | + return $this->configuration->$name; |
|
154 | + } |
|
155 | + |
|
156 | + /** |
|
157 | + * @param string $name |
|
158 | + * @param mixed $value |
|
159 | + */ |
|
160 | + public function __set($name, $value) { |
|
161 | + $this->doNotValidate = false; |
|
162 | + $before = $this->configuration->$name; |
|
163 | + $this->configuration->$name = $value; |
|
164 | + $after = $this->configuration->$name; |
|
165 | + if ($before !== $after) { |
|
166 | + if ($this->configID !== '' && $this->configID !== null) { |
|
167 | + $this->configuration->saveConfiguration(); |
|
168 | + } |
|
169 | + $this->validateConfiguration(); |
|
170 | + } |
|
171 | + } |
|
172 | + |
|
173 | + /** |
|
174 | + * @param string $rule |
|
175 | + * @return array |
|
176 | + * @throws \RuntimeException |
|
177 | + */ |
|
178 | + public function resolveRule($rule) { |
|
179 | + return $this->configuration->resolveRule($rule); |
|
180 | + } |
|
181 | + |
|
182 | + /** |
|
183 | + * sets whether the result of the configuration validation shall |
|
184 | + * be ignored when establishing the connection. Used by the Wizard |
|
185 | + * in early configuration state. |
|
186 | + * @param bool $state |
|
187 | + */ |
|
188 | + public function setIgnoreValidation($state) { |
|
189 | + $this->ignoreValidation = (bool)$state; |
|
190 | + } |
|
191 | + |
|
192 | + /** |
|
193 | + * initializes the LDAP backend |
|
194 | + * @param bool $force read the config settings no matter what |
|
195 | + */ |
|
196 | + public function init($force = false) { |
|
197 | + $this->readConfiguration($force); |
|
198 | + $this->establishConnection(); |
|
199 | + } |
|
200 | + |
|
201 | + /** |
|
202 | + * Returns the LDAP handler |
|
203 | + */ |
|
204 | + public function getConnectionResource() { |
|
205 | + if (!$this->ldapConnectionRes) { |
|
206 | + $this->init(); |
|
207 | + } elseif (!$this->ldap->isResource($this->ldapConnectionRes)) { |
|
208 | + $this->ldapConnectionRes = null; |
|
209 | + $this->establishConnection(); |
|
210 | + } |
|
211 | + if (is_null($this->ldapConnectionRes)) { |
|
212 | + \OCP\Util::writeLog('user_ldap', 'No LDAP Connection to server ' . $this->configuration->ldapHost, ILogger::ERROR); |
|
213 | + throw new ServerNotAvailableException('Connection to LDAP server could not be established'); |
|
214 | + } |
|
215 | + return $this->ldapConnectionRes; |
|
216 | + } |
|
217 | + |
|
218 | + /** |
|
219 | + * resets the connection resource |
|
220 | + */ |
|
221 | + public function resetConnectionResource() { |
|
222 | + if (!is_null($this->ldapConnectionRes)) { |
|
223 | + @$this->ldap->unbind($this->ldapConnectionRes); |
|
224 | + $this->ldapConnectionRes = null; |
|
225 | + $this->bindResult = []; |
|
226 | + } |
|
227 | + } |
|
228 | + |
|
229 | + /** |
|
230 | + * @param string|null $key |
|
231 | + * @return string |
|
232 | + */ |
|
233 | + private function getCacheKey($key) { |
|
234 | + $prefix = 'LDAP-'.$this->configID.'-'.$this->configPrefix.'-'; |
|
235 | + if (is_null($key)) { |
|
236 | + return $prefix; |
|
237 | + } |
|
238 | + return $prefix.hash('sha256', $key); |
|
239 | + } |
|
240 | + |
|
241 | + /** |
|
242 | + * @param string $key |
|
243 | + * @return mixed|null |
|
244 | + */ |
|
245 | + public function getFromCache($key) { |
|
246 | + if (!$this->configured) { |
|
247 | + $this->readConfiguration(); |
|
248 | + } |
|
249 | + if (is_null($this->cache) || !$this->configuration->ldapCacheTTL) { |
|
250 | + return null; |
|
251 | + } |
|
252 | + $key = $this->getCacheKey($key); |
|
253 | + |
|
254 | + return json_decode(base64_decode($this->cache->get($key)), true); |
|
255 | + } |
|
256 | + |
|
257 | + /** |
|
258 | + * @param string $key |
|
259 | + * @param mixed $value |
|
260 | + * |
|
261 | + * @return string |
|
262 | + */ |
|
263 | + public function writeToCache($key, $value) { |
|
264 | + if (!$this->configured) { |
|
265 | + $this->readConfiguration(); |
|
266 | + } |
|
267 | + if (is_null($this->cache) |
|
268 | + || !$this->configuration->ldapCacheTTL |
|
269 | + || !$this->configuration->ldapConfigurationActive) { |
|
270 | + return null; |
|
271 | + } |
|
272 | + $key = $this->getCacheKey($key); |
|
273 | + $value = base64_encode(json_encode($value)); |
|
274 | + $this->cache->set($key, $value, $this->configuration->ldapCacheTTL); |
|
275 | + } |
|
276 | + |
|
277 | + public function clearCache() { |
|
278 | + if (!is_null($this->cache)) { |
|
279 | + $this->cache->clear($this->getCacheKey(null)); |
|
280 | + } |
|
281 | + } |
|
282 | + |
|
283 | + /** |
|
284 | + * Caches the general LDAP configuration. |
|
285 | + * @param bool $force optional. true, if the re-read should be forced. defaults |
|
286 | + * to false. |
|
287 | + * @return null |
|
288 | + */ |
|
289 | + private function readConfiguration($force = false) { |
|
290 | + if ((!$this->configured || $force) && !is_null($this->configID)) { |
|
291 | + $this->configuration->readConfiguration(); |
|
292 | + $this->configured = $this->validateConfiguration(); |
|
293 | + } |
|
294 | + } |
|
295 | + |
|
296 | + /** |
|
297 | + * set LDAP configuration with values delivered by an array, not read from configuration |
|
298 | + * @param array $config array that holds the config parameters in an associated array |
|
299 | + * @param array &$setParameters optional; array where the set fields will be given to |
|
300 | + * @return boolean true if config validates, false otherwise. Check with $setParameters for detailed success on single parameters |
|
301 | + */ |
|
302 | + public function setConfiguration($config, &$setParameters = null) { |
|
303 | + if (is_null($setParameters)) { |
|
304 | + $setParameters = []; |
|
305 | + } |
|
306 | + $this->doNotValidate = false; |
|
307 | + $this->configuration->setConfiguration($config, $setParameters); |
|
308 | + if (count($setParameters) > 0) { |
|
309 | + $this->configured = $this->validateConfiguration(); |
|
310 | + } |
|
311 | + |
|
312 | + |
|
313 | + return $this->configured; |
|
314 | + } |
|
315 | + |
|
316 | + /** |
|
317 | + * saves the current Configuration in the database and empties the |
|
318 | + * cache |
|
319 | + * @return null |
|
320 | + */ |
|
321 | + public function saveConfiguration() { |
|
322 | + $this->configuration->saveConfiguration(); |
|
323 | + $this->clearCache(); |
|
324 | + } |
|
325 | + |
|
326 | + /** |
|
327 | + * get the current LDAP configuration |
|
328 | + * @return array |
|
329 | + */ |
|
330 | + public function getConfiguration() { |
|
331 | + $this->readConfiguration(); |
|
332 | + $config = $this->configuration->getConfiguration(); |
|
333 | + $cta = $this->configuration->getConfigTranslationArray(); |
|
334 | + $result = []; |
|
335 | + foreach ($cta as $dbkey => $configkey) { |
|
336 | + switch ($configkey) { |
|
337 | + case 'homeFolderNamingRule': |
|
338 | + if (strpos($config[$configkey], 'attr:') === 0) { |
|
339 | + $result[$dbkey] = substr($config[$configkey], 5); |
|
340 | + } else { |
|
341 | + $result[$dbkey] = ''; |
|
342 | + } |
|
343 | + break; |
|
344 | + case 'ldapBase': |
|
345 | + case 'ldapBaseUsers': |
|
346 | + case 'ldapBaseGroups': |
|
347 | + case 'ldapAttributesForUserSearch': |
|
348 | + case 'ldapAttributesForGroupSearch': |
|
349 | + if (is_array($config[$configkey])) { |
|
350 | + $result[$dbkey] = implode("\n", $config[$configkey]); |
|
351 | + break; |
|
352 | + } //else follows default |
|
353 | + // no break |
|
354 | + default: |
|
355 | + $result[$dbkey] = $config[$configkey]; |
|
356 | + } |
|
357 | + } |
|
358 | + return $result; |
|
359 | + } |
|
360 | + |
|
361 | + private function doSoftValidation() { |
|
362 | + //if User or Group Base are not set, take over Base DN setting |
|
363 | + foreach (['ldapBaseUsers', 'ldapBaseGroups'] as $keyBase) { |
|
364 | + $val = $this->configuration->$keyBase; |
|
365 | + if (empty($val)) { |
|
366 | + $this->configuration->$keyBase = $this->configuration->ldapBase; |
|
367 | + } |
|
368 | + } |
|
369 | + |
|
370 | + foreach (['ldapExpertUUIDUserAttr' => 'ldapUuidUserAttribute', |
|
371 | + 'ldapExpertUUIDGroupAttr' => 'ldapUuidGroupAttribute'] |
|
372 | + as $expertSetting => $effectiveSetting) { |
|
373 | + $uuidOverride = $this->configuration->$expertSetting; |
|
374 | + if (!empty($uuidOverride)) { |
|
375 | + $this->configuration->$effectiveSetting = $uuidOverride; |
|
376 | + } else { |
|
377 | + $uuidAttributes = Access::UUID_ATTRIBUTES; |
|
378 | + array_unshift($uuidAttributes, 'auto'); |
|
379 | + if (!in_array($this->configuration->$effectiveSetting, |
|
380 | + $uuidAttributes) |
|
381 | + && (!is_null($this->configID))) { |
|
382 | + $this->configuration->$effectiveSetting = 'auto'; |
|
383 | + $this->configuration->saveConfiguration(); |
|
384 | + \OCP\Util::writeLog('user_ldap', |
|
385 | + 'Illegal value for the '. |
|
386 | + $effectiveSetting.', '.'reset to '. |
|
387 | + 'autodetect.', ILogger::INFO); |
|
388 | + } |
|
389 | + } |
|
390 | + } |
|
391 | + |
|
392 | + $backupPort = (int)$this->configuration->ldapBackupPort; |
|
393 | + if ($backupPort <= 0) { |
|
394 | + $this->configuration->backupPort = $this->configuration->ldapPort; |
|
395 | + } |
|
396 | + |
|
397 | + //make sure empty search attributes are saved as simple, empty array |
|
398 | + $saKeys = ['ldapAttributesForUserSearch', |
|
399 | + 'ldapAttributesForGroupSearch']; |
|
400 | + foreach ($saKeys as $key) { |
|
401 | + $val = $this->configuration->$key; |
|
402 | + if (is_array($val) && count($val) === 1 && empty($val[0])) { |
|
403 | + $this->configuration->$key = []; |
|
404 | + } |
|
405 | + } |
|
406 | + |
|
407 | + if ((stripos($this->configuration->ldapHost, 'ldaps://') === 0) |
|
408 | + && $this->configuration->ldapTLS) { |
|
409 | + $this->configuration->ldapTLS = false; |
|
410 | + \OCP\Util::writeLog( |
|
411 | + 'user_ldap', |
|
412 | + 'LDAPS (already using secure connection) and TLS do not work together. Switched off TLS.', |
|
413 | + ILogger::INFO |
|
414 | + ); |
|
415 | + } |
|
416 | + } |
|
417 | + |
|
418 | + /** |
|
419 | + * @return bool |
|
420 | + */ |
|
421 | + private function doCriticalValidation() { |
|
422 | + $configurationOK = true; |
|
423 | + $errorStr = 'Configuration Error (prefix '. |
|
424 | + (string)$this->configPrefix .'): '; |
|
425 | + |
|
426 | + //options that shall not be empty |
|
427 | + $options = ['ldapHost', 'ldapPort', 'ldapUserDisplayName', |
|
428 | + 'ldapGroupDisplayName', 'ldapLoginFilter']; |
|
429 | + foreach ($options as $key) { |
|
430 | + $val = $this->configuration->$key; |
|
431 | + if (empty($val)) { |
|
432 | + switch ($key) { |
|
433 | + case 'ldapHost': |
|
434 | + $subj = 'LDAP Host'; |
|
435 | + break; |
|
436 | + case 'ldapPort': |
|
437 | + $subj = 'LDAP Port'; |
|
438 | + break; |
|
439 | + case 'ldapUserDisplayName': |
|
440 | + $subj = 'LDAP User Display Name'; |
|
441 | + break; |
|
442 | + case 'ldapGroupDisplayName': |
|
443 | + $subj = 'LDAP Group Display Name'; |
|
444 | + break; |
|
445 | + case 'ldapLoginFilter': |
|
446 | + $subj = 'LDAP Login Filter'; |
|
447 | + break; |
|
448 | + default: |
|
449 | + $subj = $key; |
|
450 | + break; |
|
451 | + } |
|
452 | + $configurationOK = false; |
|
453 | + \OCP\Util::writeLog( |
|
454 | + 'user_ldap', |
|
455 | + $errorStr.'No '.$subj.' given!', |
|
456 | + ILogger::WARN |
|
457 | + ); |
|
458 | + } |
|
459 | + } |
|
460 | + |
|
461 | + //combinations |
|
462 | + $agent = $this->configuration->ldapAgentName; |
|
463 | + $pwd = $this->configuration->ldapAgentPassword; |
|
464 | + if ( |
|
465 | + ($agent === '' && $pwd !== '') |
|
466 | + || ($agent !== '' && $pwd === '') |
|
467 | + ) { |
|
468 | + \OCP\Util::writeLog( |
|
469 | + 'user_ldap', |
|
470 | + $errorStr.'either no password is given for the user ' . |
|
471 | + 'agent or a password is given, but not an LDAP agent.', |
|
472 | + ILogger::WARN); |
|
473 | + $configurationOK = false; |
|
474 | + } |
|
475 | + |
|
476 | + $base = $this->configuration->ldapBase; |
|
477 | + $baseUsers = $this->configuration->ldapBaseUsers; |
|
478 | + $baseGroups = $this->configuration->ldapBaseGroups; |
|
479 | + |
|
480 | + if (empty($base) && empty($baseUsers) && empty($baseGroups)) { |
|
481 | + \OCP\Util::writeLog( |
|
482 | + 'user_ldap', |
|
483 | + $errorStr.'Not a single Base DN given.', |
|
484 | + ILogger::WARN |
|
485 | + ); |
|
486 | + $configurationOK = false; |
|
487 | + } |
|
488 | + |
|
489 | + if (mb_strpos($this->configuration->ldapLoginFilter, '%uid', 0, 'UTF-8') |
|
490 | + === false) { |
|
491 | + \OCP\Util::writeLog( |
|
492 | + 'user_ldap', |
|
493 | + $errorStr.'login filter does not contain %uid place holder.', |
|
494 | + ILogger::WARN |
|
495 | + ); |
|
496 | + $configurationOK = false; |
|
497 | + } |
|
498 | + |
|
499 | + return $configurationOK; |
|
500 | + } |
|
501 | + |
|
502 | + /** |
|
503 | + * Validates the user specified configuration |
|
504 | + * @return bool true if configuration seems OK, false otherwise |
|
505 | + */ |
|
506 | + private function validateConfiguration() { |
|
507 | + if ($this->doNotValidate) { |
|
508 | + //don't do a validation if it is a new configuration with pure |
|
509 | + //default values. Will be allowed on changes via __set or |
|
510 | + //setConfiguration |
|
511 | + return false; |
|
512 | + } |
|
513 | + |
|
514 | + // first step: "soft" checks: settings that are not really |
|
515 | + // necessary, but advisable. If left empty, give an info message |
|
516 | + $this->doSoftValidation(); |
|
517 | + |
|
518 | + //second step: critical checks. If left empty or filled wrong, mark as |
|
519 | + //not configured and give a warning. |
|
520 | + return $this->doCriticalValidation(); |
|
521 | + } |
|
522 | + |
|
523 | + |
|
524 | + /** |
|
525 | + * Connects and Binds to LDAP |
|
526 | + * |
|
527 | + * @throws ServerNotAvailableException |
|
528 | + */ |
|
529 | + private function establishConnection() { |
|
530 | + if (!$this->configuration->ldapConfigurationActive) { |
|
531 | + return null; |
|
532 | + } |
|
533 | + static $phpLDAPinstalled = true; |
|
534 | + if (!$phpLDAPinstalled) { |
|
535 | + return false; |
|
536 | + } |
|
537 | + if (!$this->ignoreValidation && !$this->configured) { |
|
538 | + \OCP\Util::writeLog( |
|
539 | + 'user_ldap', |
|
540 | + 'Configuration is invalid, cannot connect', |
|
541 | + ILogger::WARN |
|
542 | + ); |
|
543 | + return false; |
|
544 | + } |
|
545 | + if (!$this->ldapConnectionRes) { |
|
546 | + if (!$this->ldap->areLDAPFunctionsAvailable()) { |
|
547 | + $phpLDAPinstalled = false; |
|
548 | + \OCP\Util::writeLog( |
|
549 | + 'user_ldap', |
|
550 | + 'function ldap_connect is not available. Make sure that the PHP ldap module is installed.', |
|
551 | + ILogger::ERROR |
|
552 | + ); |
|
553 | + |
|
554 | + return false; |
|
555 | + } |
|
556 | + if ($this->configuration->turnOffCertCheck) { |
|
557 | + if (putenv('LDAPTLS_REQCERT=never')) { |
|
558 | + \OCP\Util::writeLog('user_ldap', |
|
559 | + 'Turned off SSL certificate validation successfully.', |
|
560 | + ILogger::DEBUG); |
|
561 | + } else { |
|
562 | + \OCP\Util::writeLog( |
|
563 | + 'user_ldap', |
|
564 | + 'Could not turn off SSL certificate validation.', |
|
565 | + ILogger::WARN |
|
566 | + ); |
|
567 | + } |
|
568 | + } |
|
569 | + |
|
570 | + $isOverrideMainServer = ($this->configuration->ldapOverrideMainServer |
|
571 | + || $this->getFromCache('overrideMainServer')); |
|
572 | + $isBackupHost = (trim($this->configuration->ldapBackupHost) !== ""); |
|
573 | + $bindStatus = false; |
|
574 | + try { |
|
575 | + if (!$isOverrideMainServer) { |
|
576 | + $this->doConnect($this->configuration->ldapHost, |
|
577 | + $this->configuration->ldapPort); |
|
578 | + return $this->bind(); |
|
579 | + } |
|
580 | + } catch (ServerNotAvailableException $e) { |
|
581 | + if (!$isBackupHost) { |
|
582 | + throw $e; |
|
583 | + } |
|
584 | + } |
|
585 | + |
|
586 | + //if LDAP server is not reachable, try the Backup (Replica!) Server |
|
587 | + if ($isBackupHost || $isOverrideMainServer) { |
|
588 | + $this->doConnect($this->configuration->ldapBackupHost, |
|
589 | + $this->configuration->ldapBackupPort); |
|
590 | + $this->bindResult = []; |
|
591 | + $bindStatus = $this->bind(); |
|
592 | + $error = $this->ldap->isResource($this->ldapConnectionRes) ? |
|
593 | + $this->ldap->errno($this->ldapConnectionRes) : -1; |
|
594 | + if ($bindStatus && $error === 0 && !$this->getFromCache('overrideMainServer')) { |
|
595 | + //when bind to backup server succeeded and failed to main server, |
|
596 | + //skip contacting him until next cache refresh |
|
597 | + $this->writeToCache('overrideMainServer', true); |
|
598 | + } |
|
599 | + } |
|
600 | + |
|
601 | + return $bindStatus; |
|
602 | + } |
|
603 | + return null; |
|
604 | + } |
|
605 | + |
|
606 | + /** |
|
607 | + * @param string $host |
|
608 | + * @param string $port |
|
609 | + * @return bool |
|
610 | + * @throws \OC\ServerNotAvailableException |
|
611 | + */ |
|
612 | + private function doConnect($host, $port) { |
|
613 | + if ($host === '') { |
|
614 | + return false; |
|
615 | + } |
|
616 | + |
|
617 | + $this->ldapConnectionRes = $this->ldap->connect($host, $port); |
|
618 | + |
|
619 | + if (!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_PROTOCOL_VERSION, 3)) { |
|
620 | + throw new ServerNotAvailableException('Could not set required LDAP Protocol version.'); |
|
621 | + } |
|
622 | + |
|
623 | + if (!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_REFERRALS, 0)) { |
|
624 | + throw new ServerNotAvailableException('Could not disable LDAP referrals.'); |
|
625 | + } |
|
626 | + |
|
627 | + if ($this->configuration->ldapTLS) { |
|
628 | + if (!$this->ldap->startTls($this->ldapConnectionRes)) { |
|
629 | + throw new ServerNotAvailableException('Start TLS failed, when connecting to LDAP host ' . $host . '.'); |
|
630 | + } |
|
631 | + } |
|
632 | + |
|
633 | + return true; |
|
634 | + } |
|
635 | + |
|
636 | + /** |
|
637 | + * Binds to LDAP |
|
638 | + */ |
|
639 | + public function bind() { |
|
640 | + if (!$this->configuration->ldapConfigurationActive) { |
|
641 | + return false; |
|
642 | + } |
|
643 | + $cr = $this->ldapConnectionRes; |
|
644 | + if (!$this->ldap->isResource($cr)) { |
|
645 | + $cr = $this->getConnectionResource(); |
|
646 | + } |
|
647 | + |
|
648 | + if ( |
|
649 | + count($this->bindResult) !== 0 |
|
650 | + && $this->bindResult['dn'] === $this->configuration->ldapAgentName |
|
651 | + && \OC::$server->getHasher()->verify( |
|
652 | + $this->configPrefix . $this->configuration->ldapAgentPassword, |
|
653 | + $this->bindResult['hash'] |
|
654 | + ) |
|
655 | + ) { |
|
656 | + // don't attempt to bind again with the same data as before |
|
657 | + // bind might have been invoked via getConnectionResource(), |
|
658 | + // but we need results specifically for e.g. user login |
|
659 | + return $this->bindResult['result']; |
|
660 | + } |
|
661 | + |
|
662 | + $ldapLogin = @$this->ldap->bind($cr, |
|
663 | + $this->configuration->ldapAgentName, |
|
664 | + $this->configuration->ldapAgentPassword); |
|
665 | + |
|
666 | + $this->bindResult = [ |
|
667 | + 'dn' => $this->configuration->ldapAgentName, |
|
668 | + 'hash' => \OC::$server->getHasher()->hash($this->configPrefix . $this->configuration->ldapAgentPassword), |
|
669 | + 'result' => $ldapLogin, |
|
670 | + ]; |
|
671 | + |
|
672 | + if (!$ldapLogin) { |
|
673 | + $errno = $this->ldap->errno($cr); |
|
674 | + |
|
675 | + \OCP\Util::writeLog('user_ldap', |
|
676 | + 'Bind failed: ' . $errno . ': ' . $this->ldap->error($cr), |
|
677 | + ILogger::WARN); |
|
678 | + |
|
679 | + // Set to failure mode, if LDAP error code is not LDAP_SUCCESS or LDAP_INVALID_CREDENTIALS |
|
680 | + // or (needed for Apple Open Directory:) LDAP_INSUFFICIENT_ACCESS |
|
681 | + if ($errno !== 0 && $errno !== 49 && $errno !== 50) { |
|
682 | + $this->ldapConnectionRes = null; |
|
683 | + } |
|
684 | + |
|
685 | + return false; |
|
686 | + } |
|
687 | + return true; |
|
688 | + } |
|
689 | 689 | } |
@@ -46,200 +46,200 @@ |
||
46 | 46 | use Psr\Log\LoggerInterface; |
47 | 47 | |
48 | 48 | class UpdateGroups extends TimedJob { |
49 | - private $groupsFromDB; |
|
50 | - |
|
51 | - /** @var Group_Proxy */ |
|
52 | - private $groupBackend; |
|
53 | - /** @var IEventDispatcher */ |
|
54 | - private $dispatcher; |
|
55 | - /** @var IGroupManager */ |
|
56 | - private $groupManager; |
|
57 | - /** @var IUserManager */ |
|
58 | - private $userManager; |
|
59 | - /** @var LoggerInterface */ |
|
60 | - private $logger; |
|
61 | - /** @var IDBConnection */ |
|
62 | - private $dbc; |
|
63 | - |
|
64 | - public function __construct( |
|
65 | - Group_Proxy $groupBackend, |
|
66 | - IEventDispatcher $dispatcher, |
|
67 | - IGroupManager $groupManager, |
|
68 | - IUserManager $userManager, |
|
69 | - LoggerInterface $logger, |
|
70 | - IDBConnection $dbc |
|
71 | - ) { |
|
72 | - $this->interval = $this->getRefreshInterval(); |
|
73 | - $this->groupBackend = $groupBackend; |
|
74 | - $this->dispatcher = $dispatcher; |
|
75 | - $this->groupManager = $groupManager; |
|
76 | - $this->userManager = $userManager; |
|
77 | - $this->logger = $logger; |
|
78 | - $this->dbc = $dbc; |
|
79 | - } |
|
80 | - |
|
81 | - /** |
|
82 | - * @return int |
|
83 | - */ |
|
84 | - private function getRefreshInterval() { |
|
85 | - //defaults to every hour |
|
86 | - return \OC::$server->getConfig()->getAppValue('user_ldap', 'bgjRefreshInterval', 3600); |
|
87 | - } |
|
88 | - |
|
89 | - /** |
|
90 | - * @param mixed $argument |
|
91 | - */ |
|
92 | - public function run($argument) { |
|
93 | - $this->updateGroups(); |
|
94 | - } |
|
95 | - |
|
96 | - public function updateGroups() { |
|
97 | - \OCP\Util::writeLog('user_ldap', 'Run background job "updateGroups"', ILogger::DEBUG); |
|
98 | - |
|
99 | - $knownGroups = array_keys($this->getKnownGroups()); |
|
100 | - $actualGroups = $this->groupBackend->getGroups(); |
|
101 | - |
|
102 | - if (empty($actualGroups) && empty($knownGroups)) { |
|
103 | - \OCP\Util::writeLog('user_ldap', |
|
104 | - 'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.', |
|
105 | - ILogger::INFO); |
|
106 | - return; |
|
107 | - } |
|
108 | - |
|
109 | - $this->handleKnownGroups(array_intersect($actualGroups, $knownGroups)); |
|
110 | - $this->handleCreatedGroups(array_diff($actualGroups, $knownGroups)); |
|
111 | - $this->handleRemovedGroups(array_diff($knownGroups, $actualGroups)); |
|
112 | - |
|
113 | - \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Finished.', ILogger::DEBUG); |
|
114 | - } |
|
115 | - |
|
116 | - /** |
|
117 | - * @return array |
|
118 | - */ |
|
119 | - private function getKnownGroups() { |
|
120 | - if (is_array($this->groupsFromDB)) { |
|
121 | - $this->groupsFromDB; |
|
122 | - } |
|
123 | - $qb = $this->dbc->getQueryBuilder(); |
|
124 | - $qb->select(['owncloudname', 'owncloudusers']) |
|
125 | - ->from('ldap_group_members'); |
|
126 | - $result = $qb->execute()->fetchAll(); |
|
127 | - |
|
128 | - $this->groupsFromDB = []; |
|
129 | - foreach ($result as $dataset) { |
|
130 | - $this->groupsFromDB[$dataset['owncloudname']] = $dataset; |
|
131 | - } |
|
132 | - |
|
133 | - return $this->groupsFromDB; |
|
134 | - } |
|
135 | - |
|
136 | - private function handleKnownGroups(array $groups) { |
|
137 | - $this->logger->debug( |
|
138 | - 'bgJ "updateGroups" – Dealing with known Groups.', |
|
139 | - ['app' => 'user_ldap'] |
|
140 | - ); |
|
141 | - $qb = $this->dbc->getQueryBuilder(); |
|
142 | - $qb->update('ldap_group_members') |
|
143 | - ->set('owncloudusers', $qb->createParameter('members')) |
|
144 | - ->where($qb->expr()->eq('owncloudname', $qb->createParameter('groupId'))); |
|
145 | - |
|
146 | - if (!is_array($this->groupsFromDB)) { |
|
147 | - $this->getKnownGroups(); |
|
148 | - } |
|
149 | - foreach ($groups as $group) { |
|
150 | - $knownUsers = unserialize($this->groupsFromDB[$group]['owncloudusers']); |
|
151 | - $actualUsers = $this->groupBackend->usersInGroup($group); |
|
152 | - $hasChanged = false; |
|
153 | - |
|
154 | - $groupObject = $this->groupManager->get($group); |
|
155 | - foreach (array_diff($knownUsers, $actualUsers) as $removedUser) { |
|
156 | - $userObject = $this->userManager->get($removedUser); |
|
157 | - if ($userObject instanceof IUser) { |
|
158 | - $this->dispatcher->dispatchTyped(new UserRemovedEvent($groupObject, $userObject)); |
|
159 | - } |
|
160 | - $this->logger->info( |
|
161 | - 'bgJ "updateGroups" – {user} removed from {group}', |
|
162 | - [ |
|
163 | - 'app' => 'user_ldap', |
|
164 | - 'user' => $removedUser, |
|
165 | - 'group' => $group |
|
166 | - ] |
|
167 | - ); |
|
168 | - $hasChanged = true; |
|
169 | - } |
|
170 | - foreach (array_diff($actualUsers, $knownUsers) as $addedUser) { |
|
171 | - $userObject = $this->userManager->get($addedUser); |
|
172 | - if ($userObject instanceof IUser) { |
|
173 | - $this->dispatcher->dispatchTyped(new UserAddedEvent($groupObject, $userObject)); |
|
174 | - } |
|
175 | - $this->logger->info( |
|
176 | - 'bgJ "updateGroups" – {user} added to {group}', |
|
177 | - [ |
|
178 | - 'app' => 'user_ldap', |
|
179 | - 'user' => $addedUser, |
|
180 | - 'group' => $group |
|
181 | - ] |
|
182 | - ); |
|
183 | - $hasChanged = true; |
|
184 | - } |
|
185 | - if ($hasChanged) { |
|
186 | - $qb->setParameters([ |
|
187 | - 'members' => serialize($actualUsers), |
|
188 | - 'groupId' => $group |
|
189 | - ]); |
|
190 | - $qb->execute(); |
|
191 | - } |
|
192 | - } |
|
193 | - $this->logger->debug( |
|
194 | - 'bgJ "updateGroups" – FINISHED dealing with known Groups.', |
|
195 | - ['app' => 'user_ldap'] |
|
196 | - ); |
|
197 | - } |
|
198 | - |
|
199 | - /** |
|
200 | - * @param string[] $createdGroups |
|
201 | - */ |
|
202 | - private function handleCreatedGroups($createdGroups) { |
|
203 | - \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with created Groups.', ILogger::DEBUG); |
|
204 | - |
|
205 | - $query = $this->dbc->getQueryBuilder(); |
|
206 | - $query->insert('ldap_group_members') |
|
207 | - ->setValue('owncloudname', $query->createParameter('owncloudname')) |
|
208 | - ->setValue('owncloudusers', $query->createParameter('owncloudusers')); |
|
209 | - foreach ($createdGroups as $createdGroup) { |
|
210 | - \OCP\Util::writeLog('user_ldap', |
|
211 | - 'bgJ "updateGroups" – new group "' . $createdGroup . '" found.', |
|
212 | - ILogger::INFO); |
|
213 | - $users = serialize($this->groupBackend->usersInGroup($createdGroup)); |
|
214 | - |
|
215 | - $query->setParameter('owncloudname', $createdGroup) |
|
216 | - ->setParameter('owncloudusers', $users); |
|
217 | - $query->execute(); |
|
218 | - } |
|
219 | - \OCP\Util::writeLog('user_ldap', |
|
220 | - 'bgJ "updateGroups" – FINISHED dealing with created Groups.', |
|
221 | - ILogger::DEBUG); |
|
222 | - } |
|
223 | - |
|
224 | - /** |
|
225 | - * @param string[] $removedGroups |
|
226 | - */ |
|
227 | - private function handleRemovedGroups($removedGroups) { |
|
228 | - \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with removed groups.', ILogger::DEBUG); |
|
229 | - |
|
230 | - $query = $this->dbc->getQueryBuilder(); |
|
231 | - $query->delete('ldap_group_members') |
|
232 | - ->where($query->expr()->eq('owncloudname', $query->createParameter('owncloudname'))); |
|
233 | - |
|
234 | - foreach ($removedGroups as $removedGroup) { |
|
235 | - \OCP\Util::writeLog('user_ldap', |
|
236 | - 'bgJ "updateGroups" – group "' . $removedGroup . '" was removed.', |
|
237 | - ILogger::INFO); |
|
238 | - $query->setParameter('owncloudname', $removedGroup); |
|
239 | - $query->execute(); |
|
240 | - } |
|
241 | - \OCP\Util::writeLog('user_ldap', |
|
242 | - 'bgJ "updateGroups" – FINISHED dealing with removed groups.', |
|
243 | - ILogger::DEBUG); |
|
244 | - } |
|
49 | + private $groupsFromDB; |
|
50 | + |
|
51 | + /** @var Group_Proxy */ |
|
52 | + private $groupBackend; |
|
53 | + /** @var IEventDispatcher */ |
|
54 | + private $dispatcher; |
|
55 | + /** @var IGroupManager */ |
|
56 | + private $groupManager; |
|
57 | + /** @var IUserManager */ |
|
58 | + private $userManager; |
|
59 | + /** @var LoggerInterface */ |
|
60 | + private $logger; |
|
61 | + /** @var IDBConnection */ |
|
62 | + private $dbc; |
|
63 | + |
|
64 | + public function __construct( |
|
65 | + Group_Proxy $groupBackend, |
|
66 | + IEventDispatcher $dispatcher, |
|
67 | + IGroupManager $groupManager, |
|
68 | + IUserManager $userManager, |
|
69 | + LoggerInterface $logger, |
|
70 | + IDBConnection $dbc |
|
71 | + ) { |
|
72 | + $this->interval = $this->getRefreshInterval(); |
|
73 | + $this->groupBackend = $groupBackend; |
|
74 | + $this->dispatcher = $dispatcher; |
|
75 | + $this->groupManager = $groupManager; |
|
76 | + $this->userManager = $userManager; |
|
77 | + $this->logger = $logger; |
|
78 | + $this->dbc = $dbc; |
|
79 | + } |
|
80 | + |
|
81 | + /** |
|
82 | + * @return int |
|
83 | + */ |
|
84 | + private function getRefreshInterval() { |
|
85 | + //defaults to every hour |
|
86 | + return \OC::$server->getConfig()->getAppValue('user_ldap', 'bgjRefreshInterval', 3600); |
|
87 | + } |
|
88 | + |
|
89 | + /** |
|
90 | + * @param mixed $argument |
|
91 | + */ |
|
92 | + public function run($argument) { |
|
93 | + $this->updateGroups(); |
|
94 | + } |
|
95 | + |
|
96 | + public function updateGroups() { |
|
97 | + \OCP\Util::writeLog('user_ldap', 'Run background job "updateGroups"', ILogger::DEBUG); |
|
98 | + |
|
99 | + $knownGroups = array_keys($this->getKnownGroups()); |
|
100 | + $actualGroups = $this->groupBackend->getGroups(); |
|
101 | + |
|
102 | + if (empty($actualGroups) && empty($knownGroups)) { |
|
103 | + \OCP\Util::writeLog('user_ldap', |
|
104 | + 'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.', |
|
105 | + ILogger::INFO); |
|
106 | + return; |
|
107 | + } |
|
108 | + |
|
109 | + $this->handleKnownGroups(array_intersect($actualGroups, $knownGroups)); |
|
110 | + $this->handleCreatedGroups(array_diff($actualGroups, $knownGroups)); |
|
111 | + $this->handleRemovedGroups(array_diff($knownGroups, $actualGroups)); |
|
112 | + |
|
113 | + \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Finished.', ILogger::DEBUG); |
|
114 | + } |
|
115 | + |
|
116 | + /** |
|
117 | + * @return array |
|
118 | + */ |
|
119 | + private function getKnownGroups() { |
|
120 | + if (is_array($this->groupsFromDB)) { |
|
121 | + $this->groupsFromDB; |
|
122 | + } |
|
123 | + $qb = $this->dbc->getQueryBuilder(); |
|
124 | + $qb->select(['owncloudname', 'owncloudusers']) |
|
125 | + ->from('ldap_group_members'); |
|
126 | + $result = $qb->execute()->fetchAll(); |
|
127 | + |
|
128 | + $this->groupsFromDB = []; |
|
129 | + foreach ($result as $dataset) { |
|
130 | + $this->groupsFromDB[$dataset['owncloudname']] = $dataset; |
|
131 | + } |
|
132 | + |
|
133 | + return $this->groupsFromDB; |
|
134 | + } |
|
135 | + |
|
136 | + private function handleKnownGroups(array $groups) { |
|
137 | + $this->logger->debug( |
|
138 | + 'bgJ "updateGroups" – Dealing with known Groups.', |
|
139 | + ['app' => 'user_ldap'] |
|
140 | + ); |
|
141 | + $qb = $this->dbc->getQueryBuilder(); |
|
142 | + $qb->update('ldap_group_members') |
|
143 | + ->set('owncloudusers', $qb->createParameter('members')) |
|
144 | + ->where($qb->expr()->eq('owncloudname', $qb->createParameter('groupId'))); |
|
145 | + |
|
146 | + if (!is_array($this->groupsFromDB)) { |
|
147 | + $this->getKnownGroups(); |
|
148 | + } |
|
149 | + foreach ($groups as $group) { |
|
150 | + $knownUsers = unserialize($this->groupsFromDB[$group]['owncloudusers']); |
|
151 | + $actualUsers = $this->groupBackend->usersInGroup($group); |
|
152 | + $hasChanged = false; |
|
153 | + |
|
154 | + $groupObject = $this->groupManager->get($group); |
|
155 | + foreach (array_diff($knownUsers, $actualUsers) as $removedUser) { |
|
156 | + $userObject = $this->userManager->get($removedUser); |
|
157 | + if ($userObject instanceof IUser) { |
|
158 | + $this->dispatcher->dispatchTyped(new UserRemovedEvent($groupObject, $userObject)); |
|
159 | + } |
|
160 | + $this->logger->info( |
|
161 | + 'bgJ "updateGroups" – {user} removed from {group}', |
|
162 | + [ |
|
163 | + 'app' => 'user_ldap', |
|
164 | + 'user' => $removedUser, |
|
165 | + 'group' => $group |
|
166 | + ] |
|
167 | + ); |
|
168 | + $hasChanged = true; |
|
169 | + } |
|
170 | + foreach (array_diff($actualUsers, $knownUsers) as $addedUser) { |
|
171 | + $userObject = $this->userManager->get($addedUser); |
|
172 | + if ($userObject instanceof IUser) { |
|
173 | + $this->dispatcher->dispatchTyped(new UserAddedEvent($groupObject, $userObject)); |
|
174 | + } |
|
175 | + $this->logger->info( |
|
176 | + 'bgJ "updateGroups" – {user} added to {group}', |
|
177 | + [ |
|
178 | + 'app' => 'user_ldap', |
|
179 | + 'user' => $addedUser, |
|
180 | + 'group' => $group |
|
181 | + ] |
|
182 | + ); |
|
183 | + $hasChanged = true; |
|
184 | + } |
|
185 | + if ($hasChanged) { |
|
186 | + $qb->setParameters([ |
|
187 | + 'members' => serialize($actualUsers), |
|
188 | + 'groupId' => $group |
|
189 | + ]); |
|
190 | + $qb->execute(); |
|
191 | + } |
|
192 | + } |
|
193 | + $this->logger->debug( |
|
194 | + 'bgJ "updateGroups" – FINISHED dealing with known Groups.', |
|
195 | + ['app' => 'user_ldap'] |
|
196 | + ); |
|
197 | + } |
|
198 | + |
|
199 | + /** |
|
200 | + * @param string[] $createdGroups |
|
201 | + */ |
|
202 | + private function handleCreatedGroups($createdGroups) { |
|
203 | + \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with created Groups.', ILogger::DEBUG); |
|
204 | + |
|
205 | + $query = $this->dbc->getQueryBuilder(); |
|
206 | + $query->insert('ldap_group_members') |
|
207 | + ->setValue('owncloudname', $query->createParameter('owncloudname')) |
|
208 | + ->setValue('owncloudusers', $query->createParameter('owncloudusers')); |
|
209 | + foreach ($createdGroups as $createdGroup) { |
|
210 | + \OCP\Util::writeLog('user_ldap', |
|
211 | + 'bgJ "updateGroups" – new group "' . $createdGroup . '" found.', |
|
212 | + ILogger::INFO); |
|
213 | + $users = serialize($this->groupBackend->usersInGroup($createdGroup)); |
|
214 | + |
|
215 | + $query->setParameter('owncloudname', $createdGroup) |
|
216 | + ->setParameter('owncloudusers', $users); |
|
217 | + $query->execute(); |
|
218 | + } |
|
219 | + \OCP\Util::writeLog('user_ldap', |
|
220 | + 'bgJ "updateGroups" – FINISHED dealing with created Groups.', |
|
221 | + ILogger::DEBUG); |
|
222 | + } |
|
223 | + |
|
224 | + /** |
|
225 | + * @param string[] $removedGroups |
|
226 | + */ |
|
227 | + private function handleRemovedGroups($removedGroups) { |
|
228 | + \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with removed groups.', ILogger::DEBUG); |
|
229 | + |
|
230 | + $query = $this->dbc->getQueryBuilder(); |
|
231 | + $query->delete('ldap_group_members') |
|
232 | + ->where($query->expr()->eq('owncloudname', $query->createParameter('owncloudname'))); |
|
233 | + |
|
234 | + foreach ($removedGroups as $removedGroup) { |
|
235 | + \OCP\Util::writeLog('user_ldap', |
|
236 | + 'bgJ "updateGroups" – group "' . $removedGroup . '" was removed.', |
|
237 | + ILogger::INFO); |
|
238 | + $query->setParameter('owncloudname', $removedGroup); |
|
239 | + $query->execute(); |
|
240 | + } |
|
241 | + \OCP\Util::writeLog('user_ldap', |
|
242 | + 'bgJ "updateGroups" – FINISHED dealing with removed groups.', |
|
243 | + ILogger::DEBUG); |
|
244 | + } |
|
245 | 245 | } |
@@ -208,7 +208,7 @@ discard block |
||
208 | 208 | ->setValue('owncloudusers', $query->createParameter('owncloudusers')); |
209 | 209 | foreach ($createdGroups as $createdGroup) { |
210 | 210 | \OCP\Util::writeLog('user_ldap', |
211 | - 'bgJ "updateGroups" – new group "' . $createdGroup . '" found.', |
|
211 | + 'bgJ "updateGroups" – new group "'.$createdGroup.'" found.', |
|
212 | 212 | ILogger::INFO); |
213 | 213 | $users = serialize($this->groupBackend->usersInGroup($createdGroup)); |
214 | 214 | |
@@ -233,7 +233,7 @@ discard block |
||
233 | 233 | |
234 | 234 | foreach ($removedGroups as $removedGroup) { |
235 | 235 | \OCP\Util::writeLog('user_ldap', |
236 | - 'bgJ "updateGroups" – group "' . $removedGroup . '" was removed.', |
|
236 | + 'bgJ "updateGroups" – group "'.$removedGroup.'" was removed.', |
|
237 | 237 | ILogger::INFO); |
238 | 238 | $query->setParameter('owncloudname', $removedGroup); |
239 | 239 | $query->execute(); |
@@ -43,187 +43,187 @@ |
||
43 | 43 | * @package OCA\User_LDAP\Jobs; |
44 | 44 | */ |
45 | 45 | class CleanUp extends TimedJob { |
46 | - /** @var int $limit amount of users that should be checked per run */ |
|
47 | - protected $limit; |
|
48 | - |
|
49 | - /** @var int $defaultIntervalMin default interval in minutes */ |
|
50 | - protected $defaultIntervalMin = 51; |
|
51 | - |
|
52 | - /** @var User_LDAP|User_Proxy $userBackend */ |
|
53 | - protected $userBackend; |
|
54 | - |
|
55 | - /** @var \OCP\IConfig $ocConfig */ |
|
56 | - protected $ocConfig; |
|
57 | - |
|
58 | - /** @var \OCP\IDBConnection $db */ |
|
59 | - protected $db; |
|
60 | - |
|
61 | - /** @var Helper $ldapHelper */ |
|
62 | - protected $ldapHelper; |
|
63 | - |
|
64 | - /** @var UserMapping */ |
|
65 | - protected $mapping; |
|
66 | - |
|
67 | - /** @var DeletedUsersIndex */ |
|
68 | - protected $dui; |
|
69 | - |
|
70 | - public function __construct(User_Proxy $userBackend, DeletedUsersIndex $dui) { |
|
71 | - $minutes = \OC::$server->getConfig()->getSystemValue( |
|
72 | - 'ldapUserCleanupInterval', (string)$this->defaultIntervalMin); |
|
73 | - $this->setInterval((int)$minutes * 60); |
|
74 | - $this->userBackend = $userBackend; |
|
75 | - $this->dui = $dui; |
|
76 | - } |
|
77 | - |
|
78 | - /** |
|
79 | - * assigns the instances passed to run() to the class properties |
|
80 | - * @param array $arguments |
|
81 | - */ |
|
82 | - public function setArguments($arguments) { |
|
83 | - //Dependency Injection is not possible, because the constructor will |
|
84 | - //only get values that are serialized to JSON. I.e. whatever we would |
|
85 | - //pass in app.php we do add here, except something else is passed e.g. |
|
86 | - //in tests. |
|
87 | - |
|
88 | - if (isset($arguments['helper'])) { |
|
89 | - $this->ldapHelper = $arguments['helper']; |
|
90 | - } else { |
|
91 | - $this->ldapHelper = new Helper(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection()); |
|
92 | - } |
|
93 | - |
|
94 | - if (isset($arguments['ocConfig'])) { |
|
95 | - $this->ocConfig = $arguments['ocConfig']; |
|
96 | - } else { |
|
97 | - $this->ocConfig = \OC::$server->getConfig(); |
|
98 | - } |
|
99 | - |
|
100 | - if (isset($arguments['userBackend'])) { |
|
101 | - $this->userBackend = $arguments['userBackend']; |
|
102 | - } |
|
103 | - |
|
104 | - if (isset($arguments['db'])) { |
|
105 | - $this->db = $arguments['db']; |
|
106 | - } else { |
|
107 | - $this->db = \OC::$server->getDatabaseConnection(); |
|
108 | - } |
|
109 | - |
|
110 | - if (isset($arguments['mapping'])) { |
|
111 | - $this->mapping = $arguments['mapping']; |
|
112 | - } else { |
|
113 | - $this->mapping = new UserMapping($this->db); |
|
114 | - } |
|
115 | - |
|
116 | - if (isset($arguments['deletedUsersIndex'])) { |
|
117 | - $this->dui = $arguments['deletedUsersIndex']; |
|
118 | - } |
|
119 | - } |
|
120 | - |
|
121 | - /** |
|
122 | - * makes the background job do its work |
|
123 | - * @param array $argument |
|
124 | - */ |
|
125 | - public function run($argument) { |
|
126 | - $this->setArguments($argument); |
|
127 | - |
|
128 | - if (!$this->isCleanUpAllowed()) { |
|
129 | - return; |
|
130 | - } |
|
131 | - $users = $this->mapping->getList($this->getOffset(), $this->getChunkSize()); |
|
132 | - if (!is_array($users)) { |
|
133 | - //something wrong? Let's start from the beginning next time and |
|
134 | - //abort |
|
135 | - $this->setOffset(true); |
|
136 | - return; |
|
137 | - } |
|
138 | - $resetOffset = $this->isOffsetResetNecessary(count($users)); |
|
139 | - $this->checkUsers($users); |
|
140 | - $this->setOffset($resetOffset); |
|
141 | - } |
|
142 | - |
|
143 | - /** |
|
144 | - * checks whether next run should start at 0 again |
|
145 | - * @param int $resultCount |
|
146 | - * @return bool |
|
147 | - */ |
|
148 | - public function isOffsetResetNecessary($resultCount) { |
|
149 | - return $resultCount < $this->getChunkSize(); |
|
150 | - } |
|
151 | - |
|
152 | - /** |
|
153 | - * checks whether cleaning up LDAP users is allowed |
|
154 | - * @return bool |
|
155 | - */ |
|
156 | - public function isCleanUpAllowed() { |
|
157 | - try { |
|
158 | - if ($this->ldapHelper->haveDisabledConfigurations()) { |
|
159 | - return false; |
|
160 | - } |
|
161 | - } catch (\Exception $e) { |
|
162 | - return false; |
|
163 | - } |
|
164 | - |
|
165 | - return $this->isCleanUpEnabled(); |
|
166 | - } |
|
167 | - |
|
168 | - /** |
|
169 | - * checks whether clean up is enabled by configuration |
|
170 | - * @return bool |
|
171 | - */ |
|
172 | - private function isCleanUpEnabled() { |
|
173 | - return (bool)$this->ocConfig->getSystemValue( |
|
174 | - 'ldapUserCleanupInterval', (string)$this->defaultIntervalMin); |
|
175 | - } |
|
176 | - |
|
177 | - /** |
|
178 | - * checks users whether they are still existing |
|
179 | - * @param array $users result from getMappedUsers() |
|
180 | - */ |
|
181 | - private function checkUsers(array $users) { |
|
182 | - foreach ($users as $user) { |
|
183 | - $this->checkUser($user); |
|
184 | - } |
|
185 | - } |
|
186 | - |
|
187 | - /** |
|
188 | - * checks whether a user is still existing in LDAP |
|
189 | - * @param string[] $user |
|
190 | - */ |
|
191 | - private function checkUser(array $user) { |
|
192 | - if ($this->userBackend->userExistsOnLDAP($user['name'])) { |
|
193 | - //still available, all good |
|
194 | - |
|
195 | - return; |
|
196 | - } |
|
197 | - |
|
198 | - $this->dui->markUser($user['name']); |
|
199 | - } |
|
200 | - |
|
201 | - /** |
|
202 | - * gets the offset to fetch users from the mappings table |
|
203 | - * @return int |
|
204 | - */ |
|
205 | - private function getOffset() { |
|
206 | - return (int)$this->ocConfig->getAppValue('user_ldap', 'cleanUpJobOffset', 0); |
|
207 | - } |
|
208 | - |
|
209 | - /** |
|
210 | - * sets the new offset for the next run |
|
211 | - * @param bool $reset whether the offset should be set to 0 |
|
212 | - */ |
|
213 | - public function setOffset($reset = false) { |
|
214 | - $newOffset = $reset ? 0 : |
|
215 | - $this->getOffset() + $this->getChunkSize(); |
|
216 | - $this->ocConfig->setAppValue('user_ldap', 'cleanUpJobOffset', $newOffset); |
|
217 | - } |
|
218 | - |
|
219 | - /** |
|
220 | - * returns the chunk size (limit in DB speak) |
|
221 | - * @return int |
|
222 | - */ |
|
223 | - public function getChunkSize() { |
|
224 | - if ($this->limit === null) { |
|
225 | - $this->limit = (int)$this->ocConfig->getAppValue('user_ldap', 'cleanUpJobChunkSize', 50); |
|
226 | - } |
|
227 | - return $this->limit; |
|
228 | - } |
|
46 | + /** @var int $limit amount of users that should be checked per run */ |
|
47 | + protected $limit; |
|
48 | + |
|
49 | + /** @var int $defaultIntervalMin default interval in minutes */ |
|
50 | + protected $defaultIntervalMin = 51; |
|
51 | + |
|
52 | + /** @var User_LDAP|User_Proxy $userBackend */ |
|
53 | + protected $userBackend; |
|
54 | + |
|
55 | + /** @var \OCP\IConfig $ocConfig */ |
|
56 | + protected $ocConfig; |
|
57 | + |
|
58 | + /** @var \OCP\IDBConnection $db */ |
|
59 | + protected $db; |
|
60 | + |
|
61 | + /** @var Helper $ldapHelper */ |
|
62 | + protected $ldapHelper; |
|
63 | + |
|
64 | + /** @var UserMapping */ |
|
65 | + protected $mapping; |
|
66 | + |
|
67 | + /** @var DeletedUsersIndex */ |
|
68 | + protected $dui; |
|
69 | + |
|
70 | + public function __construct(User_Proxy $userBackend, DeletedUsersIndex $dui) { |
|
71 | + $minutes = \OC::$server->getConfig()->getSystemValue( |
|
72 | + 'ldapUserCleanupInterval', (string)$this->defaultIntervalMin); |
|
73 | + $this->setInterval((int)$minutes * 60); |
|
74 | + $this->userBackend = $userBackend; |
|
75 | + $this->dui = $dui; |
|
76 | + } |
|
77 | + |
|
78 | + /** |
|
79 | + * assigns the instances passed to run() to the class properties |
|
80 | + * @param array $arguments |
|
81 | + */ |
|
82 | + public function setArguments($arguments) { |
|
83 | + //Dependency Injection is not possible, because the constructor will |
|
84 | + //only get values that are serialized to JSON. I.e. whatever we would |
|
85 | + //pass in app.php we do add here, except something else is passed e.g. |
|
86 | + //in tests. |
|
87 | + |
|
88 | + if (isset($arguments['helper'])) { |
|
89 | + $this->ldapHelper = $arguments['helper']; |
|
90 | + } else { |
|
91 | + $this->ldapHelper = new Helper(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection()); |
|
92 | + } |
|
93 | + |
|
94 | + if (isset($arguments['ocConfig'])) { |
|
95 | + $this->ocConfig = $arguments['ocConfig']; |
|
96 | + } else { |
|
97 | + $this->ocConfig = \OC::$server->getConfig(); |
|
98 | + } |
|
99 | + |
|
100 | + if (isset($arguments['userBackend'])) { |
|
101 | + $this->userBackend = $arguments['userBackend']; |
|
102 | + } |
|
103 | + |
|
104 | + if (isset($arguments['db'])) { |
|
105 | + $this->db = $arguments['db']; |
|
106 | + } else { |
|
107 | + $this->db = \OC::$server->getDatabaseConnection(); |
|
108 | + } |
|
109 | + |
|
110 | + if (isset($arguments['mapping'])) { |
|
111 | + $this->mapping = $arguments['mapping']; |
|
112 | + } else { |
|
113 | + $this->mapping = new UserMapping($this->db); |
|
114 | + } |
|
115 | + |
|
116 | + if (isset($arguments['deletedUsersIndex'])) { |
|
117 | + $this->dui = $arguments['deletedUsersIndex']; |
|
118 | + } |
|
119 | + } |
|
120 | + |
|
121 | + /** |
|
122 | + * makes the background job do its work |
|
123 | + * @param array $argument |
|
124 | + */ |
|
125 | + public function run($argument) { |
|
126 | + $this->setArguments($argument); |
|
127 | + |
|
128 | + if (!$this->isCleanUpAllowed()) { |
|
129 | + return; |
|
130 | + } |
|
131 | + $users = $this->mapping->getList($this->getOffset(), $this->getChunkSize()); |
|
132 | + if (!is_array($users)) { |
|
133 | + //something wrong? Let's start from the beginning next time and |
|
134 | + //abort |
|
135 | + $this->setOffset(true); |
|
136 | + return; |
|
137 | + } |
|
138 | + $resetOffset = $this->isOffsetResetNecessary(count($users)); |
|
139 | + $this->checkUsers($users); |
|
140 | + $this->setOffset($resetOffset); |
|
141 | + } |
|
142 | + |
|
143 | + /** |
|
144 | + * checks whether next run should start at 0 again |
|
145 | + * @param int $resultCount |
|
146 | + * @return bool |
|
147 | + */ |
|
148 | + public function isOffsetResetNecessary($resultCount) { |
|
149 | + return $resultCount < $this->getChunkSize(); |
|
150 | + } |
|
151 | + |
|
152 | + /** |
|
153 | + * checks whether cleaning up LDAP users is allowed |
|
154 | + * @return bool |
|
155 | + */ |
|
156 | + public function isCleanUpAllowed() { |
|
157 | + try { |
|
158 | + if ($this->ldapHelper->haveDisabledConfigurations()) { |
|
159 | + return false; |
|
160 | + } |
|
161 | + } catch (\Exception $e) { |
|
162 | + return false; |
|
163 | + } |
|
164 | + |
|
165 | + return $this->isCleanUpEnabled(); |
|
166 | + } |
|
167 | + |
|
168 | + /** |
|
169 | + * checks whether clean up is enabled by configuration |
|
170 | + * @return bool |
|
171 | + */ |
|
172 | + private function isCleanUpEnabled() { |
|
173 | + return (bool)$this->ocConfig->getSystemValue( |
|
174 | + 'ldapUserCleanupInterval', (string)$this->defaultIntervalMin); |
|
175 | + } |
|
176 | + |
|
177 | + /** |
|
178 | + * checks users whether they are still existing |
|
179 | + * @param array $users result from getMappedUsers() |
|
180 | + */ |
|
181 | + private function checkUsers(array $users) { |
|
182 | + foreach ($users as $user) { |
|
183 | + $this->checkUser($user); |
|
184 | + } |
|
185 | + } |
|
186 | + |
|
187 | + /** |
|
188 | + * checks whether a user is still existing in LDAP |
|
189 | + * @param string[] $user |
|
190 | + */ |
|
191 | + private function checkUser(array $user) { |
|
192 | + if ($this->userBackend->userExistsOnLDAP($user['name'])) { |
|
193 | + //still available, all good |
|
194 | + |
|
195 | + return; |
|
196 | + } |
|
197 | + |
|
198 | + $this->dui->markUser($user['name']); |
|
199 | + } |
|
200 | + |
|
201 | + /** |
|
202 | + * gets the offset to fetch users from the mappings table |
|
203 | + * @return int |
|
204 | + */ |
|
205 | + private function getOffset() { |
|
206 | + return (int)$this->ocConfig->getAppValue('user_ldap', 'cleanUpJobOffset', 0); |
|
207 | + } |
|
208 | + |
|
209 | + /** |
|
210 | + * sets the new offset for the next run |
|
211 | + * @param bool $reset whether the offset should be set to 0 |
|
212 | + */ |
|
213 | + public function setOffset($reset = false) { |
|
214 | + $newOffset = $reset ? 0 : |
|
215 | + $this->getOffset() + $this->getChunkSize(); |
|
216 | + $this->ocConfig->setAppValue('user_ldap', 'cleanUpJobOffset', $newOffset); |
|
217 | + } |
|
218 | + |
|
219 | + /** |
|
220 | + * returns the chunk size (limit in DB speak) |
|
221 | + * @return int |
|
222 | + */ |
|
223 | + public function getChunkSize() { |
|
224 | + if ($this->limit === null) { |
|
225 | + $this->limit = (int)$this->ocConfig->getAppValue('user_ldap', 'cleanUpJobChunkSize', 50); |
|
226 | + } |
|
227 | + return $this->limit; |
|
228 | + } |
|
229 | 229 | } |
@@ -40,333 +40,333 @@ |
||
40 | 40 | use OCP\Notification\IManager; |
41 | 41 | |
42 | 42 | class Sync extends TimedJob { |
43 | - public const MAX_INTERVAL = 12 * 60 * 60; // 12h |
|
44 | - public const MIN_INTERVAL = 30 * 60; // 30min |
|
45 | - /** @var Helper */ |
|
46 | - protected $ldapHelper; |
|
47 | - /** @var LDAP */ |
|
48 | - protected $ldap; |
|
49 | - /** @var Manager */ |
|
50 | - protected $userManager; |
|
51 | - /** @var UserMapping */ |
|
52 | - protected $mapper; |
|
53 | - /** @var IConfig */ |
|
54 | - protected $config; |
|
55 | - /** @var IAvatarManager */ |
|
56 | - protected $avatarManager; |
|
57 | - /** @var IDBConnection */ |
|
58 | - protected $dbc; |
|
59 | - /** @var IUserManager */ |
|
60 | - protected $ncUserManager; |
|
61 | - /** @var IManager */ |
|
62 | - protected $notificationManager; |
|
63 | - /** @var ConnectionFactory */ |
|
64 | - protected $connectionFactory; |
|
65 | - /** @var AccessFactory */ |
|
66 | - protected $accessFactory; |
|
67 | - |
|
68 | - public function __construct(Manager $userManager) { |
|
69 | - $this->userManager = $userManager; |
|
70 | - $this->setInterval( |
|
71 | - \OC::$server->getConfig()->getAppValue( |
|
72 | - 'user_ldap', |
|
73 | - 'background_sync_interval', |
|
74 | - self::MIN_INTERVAL |
|
75 | - ) |
|
76 | - ); |
|
77 | - } |
|
78 | - |
|
79 | - /** |
|
80 | - * updates the interval |
|
81 | - * |
|
82 | - * the idea is to adjust the interval depending on the amount of known users |
|
83 | - * and the attempt to update each user one day. At most it would run every |
|
84 | - * 30 minutes, and at least every 12 hours. |
|
85 | - */ |
|
86 | - public function updateInterval() { |
|
87 | - $minPagingSize = $this->getMinPagingSize(); |
|
88 | - $mappedUsers = $this->mapper->count(); |
|
89 | - |
|
90 | - $runsPerDay = ($minPagingSize === 0 || $mappedUsers === 0) ? self::MAX_INTERVAL |
|
91 | - : $mappedUsers / $minPagingSize; |
|
92 | - $interval = floor(24 * 60 * 60 / $runsPerDay); |
|
93 | - $interval = min(max($interval, self::MIN_INTERVAL), self::MAX_INTERVAL); |
|
94 | - |
|
95 | - $this->config->setAppValue('user_ldap', 'background_sync_interval', $interval); |
|
96 | - } |
|
97 | - |
|
98 | - /** |
|
99 | - * returns the smallest configured paging size |
|
100 | - * @return int |
|
101 | - */ |
|
102 | - protected function getMinPagingSize() { |
|
103 | - $configKeys = $this->config->getAppKeys('user_ldap'); |
|
104 | - $configKeys = array_filter($configKeys, function ($key) { |
|
105 | - return strpos($key, 'ldap_paging_size') !== false; |
|
106 | - }); |
|
107 | - $minPagingSize = null; |
|
108 | - foreach ($configKeys as $configKey) { |
|
109 | - $pagingSize = $this->config->getAppValue('user_ldap', $configKey, $minPagingSize); |
|
110 | - $minPagingSize = $minPagingSize === null ? $pagingSize : min($minPagingSize, $pagingSize); |
|
111 | - } |
|
112 | - return (int)$minPagingSize; |
|
113 | - } |
|
114 | - |
|
115 | - /** |
|
116 | - * @param array $argument |
|
117 | - */ |
|
118 | - public function run($argument) { |
|
119 | - $this->setArgument($argument); |
|
120 | - |
|
121 | - $isBackgroundJobModeAjax = $this->config |
|
122 | - ->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax'; |
|
123 | - if ($isBackgroundJobModeAjax) { |
|
124 | - return; |
|
125 | - } |
|
126 | - |
|
127 | - $cycleData = $this->getCycle(); |
|
128 | - if ($cycleData === null) { |
|
129 | - $cycleData = $this->determineNextCycle(); |
|
130 | - if ($cycleData === null) { |
|
131 | - $this->updateInterval(); |
|
132 | - return; |
|
133 | - } |
|
134 | - } |
|
135 | - |
|
136 | - if (!$this->qualifiesToRun($cycleData)) { |
|
137 | - $this->updateInterval(); |
|
138 | - return; |
|
139 | - } |
|
140 | - |
|
141 | - try { |
|
142 | - $expectMoreResults = $this->runCycle($cycleData); |
|
143 | - if ($expectMoreResults) { |
|
144 | - $this->increaseOffset($cycleData); |
|
145 | - } else { |
|
146 | - $this->determineNextCycle($cycleData); |
|
147 | - } |
|
148 | - $this->updateInterval(); |
|
149 | - } catch (ServerNotAvailableException $e) { |
|
150 | - $this->determineNextCycle($cycleData); |
|
151 | - } |
|
152 | - } |
|
153 | - |
|
154 | - /** |
|
155 | - * @param array $cycleData |
|
156 | - * @return bool whether more results are expected from the same configuration |
|
157 | - */ |
|
158 | - public function runCycle($cycleData) { |
|
159 | - $connection = $this->connectionFactory->get($cycleData['prefix']); |
|
160 | - $access = $this->accessFactory->get($connection); |
|
161 | - $access->setUserMapper($this->mapper); |
|
162 | - |
|
163 | - $filter = $access->combineFilterWithAnd([ |
|
164 | - $access->connection->ldapUserFilter, |
|
165 | - $access->connection->ldapUserDisplayName . '=*', |
|
166 | - $access->getFilterPartForUserSearch('') |
|
167 | - ]); |
|
168 | - $results = $access->fetchListOfUsers( |
|
169 | - $filter, |
|
170 | - $access->userManager->getAttributes(), |
|
171 | - $connection->ldapPagingSize, |
|
172 | - $cycleData['offset'], |
|
173 | - true |
|
174 | - ); |
|
175 | - |
|
176 | - if ((int)$connection->ldapPagingSize === 0) { |
|
177 | - return false; |
|
178 | - } |
|
179 | - return count($results) >= (int)$connection->ldapPagingSize; |
|
180 | - } |
|
181 | - |
|
182 | - /** |
|
183 | - * returns the info about the current cycle that should be run, if any, |
|
184 | - * otherwise null |
|
185 | - * |
|
186 | - * @return array|null |
|
187 | - */ |
|
188 | - public function getCycle() { |
|
189 | - $prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true); |
|
190 | - if (count($prefixes) === 0) { |
|
191 | - return null; |
|
192 | - } |
|
193 | - |
|
194 | - $cycleData = [ |
|
195 | - 'prefix' => $this->config->getAppValue('user_ldap', 'background_sync_prefix', null), |
|
196 | - 'offset' => (int)$this->config->getAppValue('user_ldap', 'background_sync_offset', 0), |
|
197 | - ]; |
|
198 | - |
|
199 | - if ( |
|
200 | - $cycleData['prefix'] !== null |
|
201 | - && in_array($cycleData['prefix'], $prefixes) |
|
202 | - ) { |
|
203 | - return $cycleData; |
|
204 | - } |
|
205 | - |
|
206 | - return null; |
|
207 | - } |
|
208 | - |
|
209 | - /** |
|
210 | - * Save the provided cycle information in the DB |
|
211 | - * |
|
212 | - * @param array $cycleData |
|
213 | - */ |
|
214 | - public function setCycle(array $cycleData) { |
|
215 | - $this->config->setAppValue('user_ldap', 'background_sync_prefix', $cycleData['prefix']); |
|
216 | - $this->config->setAppValue('user_ldap', 'background_sync_offset', $cycleData['offset']); |
|
217 | - } |
|
218 | - |
|
219 | - /** |
|
220 | - * returns data about the next cycle that should run, if any, otherwise |
|
221 | - * null. It also always goes for the next LDAP configuration! |
|
222 | - * |
|
223 | - * @param array|null $cycleData the old cycle |
|
224 | - * @return array|null |
|
225 | - */ |
|
226 | - public function determineNextCycle(array $cycleData = null) { |
|
227 | - $prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true); |
|
228 | - if (count($prefixes) === 0) { |
|
229 | - return null; |
|
230 | - } |
|
231 | - |
|
232 | - // get the next prefix in line and remember it |
|
233 | - $oldPrefix = $cycleData === null ? null : $cycleData['prefix']; |
|
234 | - $prefix = $this->getNextPrefix($oldPrefix); |
|
235 | - if ($prefix === null) { |
|
236 | - return null; |
|
237 | - } |
|
238 | - $cycleData['prefix'] = $prefix; |
|
239 | - $cycleData['offset'] = 0; |
|
240 | - $this->setCycle(['prefix' => $prefix, 'offset' => 0]); |
|
241 | - |
|
242 | - return $cycleData; |
|
243 | - } |
|
244 | - |
|
245 | - /** |
|
246 | - * Checks whether the provided cycle should be run. Currently only the |
|
247 | - * last configuration change goes into account (at least one hour). |
|
248 | - * |
|
249 | - * @param $cycleData |
|
250 | - * @return bool |
|
251 | - */ |
|
252 | - public function qualifiesToRun($cycleData) { |
|
253 | - $lastChange = $this->config->getAppValue('user_ldap', $cycleData['prefix'] . '_lastChange', 0); |
|
254 | - if ((time() - $lastChange) > 60 * 30) { |
|
255 | - return true; |
|
256 | - } |
|
257 | - return false; |
|
258 | - } |
|
259 | - |
|
260 | - /** |
|
261 | - * increases the offset of the current cycle for the next run |
|
262 | - * |
|
263 | - * @param $cycleData |
|
264 | - */ |
|
265 | - protected function increaseOffset($cycleData) { |
|
266 | - $ldapConfig = new Configuration($cycleData['prefix']); |
|
267 | - $cycleData['offset'] += (int)$ldapConfig->ldapPagingSize; |
|
268 | - $this->setCycle($cycleData); |
|
269 | - } |
|
270 | - |
|
271 | - /** |
|
272 | - * determines the next configuration prefix based on the last one (if any) |
|
273 | - * |
|
274 | - * @param string|null $lastPrefix |
|
275 | - * @return string|null |
|
276 | - */ |
|
277 | - protected function getNextPrefix($lastPrefix) { |
|
278 | - $prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true); |
|
279 | - $noOfPrefixes = count($prefixes); |
|
280 | - if ($noOfPrefixes === 0) { |
|
281 | - return null; |
|
282 | - } |
|
283 | - $i = $lastPrefix === null ? false : array_search($lastPrefix, $prefixes, true); |
|
284 | - if ($i === false) { |
|
285 | - $i = -1; |
|
286 | - } else { |
|
287 | - $i++; |
|
288 | - } |
|
289 | - |
|
290 | - if (!isset($prefixes[$i])) { |
|
291 | - $i = 0; |
|
292 | - } |
|
293 | - return $prefixes[$i]; |
|
294 | - } |
|
295 | - |
|
296 | - /** |
|
297 | - * "fixes" DI |
|
298 | - * |
|
299 | - * @param array $argument |
|
300 | - */ |
|
301 | - public function setArgument($argument) { |
|
302 | - if (isset($argument['config'])) { |
|
303 | - $this->config = $argument['config']; |
|
304 | - } else { |
|
305 | - $this->config = \OC::$server->getConfig(); |
|
306 | - } |
|
307 | - |
|
308 | - if (isset($argument['helper'])) { |
|
309 | - $this->ldapHelper = $argument['helper']; |
|
310 | - } else { |
|
311 | - $this->ldapHelper = new Helper($this->config, \OC::$server->getDatabaseConnection()); |
|
312 | - } |
|
313 | - |
|
314 | - if (isset($argument['ldapWrapper'])) { |
|
315 | - $this->ldap = $argument['ldapWrapper']; |
|
316 | - } else { |
|
317 | - $this->ldap = new LDAP(); |
|
318 | - } |
|
319 | - |
|
320 | - if (isset($argument['avatarManager'])) { |
|
321 | - $this->avatarManager = $argument['avatarManager']; |
|
322 | - } else { |
|
323 | - $this->avatarManager = \OC::$server->getAvatarManager(); |
|
324 | - } |
|
325 | - |
|
326 | - if (isset($argument['dbc'])) { |
|
327 | - $this->dbc = $argument['dbc']; |
|
328 | - } else { |
|
329 | - $this->dbc = \OC::$server->getDatabaseConnection(); |
|
330 | - } |
|
331 | - |
|
332 | - if (isset($argument['ncUserManager'])) { |
|
333 | - $this->ncUserManager = $argument['ncUserManager']; |
|
334 | - } else { |
|
335 | - $this->ncUserManager = \OC::$server->getUserManager(); |
|
336 | - } |
|
337 | - |
|
338 | - if (isset($argument['notificationManager'])) { |
|
339 | - $this->notificationManager = $argument['notificationManager']; |
|
340 | - } else { |
|
341 | - $this->notificationManager = \OC::$server->getNotificationManager(); |
|
342 | - } |
|
343 | - |
|
344 | - if (isset($argument['userManager'])) { |
|
345 | - $this->userManager = $argument['userManager']; |
|
346 | - } |
|
347 | - |
|
348 | - if (isset($argument['mapper'])) { |
|
349 | - $this->mapper = $argument['mapper']; |
|
350 | - } else { |
|
351 | - $this->mapper = new UserMapping($this->dbc); |
|
352 | - } |
|
353 | - |
|
354 | - if (isset($argument['connectionFactory'])) { |
|
355 | - $this->connectionFactory = $argument['connectionFactory']; |
|
356 | - } else { |
|
357 | - $this->connectionFactory = new ConnectionFactory($this->ldap); |
|
358 | - } |
|
359 | - |
|
360 | - if (isset($argument['accessFactory'])) { |
|
361 | - $this->accessFactory = $argument['accessFactory']; |
|
362 | - } else { |
|
363 | - $this->accessFactory = new AccessFactory( |
|
364 | - $this->ldap, |
|
365 | - $this->userManager, |
|
366 | - $this->ldapHelper, |
|
367 | - $this->config, |
|
368 | - $this->ncUserManager |
|
369 | - ); |
|
370 | - } |
|
371 | - } |
|
43 | + public const MAX_INTERVAL = 12 * 60 * 60; // 12h |
|
44 | + public const MIN_INTERVAL = 30 * 60; // 30min |
|
45 | + /** @var Helper */ |
|
46 | + protected $ldapHelper; |
|
47 | + /** @var LDAP */ |
|
48 | + protected $ldap; |
|
49 | + /** @var Manager */ |
|
50 | + protected $userManager; |
|
51 | + /** @var UserMapping */ |
|
52 | + protected $mapper; |
|
53 | + /** @var IConfig */ |
|
54 | + protected $config; |
|
55 | + /** @var IAvatarManager */ |
|
56 | + protected $avatarManager; |
|
57 | + /** @var IDBConnection */ |
|
58 | + protected $dbc; |
|
59 | + /** @var IUserManager */ |
|
60 | + protected $ncUserManager; |
|
61 | + /** @var IManager */ |
|
62 | + protected $notificationManager; |
|
63 | + /** @var ConnectionFactory */ |
|
64 | + protected $connectionFactory; |
|
65 | + /** @var AccessFactory */ |
|
66 | + protected $accessFactory; |
|
67 | + |
|
68 | + public function __construct(Manager $userManager) { |
|
69 | + $this->userManager = $userManager; |
|
70 | + $this->setInterval( |
|
71 | + \OC::$server->getConfig()->getAppValue( |
|
72 | + 'user_ldap', |
|
73 | + 'background_sync_interval', |
|
74 | + self::MIN_INTERVAL |
|
75 | + ) |
|
76 | + ); |
|
77 | + } |
|
78 | + |
|
79 | + /** |
|
80 | + * updates the interval |
|
81 | + * |
|
82 | + * the idea is to adjust the interval depending on the amount of known users |
|
83 | + * and the attempt to update each user one day. At most it would run every |
|
84 | + * 30 minutes, and at least every 12 hours. |
|
85 | + */ |
|
86 | + public function updateInterval() { |
|
87 | + $minPagingSize = $this->getMinPagingSize(); |
|
88 | + $mappedUsers = $this->mapper->count(); |
|
89 | + |
|
90 | + $runsPerDay = ($minPagingSize === 0 || $mappedUsers === 0) ? self::MAX_INTERVAL |
|
91 | + : $mappedUsers / $minPagingSize; |
|
92 | + $interval = floor(24 * 60 * 60 / $runsPerDay); |
|
93 | + $interval = min(max($interval, self::MIN_INTERVAL), self::MAX_INTERVAL); |
|
94 | + |
|
95 | + $this->config->setAppValue('user_ldap', 'background_sync_interval', $interval); |
|
96 | + } |
|
97 | + |
|
98 | + /** |
|
99 | + * returns the smallest configured paging size |
|
100 | + * @return int |
|
101 | + */ |
|
102 | + protected function getMinPagingSize() { |
|
103 | + $configKeys = $this->config->getAppKeys('user_ldap'); |
|
104 | + $configKeys = array_filter($configKeys, function ($key) { |
|
105 | + return strpos($key, 'ldap_paging_size') !== false; |
|
106 | + }); |
|
107 | + $minPagingSize = null; |
|
108 | + foreach ($configKeys as $configKey) { |
|
109 | + $pagingSize = $this->config->getAppValue('user_ldap', $configKey, $minPagingSize); |
|
110 | + $minPagingSize = $minPagingSize === null ? $pagingSize : min($minPagingSize, $pagingSize); |
|
111 | + } |
|
112 | + return (int)$minPagingSize; |
|
113 | + } |
|
114 | + |
|
115 | + /** |
|
116 | + * @param array $argument |
|
117 | + */ |
|
118 | + public function run($argument) { |
|
119 | + $this->setArgument($argument); |
|
120 | + |
|
121 | + $isBackgroundJobModeAjax = $this->config |
|
122 | + ->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax'; |
|
123 | + if ($isBackgroundJobModeAjax) { |
|
124 | + return; |
|
125 | + } |
|
126 | + |
|
127 | + $cycleData = $this->getCycle(); |
|
128 | + if ($cycleData === null) { |
|
129 | + $cycleData = $this->determineNextCycle(); |
|
130 | + if ($cycleData === null) { |
|
131 | + $this->updateInterval(); |
|
132 | + return; |
|
133 | + } |
|
134 | + } |
|
135 | + |
|
136 | + if (!$this->qualifiesToRun($cycleData)) { |
|
137 | + $this->updateInterval(); |
|
138 | + return; |
|
139 | + } |
|
140 | + |
|
141 | + try { |
|
142 | + $expectMoreResults = $this->runCycle($cycleData); |
|
143 | + if ($expectMoreResults) { |
|
144 | + $this->increaseOffset($cycleData); |
|
145 | + } else { |
|
146 | + $this->determineNextCycle($cycleData); |
|
147 | + } |
|
148 | + $this->updateInterval(); |
|
149 | + } catch (ServerNotAvailableException $e) { |
|
150 | + $this->determineNextCycle($cycleData); |
|
151 | + } |
|
152 | + } |
|
153 | + |
|
154 | + /** |
|
155 | + * @param array $cycleData |
|
156 | + * @return bool whether more results are expected from the same configuration |
|
157 | + */ |
|
158 | + public function runCycle($cycleData) { |
|
159 | + $connection = $this->connectionFactory->get($cycleData['prefix']); |
|
160 | + $access = $this->accessFactory->get($connection); |
|
161 | + $access->setUserMapper($this->mapper); |
|
162 | + |
|
163 | + $filter = $access->combineFilterWithAnd([ |
|
164 | + $access->connection->ldapUserFilter, |
|
165 | + $access->connection->ldapUserDisplayName . '=*', |
|
166 | + $access->getFilterPartForUserSearch('') |
|
167 | + ]); |
|
168 | + $results = $access->fetchListOfUsers( |
|
169 | + $filter, |
|
170 | + $access->userManager->getAttributes(), |
|
171 | + $connection->ldapPagingSize, |
|
172 | + $cycleData['offset'], |
|
173 | + true |
|
174 | + ); |
|
175 | + |
|
176 | + if ((int)$connection->ldapPagingSize === 0) { |
|
177 | + return false; |
|
178 | + } |
|
179 | + return count($results) >= (int)$connection->ldapPagingSize; |
|
180 | + } |
|
181 | + |
|
182 | + /** |
|
183 | + * returns the info about the current cycle that should be run, if any, |
|
184 | + * otherwise null |
|
185 | + * |
|
186 | + * @return array|null |
|
187 | + */ |
|
188 | + public function getCycle() { |
|
189 | + $prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true); |
|
190 | + if (count($prefixes) === 0) { |
|
191 | + return null; |
|
192 | + } |
|
193 | + |
|
194 | + $cycleData = [ |
|
195 | + 'prefix' => $this->config->getAppValue('user_ldap', 'background_sync_prefix', null), |
|
196 | + 'offset' => (int)$this->config->getAppValue('user_ldap', 'background_sync_offset', 0), |
|
197 | + ]; |
|
198 | + |
|
199 | + if ( |
|
200 | + $cycleData['prefix'] !== null |
|
201 | + && in_array($cycleData['prefix'], $prefixes) |
|
202 | + ) { |
|
203 | + return $cycleData; |
|
204 | + } |
|
205 | + |
|
206 | + return null; |
|
207 | + } |
|
208 | + |
|
209 | + /** |
|
210 | + * Save the provided cycle information in the DB |
|
211 | + * |
|
212 | + * @param array $cycleData |
|
213 | + */ |
|
214 | + public function setCycle(array $cycleData) { |
|
215 | + $this->config->setAppValue('user_ldap', 'background_sync_prefix', $cycleData['prefix']); |
|
216 | + $this->config->setAppValue('user_ldap', 'background_sync_offset', $cycleData['offset']); |
|
217 | + } |
|
218 | + |
|
219 | + /** |
|
220 | + * returns data about the next cycle that should run, if any, otherwise |
|
221 | + * null. It also always goes for the next LDAP configuration! |
|
222 | + * |
|
223 | + * @param array|null $cycleData the old cycle |
|
224 | + * @return array|null |
|
225 | + */ |
|
226 | + public function determineNextCycle(array $cycleData = null) { |
|
227 | + $prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true); |
|
228 | + if (count($prefixes) === 0) { |
|
229 | + return null; |
|
230 | + } |
|
231 | + |
|
232 | + // get the next prefix in line and remember it |
|
233 | + $oldPrefix = $cycleData === null ? null : $cycleData['prefix']; |
|
234 | + $prefix = $this->getNextPrefix($oldPrefix); |
|
235 | + if ($prefix === null) { |
|
236 | + return null; |
|
237 | + } |
|
238 | + $cycleData['prefix'] = $prefix; |
|
239 | + $cycleData['offset'] = 0; |
|
240 | + $this->setCycle(['prefix' => $prefix, 'offset' => 0]); |
|
241 | + |
|
242 | + return $cycleData; |
|
243 | + } |
|
244 | + |
|
245 | + /** |
|
246 | + * Checks whether the provided cycle should be run. Currently only the |
|
247 | + * last configuration change goes into account (at least one hour). |
|
248 | + * |
|
249 | + * @param $cycleData |
|
250 | + * @return bool |
|
251 | + */ |
|
252 | + public function qualifiesToRun($cycleData) { |
|
253 | + $lastChange = $this->config->getAppValue('user_ldap', $cycleData['prefix'] . '_lastChange', 0); |
|
254 | + if ((time() - $lastChange) > 60 * 30) { |
|
255 | + return true; |
|
256 | + } |
|
257 | + return false; |
|
258 | + } |
|
259 | + |
|
260 | + /** |
|
261 | + * increases the offset of the current cycle for the next run |
|
262 | + * |
|
263 | + * @param $cycleData |
|
264 | + */ |
|
265 | + protected function increaseOffset($cycleData) { |
|
266 | + $ldapConfig = new Configuration($cycleData['prefix']); |
|
267 | + $cycleData['offset'] += (int)$ldapConfig->ldapPagingSize; |
|
268 | + $this->setCycle($cycleData); |
|
269 | + } |
|
270 | + |
|
271 | + /** |
|
272 | + * determines the next configuration prefix based on the last one (if any) |
|
273 | + * |
|
274 | + * @param string|null $lastPrefix |
|
275 | + * @return string|null |
|
276 | + */ |
|
277 | + protected function getNextPrefix($lastPrefix) { |
|
278 | + $prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true); |
|
279 | + $noOfPrefixes = count($prefixes); |
|
280 | + if ($noOfPrefixes === 0) { |
|
281 | + return null; |
|
282 | + } |
|
283 | + $i = $lastPrefix === null ? false : array_search($lastPrefix, $prefixes, true); |
|
284 | + if ($i === false) { |
|
285 | + $i = -1; |
|
286 | + } else { |
|
287 | + $i++; |
|
288 | + } |
|
289 | + |
|
290 | + if (!isset($prefixes[$i])) { |
|
291 | + $i = 0; |
|
292 | + } |
|
293 | + return $prefixes[$i]; |
|
294 | + } |
|
295 | + |
|
296 | + /** |
|
297 | + * "fixes" DI |
|
298 | + * |
|
299 | + * @param array $argument |
|
300 | + */ |
|
301 | + public function setArgument($argument) { |
|
302 | + if (isset($argument['config'])) { |
|
303 | + $this->config = $argument['config']; |
|
304 | + } else { |
|
305 | + $this->config = \OC::$server->getConfig(); |
|
306 | + } |
|
307 | + |
|
308 | + if (isset($argument['helper'])) { |
|
309 | + $this->ldapHelper = $argument['helper']; |
|
310 | + } else { |
|
311 | + $this->ldapHelper = new Helper($this->config, \OC::$server->getDatabaseConnection()); |
|
312 | + } |
|
313 | + |
|
314 | + if (isset($argument['ldapWrapper'])) { |
|
315 | + $this->ldap = $argument['ldapWrapper']; |
|
316 | + } else { |
|
317 | + $this->ldap = new LDAP(); |
|
318 | + } |
|
319 | + |
|
320 | + if (isset($argument['avatarManager'])) { |
|
321 | + $this->avatarManager = $argument['avatarManager']; |
|
322 | + } else { |
|
323 | + $this->avatarManager = \OC::$server->getAvatarManager(); |
|
324 | + } |
|
325 | + |
|
326 | + if (isset($argument['dbc'])) { |
|
327 | + $this->dbc = $argument['dbc']; |
|
328 | + } else { |
|
329 | + $this->dbc = \OC::$server->getDatabaseConnection(); |
|
330 | + } |
|
331 | + |
|
332 | + if (isset($argument['ncUserManager'])) { |
|
333 | + $this->ncUserManager = $argument['ncUserManager']; |
|
334 | + } else { |
|
335 | + $this->ncUserManager = \OC::$server->getUserManager(); |
|
336 | + } |
|
337 | + |
|
338 | + if (isset($argument['notificationManager'])) { |
|
339 | + $this->notificationManager = $argument['notificationManager']; |
|
340 | + } else { |
|
341 | + $this->notificationManager = \OC::$server->getNotificationManager(); |
|
342 | + } |
|
343 | + |
|
344 | + if (isset($argument['userManager'])) { |
|
345 | + $this->userManager = $argument['userManager']; |
|
346 | + } |
|
347 | + |
|
348 | + if (isset($argument['mapper'])) { |
|
349 | + $this->mapper = $argument['mapper']; |
|
350 | + } else { |
|
351 | + $this->mapper = new UserMapping($this->dbc); |
|
352 | + } |
|
353 | + |
|
354 | + if (isset($argument['connectionFactory'])) { |
|
355 | + $this->connectionFactory = $argument['connectionFactory']; |
|
356 | + } else { |
|
357 | + $this->connectionFactory = new ConnectionFactory($this->ldap); |
|
358 | + } |
|
359 | + |
|
360 | + if (isset($argument['accessFactory'])) { |
|
361 | + $this->accessFactory = $argument['accessFactory']; |
|
362 | + } else { |
|
363 | + $this->accessFactory = new AccessFactory( |
|
364 | + $this->ldap, |
|
365 | + $this->userManager, |
|
366 | + $this->ldapHelper, |
|
367 | + $this->config, |
|
368 | + $this->ncUserManager |
|
369 | + ); |
|
370 | + } |
|
371 | + } |
|
372 | 372 | } |
@@ -43,1318 +43,1318 @@ |
||
43 | 43 | use OCP\ILogger; |
44 | 44 | |
45 | 45 | class Wizard extends LDAPUtility { |
46 | - /** @var \OCP\IL10N */ |
|
47 | - protected static $l; |
|
48 | - protected $access; |
|
49 | - protected $cr; |
|
50 | - protected $configuration; |
|
51 | - protected $result; |
|
52 | - protected $resultCache = []; |
|
53 | - |
|
54 | - public const LRESULT_PROCESSED_OK = 2; |
|
55 | - public const LRESULT_PROCESSED_INVALID = 3; |
|
56 | - public const LRESULT_PROCESSED_SKIP = 4; |
|
57 | - |
|
58 | - public const LFILTER_LOGIN = 2; |
|
59 | - public const LFILTER_USER_LIST = 3; |
|
60 | - public const LFILTER_GROUP_LIST = 4; |
|
61 | - |
|
62 | - public const LFILTER_MODE_ASSISTED = 2; |
|
63 | - public const LFILTER_MODE_RAW = 1; |
|
64 | - |
|
65 | - public const LDAP_NW_TIMEOUT = 4; |
|
66 | - |
|
67 | - /** |
|
68 | - * Constructor |
|
69 | - * @param Configuration $configuration an instance of Configuration |
|
70 | - * @param ILDAPWrapper $ldap an instance of ILDAPWrapper |
|
71 | - * @param Access $access |
|
72 | - */ |
|
73 | - public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) { |
|
74 | - parent::__construct($ldap); |
|
75 | - $this->configuration = $configuration; |
|
76 | - if (is_null(Wizard::$l)) { |
|
77 | - Wizard::$l = \OC::$server->getL10N('user_ldap'); |
|
78 | - } |
|
79 | - $this->access = $access; |
|
80 | - $this->result = new WizardResult(); |
|
81 | - } |
|
82 | - |
|
83 | - public function __destruct() { |
|
84 | - if ($this->result->hasChanges()) { |
|
85 | - $this->configuration->saveConfiguration(); |
|
86 | - } |
|
87 | - } |
|
88 | - |
|
89 | - /** |
|
90 | - * counts entries in the LDAP directory |
|
91 | - * |
|
92 | - * @param string $filter the LDAP search filter |
|
93 | - * @param string $type a string being either 'users' or 'groups'; |
|
94 | - * @return int |
|
95 | - * @throws \Exception |
|
96 | - */ |
|
97 | - public function countEntries(string $filter, string $type): int { |
|
98 | - $reqs = ['ldapHost', 'ldapPort', 'ldapBase']; |
|
99 | - if ($type === 'users') { |
|
100 | - $reqs[] = 'ldapUserFilter'; |
|
101 | - } |
|
102 | - if (!$this->checkRequirements($reqs)) { |
|
103 | - throw new \Exception('Requirements not met', 400); |
|
104 | - } |
|
105 | - |
|
106 | - $attr = ['dn']; // default |
|
107 | - $limit = 1001; |
|
108 | - if ($type === 'groups') { |
|
109 | - $result = $this->access->countGroups($filter, $attr, $limit); |
|
110 | - } elseif ($type === 'users') { |
|
111 | - $result = $this->access->countUsers($filter, $attr, $limit); |
|
112 | - } elseif ($type === 'objects') { |
|
113 | - $result = $this->access->countObjects($limit); |
|
114 | - } else { |
|
115 | - throw new \Exception('Internal error: Invalid object type', 500); |
|
116 | - } |
|
117 | - |
|
118 | - return (int)$result; |
|
119 | - } |
|
120 | - |
|
121 | - /** |
|
122 | - * formats the return value of a count operation to the string to be |
|
123 | - * inserted. |
|
124 | - * |
|
125 | - * @param int $count |
|
126 | - * @return string |
|
127 | - */ |
|
128 | - private function formatCountResult(int $count): string { |
|
129 | - if ($count > 1000) { |
|
130 | - return '> 1000'; |
|
131 | - } |
|
132 | - return (string)$count; |
|
133 | - } |
|
134 | - |
|
135 | - public function countGroups() { |
|
136 | - $filter = $this->configuration->ldapGroupFilter; |
|
137 | - |
|
138 | - if (empty($filter)) { |
|
139 | - $output = self::$l->n('%s group found', '%s groups found', 0, [0]); |
|
140 | - $this->result->addChange('ldap_group_count', $output); |
|
141 | - return $this->result; |
|
142 | - } |
|
143 | - |
|
144 | - try { |
|
145 | - $groupsTotal = $this->countEntries($filter, 'groups'); |
|
146 | - } catch (\Exception $e) { |
|
147 | - //400 can be ignored, 500 is forwarded |
|
148 | - if ($e->getCode() === 500) { |
|
149 | - throw $e; |
|
150 | - } |
|
151 | - return false; |
|
152 | - } |
|
153 | - $output = self::$l->n( |
|
154 | - '%s group found', |
|
155 | - '%s groups found', |
|
156 | - $groupsTotal, |
|
157 | - [$this->formatCountResult($groupsTotal)] |
|
158 | - ); |
|
159 | - $this->result->addChange('ldap_group_count', $output); |
|
160 | - return $this->result; |
|
161 | - } |
|
162 | - |
|
163 | - /** |
|
164 | - * @return WizardResult |
|
165 | - * @throws \Exception |
|
166 | - */ |
|
167 | - public function countUsers() { |
|
168 | - $filter = $this->access->getFilterForUserCount(); |
|
169 | - |
|
170 | - $usersTotal = $this->countEntries($filter, 'users'); |
|
171 | - $output = self::$l->n( |
|
172 | - '%s user found', |
|
173 | - '%s users found', |
|
174 | - $usersTotal, |
|
175 | - [$this->formatCountResult($usersTotal)] |
|
176 | - ); |
|
177 | - $this->result->addChange('ldap_user_count', $output); |
|
178 | - return $this->result; |
|
179 | - } |
|
180 | - |
|
181 | - /** |
|
182 | - * counts any objects in the currently set base dn |
|
183 | - * |
|
184 | - * @return WizardResult |
|
185 | - * @throws \Exception |
|
186 | - */ |
|
187 | - public function countInBaseDN() { |
|
188 | - // we don't need to provide a filter in this case |
|
189 | - $total = $this->countEntries('', 'objects'); |
|
190 | - if ($total === false) { |
|
191 | - throw new \Exception('invalid results received'); |
|
192 | - } |
|
193 | - $this->result->addChange('ldap_test_base', $total); |
|
194 | - return $this->result; |
|
195 | - } |
|
196 | - |
|
197 | - /** |
|
198 | - * counts users with a specified attribute |
|
199 | - * @param string $attr |
|
200 | - * @param bool $existsCheck |
|
201 | - * @return int|bool |
|
202 | - */ |
|
203 | - public function countUsersWithAttribute($attr, $existsCheck = false) { |
|
204 | - if (!$this->checkRequirements(['ldapHost', |
|
205 | - 'ldapPort', |
|
206 | - 'ldapBase', |
|
207 | - 'ldapUserFilter', |
|
208 | - ])) { |
|
209 | - return false; |
|
210 | - } |
|
211 | - |
|
212 | - $filter = $this->access->combineFilterWithAnd([ |
|
213 | - $this->configuration->ldapUserFilter, |
|
214 | - $attr . '=*' |
|
215 | - ]); |
|
216 | - |
|
217 | - $limit = ($existsCheck === false) ? null : 1; |
|
218 | - |
|
219 | - return $this->access->countUsers($filter, ['dn'], $limit); |
|
220 | - } |
|
221 | - |
|
222 | - /** |
|
223 | - * detects the display name attribute. If a setting is already present that |
|
224 | - * returns at least one hit, the detection will be canceled. |
|
225 | - * @return WizardResult|bool |
|
226 | - * @throws \Exception |
|
227 | - */ |
|
228 | - public function detectUserDisplayNameAttribute() { |
|
229 | - if (!$this->checkRequirements(['ldapHost', |
|
230 | - 'ldapPort', |
|
231 | - 'ldapBase', |
|
232 | - 'ldapUserFilter', |
|
233 | - ])) { |
|
234 | - return false; |
|
235 | - } |
|
236 | - |
|
237 | - $attr = $this->configuration->ldapUserDisplayName; |
|
238 | - if ($attr !== '' && $attr !== 'displayName') { |
|
239 | - // most likely not the default value with upper case N, |
|
240 | - // verify it still produces a result |
|
241 | - $count = (int)$this->countUsersWithAttribute($attr, true); |
|
242 | - if ($count > 0) { |
|
243 | - //no change, but we sent it back to make sure the user interface |
|
244 | - //is still correct, even if the ajax call was cancelled meanwhile |
|
245 | - $this->result->addChange('ldap_display_name', $attr); |
|
246 | - return $this->result; |
|
247 | - } |
|
248 | - } |
|
249 | - |
|
250 | - // first attribute that has at least one result wins |
|
251 | - $displayNameAttrs = ['displayname', 'cn']; |
|
252 | - foreach ($displayNameAttrs as $attr) { |
|
253 | - $count = (int)$this->countUsersWithAttribute($attr, true); |
|
254 | - |
|
255 | - if ($count > 0) { |
|
256 | - $this->applyFind('ldap_display_name', $attr); |
|
257 | - return $this->result; |
|
258 | - } |
|
259 | - } |
|
260 | - |
|
261 | - throw new \Exception(self::$l->t('Could not detect user display name attribute. Please specify it yourself in advanced LDAP settings.')); |
|
262 | - } |
|
263 | - |
|
264 | - /** |
|
265 | - * detects the most often used email attribute for users applying to the |
|
266 | - * user list filter. If a setting is already present that returns at least |
|
267 | - * one hit, the detection will be canceled. |
|
268 | - * @return WizardResult|bool |
|
269 | - */ |
|
270 | - public function detectEmailAttribute() { |
|
271 | - if (!$this->checkRequirements(['ldapHost', |
|
272 | - 'ldapPort', |
|
273 | - 'ldapBase', |
|
274 | - 'ldapUserFilter', |
|
275 | - ])) { |
|
276 | - return false; |
|
277 | - } |
|
278 | - |
|
279 | - $attr = $this->configuration->ldapEmailAttribute; |
|
280 | - if ($attr !== '') { |
|
281 | - $count = (int)$this->countUsersWithAttribute($attr, true); |
|
282 | - if ($count > 0) { |
|
283 | - return false; |
|
284 | - } |
|
285 | - $writeLog = true; |
|
286 | - } else { |
|
287 | - $writeLog = false; |
|
288 | - } |
|
289 | - |
|
290 | - $emailAttributes = ['mail', 'mailPrimaryAddress']; |
|
291 | - $winner = ''; |
|
292 | - $maxUsers = 0; |
|
293 | - foreach ($emailAttributes as $attr) { |
|
294 | - $count = $this->countUsersWithAttribute($attr); |
|
295 | - if ($count > $maxUsers) { |
|
296 | - $maxUsers = $count; |
|
297 | - $winner = $attr; |
|
298 | - } |
|
299 | - } |
|
300 | - |
|
301 | - if ($winner !== '') { |
|
302 | - $this->applyFind('ldap_email_attr', $winner); |
|
303 | - if ($writeLog) { |
|
304 | - \OCP\Util::writeLog('user_ldap', 'The mail attribute has ' . |
|
305 | - 'automatically been reset, because the original value ' . |
|
306 | - 'did not return any results.', ILogger::INFO); |
|
307 | - } |
|
308 | - } |
|
309 | - |
|
310 | - return $this->result; |
|
311 | - } |
|
312 | - |
|
313 | - /** |
|
314 | - * @return WizardResult |
|
315 | - * @throws \Exception |
|
316 | - */ |
|
317 | - public function determineAttributes() { |
|
318 | - if (!$this->checkRequirements(['ldapHost', |
|
319 | - 'ldapPort', |
|
320 | - 'ldapBase', |
|
321 | - 'ldapUserFilter', |
|
322 | - ])) { |
|
323 | - return false; |
|
324 | - } |
|
325 | - |
|
326 | - $attributes = $this->getUserAttributes(); |
|
327 | - |
|
328 | - natcasesort($attributes); |
|
329 | - $attributes = array_values($attributes); |
|
330 | - |
|
331 | - $this->result->addOptions('ldap_loginfilter_attributes', $attributes); |
|
332 | - |
|
333 | - $selected = $this->configuration->ldapLoginFilterAttributes; |
|
334 | - if (is_array($selected) && !empty($selected)) { |
|
335 | - $this->result->addChange('ldap_loginfilter_attributes', $selected); |
|
336 | - } |
|
337 | - |
|
338 | - return $this->result; |
|
339 | - } |
|
340 | - |
|
341 | - /** |
|
342 | - * detects the available LDAP attributes |
|
343 | - * @return array|false The instance's WizardResult instance |
|
344 | - * @throws \Exception |
|
345 | - */ |
|
346 | - private function getUserAttributes() { |
|
347 | - if (!$this->checkRequirements(['ldapHost', |
|
348 | - 'ldapPort', |
|
349 | - 'ldapBase', |
|
350 | - 'ldapUserFilter', |
|
351 | - ])) { |
|
352 | - return false; |
|
353 | - } |
|
354 | - $cr = $this->getConnection(); |
|
355 | - if (!$cr) { |
|
356 | - throw new \Exception('Could not connect to LDAP'); |
|
357 | - } |
|
358 | - |
|
359 | - $base = $this->configuration->ldapBase[0]; |
|
360 | - $filter = $this->configuration->ldapUserFilter; |
|
361 | - $rr = $this->ldap->search($cr, $base, $filter, [], 1, 1); |
|
362 | - if (!$this->ldap->isResource($rr)) { |
|
363 | - return false; |
|
364 | - } |
|
365 | - $er = $this->ldap->firstEntry($cr, $rr); |
|
366 | - $attributes = $this->ldap->getAttributes($cr, $er); |
|
367 | - $pureAttributes = []; |
|
368 | - for ($i = 0; $i < $attributes['count']; $i++) { |
|
369 | - $pureAttributes[] = $attributes[$i]; |
|
370 | - } |
|
371 | - |
|
372 | - return $pureAttributes; |
|
373 | - } |
|
374 | - |
|
375 | - /** |
|
376 | - * detects the available LDAP groups |
|
377 | - * @return WizardResult|false the instance's WizardResult instance |
|
378 | - */ |
|
379 | - public function determineGroupsForGroups() { |
|
380 | - return $this->determineGroups('ldap_groupfilter_groups', |
|
381 | - 'ldapGroupFilterGroups', |
|
382 | - false); |
|
383 | - } |
|
384 | - |
|
385 | - /** |
|
386 | - * detects the available LDAP groups |
|
387 | - * @return WizardResult|false the instance's WizardResult instance |
|
388 | - */ |
|
389 | - public function determineGroupsForUsers() { |
|
390 | - return $this->determineGroups('ldap_userfilter_groups', |
|
391 | - 'ldapUserFilterGroups'); |
|
392 | - } |
|
393 | - |
|
394 | - /** |
|
395 | - * detects the available LDAP groups |
|
396 | - * @param string $dbKey |
|
397 | - * @param string $confKey |
|
398 | - * @param bool $testMemberOf |
|
399 | - * @return WizardResult|false the instance's WizardResult instance |
|
400 | - * @throws \Exception |
|
401 | - */ |
|
402 | - private function determineGroups($dbKey, $confKey, $testMemberOf = true) { |
|
403 | - if (!$this->checkRequirements(['ldapHost', |
|
404 | - 'ldapPort', |
|
405 | - 'ldapBase', |
|
406 | - ])) { |
|
407 | - return false; |
|
408 | - } |
|
409 | - $cr = $this->getConnection(); |
|
410 | - if (!$cr) { |
|
411 | - throw new \Exception('Could not connect to LDAP'); |
|
412 | - } |
|
413 | - |
|
414 | - $this->fetchGroups($dbKey, $confKey); |
|
415 | - |
|
416 | - if ($testMemberOf) { |
|
417 | - $this->configuration->hasMemberOfFilterSupport = $this->testMemberOf(); |
|
418 | - $this->result->markChange(); |
|
419 | - if (!$this->configuration->hasMemberOfFilterSupport) { |
|
420 | - throw new \Exception('memberOf is not supported by the server'); |
|
421 | - } |
|
422 | - } |
|
423 | - |
|
424 | - return $this->result; |
|
425 | - } |
|
426 | - |
|
427 | - /** |
|
428 | - * fetches all groups from LDAP and adds them to the result object |
|
429 | - * |
|
430 | - * @param string $dbKey |
|
431 | - * @param string $confKey |
|
432 | - * @return array $groupEntries |
|
433 | - * @throws \Exception |
|
434 | - */ |
|
435 | - public function fetchGroups($dbKey, $confKey) { |
|
436 | - $obclasses = ['posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames', 'groupOfUniqueNames']; |
|
437 | - |
|
438 | - $filterParts = []; |
|
439 | - foreach ($obclasses as $obclass) { |
|
440 | - $filterParts[] = 'objectclass='.$obclass; |
|
441 | - } |
|
442 | - //we filter for everything |
|
443 | - //- that looks like a group and |
|
444 | - //- has the group display name set |
|
445 | - $filter = $this->access->combineFilterWithOr($filterParts); |
|
446 | - $filter = $this->access->combineFilterWithAnd([$filter, 'cn=*']); |
|
447 | - |
|
448 | - $groupNames = []; |
|
449 | - $groupEntries = []; |
|
450 | - $limit = 400; |
|
451 | - $offset = 0; |
|
452 | - do { |
|
453 | - // we need to request dn additionally here, otherwise memberOf |
|
454 | - // detection will fail later |
|
455 | - $result = $this->access->searchGroups($filter, ['cn', 'dn'], $limit, $offset); |
|
456 | - foreach ($result as $item) { |
|
457 | - if (!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) { |
|
458 | - // just in case - no issue known |
|
459 | - continue; |
|
460 | - } |
|
461 | - $groupNames[] = $item['cn'][0]; |
|
462 | - $groupEntries[] = $item; |
|
463 | - } |
|
464 | - $offset += $limit; |
|
465 | - } while ($this->access->hasMoreResults()); |
|
466 | - |
|
467 | - if (count($groupNames) > 0) { |
|
468 | - natsort($groupNames); |
|
469 | - $this->result->addOptions($dbKey, array_values($groupNames)); |
|
470 | - } else { |
|
471 | - throw new \Exception(self::$l->t('Could not find the desired feature')); |
|
472 | - } |
|
473 | - |
|
474 | - $setFeatures = $this->configuration->$confKey; |
|
475 | - if (is_array($setFeatures) && !empty($setFeatures)) { |
|
476 | - //something is already configured? pre-select it. |
|
477 | - $this->result->addChange($dbKey, $setFeatures); |
|
478 | - } |
|
479 | - return $groupEntries; |
|
480 | - } |
|
481 | - |
|
482 | - public function determineGroupMemberAssoc() { |
|
483 | - if (!$this->checkRequirements(['ldapHost', |
|
484 | - 'ldapPort', |
|
485 | - 'ldapGroupFilter', |
|
486 | - ])) { |
|
487 | - return false; |
|
488 | - } |
|
489 | - $attribute = $this->detectGroupMemberAssoc(); |
|
490 | - if ($attribute === false) { |
|
491 | - return false; |
|
492 | - } |
|
493 | - $this->configuration->setConfiguration(['ldapGroupMemberAssocAttr' => $attribute]); |
|
494 | - $this->result->addChange('ldap_group_member_assoc_attribute', $attribute); |
|
495 | - |
|
496 | - return $this->result; |
|
497 | - } |
|
498 | - |
|
499 | - /** |
|
500 | - * Detects the available object classes |
|
501 | - * @return WizardResult|false the instance's WizardResult instance |
|
502 | - * @throws \Exception |
|
503 | - */ |
|
504 | - public function determineGroupObjectClasses() { |
|
505 | - if (!$this->checkRequirements(['ldapHost', |
|
506 | - 'ldapPort', |
|
507 | - 'ldapBase', |
|
508 | - ])) { |
|
509 | - return false; |
|
510 | - } |
|
511 | - $cr = $this->getConnection(); |
|
512 | - if (!$cr) { |
|
513 | - throw new \Exception('Could not connect to LDAP'); |
|
514 | - } |
|
515 | - |
|
516 | - $obclasses = ['groupOfNames', 'groupOfUniqueNames', 'group', 'posixGroup', '*']; |
|
517 | - $this->determineFeature($obclasses, |
|
518 | - 'objectclass', |
|
519 | - 'ldap_groupfilter_objectclass', |
|
520 | - 'ldapGroupFilterObjectclass', |
|
521 | - false); |
|
522 | - |
|
523 | - return $this->result; |
|
524 | - } |
|
525 | - |
|
526 | - /** |
|
527 | - * detects the available object classes |
|
528 | - * @return WizardResult |
|
529 | - * @throws \Exception |
|
530 | - */ |
|
531 | - public function determineUserObjectClasses() { |
|
532 | - if (!$this->checkRequirements(['ldapHost', |
|
533 | - 'ldapPort', |
|
534 | - 'ldapBase', |
|
535 | - ])) { |
|
536 | - return false; |
|
537 | - } |
|
538 | - $cr = $this->getConnection(); |
|
539 | - if (!$cr) { |
|
540 | - throw new \Exception('Could not connect to LDAP'); |
|
541 | - } |
|
542 | - |
|
543 | - $obclasses = ['inetOrgPerson', 'person', 'organizationalPerson', |
|
544 | - 'user', 'posixAccount', '*']; |
|
545 | - $filter = $this->configuration->ldapUserFilter; |
|
546 | - //if filter is empty, it is probably the first time the wizard is called |
|
547 | - //then, apply suggestions. |
|
548 | - $this->determineFeature($obclasses, |
|
549 | - 'objectclass', |
|
550 | - 'ldap_userfilter_objectclass', |
|
551 | - 'ldapUserFilterObjectclass', |
|
552 | - empty($filter)); |
|
553 | - |
|
554 | - return $this->result; |
|
555 | - } |
|
556 | - |
|
557 | - /** |
|
558 | - * @return WizardResult|false |
|
559 | - * @throws \Exception |
|
560 | - */ |
|
561 | - public function getGroupFilter() { |
|
562 | - if (!$this->checkRequirements(['ldapHost', |
|
563 | - 'ldapPort', |
|
564 | - 'ldapBase', |
|
565 | - ])) { |
|
566 | - return false; |
|
567 | - } |
|
568 | - //make sure the use display name is set |
|
569 | - $displayName = $this->configuration->ldapGroupDisplayName; |
|
570 | - if ($displayName === '') { |
|
571 | - $d = $this->configuration->getDefaults(); |
|
572 | - $this->applyFind('ldap_group_display_name', |
|
573 | - $d['ldap_group_display_name']); |
|
574 | - } |
|
575 | - $filter = $this->composeLdapFilter(self::LFILTER_GROUP_LIST); |
|
576 | - |
|
577 | - $this->applyFind('ldap_group_filter', $filter); |
|
578 | - return $this->result; |
|
579 | - } |
|
580 | - |
|
581 | - /** |
|
582 | - * @return WizardResult|false |
|
583 | - * @throws \Exception |
|
584 | - */ |
|
585 | - public function getUserListFilter() { |
|
586 | - if (!$this->checkRequirements(['ldapHost', |
|
587 | - 'ldapPort', |
|
588 | - 'ldapBase', |
|
589 | - ])) { |
|
590 | - return false; |
|
591 | - } |
|
592 | - //make sure the use display name is set |
|
593 | - $displayName = $this->configuration->ldapUserDisplayName; |
|
594 | - if ($displayName === '') { |
|
595 | - $d = $this->configuration->getDefaults(); |
|
596 | - $this->applyFind('ldap_display_name', $d['ldap_display_name']); |
|
597 | - } |
|
598 | - $filter = $this->composeLdapFilter(self::LFILTER_USER_LIST); |
|
599 | - if (!$filter) { |
|
600 | - throw new \Exception('Cannot create filter'); |
|
601 | - } |
|
602 | - |
|
603 | - $this->applyFind('ldap_userlist_filter', $filter); |
|
604 | - return $this->result; |
|
605 | - } |
|
606 | - |
|
607 | - /** |
|
608 | - * @return bool|WizardResult |
|
609 | - * @throws \Exception |
|
610 | - */ |
|
611 | - public function getUserLoginFilter() { |
|
612 | - if (!$this->checkRequirements(['ldapHost', |
|
613 | - 'ldapPort', |
|
614 | - 'ldapBase', |
|
615 | - 'ldapUserFilter', |
|
616 | - ])) { |
|
617 | - return false; |
|
618 | - } |
|
619 | - |
|
620 | - $filter = $this->composeLdapFilter(self::LFILTER_LOGIN); |
|
621 | - if (!$filter) { |
|
622 | - throw new \Exception('Cannot create filter'); |
|
623 | - } |
|
624 | - |
|
625 | - $this->applyFind('ldap_login_filter', $filter); |
|
626 | - return $this->result; |
|
627 | - } |
|
628 | - |
|
629 | - /** |
|
630 | - * @return bool|WizardResult |
|
631 | - * @param string $loginName |
|
632 | - * @throws \Exception |
|
633 | - */ |
|
634 | - public function testLoginName($loginName) { |
|
635 | - if (!$this->checkRequirements(['ldapHost', |
|
636 | - 'ldapPort', |
|
637 | - 'ldapBase', |
|
638 | - 'ldapLoginFilter', |
|
639 | - ])) { |
|
640 | - return false; |
|
641 | - } |
|
642 | - |
|
643 | - $cr = $this->access->connection->getConnectionResource(); |
|
644 | - if (!$this->ldap->isResource($cr)) { |
|
645 | - throw new \Exception('connection error'); |
|
646 | - } |
|
647 | - |
|
648 | - if (mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8') |
|
649 | - === false) { |
|
650 | - throw new \Exception('missing placeholder'); |
|
651 | - } |
|
652 | - |
|
653 | - $users = $this->access->countUsersByLoginName($loginName); |
|
654 | - if ($this->ldap->errno($cr) !== 0) { |
|
655 | - throw new \Exception($this->ldap->error($cr)); |
|
656 | - } |
|
657 | - $filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter); |
|
658 | - $this->result->addChange('ldap_test_loginname', $users); |
|
659 | - $this->result->addChange('ldap_test_effective_filter', $filter); |
|
660 | - return $this->result; |
|
661 | - } |
|
662 | - |
|
663 | - /** |
|
664 | - * Tries to determine the port, requires given Host, User DN and Password |
|
665 | - * @return WizardResult|false WizardResult on success, false otherwise |
|
666 | - * @throws \Exception |
|
667 | - */ |
|
668 | - public function guessPortAndTLS() { |
|
669 | - if (!$this->checkRequirements(['ldapHost', |
|
670 | - ])) { |
|
671 | - return false; |
|
672 | - } |
|
673 | - $this->checkHost(); |
|
674 | - $portSettings = $this->getPortSettingsToTry(); |
|
675 | - |
|
676 | - if (!is_array($portSettings)) { |
|
677 | - throw new \Exception(print_r($portSettings, true)); |
|
678 | - } |
|
679 | - |
|
680 | - //proceed from the best configuration and return on first success |
|
681 | - foreach ($portSettings as $setting) { |
|
682 | - $p = $setting['port']; |
|
683 | - $t = $setting['tls']; |
|
684 | - \OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, ILogger::DEBUG); |
|
685 | - //connectAndBind may throw Exception, it needs to be catched by the |
|
686 | - //callee of this method |
|
687 | - |
|
688 | - try { |
|
689 | - $settingsFound = $this->connectAndBind($p, $t); |
|
690 | - } catch (\Exception $e) { |
|
691 | - // any reply other than -1 (= cannot connect) is already okay, |
|
692 | - // because then we found the server |
|
693 | - // unavailable startTLS returns -11 |
|
694 | - if ($e->getCode() > 0) { |
|
695 | - $settingsFound = true; |
|
696 | - } else { |
|
697 | - throw $e; |
|
698 | - } |
|
699 | - } |
|
700 | - |
|
701 | - if ($settingsFound === true) { |
|
702 | - $config = [ |
|
703 | - 'ldapPort' => $p, |
|
704 | - 'ldapTLS' => (int)$t |
|
705 | - ]; |
|
706 | - $this->configuration->setConfiguration($config); |
|
707 | - \OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, ILogger::DEBUG); |
|
708 | - $this->result->addChange('ldap_port', $p); |
|
709 | - return $this->result; |
|
710 | - } |
|
711 | - } |
|
712 | - |
|
713 | - //custom port, undetected (we do not brute force) |
|
714 | - return false; |
|
715 | - } |
|
716 | - |
|
717 | - /** |
|
718 | - * tries to determine a base dn from User DN or LDAP Host |
|
719 | - * @return WizardResult|false WizardResult on success, false otherwise |
|
720 | - */ |
|
721 | - public function guessBaseDN() { |
|
722 | - if (!$this->checkRequirements(['ldapHost', |
|
723 | - 'ldapPort', |
|
724 | - ])) { |
|
725 | - return false; |
|
726 | - } |
|
727 | - |
|
728 | - //check whether a DN is given in the agent name (99.9% of all cases) |
|
729 | - $base = null; |
|
730 | - $i = stripos($this->configuration->ldapAgentName, 'dc='); |
|
731 | - if ($i !== false) { |
|
732 | - $base = substr($this->configuration->ldapAgentName, $i); |
|
733 | - if ($this->testBaseDN($base)) { |
|
734 | - $this->applyFind('ldap_base', $base); |
|
735 | - return $this->result; |
|
736 | - } |
|
737 | - } |
|
738 | - |
|
739 | - //this did not help :( |
|
740 | - //Let's see whether we can parse the Host URL and convert the domain to |
|
741 | - //a base DN |
|
742 | - $helper = new Helper(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection()); |
|
743 | - $domain = $helper->getDomainFromURL($this->configuration->ldapHost); |
|
744 | - if (!$domain) { |
|
745 | - return false; |
|
746 | - } |
|
747 | - |
|
748 | - $dparts = explode('.', $domain); |
|
749 | - while (count($dparts) > 0) { |
|
750 | - $base2 = 'dc=' . implode(',dc=', $dparts); |
|
751 | - if ($base !== $base2 && $this->testBaseDN($base2)) { |
|
752 | - $this->applyFind('ldap_base', $base2); |
|
753 | - return $this->result; |
|
754 | - } |
|
755 | - array_shift($dparts); |
|
756 | - } |
|
757 | - |
|
758 | - return false; |
|
759 | - } |
|
760 | - |
|
761 | - /** |
|
762 | - * sets the found value for the configuration key in the WizardResult |
|
763 | - * as well as in the Configuration instance |
|
764 | - * @param string $key the configuration key |
|
765 | - * @param string $value the (detected) value |
|
766 | - * |
|
767 | - */ |
|
768 | - private function applyFind($key, $value) { |
|
769 | - $this->result->addChange($key, $value); |
|
770 | - $this->configuration->setConfiguration([$key => $value]); |
|
771 | - } |
|
772 | - |
|
773 | - /** |
|
774 | - * Checks, whether a port was entered in the Host configuration |
|
775 | - * field. In this case the port will be stripped off, but also stored as |
|
776 | - * setting. |
|
777 | - */ |
|
778 | - private function checkHost() { |
|
779 | - $host = $this->configuration->ldapHost; |
|
780 | - $hostInfo = parse_url($host); |
|
781 | - |
|
782 | - //removes Port from Host |
|
783 | - if (is_array($hostInfo) && isset($hostInfo['port'])) { |
|
784 | - $port = $hostInfo['port']; |
|
785 | - $host = str_replace(':'.$port, '', $host); |
|
786 | - $this->applyFind('ldap_host', $host); |
|
787 | - $this->applyFind('ldap_port', $port); |
|
788 | - } |
|
789 | - } |
|
790 | - |
|
791 | - /** |
|
792 | - * tries to detect the group member association attribute which is |
|
793 | - * one of 'uniqueMember', 'memberUid', 'member', 'gidNumber' |
|
794 | - * @return string|false, string with the attribute name, false on error |
|
795 | - * @throws \Exception |
|
796 | - */ |
|
797 | - private function detectGroupMemberAssoc() { |
|
798 | - $possibleAttrs = ['uniqueMember', 'memberUid', 'member', 'gidNumber', 'zimbraMailForwardingAddress']; |
|
799 | - $filter = $this->configuration->ldapGroupFilter; |
|
800 | - if (empty($filter)) { |
|
801 | - return false; |
|
802 | - } |
|
803 | - $cr = $this->getConnection(); |
|
804 | - if (!$cr) { |
|
805 | - throw new \Exception('Could not connect to LDAP'); |
|
806 | - } |
|
807 | - $base = $this->configuration->ldapBaseGroups[0] ?: $this->configuration->ldapBase[0]; |
|
808 | - $rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000); |
|
809 | - if (!$this->ldap->isResource($rr)) { |
|
810 | - return false; |
|
811 | - } |
|
812 | - $er = $this->ldap->firstEntry($cr, $rr); |
|
813 | - while (is_resource($er)) { |
|
814 | - $this->ldap->getDN($cr, $er); |
|
815 | - $attrs = $this->ldap->getAttributes($cr, $er); |
|
816 | - $result = []; |
|
817 | - $possibleAttrsCount = count($possibleAttrs); |
|
818 | - for ($i = 0; $i < $possibleAttrsCount; $i++) { |
|
819 | - if (isset($attrs[$possibleAttrs[$i]])) { |
|
820 | - $result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count']; |
|
821 | - } |
|
822 | - } |
|
823 | - if (!empty($result)) { |
|
824 | - natsort($result); |
|
825 | - return key($result); |
|
826 | - } |
|
827 | - |
|
828 | - $er = $this->ldap->nextEntry($cr, $er); |
|
829 | - } |
|
830 | - |
|
831 | - return false; |
|
832 | - } |
|
833 | - |
|
834 | - /** |
|
835 | - * Checks whether for a given BaseDN results will be returned |
|
836 | - * @param string $base the BaseDN to test |
|
837 | - * @return bool true on success, false otherwise |
|
838 | - * @throws \Exception |
|
839 | - */ |
|
840 | - private function testBaseDN($base) { |
|
841 | - $cr = $this->getConnection(); |
|
842 | - if (!$cr) { |
|
843 | - throw new \Exception('Could not connect to LDAP'); |
|
844 | - } |
|
845 | - |
|
846 | - //base is there, let's validate it. If we search for anything, we should |
|
847 | - //get a result set > 0 on a proper base |
|
848 | - $rr = $this->ldap->search($cr, $base, 'objectClass=*', ['dn'], 0, 1); |
|
849 | - if (!$this->ldap->isResource($rr)) { |
|
850 | - $errorNo = $this->ldap->errno($cr); |
|
851 | - $errorMsg = $this->ldap->error($cr); |
|
852 | - \OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base. |
|
853 | - ' Error '.$errorNo.': '.$errorMsg, ILogger::INFO); |
|
854 | - return false; |
|
855 | - } |
|
856 | - $entries = $this->ldap->countEntries($cr, $rr); |
|
857 | - return ($entries !== false) && ($entries > 0); |
|
858 | - } |
|
859 | - |
|
860 | - /** |
|
861 | - * Checks whether the server supports memberOf in LDAP Filter. |
|
862 | - * Note: at least in OpenLDAP, availability of memberOf is dependent on |
|
863 | - * a configured objectClass. I.e. not necessarily for all available groups |
|
864 | - * memberOf does work. |
|
865 | - * |
|
866 | - * @return bool true if it does, false otherwise |
|
867 | - * @throws \Exception |
|
868 | - */ |
|
869 | - private function testMemberOf() { |
|
870 | - $cr = $this->getConnection(); |
|
871 | - if (!$cr) { |
|
872 | - throw new \Exception('Could not connect to LDAP'); |
|
873 | - } |
|
874 | - $result = $this->access->countUsers('memberOf=*', ['memberOf'], 1); |
|
875 | - if (is_int($result) && $result > 0) { |
|
876 | - return true; |
|
877 | - } |
|
878 | - return false; |
|
879 | - } |
|
880 | - |
|
881 | - /** |
|
882 | - * creates an LDAP Filter from given configuration |
|
883 | - * @param integer $filterType int, for which use case the filter shall be created |
|
884 | - * can be any of self::LFILTER_USER_LIST, self::LFILTER_LOGIN or |
|
885 | - * self::LFILTER_GROUP_LIST |
|
886 | - * @return string|false string with the filter on success, false otherwise |
|
887 | - * @throws \Exception |
|
888 | - */ |
|
889 | - private function composeLdapFilter($filterType) { |
|
890 | - $filter = ''; |
|
891 | - $parts = 0; |
|
892 | - switch ($filterType) { |
|
893 | - case self::LFILTER_USER_LIST: |
|
894 | - $objcs = $this->configuration->ldapUserFilterObjectclass; |
|
895 | - //glue objectclasses |
|
896 | - if (is_array($objcs) && count($objcs) > 0) { |
|
897 | - $filter .= '(|'; |
|
898 | - foreach ($objcs as $objc) { |
|
899 | - $filter .= '(objectclass=' . $objc . ')'; |
|
900 | - } |
|
901 | - $filter .= ')'; |
|
902 | - $parts++; |
|
903 | - } |
|
904 | - //glue group memberships |
|
905 | - if ($this->configuration->hasMemberOfFilterSupport) { |
|
906 | - $cns = $this->configuration->ldapUserFilterGroups; |
|
907 | - if (is_array($cns) && count($cns) > 0) { |
|
908 | - $filter .= '(|'; |
|
909 | - $cr = $this->getConnection(); |
|
910 | - if (!$cr) { |
|
911 | - throw new \Exception('Could not connect to LDAP'); |
|
912 | - } |
|
913 | - $base = $this->configuration->ldapBase[0]; |
|
914 | - foreach ($cns as $cn) { |
|
915 | - $rr = $this->ldap->search($cr, $base, 'cn=' . $cn, ['dn', 'primaryGroupToken']); |
|
916 | - if (!$this->ldap->isResource($rr)) { |
|
917 | - continue; |
|
918 | - } |
|
919 | - $er = $this->ldap->firstEntry($cr, $rr); |
|
920 | - $attrs = $this->ldap->getAttributes($cr, $er); |
|
921 | - $dn = $this->ldap->getDN($cr, $er); |
|
922 | - if ($dn === false || $dn === '') { |
|
923 | - continue; |
|
924 | - } |
|
925 | - $filterPart = '(memberof=' . $dn . ')'; |
|
926 | - if (isset($attrs['primaryGroupToken'])) { |
|
927 | - $pgt = $attrs['primaryGroupToken'][0]; |
|
928 | - $primaryFilterPart = '(primaryGroupID=' . $pgt .')'; |
|
929 | - $filterPart = '(|' . $filterPart . $primaryFilterPart . ')'; |
|
930 | - } |
|
931 | - $filter .= $filterPart; |
|
932 | - } |
|
933 | - $filter .= ')'; |
|
934 | - } |
|
935 | - $parts++; |
|
936 | - } |
|
937 | - //wrap parts in AND condition |
|
938 | - if ($parts > 1) { |
|
939 | - $filter = '(&' . $filter . ')'; |
|
940 | - } |
|
941 | - if ($filter === '') { |
|
942 | - $filter = '(objectclass=*)'; |
|
943 | - } |
|
944 | - break; |
|
945 | - |
|
946 | - case self::LFILTER_GROUP_LIST: |
|
947 | - $objcs = $this->configuration->ldapGroupFilterObjectclass; |
|
948 | - //glue objectclasses |
|
949 | - if (is_array($objcs) && count($objcs) > 0) { |
|
950 | - $filter .= '(|'; |
|
951 | - foreach ($objcs as $objc) { |
|
952 | - $filter .= '(objectclass=' . $objc . ')'; |
|
953 | - } |
|
954 | - $filter .= ')'; |
|
955 | - $parts++; |
|
956 | - } |
|
957 | - //glue group memberships |
|
958 | - $cns = $this->configuration->ldapGroupFilterGroups; |
|
959 | - if (is_array($cns) && count($cns) > 0) { |
|
960 | - $filter .= '(|'; |
|
961 | - foreach ($cns as $cn) { |
|
962 | - $filter .= '(cn=' . $cn . ')'; |
|
963 | - } |
|
964 | - $filter .= ')'; |
|
965 | - } |
|
966 | - $parts++; |
|
967 | - //wrap parts in AND condition |
|
968 | - if ($parts > 1) { |
|
969 | - $filter = '(&' . $filter . ')'; |
|
970 | - } |
|
971 | - break; |
|
972 | - |
|
973 | - case self::LFILTER_LOGIN: |
|
974 | - $ulf = $this->configuration->ldapUserFilter; |
|
975 | - $loginpart = '=%uid'; |
|
976 | - $filterUsername = ''; |
|
977 | - $userAttributes = $this->getUserAttributes(); |
|
978 | - $userAttributes = array_change_key_case(array_flip($userAttributes)); |
|
979 | - $parts = 0; |
|
980 | - |
|
981 | - if ($this->configuration->ldapLoginFilterUsername === '1') { |
|
982 | - $attr = ''; |
|
983 | - if (isset($userAttributes['uid'])) { |
|
984 | - $attr = 'uid'; |
|
985 | - } elseif (isset($userAttributes['samaccountname'])) { |
|
986 | - $attr = 'samaccountname'; |
|
987 | - } elseif (isset($userAttributes['cn'])) { |
|
988 | - //fallback |
|
989 | - $attr = 'cn'; |
|
990 | - } |
|
991 | - if ($attr !== '') { |
|
992 | - $filterUsername = '(' . $attr . $loginpart . ')'; |
|
993 | - $parts++; |
|
994 | - } |
|
995 | - } |
|
996 | - |
|
997 | - $filterEmail = ''; |
|
998 | - if ($this->configuration->ldapLoginFilterEmail === '1') { |
|
999 | - $filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))'; |
|
1000 | - $parts++; |
|
1001 | - } |
|
1002 | - |
|
1003 | - $filterAttributes = ''; |
|
1004 | - $attrsToFilter = $this->configuration->ldapLoginFilterAttributes; |
|
1005 | - if (is_array($attrsToFilter) && count($attrsToFilter) > 0) { |
|
1006 | - $filterAttributes = '(|'; |
|
1007 | - foreach ($attrsToFilter as $attribute) { |
|
1008 | - $filterAttributes .= '(' . $attribute . $loginpart . ')'; |
|
1009 | - } |
|
1010 | - $filterAttributes .= ')'; |
|
1011 | - $parts++; |
|
1012 | - } |
|
1013 | - |
|
1014 | - $filterLogin = ''; |
|
1015 | - if ($parts > 1) { |
|
1016 | - $filterLogin = '(|'; |
|
1017 | - } |
|
1018 | - $filterLogin .= $filterUsername; |
|
1019 | - $filterLogin .= $filterEmail; |
|
1020 | - $filterLogin .= $filterAttributes; |
|
1021 | - if ($parts > 1) { |
|
1022 | - $filterLogin .= ')'; |
|
1023 | - } |
|
1024 | - |
|
1025 | - $filter = '(&'.$ulf.$filterLogin.')'; |
|
1026 | - break; |
|
1027 | - } |
|
1028 | - |
|
1029 | - \OCP\Util::writeLog('user_ldap', 'Wiz: Final filter '.$filter, ILogger::DEBUG); |
|
1030 | - |
|
1031 | - return $filter; |
|
1032 | - } |
|
1033 | - |
|
1034 | - /** |
|
1035 | - * Connects and Binds to an LDAP Server |
|
1036 | - * |
|
1037 | - * @param int $port the port to connect with |
|
1038 | - * @param bool $tls whether startTLS is to be used |
|
1039 | - * @return bool |
|
1040 | - * @throws \Exception |
|
1041 | - */ |
|
1042 | - private function connectAndBind($port, $tls) { |
|
1043 | - //connect, does not really trigger any server communication |
|
1044 | - $host = $this->configuration->ldapHost; |
|
1045 | - $hostInfo = parse_url($host); |
|
1046 | - if (!$hostInfo) { |
|
1047 | - throw new \Exception(self::$l->t('Invalid Host')); |
|
1048 | - } |
|
1049 | - \OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', ILogger::DEBUG); |
|
1050 | - $cr = $this->ldap->connect($host, $port); |
|
1051 | - if (!is_resource($cr)) { |
|
1052 | - throw new \Exception(self::$l->t('Invalid Host')); |
|
1053 | - } |
|
1054 | - |
|
1055 | - //set LDAP options |
|
1056 | - $this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3); |
|
1057 | - $this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0); |
|
1058 | - $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT); |
|
1059 | - |
|
1060 | - try { |
|
1061 | - if ($tls) { |
|
1062 | - $isTlsWorking = @$this->ldap->startTls($cr); |
|
1063 | - if (!$isTlsWorking) { |
|
1064 | - return false; |
|
1065 | - } |
|
1066 | - } |
|
1067 | - |
|
1068 | - \OCP\Util::writeLog('user_ldap', 'Wiz: Attemping to Bind ', ILogger::DEBUG); |
|
1069 | - //interesting part: do the bind! |
|
1070 | - $login = $this->ldap->bind($cr, |
|
1071 | - $this->configuration->ldapAgentName, |
|
1072 | - $this->configuration->ldapAgentPassword |
|
1073 | - ); |
|
1074 | - $errNo = $this->ldap->errno($cr); |
|
1075 | - $error = ldap_error($cr); |
|
1076 | - $this->ldap->unbind($cr); |
|
1077 | - } catch (ServerNotAvailableException $e) { |
|
1078 | - return false; |
|
1079 | - } |
|
1080 | - |
|
1081 | - if ($login === true) { |
|
1082 | - $this->ldap->unbind($cr); |
|
1083 | - \OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . (int)$tls, ILogger::DEBUG); |
|
1084 | - return true; |
|
1085 | - } |
|
1086 | - |
|
1087 | - if ($errNo === -1) { |
|
1088 | - //host, port or TLS wrong |
|
1089 | - return false; |
|
1090 | - } |
|
1091 | - throw new \Exception($error, $errNo); |
|
1092 | - } |
|
1093 | - |
|
1094 | - /** |
|
1095 | - * checks whether a valid combination of agent and password has been |
|
1096 | - * provided (either two values or nothing for anonymous connect) |
|
1097 | - * @return bool, true if everything is fine, false otherwise |
|
1098 | - */ |
|
1099 | - private function checkAgentRequirements() { |
|
1100 | - $agent = $this->configuration->ldapAgentName; |
|
1101 | - $pwd = $this->configuration->ldapAgentPassword; |
|
1102 | - |
|
1103 | - return |
|
1104 | - ($agent !== '' && $pwd !== '') |
|
1105 | - || ($agent === '' && $pwd === '') |
|
1106 | - ; |
|
1107 | - } |
|
1108 | - |
|
1109 | - /** |
|
1110 | - * @param array $reqs |
|
1111 | - * @return bool |
|
1112 | - */ |
|
1113 | - private function checkRequirements($reqs) { |
|
1114 | - $this->checkAgentRequirements(); |
|
1115 | - foreach ($reqs as $option) { |
|
1116 | - $value = $this->configuration->$option; |
|
1117 | - if (empty($value)) { |
|
1118 | - return false; |
|
1119 | - } |
|
1120 | - } |
|
1121 | - return true; |
|
1122 | - } |
|
1123 | - |
|
1124 | - /** |
|
1125 | - * does a cumulativeSearch on LDAP to get different values of a |
|
1126 | - * specified attribute |
|
1127 | - * @param string[] $filters array, the filters that shall be used in the search |
|
1128 | - * @param string $attr the attribute of which a list of values shall be returned |
|
1129 | - * @param int $dnReadLimit the amount of how many DNs should be analyzed. |
|
1130 | - * The lower, the faster |
|
1131 | - * @param string $maxF string. if not null, this variable will have the filter that |
|
1132 | - * yields most result entries |
|
1133 | - * @return array|false an array with the values on success, false otherwise |
|
1134 | - */ |
|
1135 | - public function cumulativeSearchOnAttribute($filters, $attr, $dnReadLimit = 3, &$maxF = null) { |
|
1136 | - $dnRead = []; |
|
1137 | - $foundItems = []; |
|
1138 | - $maxEntries = 0; |
|
1139 | - if (!is_array($this->configuration->ldapBase) |
|
1140 | - || !isset($this->configuration->ldapBase[0])) { |
|
1141 | - return false; |
|
1142 | - } |
|
1143 | - $base = $this->configuration->ldapBase[0]; |
|
1144 | - $cr = $this->getConnection(); |
|
1145 | - if (!$this->ldap->isResource($cr)) { |
|
1146 | - return false; |
|
1147 | - } |
|
1148 | - $lastFilter = null; |
|
1149 | - if (isset($filters[count($filters) - 1])) { |
|
1150 | - $lastFilter = $filters[count($filters) - 1]; |
|
1151 | - } |
|
1152 | - foreach ($filters as $filter) { |
|
1153 | - if ($lastFilter === $filter && count($foundItems) > 0) { |
|
1154 | - //skip when the filter is a wildcard and results were found |
|
1155 | - continue; |
|
1156 | - } |
|
1157 | - // 20k limit for performance and reason |
|
1158 | - $rr = $this->ldap->search($cr, $base, $filter, [$attr], 0, 20000); |
|
1159 | - if (!$this->ldap->isResource($rr)) { |
|
1160 | - continue; |
|
1161 | - } |
|
1162 | - $entries = $this->ldap->countEntries($cr, $rr); |
|
1163 | - $getEntryFunc = 'firstEntry'; |
|
1164 | - if (($entries !== false) && ($entries > 0)) { |
|
1165 | - if (!is_null($maxF) && $entries > $maxEntries) { |
|
1166 | - $maxEntries = $entries; |
|
1167 | - $maxF = $filter; |
|
1168 | - } |
|
1169 | - $dnReadCount = 0; |
|
1170 | - do { |
|
1171 | - $entry = $this->ldap->$getEntryFunc($cr, $rr); |
|
1172 | - $getEntryFunc = 'nextEntry'; |
|
1173 | - if (!$this->ldap->isResource($entry)) { |
|
1174 | - continue 2; |
|
1175 | - } |
|
1176 | - $rr = $entry; //will be expected by nextEntry next round |
|
1177 | - $attributes = $this->ldap->getAttributes($cr, $entry); |
|
1178 | - $dn = $this->ldap->getDN($cr, $entry); |
|
1179 | - if ($dn === false || in_array($dn, $dnRead)) { |
|
1180 | - continue; |
|
1181 | - } |
|
1182 | - $newItems = []; |
|
1183 | - $state = $this->getAttributeValuesFromEntry($attributes, |
|
1184 | - $attr, |
|
1185 | - $newItems); |
|
1186 | - $dnReadCount++; |
|
1187 | - $foundItems = array_merge($foundItems, $newItems); |
|
1188 | - $this->resultCache[$dn][$attr] = $newItems; |
|
1189 | - $dnRead[] = $dn; |
|
1190 | - } while (($state === self::LRESULT_PROCESSED_SKIP |
|
1191 | - || $this->ldap->isResource($entry)) |
|
1192 | - && ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit)); |
|
1193 | - } |
|
1194 | - } |
|
1195 | - |
|
1196 | - return array_unique($foundItems); |
|
1197 | - } |
|
1198 | - |
|
1199 | - /** |
|
1200 | - * determines if and which $attr are available on the LDAP server |
|
1201 | - * @param string[] $objectclasses the objectclasses to use as search filter |
|
1202 | - * @param string $attr the attribute to look for |
|
1203 | - * @param string $dbkey the dbkey of the setting the feature is connected to |
|
1204 | - * @param string $confkey the confkey counterpart for the $dbkey as used in the |
|
1205 | - * Configuration class |
|
1206 | - * @param bool $po whether the objectClass with most result entries |
|
1207 | - * shall be pre-selected via the result |
|
1208 | - * @return array|false list of found items. |
|
1209 | - * @throws \Exception |
|
1210 | - */ |
|
1211 | - private function determineFeature($objectclasses, $attr, $dbkey, $confkey, $po = false) { |
|
1212 | - $cr = $this->getConnection(); |
|
1213 | - if (!$cr) { |
|
1214 | - throw new \Exception('Could not connect to LDAP'); |
|
1215 | - } |
|
1216 | - $p = 'objectclass='; |
|
1217 | - foreach ($objectclasses as $key => $value) { |
|
1218 | - $objectclasses[$key] = $p.$value; |
|
1219 | - } |
|
1220 | - $maxEntryObjC = ''; |
|
1221 | - |
|
1222 | - //how deep to dig? |
|
1223 | - //When looking for objectclasses, testing few entries is sufficient, |
|
1224 | - $dig = 3; |
|
1225 | - |
|
1226 | - $availableFeatures = |
|
1227 | - $this->cumulativeSearchOnAttribute($objectclasses, $attr, |
|
1228 | - $dig, $maxEntryObjC); |
|
1229 | - if (is_array($availableFeatures) |
|
1230 | - && count($availableFeatures) > 0) { |
|
1231 | - natcasesort($availableFeatures); |
|
1232 | - //natcasesort keeps indices, but we must get rid of them for proper |
|
1233 | - //sorting in the web UI. Therefore: array_values |
|
1234 | - $this->result->addOptions($dbkey, array_values($availableFeatures)); |
|
1235 | - } else { |
|
1236 | - throw new \Exception(self::$l->t('Could not find the desired feature')); |
|
1237 | - } |
|
1238 | - |
|
1239 | - $setFeatures = $this->configuration->$confkey; |
|
1240 | - if (is_array($setFeatures) && !empty($setFeatures)) { |
|
1241 | - //something is already configured? pre-select it. |
|
1242 | - $this->result->addChange($dbkey, $setFeatures); |
|
1243 | - } elseif ($po && $maxEntryObjC !== '') { |
|
1244 | - //pre-select objectclass with most result entries |
|
1245 | - $maxEntryObjC = str_replace($p, '', $maxEntryObjC); |
|
1246 | - $this->applyFind($dbkey, $maxEntryObjC); |
|
1247 | - $this->result->addChange($dbkey, $maxEntryObjC); |
|
1248 | - } |
|
1249 | - |
|
1250 | - return $availableFeatures; |
|
1251 | - } |
|
1252 | - |
|
1253 | - /** |
|
1254 | - * appends a list of values fr |
|
1255 | - * @param resource $result the return value from ldap_get_attributes |
|
1256 | - * @param string $attribute the attribute values to look for |
|
1257 | - * @param array &$known new values will be appended here |
|
1258 | - * @return int, state on of the class constants LRESULT_PROCESSED_OK, |
|
1259 | - * LRESULT_PROCESSED_INVALID or LRESULT_PROCESSED_SKIP |
|
1260 | - */ |
|
1261 | - private function getAttributeValuesFromEntry($result, $attribute, &$known) { |
|
1262 | - if (!is_array($result) |
|
1263 | - || !isset($result['count']) |
|
1264 | - || !$result['count'] > 0) { |
|
1265 | - return self::LRESULT_PROCESSED_INVALID; |
|
1266 | - } |
|
1267 | - |
|
1268 | - // strtolower on all keys for proper comparison |
|
1269 | - $result = \OCP\Util::mb_array_change_key_case($result); |
|
1270 | - $attribute = strtolower($attribute); |
|
1271 | - if (isset($result[$attribute])) { |
|
1272 | - foreach ($result[$attribute] as $key => $val) { |
|
1273 | - if ($key === 'count') { |
|
1274 | - continue; |
|
1275 | - } |
|
1276 | - if (!in_array($val, $known)) { |
|
1277 | - $known[] = $val; |
|
1278 | - } |
|
1279 | - } |
|
1280 | - return self::LRESULT_PROCESSED_OK; |
|
1281 | - } else { |
|
1282 | - return self::LRESULT_PROCESSED_SKIP; |
|
1283 | - } |
|
1284 | - } |
|
1285 | - |
|
1286 | - /** |
|
1287 | - * @return bool|mixed |
|
1288 | - */ |
|
1289 | - private function getConnection() { |
|
1290 | - if (!is_null($this->cr)) { |
|
1291 | - return $this->cr; |
|
1292 | - } |
|
1293 | - |
|
1294 | - $cr = $this->ldap->connect( |
|
1295 | - $this->configuration->ldapHost, |
|
1296 | - $this->configuration->ldapPort |
|
1297 | - ); |
|
1298 | - |
|
1299 | - $this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3); |
|
1300 | - $this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0); |
|
1301 | - $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT); |
|
1302 | - if ($this->configuration->ldapTLS === 1) { |
|
1303 | - $this->ldap->startTls($cr); |
|
1304 | - } |
|
1305 | - |
|
1306 | - $lo = @$this->ldap->bind($cr, |
|
1307 | - $this->configuration->ldapAgentName, |
|
1308 | - $this->configuration->ldapAgentPassword); |
|
1309 | - if ($lo === true) { |
|
1310 | - $this->$cr = $cr; |
|
1311 | - return $cr; |
|
1312 | - } |
|
1313 | - |
|
1314 | - return false; |
|
1315 | - } |
|
1316 | - |
|
1317 | - /** |
|
1318 | - * @return array |
|
1319 | - */ |
|
1320 | - private function getDefaultLdapPortSettings() { |
|
1321 | - static $settings = [ |
|
1322 | - ['port' => 7636, 'tls' => false], |
|
1323 | - ['port' => 636, 'tls' => false], |
|
1324 | - ['port' => 7389, 'tls' => true], |
|
1325 | - ['port' => 389, 'tls' => true], |
|
1326 | - ['port' => 7389, 'tls' => false], |
|
1327 | - ['port' => 389, 'tls' => false], |
|
1328 | - ]; |
|
1329 | - return $settings; |
|
1330 | - } |
|
1331 | - |
|
1332 | - /** |
|
1333 | - * @return array |
|
1334 | - */ |
|
1335 | - private function getPortSettingsToTry() { |
|
1336 | - //389 ← LDAP / Unencrypted or StartTLS |
|
1337 | - //636 ← LDAPS / SSL |
|
1338 | - //7xxx ← UCS. need to be checked first, because both ports may be open |
|
1339 | - $host = $this->configuration->ldapHost; |
|
1340 | - $port = (int)$this->configuration->ldapPort; |
|
1341 | - $portSettings = []; |
|
1342 | - |
|
1343 | - //In case the port is already provided, we will check this first |
|
1344 | - if ($port > 0) { |
|
1345 | - $hostInfo = parse_url($host); |
|
1346 | - if (!(is_array($hostInfo) |
|
1347 | - && isset($hostInfo['scheme']) |
|
1348 | - && stripos($hostInfo['scheme'], 'ldaps') !== false)) { |
|
1349 | - $portSettings[] = ['port' => $port, 'tls' => true]; |
|
1350 | - } |
|
1351 | - $portSettings[] = ['port' => $port, 'tls' => false]; |
|
1352 | - } |
|
1353 | - |
|
1354 | - //default ports |
|
1355 | - $portSettings = array_merge($portSettings, |
|
1356 | - $this->getDefaultLdapPortSettings()); |
|
1357 | - |
|
1358 | - return $portSettings; |
|
1359 | - } |
|
46 | + /** @var \OCP\IL10N */ |
|
47 | + protected static $l; |
|
48 | + protected $access; |
|
49 | + protected $cr; |
|
50 | + protected $configuration; |
|
51 | + protected $result; |
|
52 | + protected $resultCache = []; |
|
53 | + |
|
54 | + public const LRESULT_PROCESSED_OK = 2; |
|
55 | + public const LRESULT_PROCESSED_INVALID = 3; |
|
56 | + public const LRESULT_PROCESSED_SKIP = 4; |
|
57 | + |
|
58 | + public const LFILTER_LOGIN = 2; |
|
59 | + public const LFILTER_USER_LIST = 3; |
|
60 | + public const LFILTER_GROUP_LIST = 4; |
|
61 | + |
|
62 | + public const LFILTER_MODE_ASSISTED = 2; |
|
63 | + public const LFILTER_MODE_RAW = 1; |
|
64 | + |
|
65 | + public const LDAP_NW_TIMEOUT = 4; |
|
66 | + |
|
67 | + /** |
|
68 | + * Constructor |
|
69 | + * @param Configuration $configuration an instance of Configuration |
|
70 | + * @param ILDAPWrapper $ldap an instance of ILDAPWrapper |
|
71 | + * @param Access $access |
|
72 | + */ |
|
73 | + public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) { |
|
74 | + parent::__construct($ldap); |
|
75 | + $this->configuration = $configuration; |
|
76 | + if (is_null(Wizard::$l)) { |
|
77 | + Wizard::$l = \OC::$server->getL10N('user_ldap'); |
|
78 | + } |
|
79 | + $this->access = $access; |
|
80 | + $this->result = new WizardResult(); |
|
81 | + } |
|
82 | + |
|
83 | + public function __destruct() { |
|
84 | + if ($this->result->hasChanges()) { |
|
85 | + $this->configuration->saveConfiguration(); |
|
86 | + } |
|
87 | + } |
|
88 | + |
|
89 | + /** |
|
90 | + * counts entries in the LDAP directory |
|
91 | + * |
|
92 | + * @param string $filter the LDAP search filter |
|
93 | + * @param string $type a string being either 'users' or 'groups'; |
|
94 | + * @return int |
|
95 | + * @throws \Exception |
|
96 | + */ |
|
97 | + public function countEntries(string $filter, string $type): int { |
|
98 | + $reqs = ['ldapHost', 'ldapPort', 'ldapBase']; |
|
99 | + if ($type === 'users') { |
|
100 | + $reqs[] = 'ldapUserFilter'; |
|
101 | + } |
|
102 | + if (!$this->checkRequirements($reqs)) { |
|
103 | + throw new \Exception('Requirements not met', 400); |
|
104 | + } |
|
105 | + |
|
106 | + $attr = ['dn']; // default |
|
107 | + $limit = 1001; |
|
108 | + if ($type === 'groups') { |
|
109 | + $result = $this->access->countGroups($filter, $attr, $limit); |
|
110 | + } elseif ($type === 'users') { |
|
111 | + $result = $this->access->countUsers($filter, $attr, $limit); |
|
112 | + } elseif ($type === 'objects') { |
|
113 | + $result = $this->access->countObjects($limit); |
|
114 | + } else { |
|
115 | + throw new \Exception('Internal error: Invalid object type', 500); |
|
116 | + } |
|
117 | + |
|
118 | + return (int)$result; |
|
119 | + } |
|
120 | + |
|
121 | + /** |
|
122 | + * formats the return value of a count operation to the string to be |
|
123 | + * inserted. |
|
124 | + * |
|
125 | + * @param int $count |
|
126 | + * @return string |
|
127 | + */ |
|
128 | + private function formatCountResult(int $count): string { |
|
129 | + if ($count > 1000) { |
|
130 | + return '> 1000'; |
|
131 | + } |
|
132 | + return (string)$count; |
|
133 | + } |
|
134 | + |
|
135 | + public function countGroups() { |
|
136 | + $filter = $this->configuration->ldapGroupFilter; |
|
137 | + |
|
138 | + if (empty($filter)) { |
|
139 | + $output = self::$l->n('%s group found', '%s groups found', 0, [0]); |
|
140 | + $this->result->addChange('ldap_group_count', $output); |
|
141 | + return $this->result; |
|
142 | + } |
|
143 | + |
|
144 | + try { |
|
145 | + $groupsTotal = $this->countEntries($filter, 'groups'); |
|
146 | + } catch (\Exception $e) { |
|
147 | + //400 can be ignored, 500 is forwarded |
|
148 | + if ($e->getCode() === 500) { |
|
149 | + throw $e; |
|
150 | + } |
|
151 | + return false; |
|
152 | + } |
|
153 | + $output = self::$l->n( |
|
154 | + '%s group found', |
|
155 | + '%s groups found', |
|
156 | + $groupsTotal, |
|
157 | + [$this->formatCountResult($groupsTotal)] |
|
158 | + ); |
|
159 | + $this->result->addChange('ldap_group_count', $output); |
|
160 | + return $this->result; |
|
161 | + } |
|
162 | + |
|
163 | + /** |
|
164 | + * @return WizardResult |
|
165 | + * @throws \Exception |
|
166 | + */ |
|
167 | + public function countUsers() { |
|
168 | + $filter = $this->access->getFilterForUserCount(); |
|
169 | + |
|
170 | + $usersTotal = $this->countEntries($filter, 'users'); |
|
171 | + $output = self::$l->n( |
|
172 | + '%s user found', |
|
173 | + '%s users found', |
|
174 | + $usersTotal, |
|
175 | + [$this->formatCountResult($usersTotal)] |
|
176 | + ); |
|
177 | + $this->result->addChange('ldap_user_count', $output); |
|
178 | + return $this->result; |
|
179 | + } |
|
180 | + |
|
181 | + /** |
|
182 | + * counts any objects in the currently set base dn |
|
183 | + * |
|
184 | + * @return WizardResult |
|
185 | + * @throws \Exception |
|
186 | + */ |
|
187 | + public function countInBaseDN() { |
|
188 | + // we don't need to provide a filter in this case |
|
189 | + $total = $this->countEntries('', 'objects'); |
|
190 | + if ($total === false) { |
|
191 | + throw new \Exception('invalid results received'); |
|
192 | + } |
|
193 | + $this->result->addChange('ldap_test_base', $total); |
|
194 | + return $this->result; |
|
195 | + } |
|
196 | + |
|
197 | + /** |
|
198 | + * counts users with a specified attribute |
|
199 | + * @param string $attr |
|
200 | + * @param bool $existsCheck |
|
201 | + * @return int|bool |
|
202 | + */ |
|
203 | + public function countUsersWithAttribute($attr, $existsCheck = false) { |
|
204 | + if (!$this->checkRequirements(['ldapHost', |
|
205 | + 'ldapPort', |
|
206 | + 'ldapBase', |
|
207 | + 'ldapUserFilter', |
|
208 | + ])) { |
|
209 | + return false; |
|
210 | + } |
|
211 | + |
|
212 | + $filter = $this->access->combineFilterWithAnd([ |
|
213 | + $this->configuration->ldapUserFilter, |
|
214 | + $attr . '=*' |
|
215 | + ]); |
|
216 | + |
|
217 | + $limit = ($existsCheck === false) ? null : 1; |
|
218 | + |
|
219 | + return $this->access->countUsers($filter, ['dn'], $limit); |
|
220 | + } |
|
221 | + |
|
222 | + /** |
|
223 | + * detects the display name attribute. If a setting is already present that |
|
224 | + * returns at least one hit, the detection will be canceled. |
|
225 | + * @return WizardResult|bool |
|
226 | + * @throws \Exception |
|
227 | + */ |
|
228 | + public function detectUserDisplayNameAttribute() { |
|
229 | + if (!$this->checkRequirements(['ldapHost', |
|
230 | + 'ldapPort', |
|
231 | + 'ldapBase', |
|
232 | + 'ldapUserFilter', |
|
233 | + ])) { |
|
234 | + return false; |
|
235 | + } |
|
236 | + |
|
237 | + $attr = $this->configuration->ldapUserDisplayName; |
|
238 | + if ($attr !== '' && $attr !== 'displayName') { |
|
239 | + // most likely not the default value with upper case N, |
|
240 | + // verify it still produces a result |
|
241 | + $count = (int)$this->countUsersWithAttribute($attr, true); |
|
242 | + if ($count > 0) { |
|
243 | + //no change, but we sent it back to make sure the user interface |
|
244 | + //is still correct, even if the ajax call was cancelled meanwhile |
|
245 | + $this->result->addChange('ldap_display_name', $attr); |
|
246 | + return $this->result; |
|
247 | + } |
|
248 | + } |
|
249 | + |
|
250 | + // first attribute that has at least one result wins |
|
251 | + $displayNameAttrs = ['displayname', 'cn']; |
|
252 | + foreach ($displayNameAttrs as $attr) { |
|
253 | + $count = (int)$this->countUsersWithAttribute($attr, true); |
|
254 | + |
|
255 | + if ($count > 0) { |
|
256 | + $this->applyFind('ldap_display_name', $attr); |
|
257 | + return $this->result; |
|
258 | + } |
|
259 | + } |
|
260 | + |
|
261 | + throw new \Exception(self::$l->t('Could not detect user display name attribute. Please specify it yourself in advanced LDAP settings.')); |
|
262 | + } |
|
263 | + |
|
264 | + /** |
|
265 | + * detects the most often used email attribute for users applying to the |
|
266 | + * user list filter. If a setting is already present that returns at least |
|
267 | + * one hit, the detection will be canceled. |
|
268 | + * @return WizardResult|bool |
|
269 | + */ |
|
270 | + public function detectEmailAttribute() { |
|
271 | + if (!$this->checkRequirements(['ldapHost', |
|
272 | + 'ldapPort', |
|
273 | + 'ldapBase', |
|
274 | + 'ldapUserFilter', |
|
275 | + ])) { |
|
276 | + return false; |
|
277 | + } |
|
278 | + |
|
279 | + $attr = $this->configuration->ldapEmailAttribute; |
|
280 | + if ($attr !== '') { |
|
281 | + $count = (int)$this->countUsersWithAttribute($attr, true); |
|
282 | + if ($count > 0) { |
|
283 | + return false; |
|
284 | + } |
|
285 | + $writeLog = true; |
|
286 | + } else { |
|
287 | + $writeLog = false; |
|
288 | + } |
|
289 | + |
|
290 | + $emailAttributes = ['mail', 'mailPrimaryAddress']; |
|
291 | + $winner = ''; |
|
292 | + $maxUsers = 0; |
|
293 | + foreach ($emailAttributes as $attr) { |
|
294 | + $count = $this->countUsersWithAttribute($attr); |
|
295 | + if ($count > $maxUsers) { |
|
296 | + $maxUsers = $count; |
|
297 | + $winner = $attr; |
|
298 | + } |
|
299 | + } |
|
300 | + |
|
301 | + if ($winner !== '') { |
|
302 | + $this->applyFind('ldap_email_attr', $winner); |
|
303 | + if ($writeLog) { |
|
304 | + \OCP\Util::writeLog('user_ldap', 'The mail attribute has ' . |
|
305 | + 'automatically been reset, because the original value ' . |
|
306 | + 'did not return any results.', ILogger::INFO); |
|
307 | + } |
|
308 | + } |
|
309 | + |
|
310 | + return $this->result; |
|
311 | + } |
|
312 | + |
|
313 | + /** |
|
314 | + * @return WizardResult |
|
315 | + * @throws \Exception |
|
316 | + */ |
|
317 | + public function determineAttributes() { |
|
318 | + if (!$this->checkRequirements(['ldapHost', |
|
319 | + 'ldapPort', |
|
320 | + 'ldapBase', |
|
321 | + 'ldapUserFilter', |
|
322 | + ])) { |
|
323 | + return false; |
|
324 | + } |
|
325 | + |
|
326 | + $attributes = $this->getUserAttributes(); |
|
327 | + |
|
328 | + natcasesort($attributes); |
|
329 | + $attributes = array_values($attributes); |
|
330 | + |
|
331 | + $this->result->addOptions('ldap_loginfilter_attributes', $attributes); |
|
332 | + |
|
333 | + $selected = $this->configuration->ldapLoginFilterAttributes; |
|
334 | + if (is_array($selected) && !empty($selected)) { |
|
335 | + $this->result->addChange('ldap_loginfilter_attributes', $selected); |
|
336 | + } |
|
337 | + |
|
338 | + return $this->result; |
|
339 | + } |
|
340 | + |
|
341 | + /** |
|
342 | + * detects the available LDAP attributes |
|
343 | + * @return array|false The instance's WizardResult instance |
|
344 | + * @throws \Exception |
|
345 | + */ |
|
346 | + private function getUserAttributes() { |
|
347 | + if (!$this->checkRequirements(['ldapHost', |
|
348 | + 'ldapPort', |
|
349 | + 'ldapBase', |
|
350 | + 'ldapUserFilter', |
|
351 | + ])) { |
|
352 | + return false; |
|
353 | + } |
|
354 | + $cr = $this->getConnection(); |
|
355 | + if (!$cr) { |
|
356 | + throw new \Exception('Could not connect to LDAP'); |
|
357 | + } |
|
358 | + |
|
359 | + $base = $this->configuration->ldapBase[0]; |
|
360 | + $filter = $this->configuration->ldapUserFilter; |
|
361 | + $rr = $this->ldap->search($cr, $base, $filter, [], 1, 1); |
|
362 | + if (!$this->ldap->isResource($rr)) { |
|
363 | + return false; |
|
364 | + } |
|
365 | + $er = $this->ldap->firstEntry($cr, $rr); |
|
366 | + $attributes = $this->ldap->getAttributes($cr, $er); |
|
367 | + $pureAttributes = []; |
|
368 | + for ($i = 0; $i < $attributes['count']; $i++) { |
|
369 | + $pureAttributes[] = $attributes[$i]; |
|
370 | + } |
|
371 | + |
|
372 | + return $pureAttributes; |
|
373 | + } |
|
374 | + |
|
375 | + /** |
|
376 | + * detects the available LDAP groups |
|
377 | + * @return WizardResult|false the instance's WizardResult instance |
|
378 | + */ |
|
379 | + public function determineGroupsForGroups() { |
|
380 | + return $this->determineGroups('ldap_groupfilter_groups', |
|
381 | + 'ldapGroupFilterGroups', |
|
382 | + false); |
|
383 | + } |
|
384 | + |
|
385 | + /** |
|
386 | + * detects the available LDAP groups |
|
387 | + * @return WizardResult|false the instance's WizardResult instance |
|
388 | + */ |
|
389 | + public function determineGroupsForUsers() { |
|
390 | + return $this->determineGroups('ldap_userfilter_groups', |
|
391 | + 'ldapUserFilterGroups'); |
|
392 | + } |
|
393 | + |
|
394 | + /** |
|
395 | + * detects the available LDAP groups |
|
396 | + * @param string $dbKey |
|
397 | + * @param string $confKey |
|
398 | + * @param bool $testMemberOf |
|
399 | + * @return WizardResult|false the instance's WizardResult instance |
|
400 | + * @throws \Exception |
|
401 | + */ |
|
402 | + private function determineGroups($dbKey, $confKey, $testMemberOf = true) { |
|
403 | + if (!$this->checkRequirements(['ldapHost', |
|
404 | + 'ldapPort', |
|
405 | + 'ldapBase', |
|
406 | + ])) { |
|
407 | + return false; |
|
408 | + } |
|
409 | + $cr = $this->getConnection(); |
|
410 | + if (!$cr) { |
|
411 | + throw new \Exception('Could not connect to LDAP'); |
|
412 | + } |
|
413 | + |
|
414 | + $this->fetchGroups($dbKey, $confKey); |
|
415 | + |
|
416 | + if ($testMemberOf) { |
|
417 | + $this->configuration->hasMemberOfFilterSupport = $this->testMemberOf(); |
|
418 | + $this->result->markChange(); |
|
419 | + if (!$this->configuration->hasMemberOfFilterSupport) { |
|
420 | + throw new \Exception('memberOf is not supported by the server'); |
|
421 | + } |
|
422 | + } |
|
423 | + |
|
424 | + return $this->result; |
|
425 | + } |
|
426 | + |
|
427 | + /** |
|
428 | + * fetches all groups from LDAP and adds them to the result object |
|
429 | + * |
|
430 | + * @param string $dbKey |
|
431 | + * @param string $confKey |
|
432 | + * @return array $groupEntries |
|
433 | + * @throws \Exception |
|
434 | + */ |
|
435 | + public function fetchGroups($dbKey, $confKey) { |
|
436 | + $obclasses = ['posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames', 'groupOfUniqueNames']; |
|
437 | + |
|
438 | + $filterParts = []; |
|
439 | + foreach ($obclasses as $obclass) { |
|
440 | + $filterParts[] = 'objectclass='.$obclass; |
|
441 | + } |
|
442 | + //we filter for everything |
|
443 | + //- that looks like a group and |
|
444 | + //- has the group display name set |
|
445 | + $filter = $this->access->combineFilterWithOr($filterParts); |
|
446 | + $filter = $this->access->combineFilterWithAnd([$filter, 'cn=*']); |
|
447 | + |
|
448 | + $groupNames = []; |
|
449 | + $groupEntries = []; |
|
450 | + $limit = 400; |
|
451 | + $offset = 0; |
|
452 | + do { |
|
453 | + // we need to request dn additionally here, otherwise memberOf |
|
454 | + // detection will fail later |
|
455 | + $result = $this->access->searchGroups($filter, ['cn', 'dn'], $limit, $offset); |
|
456 | + foreach ($result as $item) { |
|
457 | + if (!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) { |
|
458 | + // just in case - no issue known |
|
459 | + continue; |
|
460 | + } |
|
461 | + $groupNames[] = $item['cn'][0]; |
|
462 | + $groupEntries[] = $item; |
|
463 | + } |
|
464 | + $offset += $limit; |
|
465 | + } while ($this->access->hasMoreResults()); |
|
466 | + |
|
467 | + if (count($groupNames) > 0) { |
|
468 | + natsort($groupNames); |
|
469 | + $this->result->addOptions($dbKey, array_values($groupNames)); |
|
470 | + } else { |
|
471 | + throw new \Exception(self::$l->t('Could not find the desired feature')); |
|
472 | + } |
|
473 | + |
|
474 | + $setFeatures = $this->configuration->$confKey; |
|
475 | + if (is_array($setFeatures) && !empty($setFeatures)) { |
|
476 | + //something is already configured? pre-select it. |
|
477 | + $this->result->addChange($dbKey, $setFeatures); |
|
478 | + } |
|
479 | + return $groupEntries; |
|
480 | + } |
|
481 | + |
|
482 | + public function determineGroupMemberAssoc() { |
|
483 | + if (!$this->checkRequirements(['ldapHost', |
|
484 | + 'ldapPort', |
|
485 | + 'ldapGroupFilter', |
|
486 | + ])) { |
|
487 | + return false; |
|
488 | + } |
|
489 | + $attribute = $this->detectGroupMemberAssoc(); |
|
490 | + if ($attribute === false) { |
|
491 | + return false; |
|
492 | + } |
|
493 | + $this->configuration->setConfiguration(['ldapGroupMemberAssocAttr' => $attribute]); |
|
494 | + $this->result->addChange('ldap_group_member_assoc_attribute', $attribute); |
|
495 | + |
|
496 | + return $this->result; |
|
497 | + } |
|
498 | + |
|
499 | + /** |
|
500 | + * Detects the available object classes |
|
501 | + * @return WizardResult|false the instance's WizardResult instance |
|
502 | + * @throws \Exception |
|
503 | + */ |
|
504 | + public function determineGroupObjectClasses() { |
|
505 | + if (!$this->checkRequirements(['ldapHost', |
|
506 | + 'ldapPort', |
|
507 | + 'ldapBase', |
|
508 | + ])) { |
|
509 | + return false; |
|
510 | + } |
|
511 | + $cr = $this->getConnection(); |
|
512 | + if (!$cr) { |
|
513 | + throw new \Exception('Could not connect to LDAP'); |
|
514 | + } |
|
515 | + |
|
516 | + $obclasses = ['groupOfNames', 'groupOfUniqueNames', 'group', 'posixGroup', '*']; |
|
517 | + $this->determineFeature($obclasses, |
|
518 | + 'objectclass', |
|
519 | + 'ldap_groupfilter_objectclass', |
|
520 | + 'ldapGroupFilterObjectclass', |
|
521 | + false); |
|
522 | + |
|
523 | + return $this->result; |
|
524 | + } |
|
525 | + |
|
526 | + /** |
|
527 | + * detects the available object classes |
|
528 | + * @return WizardResult |
|
529 | + * @throws \Exception |
|
530 | + */ |
|
531 | + public function determineUserObjectClasses() { |
|
532 | + if (!$this->checkRequirements(['ldapHost', |
|
533 | + 'ldapPort', |
|
534 | + 'ldapBase', |
|
535 | + ])) { |
|
536 | + return false; |
|
537 | + } |
|
538 | + $cr = $this->getConnection(); |
|
539 | + if (!$cr) { |
|
540 | + throw new \Exception('Could not connect to LDAP'); |
|
541 | + } |
|
542 | + |
|
543 | + $obclasses = ['inetOrgPerson', 'person', 'organizationalPerson', |
|
544 | + 'user', 'posixAccount', '*']; |
|
545 | + $filter = $this->configuration->ldapUserFilter; |
|
546 | + //if filter is empty, it is probably the first time the wizard is called |
|
547 | + //then, apply suggestions. |
|
548 | + $this->determineFeature($obclasses, |
|
549 | + 'objectclass', |
|
550 | + 'ldap_userfilter_objectclass', |
|
551 | + 'ldapUserFilterObjectclass', |
|
552 | + empty($filter)); |
|
553 | + |
|
554 | + return $this->result; |
|
555 | + } |
|
556 | + |
|
557 | + /** |
|
558 | + * @return WizardResult|false |
|
559 | + * @throws \Exception |
|
560 | + */ |
|
561 | + public function getGroupFilter() { |
|
562 | + if (!$this->checkRequirements(['ldapHost', |
|
563 | + 'ldapPort', |
|
564 | + 'ldapBase', |
|
565 | + ])) { |
|
566 | + return false; |
|
567 | + } |
|
568 | + //make sure the use display name is set |
|
569 | + $displayName = $this->configuration->ldapGroupDisplayName; |
|
570 | + if ($displayName === '') { |
|
571 | + $d = $this->configuration->getDefaults(); |
|
572 | + $this->applyFind('ldap_group_display_name', |
|
573 | + $d['ldap_group_display_name']); |
|
574 | + } |
|
575 | + $filter = $this->composeLdapFilter(self::LFILTER_GROUP_LIST); |
|
576 | + |
|
577 | + $this->applyFind('ldap_group_filter', $filter); |
|
578 | + return $this->result; |
|
579 | + } |
|
580 | + |
|
581 | + /** |
|
582 | + * @return WizardResult|false |
|
583 | + * @throws \Exception |
|
584 | + */ |
|
585 | + public function getUserListFilter() { |
|
586 | + if (!$this->checkRequirements(['ldapHost', |
|
587 | + 'ldapPort', |
|
588 | + 'ldapBase', |
|
589 | + ])) { |
|
590 | + return false; |
|
591 | + } |
|
592 | + //make sure the use display name is set |
|
593 | + $displayName = $this->configuration->ldapUserDisplayName; |
|
594 | + if ($displayName === '') { |
|
595 | + $d = $this->configuration->getDefaults(); |
|
596 | + $this->applyFind('ldap_display_name', $d['ldap_display_name']); |
|
597 | + } |
|
598 | + $filter = $this->composeLdapFilter(self::LFILTER_USER_LIST); |
|
599 | + if (!$filter) { |
|
600 | + throw new \Exception('Cannot create filter'); |
|
601 | + } |
|
602 | + |
|
603 | + $this->applyFind('ldap_userlist_filter', $filter); |
|
604 | + return $this->result; |
|
605 | + } |
|
606 | + |
|
607 | + /** |
|
608 | + * @return bool|WizardResult |
|
609 | + * @throws \Exception |
|
610 | + */ |
|
611 | + public function getUserLoginFilter() { |
|
612 | + if (!$this->checkRequirements(['ldapHost', |
|
613 | + 'ldapPort', |
|
614 | + 'ldapBase', |
|
615 | + 'ldapUserFilter', |
|
616 | + ])) { |
|
617 | + return false; |
|
618 | + } |
|
619 | + |
|
620 | + $filter = $this->composeLdapFilter(self::LFILTER_LOGIN); |
|
621 | + if (!$filter) { |
|
622 | + throw new \Exception('Cannot create filter'); |
|
623 | + } |
|
624 | + |
|
625 | + $this->applyFind('ldap_login_filter', $filter); |
|
626 | + return $this->result; |
|
627 | + } |
|
628 | + |
|
629 | + /** |
|
630 | + * @return bool|WizardResult |
|
631 | + * @param string $loginName |
|
632 | + * @throws \Exception |
|
633 | + */ |
|
634 | + public function testLoginName($loginName) { |
|
635 | + if (!$this->checkRequirements(['ldapHost', |
|
636 | + 'ldapPort', |
|
637 | + 'ldapBase', |
|
638 | + 'ldapLoginFilter', |
|
639 | + ])) { |
|
640 | + return false; |
|
641 | + } |
|
642 | + |
|
643 | + $cr = $this->access->connection->getConnectionResource(); |
|
644 | + if (!$this->ldap->isResource($cr)) { |
|
645 | + throw new \Exception('connection error'); |
|
646 | + } |
|
647 | + |
|
648 | + if (mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8') |
|
649 | + === false) { |
|
650 | + throw new \Exception('missing placeholder'); |
|
651 | + } |
|
652 | + |
|
653 | + $users = $this->access->countUsersByLoginName($loginName); |
|
654 | + if ($this->ldap->errno($cr) !== 0) { |
|
655 | + throw new \Exception($this->ldap->error($cr)); |
|
656 | + } |
|
657 | + $filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter); |
|
658 | + $this->result->addChange('ldap_test_loginname', $users); |
|
659 | + $this->result->addChange('ldap_test_effective_filter', $filter); |
|
660 | + return $this->result; |
|
661 | + } |
|
662 | + |
|
663 | + /** |
|
664 | + * Tries to determine the port, requires given Host, User DN and Password |
|
665 | + * @return WizardResult|false WizardResult on success, false otherwise |
|
666 | + * @throws \Exception |
|
667 | + */ |
|
668 | + public function guessPortAndTLS() { |
|
669 | + if (!$this->checkRequirements(['ldapHost', |
|
670 | + ])) { |
|
671 | + return false; |
|
672 | + } |
|
673 | + $this->checkHost(); |
|
674 | + $portSettings = $this->getPortSettingsToTry(); |
|
675 | + |
|
676 | + if (!is_array($portSettings)) { |
|
677 | + throw new \Exception(print_r($portSettings, true)); |
|
678 | + } |
|
679 | + |
|
680 | + //proceed from the best configuration and return on first success |
|
681 | + foreach ($portSettings as $setting) { |
|
682 | + $p = $setting['port']; |
|
683 | + $t = $setting['tls']; |
|
684 | + \OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, ILogger::DEBUG); |
|
685 | + //connectAndBind may throw Exception, it needs to be catched by the |
|
686 | + //callee of this method |
|
687 | + |
|
688 | + try { |
|
689 | + $settingsFound = $this->connectAndBind($p, $t); |
|
690 | + } catch (\Exception $e) { |
|
691 | + // any reply other than -1 (= cannot connect) is already okay, |
|
692 | + // because then we found the server |
|
693 | + // unavailable startTLS returns -11 |
|
694 | + if ($e->getCode() > 0) { |
|
695 | + $settingsFound = true; |
|
696 | + } else { |
|
697 | + throw $e; |
|
698 | + } |
|
699 | + } |
|
700 | + |
|
701 | + if ($settingsFound === true) { |
|
702 | + $config = [ |
|
703 | + 'ldapPort' => $p, |
|
704 | + 'ldapTLS' => (int)$t |
|
705 | + ]; |
|
706 | + $this->configuration->setConfiguration($config); |
|
707 | + \OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, ILogger::DEBUG); |
|
708 | + $this->result->addChange('ldap_port', $p); |
|
709 | + return $this->result; |
|
710 | + } |
|
711 | + } |
|
712 | + |
|
713 | + //custom port, undetected (we do not brute force) |
|
714 | + return false; |
|
715 | + } |
|
716 | + |
|
717 | + /** |
|
718 | + * tries to determine a base dn from User DN or LDAP Host |
|
719 | + * @return WizardResult|false WizardResult on success, false otherwise |
|
720 | + */ |
|
721 | + public function guessBaseDN() { |
|
722 | + if (!$this->checkRequirements(['ldapHost', |
|
723 | + 'ldapPort', |
|
724 | + ])) { |
|
725 | + return false; |
|
726 | + } |
|
727 | + |
|
728 | + //check whether a DN is given in the agent name (99.9% of all cases) |
|
729 | + $base = null; |
|
730 | + $i = stripos($this->configuration->ldapAgentName, 'dc='); |
|
731 | + if ($i !== false) { |
|
732 | + $base = substr($this->configuration->ldapAgentName, $i); |
|
733 | + if ($this->testBaseDN($base)) { |
|
734 | + $this->applyFind('ldap_base', $base); |
|
735 | + return $this->result; |
|
736 | + } |
|
737 | + } |
|
738 | + |
|
739 | + //this did not help :( |
|
740 | + //Let's see whether we can parse the Host URL and convert the domain to |
|
741 | + //a base DN |
|
742 | + $helper = new Helper(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection()); |
|
743 | + $domain = $helper->getDomainFromURL($this->configuration->ldapHost); |
|
744 | + if (!$domain) { |
|
745 | + return false; |
|
746 | + } |
|
747 | + |
|
748 | + $dparts = explode('.', $domain); |
|
749 | + while (count($dparts) > 0) { |
|
750 | + $base2 = 'dc=' . implode(',dc=', $dparts); |
|
751 | + if ($base !== $base2 && $this->testBaseDN($base2)) { |
|
752 | + $this->applyFind('ldap_base', $base2); |
|
753 | + return $this->result; |
|
754 | + } |
|
755 | + array_shift($dparts); |
|
756 | + } |
|
757 | + |
|
758 | + return false; |
|
759 | + } |
|
760 | + |
|
761 | + /** |
|
762 | + * sets the found value for the configuration key in the WizardResult |
|
763 | + * as well as in the Configuration instance |
|
764 | + * @param string $key the configuration key |
|
765 | + * @param string $value the (detected) value |
|
766 | + * |
|
767 | + */ |
|
768 | + private function applyFind($key, $value) { |
|
769 | + $this->result->addChange($key, $value); |
|
770 | + $this->configuration->setConfiguration([$key => $value]); |
|
771 | + } |
|
772 | + |
|
773 | + /** |
|
774 | + * Checks, whether a port was entered in the Host configuration |
|
775 | + * field. In this case the port will be stripped off, but also stored as |
|
776 | + * setting. |
|
777 | + */ |
|
778 | + private function checkHost() { |
|
779 | + $host = $this->configuration->ldapHost; |
|
780 | + $hostInfo = parse_url($host); |
|
781 | + |
|
782 | + //removes Port from Host |
|
783 | + if (is_array($hostInfo) && isset($hostInfo['port'])) { |
|
784 | + $port = $hostInfo['port']; |
|
785 | + $host = str_replace(':'.$port, '', $host); |
|
786 | + $this->applyFind('ldap_host', $host); |
|
787 | + $this->applyFind('ldap_port', $port); |
|
788 | + } |
|
789 | + } |
|
790 | + |
|
791 | + /** |
|
792 | + * tries to detect the group member association attribute which is |
|
793 | + * one of 'uniqueMember', 'memberUid', 'member', 'gidNumber' |
|
794 | + * @return string|false, string with the attribute name, false on error |
|
795 | + * @throws \Exception |
|
796 | + */ |
|
797 | + private function detectGroupMemberAssoc() { |
|
798 | + $possibleAttrs = ['uniqueMember', 'memberUid', 'member', 'gidNumber', 'zimbraMailForwardingAddress']; |
|
799 | + $filter = $this->configuration->ldapGroupFilter; |
|
800 | + if (empty($filter)) { |
|
801 | + return false; |
|
802 | + } |
|
803 | + $cr = $this->getConnection(); |
|
804 | + if (!$cr) { |
|
805 | + throw new \Exception('Could not connect to LDAP'); |
|
806 | + } |
|
807 | + $base = $this->configuration->ldapBaseGroups[0] ?: $this->configuration->ldapBase[0]; |
|
808 | + $rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000); |
|
809 | + if (!$this->ldap->isResource($rr)) { |
|
810 | + return false; |
|
811 | + } |
|
812 | + $er = $this->ldap->firstEntry($cr, $rr); |
|
813 | + while (is_resource($er)) { |
|
814 | + $this->ldap->getDN($cr, $er); |
|
815 | + $attrs = $this->ldap->getAttributes($cr, $er); |
|
816 | + $result = []; |
|
817 | + $possibleAttrsCount = count($possibleAttrs); |
|
818 | + for ($i = 0; $i < $possibleAttrsCount; $i++) { |
|
819 | + if (isset($attrs[$possibleAttrs[$i]])) { |
|
820 | + $result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count']; |
|
821 | + } |
|
822 | + } |
|
823 | + if (!empty($result)) { |
|
824 | + natsort($result); |
|
825 | + return key($result); |
|
826 | + } |
|
827 | + |
|
828 | + $er = $this->ldap->nextEntry($cr, $er); |
|
829 | + } |
|
830 | + |
|
831 | + return false; |
|
832 | + } |
|
833 | + |
|
834 | + /** |
|
835 | + * Checks whether for a given BaseDN results will be returned |
|
836 | + * @param string $base the BaseDN to test |
|
837 | + * @return bool true on success, false otherwise |
|
838 | + * @throws \Exception |
|
839 | + */ |
|
840 | + private function testBaseDN($base) { |
|
841 | + $cr = $this->getConnection(); |
|
842 | + if (!$cr) { |
|
843 | + throw new \Exception('Could not connect to LDAP'); |
|
844 | + } |
|
845 | + |
|
846 | + //base is there, let's validate it. If we search for anything, we should |
|
847 | + //get a result set > 0 on a proper base |
|
848 | + $rr = $this->ldap->search($cr, $base, 'objectClass=*', ['dn'], 0, 1); |
|
849 | + if (!$this->ldap->isResource($rr)) { |
|
850 | + $errorNo = $this->ldap->errno($cr); |
|
851 | + $errorMsg = $this->ldap->error($cr); |
|
852 | + \OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base. |
|
853 | + ' Error '.$errorNo.': '.$errorMsg, ILogger::INFO); |
|
854 | + return false; |
|
855 | + } |
|
856 | + $entries = $this->ldap->countEntries($cr, $rr); |
|
857 | + return ($entries !== false) && ($entries > 0); |
|
858 | + } |
|
859 | + |
|
860 | + /** |
|
861 | + * Checks whether the server supports memberOf in LDAP Filter. |
|
862 | + * Note: at least in OpenLDAP, availability of memberOf is dependent on |
|
863 | + * a configured objectClass. I.e. not necessarily for all available groups |
|
864 | + * memberOf does work. |
|
865 | + * |
|
866 | + * @return bool true if it does, false otherwise |
|
867 | + * @throws \Exception |
|
868 | + */ |
|
869 | + private function testMemberOf() { |
|
870 | + $cr = $this->getConnection(); |
|
871 | + if (!$cr) { |
|
872 | + throw new \Exception('Could not connect to LDAP'); |
|
873 | + } |
|
874 | + $result = $this->access->countUsers('memberOf=*', ['memberOf'], 1); |
|
875 | + if (is_int($result) && $result > 0) { |
|
876 | + return true; |
|
877 | + } |
|
878 | + return false; |
|
879 | + } |
|
880 | + |
|
881 | + /** |
|
882 | + * creates an LDAP Filter from given configuration |
|
883 | + * @param integer $filterType int, for which use case the filter shall be created |
|
884 | + * can be any of self::LFILTER_USER_LIST, self::LFILTER_LOGIN or |
|
885 | + * self::LFILTER_GROUP_LIST |
|
886 | + * @return string|false string with the filter on success, false otherwise |
|
887 | + * @throws \Exception |
|
888 | + */ |
|
889 | + private function composeLdapFilter($filterType) { |
|
890 | + $filter = ''; |
|
891 | + $parts = 0; |
|
892 | + switch ($filterType) { |
|
893 | + case self::LFILTER_USER_LIST: |
|
894 | + $objcs = $this->configuration->ldapUserFilterObjectclass; |
|
895 | + //glue objectclasses |
|
896 | + if (is_array($objcs) && count($objcs) > 0) { |
|
897 | + $filter .= '(|'; |
|
898 | + foreach ($objcs as $objc) { |
|
899 | + $filter .= '(objectclass=' . $objc . ')'; |
|
900 | + } |
|
901 | + $filter .= ')'; |
|
902 | + $parts++; |
|
903 | + } |
|
904 | + //glue group memberships |
|
905 | + if ($this->configuration->hasMemberOfFilterSupport) { |
|
906 | + $cns = $this->configuration->ldapUserFilterGroups; |
|
907 | + if (is_array($cns) && count($cns) > 0) { |
|
908 | + $filter .= '(|'; |
|
909 | + $cr = $this->getConnection(); |
|
910 | + if (!$cr) { |
|
911 | + throw new \Exception('Could not connect to LDAP'); |
|
912 | + } |
|
913 | + $base = $this->configuration->ldapBase[0]; |
|
914 | + foreach ($cns as $cn) { |
|
915 | + $rr = $this->ldap->search($cr, $base, 'cn=' . $cn, ['dn', 'primaryGroupToken']); |
|
916 | + if (!$this->ldap->isResource($rr)) { |
|
917 | + continue; |
|
918 | + } |
|
919 | + $er = $this->ldap->firstEntry($cr, $rr); |
|
920 | + $attrs = $this->ldap->getAttributes($cr, $er); |
|
921 | + $dn = $this->ldap->getDN($cr, $er); |
|
922 | + if ($dn === false || $dn === '') { |
|
923 | + continue; |
|
924 | + } |
|
925 | + $filterPart = '(memberof=' . $dn . ')'; |
|
926 | + if (isset($attrs['primaryGroupToken'])) { |
|
927 | + $pgt = $attrs['primaryGroupToken'][0]; |
|
928 | + $primaryFilterPart = '(primaryGroupID=' . $pgt .')'; |
|
929 | + $filterPart = '(|' . $filterPart . $primaryFilterPart . ')'; |
|
930 | + } |
|
931 | + $filter .= $filterPart; |
|
932 | + } |
|
933 | + $filter .= ')'; |
|
934 | + } |
|
935 | + $parts++; |
|
936 | + } |
|
937 | + //wrap parts in AND condition |
|
938 | + if ($parts > 1) { |
|
939 | + $filter = '(&' . $filter . ')'; |
|
940 | + } |
|
941 | + if ($filter === '') { |
|
942 | + $filter = '(objectclass=*)'; |
|
943 | + } |
|
944 | + break; |
|
945 | + |
|
946 | + case self::LFILTER_GROUP_LIST: |
|
947 | + $objcs = $this->configuration->ldapGroupFilterObjectclass; |
|
948 | + //glue objectclasses |
|
949 | + if (is_array($objcs) && count($objcs) > 0) { |
|
950 | + $filter .= '(|'; |
|
951 | + foreach ($objcs as $objc) { |
|
952 | + $filter .= '(objectclass=' . $objc . ')'; |
|
953 | + } |
|
954 | + $filter .= ')'; |
|
955 | + $parts++; |
|
956 | + } |
|
957 | + //glue group memberships |
|
958 | + $cns = $this->configuration->ldapGroupFilterGroups; |
|
959 | + if (is_array($cns) && count($cns) > 0) { |
|
960 | + $filter .= '(|'; |
|
961 | + foreach ($cns as $cn) { |
|
962 | + $filter .= '(cn=' . $cn . ')'; |
|
963 | + } |
|
964 | + $filter .= ')'; |
|
965 | + } |
|
966 | + $parts++; |
|
967 | + //wrap parts in AND condition |
|
968 | + if ($parts > 1) { |
|
969 | + $filter = '(&' . $filter . ')'; |
|
970 | + } |
|
971 | + break; |
|
972 | + |
|
973 | + case self::LFILTER_LOGIN: |
|
974 | + $ulf = $this->configuration->ldapUserFilter; |
|
975 | + $loginpart = '=%uid'; |
|
976 | + $filterUsername = ''; |
|
977 | + $userAttributes = $this->getUserAttributes(); |
|
978 | + $userAttributes = array_change_key_case(array_flip($userAttributes)); |
|
979 | + $parts = 0; |
|
980 | + |
|
981 | + if ($this->configuration->ldapLoginFilterUsername === '1') { |
|
982 | + $attr = ''; |
|
983 | + if (isset($userAttributes['uid'])) { |
|
984 | + $attr = 'uid'; |
|
985 | + } elseif (isset($userAttributes['samaccountname'])) { |
|
986 | + $attr = 'samaccountname'; |
|
987 | + } elseif (isset($userAttributes['cn'])) { |
|
988 | + //fallback |
|
989 | + $attr = 'cn'; |
|
990 | + } |
|
991 | + if ($attr !== '') { |
|
992 | + $filterUsername = '(' . $attr . $loginpart . ')'; |
|
993 | + $parts++; |
|
994 | + } |
|
995 | + } |
|
996 | + |
|
997 | + $filterEmail = ''; |
|
998 | + if ($this->configuration->ldapLoginFilterEmail === '1') { |
|
999 | + $filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))'; |
|
1000 | + $parts++; |
|
1001 | + } |
|
1002 | + |
|
1003 | + $filterAttributes = ''; |
|
1004 | + $attrsToFilter = $this->configuration->ldapLoginFilterAttributes; |
|
1005 | + if (is_array($attrsToFilter) && count($attrsToFilter) > 0) { |
|
1006 | + $filterAttributes = '(|'; |
|
1007 | + foreach ($attrsToFilter as $attribute) { |
|
1008 | + $filterAttributes .= '(' . $attribute . $loginpart . ')'; |
|
1009 | + } |
|
1010 | + $filterAttributes .= ')'; |
|
1011 | + $parts++; |
|
1012 | + } |
|
1013 | + |
|
1014 | + $filterLogin = ''; |
|
1015 | + if ($parts > 1) { |
|
1016 | + $filterLogin = '(|'; |
|
1017 | + } |
|
1018 | + $filterLogin .= $filterUsername; |
|
1019 | + $filterLogin .= $filterEmail; |
|
1020 | + $filterLogin .= $filterAttributes; |
|
1021 | + if ($parts > 1) { |
|
1022 | + $filterLogin .= ')'; |
|
1023 | + } |
|
1024 | + |
|
1025 | + $filter = '(&'.$ulf.$filterLogin.')'; |
|
1026 | + break; |
|
1027 | + } |
|
1028 | + |
|
1029 | + \OCP\Util::writeLog('user_ldap', 'Wiz: Final filter '.$filter, ILogger::DEBUG); |
|
1030 | + |
|
1031 | + return $filter; |
|
1032 | + } |
|
1033 | + |
|
1034 | + /** |
|
1035 | + * Connects and Binds to an LDAP Server |
|
1036 | + * |
|
1037 | + * @param int $port the port to connect with |
|
1038 | + * @param bool $tls whether startTLS is to be used |
|
1039 | + * @return bool |
|
1040 | + * @throws \Exception |
|
1041 | + */ |
|
1042 | + private function connectAndBind($port, $tls) { |
|
1043 | + //connect, does not really trigger any server communication |
|
1044 | + $host = $this->configuration->ldapHost; |
|
1045 | + $hostInfo = parse_url($host); |
|
1046 | + if (!$hostInfo) { |
|
1047 | + throw new \Exception(self::$l->t('Invalid Host')); |
|
1048 | + } |
|
1049 | + \OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', ILogger::DEBUG); |
|
1050 | + $cr = $this->ldap->connect($host, $port); |
|
1051 | + if (!is_resource($cr)) { |
|
1052 | + throw new \Exception(self::$l->t('Invalid Host')); |
|
1053 | + } |
|
1054 | + |
|
1055 | + //set LDAP options |
|
1056 | + $this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3); |
|
1057 | + $this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0); |
|
1058 | + $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT); |
|
1059 | + |
|
1060 | + try { |
|
1061 | + if ($tls) { |
|
1062 | + $isTlsWorking = @$this->ldap->startTls($cr); |
|
1063 | + if (!$isTlsWorking) { |
|
1064 | + return false; |
|
1065 | + } |
|
1066 | + } |
|
1067 | + |
|
1068 | + \OCP\Util::writeLog('user_ldap', 'Wiz: Attemping to Bind ', ILogger::DEBUG); |
|
1069 | + //interesting part: do the bind! |
|
1070 | + $login = $this->ldap->bind($cr, |
|
1071 | + $this->configuration->ldapAgentName, |
|
1072 | + $this->configuration->ldapAgentPassword |
|
1073 | + ); |
|
1074 | + $errNo = $this->ldap->errno($cr); |
|
1075 | + $error = ldap_error($cr); |
|
1076 | + $this->ldap->unbind($cr); |
|
1077 | + } catch (ServerNotAvailableException $e) { |
|
1078 | + return false; |
|
1079 | + } |
|
1080 | + |
|
1081 | + if ($login === true) { |
|
1082 | + $this->ldap->unbind($cr); |
|
1083 | + \OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . (int)$tls, ILogger::DEBUG); |
|
1084 | + return true; |
|
1085 | + } |
|
1086 | + |
|
1087 | + if ($errNo === -1) { |
|
1088 | + //host, port or TLS wrong |
|
1089 | + return false; |
|
1090 | + } |
|
1091 | + throw new \Exception($error, $errNo); |
|
1092 | + } |
|
1093 | + |
|
1094 | + /** |
|
1095 | + * checks whether a valid combination of agent and password has been |
|
1096 | + * provided (either two values or nothing for anonymous connect) |
|
1097 | + * @return bool, true if everything is fine, false otherwise |
|
1098 | + */ |
|
1099 | + private function checkAgentRequirements() { |
|
1100 | + $agent = $this->configuration->ldapAgentName; |
|
1101 | + $pwd = $this->configuration->ldapAgentPassword; |
|
1102 | + |
|
1103 | + return |
|
1104 | + ($agent !== '' && $pwd !== '') |
|
1105 | + || ($agent === '' && $pwd === '') |
|
1106 | + ; |
|
1107 | + } |
|
1108 | + |
|
1109 | + /** |
|
1110 | + * @param array $reqs |
|
1111 | + * @return bool |
|
1112 | + */ |
|
1113 | + private function checkRequirements($reqs) { |
|
1114 | + $this->checkAgentRequirements(); |
|
1115 | + foreach ($reqs as $option) { |
|
1116 | + $value = $this->configuration->$option; |
|
1117 | + if (empty($value)) { |
|
1118 | + return false; |
|
1119 | + } |
|
1120 | + } |
|
1121 | + return true; |
|
1122 | + } |
|
1123 | + |
|
1124 | + /** |
|
1125 | + * does a cumulativeSearch on LDAP to get different values of a |
|
1126 | + * specified attribute |
|
1127 | + * @param string[] $filters array, the filters that shall be used in the search |
|
1128 | + * @param string $attr the attribute of which a list of values shall be returned |
|
1129 | + * @param int $dnReadLimit the amount of how many DNs should be analyzed. |
|
1130 | + * The lower, the faster |
|
1131 | + * @param string $maxF string. if not null, this variable will have the filter that |
|
1132 | + * yields most result entries |
|
1133 | + * @return array|false an array with the values on success, false otherwise |
|
1134 | + */ |
|
1135 | + public function cumulativeSearchOnAttribute($filters, $attr, $dnReadLimit = 3, &$maxF = null) { |
|
1136 | + $dnRead = []; |
|
1137 | + $foundItems = []; |
|
1138 | + $maxEntries = 0; |
|
1139 | + if (!is_array($this->configuration->ldapBase) |
|
1140 | + || !isset($this->configuration->ldapBase[0])) { |
|
1141 | + return false; |
|
1142 | + } |
|
1143 | + $base = $this->configuration->ldapBase[0]; |
|
1144 | + $cr = $this->getConnection(); |
|
1145 | + if (!$this->ldap->isResource($cr)) { |
|
1146 | + return false; |
|
1147 | + } |
|
1148 | + $lastFilter = null; |
|
1149 | + if (isset($filters[count($filters) - 1])) { |
|
1150 | + $lastFilter = $filters[count($filters) - 1]; |
|
1151 | + } |
|
1152 | + foreach ($filters as $filter) { |
|
1153 | + if ($lastFilter === $filter && count($foundItems) > 0) { |
|
1154 | + //skip when the filter is a wildcard and results were found |
|
1155 | + continue; |
|
1156 | + } |
|
1157 | + // 20k limit for performance and reason |
|
1158 | + $rr = $this->ldap->search($cr, $base, $filter, [$attr], 0, 20000); |
|
1159 | + if (!$this->ldap->isResource($rr)) { |
|
1160 | + continue; |
|
1161 | + } |
|
1162 | + $entries = $this->ldap->countEntries($cr, $rr); |
|
1163 | + $getEntryFunc = 'firstEntry'; |
|
1164 | + if (($entries !== false) && ($entries > 0)) { |
|
1165 | + if (!is_null($maxF) && $entries > $maxEntries) { |
|
1166 | + $maxEntries = $entries; |
|
1167 | + $maxF = $filter; |
|
1168 | + } |
|
1169 | + $dnReadCount = 0; |
|
1170 | + do { |
|
1171 | + $entry = $this->ldap->$getEntryFunc($cr, $rr); |
|
1172 | + $getEntryFunc = 'nextEntry'; |
|
1173 | + if (!$this->ldap->isResource($entry)) { |
|
1174 | + continue 2; |
|
1175 | + } |
|
1176 | + $rr = $entry; //will be expected by nextEntry next round |
|
1177 | + $attributes = $this->ldap->getAttributes($cr, $entry); |
|
1178 | + $dn = $this->ldap->getDN($cr, $entry); |
|
1179 | + if ($dn === false || in_array($dn, $dnRead)) { |
|
1180 | + continue; |
|
1181 | + } |
|
1182 | + $newItems = []; |
|
1183 | + $state = $this->getAttributeValuesFromEntry($attributes, |
|
1184 | + $attr, |
|
1185 | + $newItems); |
|
1186 | + $dnReadCount++; |
|
1187 | + $foundItems = array_merge($foundItems, $newItems); |
|
1188 | + $this->resultCache[$dn][$attr] = $newItems; |
|
1189 | + $dnRead[] = $dn; |
|
1190 | + } while (($state === self::LRESULT_PROCESSED_SKIP |
|
1191 | + || $this->ldap->isResource($entry)) |
|
1192 | + && ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit)); |
|
1193 | + } |
|
1194 | + } |
|
1195 | + |
|
1196 | + return array_unique($foundItems); |
|
1197 | + } |
|
1198 | + |
|
1199 | + /** |
|
1200 | + * determines if and which $attr are available on the LDAP server |
|
1201 | + * @param string[] $objectclasses the objectclasses to use as search filter |
|
1202 | + * @param string $attr the attribute to look for |
|
1203 | + * @param string $dbkey the dbkey of the setting the feature is connected to |
|
1204 | + * @param string $confkey the confkey counterpart for the $dbkey as used in the |
|
1205 | + * Configuration class |
|
1206 | + * @param bool $po whether the objectClass with most result entries |
|
1207 | + * shall be pre-selected via the result |
|
1208 | + * @return array|false list of found items. |
|
1209 | + * @throws \Exception |
|
1210 | + */ |
|
1211 | + private function determineFeature($objectclasses, $attr, $dbkey, $confkey, $po = false) { |
|
1212 | + $cr = $this->getConnection(); |
|
1213 | + if (!$cr) { |
|
1214 | + throw new \Exception('Could not connect to LDAP'); |
|
1215 | + } |
|
1216 | + $p = 'objectclass='; |
|
1217 | + foreach ($objectclasses as $key => $value) { |
|
1218 | + $objectclasses[$key] = $p.$value; |
|
1219 | + } |
|
1220 | + $maxEntryObjC = ''; |
|
1221 | + |
|
1222 | + //how deep to dig? |
|
1223 | + //When looking for objectclasses, testing few entries is sufficient, |
|
1224 | + $dig = 3; |
|
1225 | + |
|
1226 | + $availableFeatures = |
|
1227 | + $this->cumulativeSearchOnAttribute($objectclasses, $attr, |
|
1228 | + $dig, $maxEntryObjC); |
|
1229 | + if (is_array($availableFeatures) |
|
1230 | + && count($availableFeatures) > 0) { |
|
1231 | + natcasesort($availableFeatures); |
|
1232 | + //natcasesort keeps indices, but we must get rid of them for proper |
|
1233 | + //sorting in the web UI. Therefore: array_values |
|
1234 | + $this->result->addOptions($dbkey, array_values($availableFeatures)); |
|
1235 | + } else { |
|
1236 | + throw new \Exception(self::$l->t('Could not find the desired feature')); |
|
1237 | + } |
|
1238 | + |
|
1239 | + $setFeatures = $this->configuration->$confkey; |
|
1240 | + if (is_array($setFeatures) && !empty($setFeatures)) { |
|
1241 | + //something is already configured? pre-select it. |
|
1242 | + $this->result->addChange($dbkey, $setFeatures); |
|
1243 | + } elseif ($po && $maxEntryObjC !== '') { |
|
1244 | + //pre-select objectclass with most result entries |
|
1245 | + $maxEntryObjC = str_replace($p, '', $maxEntryObjC); |
|
1246 | + $this->applyFind($dbkey, $maxEntryObjC); |
|
1247 | + $this->result->addChange($dbkey, $maxEntryObjC); |
|
1248 | + } |
|
1249 | + |
|
1250 | + return $availableFeatures; |
|
1251 | + } |
|
1252 | + |
|
1253 | + /** |
|
1254 | + * appends a list of values fr |
|
1255 | + * @param resource $result the return value from ldap_get_attributes |
|
1256 | + * @param string $attribute the attribute values to look for |
|
1257 | + * @param array &$known new values will be appended here |
|
1258 | + * @return int, state on of the class constants LRESULT_PROCESSED_OK, |
|
1259 | + * LRESULT_PROCESSED_INVALID or LRESULT_PROCESSED_SKIP |
|
1260 | + */ |
|
1261 | + private function getAttributeValuesFromEntry($result, $attribute, &$known) { |
|
1262 | + if (!is_array($result) |
|
1263 | + || !isset($result['count']) |
|
1264 | + || !$result['count'] > 0) { |
|
1265 | + return self::LRESULT_PROCESSED_INVALID; |
|
1266 | + } |
|
1267 | + |
|
1268 | + // strtolower on all keys for proper comparison |
|
1269 | + $result = \OCP\Util::mb_array_change_key_case($result); |
|
1270 | + $attribute = strtolower($attribute); |
|
1271 | + if (isset($result[$attribute])) { |
|
1272 | + foreach ($result[$attribute] as $key => $val) { |
|
1273 | + if ($key === 'count') { |
|
1274 | + continue; |
|
1275 | + } |
|
1276 | + if (!in_array($val, $known)) { |
|
1277 | + $known[] = $val; |
|
1278 | + } |
|
1279 | + } |
|
1280 | + return self::LRESULT_PROCESSED_OK; |
|
1281 | + } else { |
|
1282 | + return self::LRESULT_PROCESSED_SKIP; |
|
1283 | + } |
|
1284 | + } |
|
1285 | + |
|
1286 | + /** |
|
1287 | + * @return bool|mixed |
|
1288 | + */ |
|
1289 | + private function getConnection() { |
|
1290 | + if (!is_null($this->cr)) { |
|
1291 | + return $this->cr; |
|
1292 | + } |
|
1293 | + |
|
1294 | + $cr = $this->ldap->connect( |
|
1295 | + $this->configuration->ldapHost, |
|
1296 | + $this->configuration->ldapPort |
|
1297 | + ); |
|
1298 | + |
|
1299 | + $this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3); |
|
1300 | + $this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0); |
|
1301 | + $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT); |
|
1302 | + if ($this->configuration->ldapTLS === 1) { |
|
1303 | + $this->ldap->startTls($cr); |
|
1304 | + } |
|
1305 | + |
|
1306 | + $lo = @$this->ldap->bind($cr, |
|
1307 | + $this->configuration->ldapAgentName, |
|
1308 | + $this->configuration->ldapAgentPassword); |
|
1309 | + if ($lo === true) { |
|
1310 | + $this->$cr = $cr; |
|
1311 | + return $cr; |
|
1312 | + } |
|
1313 | + |
|
1314 | + return false; |
|
1315 | + } |
|
1316 | + |
|
1317 | + /** |
|
1318 | + * @return array |
|
1319 | + */ |
|
1320 | + private function getDefaultLdapPortSettings() { |
|
1321 | + static $settings = [ |
|
1322 | + ['port' => 7636, 'tls' => false], |
|
1323 | + ['port' => 636, 'tls' => false], |
|
1324 | + ['port' => 7389, 'tls' => true], |
|
1325 | + ['port' => 389, 'tls' => true], |
|
1326 | + ['port' => 7389, 'tls' => false], |
|
1327 | + ['port' => 389, 'tls' => false], |
|
1328 | + ]; |
|
1329 | + return $settings; |
|
1330 | + } |
|
1331 | + |
|
1332 | + /** |
|
1333 | + * @return array |
|
1334 | + */ |
|
1335 | + private function getPortSettingsToTry() { |
|
1336 | + //389 ← LDAP / Unencrypted or StartTLS |
|
1337 | + //636 ← LDAPS / SSL |
|
1338 | + //7xxx ← UCS. need to be checked first, because both ports may be open |
|
1339 | + $host = $this->configuration->ldapHost; |
|
1340 | + $port = (int)$this->configuration->ldapPort; |
|
1341 | + $portSettings = []; |
|
1342 | + |
|
1343 | + //In case the port is already provided, we will check this first |
|
1344 | + if ($port > 0) { |
|
1345 | + $hostInfo = parse_url($host); |
|
1346 | + if (!(is_array($hostInfo) |
|
1347 | + && isset($hostInfo['scheme']) |
|
1348 | + && stripos($hostInfo['scheme'], 'ldaps') !== false)) { |
|
1349 | + $portSettings[] = ['port' => $port, 'tls' => true]; |
|
1350 | + } |
|
1351 | + $portSettings[] = ['port' => $port, 'tls' => false]; |
|
1352 | + } |
|
1353 | + |
|
1354 | + //default ports |
|
1355 | + $portSettings = array_merge($portSettings, |
|
1356 | + $this->getDefaultLdapPortSettings()); |
|
1357 | + |
|
1358 | + return $portSettings; |
|
1359 | + } |
|
1360 | 1360 | } |