diff options
Diffstat (limited to 'apps/user_ldap/lib')
47 files changed, 741 insertions, 773 deletions
diff --git a/apps/user_ldap/lib/Access.php b/apps/user_ldap/lib/Access.php index 5677f3614cc..6744b044cdf 100644 --- a/apps/user_ldap/lib/Access.php +++ b/apps/user_ldap/lib/Access.php @@ -134,7 +134,7 @@ class Access extends LDAPUtility { * @return AbstractMapping */ public function getUserMapper() { - if(is_null($this->userMapper)) { + if (is_null($this->userMapper)) { throw new \Exception('UserMapper was not assigned to this Access instance.'); } return $this->userMapper; @@ -154,7 +154,7 @@ class Access extends LDAPUtility { * @return AbstractMapping */ public function getGroupMapper() { - if(is_null($this->groupMapper)) { + if (is_null($this->groupMapper)) { throw new \Exception('GroupMapper was not assigned to this Access instance.'); } return $this->groupMapper; @@ -187,14 +187,14 @@ class Access extends LDAPUtility { * @throws ServerNotAvailableException */ public function readAttribute($dn, $attr, $filter = 'objectClass=*') { - if(!$this->checkConnection()) { + if (!$this->checkConnection()) { \OCP\Util::writeLog('user_ldap', 'No LDAP Connector assigned, access impossible for readAttribute.', ILogger::WARN); return false; } $cr = $this->connection->getConnectionResource(); - if(!$this->ldap->isResource($cr)) { + if (!$this->ldap->isResource($cr)) { //LDAP not available \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG); return false; @@ -217,7 +217,7 @@ class Access extends LDAPUtility { $isRangeRequest = false; do { $result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults); - if(is_bool($result)) { + if (is_bool($result)) { // when an exists request was run and it was successful, an empty // array must be returned return $result ? [] : false; @@ -239,7 +239,7 @@ class Access extends LDAPUtility { ); $values = array_merge($values, $normalizedResult); - if($result['rangeHigh'] === '*') { + if ($result['rangeHigh'] === '*') { // when server replies with * as high range value, there are // no more results left return $values; @@ -249,7 +249,7 @@ class Access extends LDAPUtility { $isRangeRequest = true; } } - } while($isRangeRequest); + } while ($isRangeRequest); \OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, ILogger::DEBUG); return false; @@ -306,12 +306,12 @@ class Access extends LDAPUtility { */ public function extractAttributeValuesFromResult($result, $attribute) { $values = []; - if(isset($result[$attribute]) && $result[$attribute]['count'] > 0) { + if (isset($result[$attribute]) && $result[$attribute]['count'] > 0) { $lowercaseAttribute = strtolower($attribute); - for($i=0;$i<$result[$attribute]['count'];$i++) { - if($this->resemblesDN($attribute)) { + for ($i=0;$i<$result[$attribute]['count'];$i++) { + if ($this->resemblesDN($attribute)) { $values[] = $this->helper->sanitizeDN($result[$attribute][$i]); - } elseif($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') { + } elseif ($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') { $values[] = $this->convertObjectGUID2Str($result[$attribute][$i]); } else { $values[] = $result[$attribute][$i]; @@ -333,10 +333,10 @@ class Access extends LDAPUtility { */ public function extractRangeData($result, $attribute) { $keys = array_keys($result); - foreach($keys as $key) { - if($key !== $attribute && strpos($key, $attribute) === 0) { + foreach ($keys as $key) { + if ($key !== $attribute && strpos($key, $attribute) === 0) { $queryData = explode(';', $key); - if(strpos($queryData[1], 'range=') === 0) { + if (strpos($queryData[1], 'range=') === 0) { $high = substr($queryData[1], 1 + strpos($queryData[1], '-')); $data = [ 'values' => $result[$key], @@ -361,11 +361,11 @@ class Access extends LDAPUtility { * @throws \Exception */ public function setPassword($userDN, $password) { - if((int)$this->connection->turnOnPasswordChange !== 1) { + if ((int)$this->connection->turnOnPasswordChange !== 1) { throw new \Exception('LDAP password changes are disabled.'); } $cr = $this->connection->getConnectionResource(); - if(!$this->ldap->isResource($cr)) { + if (!$this->ldap->isResource($cr)) { //LDAP not available \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG); return false; @@ -374,7 +374,7 @@ class Access extends LDAPUtility { // try PASSWD extended operation first return @$this->invokeLDAPMethod('exopPasswd', $cr, $userDN, '', $password) || @$this->invokeLDAPMethod('modReplace', $cr, $userDN, $password); - } catch(ConstraintViolationException $e) { + } catch (ConstraintViolationException $e) { throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ').$e->getMessage(), $e->getCode()); } } @@ -416,17 +416,17 @@ class Access extends LDAPUtility { */ public function getDomainDNFromDN($dn) { $allParts = $this->ldap->explodeDN($dn, 0); - if($allParts === false) { + if ($allParts === false) { //not a valid DN return ''; } $domainParts = []; $dcFound = false; - foreach($allParts as $part) { - if(!$dcFound && strpos($part, 'dc=') === 0) { + foreach ($allParts as $part) { + if (!$dcFound && strpos($part, 'dc=') === 0) { $dcFound = true; } - if($dcFound) { + if ($dcFound) { $domainParts[] = $part; } } @@ -452,7 +452,7 @@ class Access extends LDAPUtility { //Check whether the DN belongs to the Base, to avoid issues on multi- //server setups - if(is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) { + if (is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) { return $fdn; } @@ -471,7 +471,7 @@ class Access extends LDAPUtility { //To avoid bypassing the base DN settings under certain circumstances //with the group support, check whether the provided DN matches one of //the given Bases - if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) { + if (!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) { return false; } @@ -489,11 +489,11 @@ class Access extends LDAPUtility { */ public function groupsMatchFilter($groupDNs) { $validGroupDNs = []; - foreach($groupDNs as $dn) { + foreach ($groupDNs as $dn) { $cacheKey = 'groupsMatchFilter-'.$dn; $groupMatchFilter = $this->connection->getFromCache($cacheKey); - if(!is_null($groupMatchFilter)) { - if($groupMatchFilter) { + if (!is_null($groupMatchFilter)) { + if ($groupMatchFilter) { $validGroupDNs[] = $dn; } continue; @@ -501,19 +501,18 @@ class Access extends LDAPUtility { // Check the base DN first. If this is not met already, we don't // need to ask the server at all. - if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) { + if (!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) { $this->connection->writeToCache($cacheKey, false); continue; } $result = $this->readAttribute($dn, '', $this->connection->ldapGroupFilter); - if(is_array($result)) { + if (is_array($result)) { $this->connection->writeToCache($cacheKey, true); $validGroupDNs[] = $dn; } else { $this->connection->writeToCache($cacheKey, false); } - } return $validGroupDNs; } @@ -530,7 +529,7 @@ class Access extends LDAPUtility { //To avoid bypassing the base DN settings under certain circumstances //with the group support, check whether the provided DN matches one of //the given Bases - if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) { + if (!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) { return false; } @@ -550,7 +549,7 @@ class Access extends LDAPUtility { */ public function dn2ocname($fdn, $ldapName = null, $isUser = true, &$newlyMapped = null, array $record = null) { $newlyMapped = false; - if($isUser) { + if ($isUser) { $mapper = $this->getUserMapper(); $nameAttribute = $this->connection->ldapUserDisplayName; $filter = $this->connection->ldapUserFilter; @@ -562,15 +561,15 @@ class Access extends LDAPUtility { //let's try to retrieve the Nextcloud name from the mappings table $ncName = $mapper->getNameByDN($fdn); - if(is_string($ncName)) { + if (is_string($ncName)) { return $ncName; } //second try: get the UUID and check if it is known. Then, update the DN and return the name. $uuid = $this->getUUID($fdn, $isUser, $record); - if(is_string($uuid)) { + if (is_string($uuid)) { $ncName = $mapper->getNameByUUID($uuid); - if(is_string($ncName)) { + if (is_string($ncName)) { $mapper->setDNbyUUID($fdn, $uuid); return $ncName; } @@ -580,16 +579,16 @@ class Access extends LDAPUtility { return false; } - if(is_null($ldapName)) { + if (is_null($ldapName)) { $ldapName = $this->readAttribute($fdn, $nameAttribute, $filter); - if(!isset($ldapName[0]) && empty($ldapName[0])) { + if (!isset($ldapName[0]) && empty($ldapName[0])) { \OCP\Util::writeLog('user_ldap', 'No or empty name for '.$fdn.' with filter '.$filter.'.', ILogger::INFO); return false; } $ldapName = $ldapName[0]; } - if($isUser) { + if ($isUser) { $usernameAttribute = (string)$this->connection->ldapExpertUsernameAttr; if ($usernameAttribute !== '') { $username = $this->readAttribute($fdn, $usernameAttribute); @@ -620,14 +619,14 @@ class Access extends LDAPUtility { // outside of core user management will still cache the user as non-existing. $originalTTL = $this->connection->ldapCacheTTL; $this->connection->setConfiguration(['ldapCacheTTL' => 0]); - if($intName !== '' + if ($intName !== '' && (($isUser && !$this->ncUserManager->userExists($intName)) || (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName)) ) ) { $this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]); $newlyMapped = $this->mapAndAnnounceIfApplicable($mapper, $fdn, $intName, $uuid, $isUser); - if($newlyMapped) { + if ($newlyMapped) { return $intName; } } @@ -635,7 +634,7 @@ class Access extends LDAPUtility { $this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]); $altName = $this->createAltInternalOwnCloudName($intName, $isUser); if (is_string($altName)) { - if($this->mapAndAnnounceIfApplicable($mapper, $fdn, $altName, $uuid, $isUser)) { + if ($this->mapAndAnnounceIfApplicable($mapper, $fdn, $altName, $uuid, $isUser)) { $newlyMapped = true; return $altName; } @@ -653,7 +652,7 @@ class Access extends LDAPUtility { string $uuid, bool $isUser ) :bool { - if($mapper->map($fdn, $name, $uuid)) { + if ($mapper->map($fdn, $name, $uuid)) { if ($this->ncUserManager instanceof PublicEmitter && $isUser) { $this->cacheUserExists($name); $this->ncUserManager->emit('\OC\User', 'assignedUserId', [$name]); @@ -698,7 +697,7 @@ class Access extends LDAPUtility { * @throws \Exception */ private function ldap2NextcloudNames($ldapObjects, $isUsers) { - if($isUsers) { + if ($isUsers) { $nameAttribute = $this->connection->ldapUserDisplayName; $sndAttribute = $this->connection->ldapUserDisplayName2; } else { @@ -706,9 +705,9 @@ class Access extends LDAPUtility { } $nextcloudNames = []; - foreach($ldapObjects as $ldapObject) { + foreach ($ldapObjects as $ldapObject) { $nameByLDAP = null; - if(isset($ldapObject[$nameAttribute]) + if (isset($ldapObject[$nameAttribute]) && is_array($ldapObject[$nameAttribute]) && isset($ldapObject[$nameAttribute][0]) ) { @@ -717,19 +716,19 @@ class Access extends LDAPUtility { } $ncName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers); - if($ncName) { + if ($ncName) { $nextcloudNames[] = $ncName; - if($isUsers) { + if ($isUsers) { $this->updateUserState($ncName); //cache the user names so it does not need to be retrieved //again later (e.g. sharing dialogue). - if(is_null($nameByLDAP)) { + if (is_null($nameByLDAP)) { continue; } $sndName = isset($ldapObject[$sndAttribute][0]) ? $ldapObject[$sndAttribute][0] : ''; $this->cacheUserDisplayName($ncName, $nameByLDAP, $sndName); - } elseif($nameByLDAP !== null) { + } elseif ($nameByLDAP !== null) { $this->cacheGroupDisplayName($ncName, $nameByLDAP); } } @@ -745,7 +744,7 @@ class Access extends LDAPUtility { */ public function updateUserState($ncname) { $user = $this->userManager->get($ncname); - if($user instanceof OfflineUser) { + if ($user instanceof OfflineUser) { $user->unmark(); } } @@ -785,7 +784,7 @@ class Access extends LDAPUtility { */ public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') { $user = $this->userManager->get($ocName); - if($user === null) { + if ($user === null) { return; } $displayName = $user->composeAndStoreDisplayName($displayName, $displayName2); @@ -810,9 +809,9 @@ class Access extends LDAPUtility { $attempts = 0; //while loop is just a precaution. If a name is not generated within //20 attempts, something else is very wrong. Avoids infinite loop. - while($attempts < 20){ + while ($attempts < 20) { $altName = $name . '_' . rand(1000,9999); - if(!$this->ncUserManager->userExists($altName)) { + if (!$this->ncUserManager->userExists($altName)) { return $altName; } $attempts++; @@ -834,7 +833,7 @@ class Access extends LDAPUtility { */ private function _createAltInternalOwnCloudNameForGroups($name) { $usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%'); - if(!$usedNames || count($usedNames) === 0) { + if (!$usedNames || count($usedNames) === 0) { $lastNo = 1; //will become name_2 } else { natsort($usedNames); @@ -845,11 +844,11 @@ class Access extends LDAPUtility { unset($usedNames); $attempts = 1; - while($attempts < 21){ + while ($attempts < 21) { // Check to be really sure it is unique // while loop is just a precaution. If a name is not generated within // 20 attempts, something else is very wrong. Avoids infinite loop. - if(!\OC::$server->getGroupManager()->groupExists($altName)) { + if (!\OC::$server->getGroupManager()->groupExists($altName)) { return $altName; } $altName = $name . '_' . ($lastNo + $attempts); @@ -867,7 +866,7 @@ class Access extends LDAPUtility { private function createAltInternalOwnCloudName($name, $isUser) { $originalTTL = $this->connection->ldapCacheTTL; $this->connection->setConfiguration(['ldapCacheTTL' => 0]); - if($isUser) { + if ($isUser) { $altName = $this->_createAltInternalOwnCloudNameForUsers($name); } else { $altName = $this->_createAltInternalOwnCloudNameForGroups($name); @@ -916,13 +915,13 @@ class Access extends LDAPUtility { public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null, $forceApplyAttributes = false) { $ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset); $recordsToUpdate = $ldapRecords; - if(!$forceApplyAttributes) { + if (!$forceApplyAttributes) { $isBackgroundJobModeAjax = $this->config ->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax'; $recordsToUpdate = array_filter($ldapRecords, function ($record) use ($isBackgroundJobModeAjax) { $newlyMapped = false; $uid = $this->dn2ocname($record['dn'][0], null, true, $newlyMapped, $record); - if(is_string($uid)) { + if (is_string($uid)) { $this->cacheUserExists($uid); } return ($uid !== false) && ($newlyMapped || $isBackgroundJobModeAjax); @@ -942,13 +941,13 @@ class Access extends LDAPUtility { */ public function batchApplyUserAttributes(array $ldapRecords) { $displayNameAttribute = strtolower($this->connection->ldapUserDisplayName); - foreach($ldapRecords as $userRecord) { - if(!isset($userRecord[$displayNameAttribute])) { + foreach ($ldapRecords as $userRecord) { + if (!isset($userRecord[$displayNameAttribute])) { // displayName is obligatory continue; } $ocName = $this->dn2ocname($userRecord['dn'][0], null, true); - if($ocName === false) { + if ($ocName === false) { continue; } $this->updateUserState($ocName); @@ -976,7 +975,7 @@ class Access extends LDAPUtility { array_walk($groupRecords, function ($record) { $newlyMapped = false; $gid = $this->dn2ocname($record['dn'][0], null, false, $newlyMapped, $record); - if(!$newlyMapped && is_string($gid)) { + if (!$newlyMapped && is_string($gid)) { $this->cacheGroupExists($gid); } }); @@ -989,8 +988,8 @@ class Access extends LDAPUtility { * @return array */ private function fetchList($list, $manyAttributes) { - if(is_array($list)) { - if($manyAttributes) { + if (is_array($list)) { + if ($manyAttributes) { return $list; } else { $list = array_reduce($list, function ($carry, $item) { @@ -1020,7 +1019,7 @@ class Access extends LDAPUtility { */ public function searchUsers($filter, $attr = null, $limit = null, $offset = null) { $result = []; - foreach($this->connection->ldapBaseUsers as $base) { + foreach ($this->connection->ldapBaseUsers as $base) { $result = array_merge($result, $this->search($filter, [$base], $attr, $limit, $offset)); } return $result; @@ -1036,7 +1035,7 @@ class Access extends LDAPUtility { */ public function countUsers($filter, $attr = ['dn'], $limit = null, $offset = null) { $result = false; - foreach($this->connection->ldapBaseUsers as $base) { + foreach ($this->connection->ldapBaseUsers as $base) { $count = $this->count($filter, [$base], $attr, $limit, $offset); $result = is_int($count) ? (int)$result + $count : $result; } @@ -1057,7 +1056,7 @@ class Access extends LDAPUtility { */ public function searchGroups($filter, $attr = null, $limit = null, $offset = null) { $result = []; - foreach($this->connection->ldapBaseGroups as $base) { + foreach ($this->connection->ldapBaseGroups as $base) { $result = array_merge($result, $this->search($filter, [$base], $attr, $limit, $offset)); } return $result; @@ -1075,7 +1074,7 @@ class Access extends LDAPUtility { */ public function countGroups($filter, $attr = ['dn'], $limit = null, $offset = null) { $result = false; - foreach($this->connection->ldapBaseGroups as $base) { + foreach ($this->connection->ldapBaseGroups as $base) { $count = $this->count($filter, [$base], $attr, $limit, $offset); $result = is_int($count) ? (int)$result + $count : $result; } @@ -1092,7 +1091,7 @@ class Access extends LDAPUtility { */ public function countObjects($limit = null, $offset = null) { $result = false; - foreach($this->connection->ldapBase as $base) { + foreach ($this->connection->ldapBase as $base) { $count = $this->count('objectclass=*', [$base], ['dn'], $limit, $offset); $result = is_int($count) ? (int)$result + $count : $result; } @@ -1137,7 +1136,7 @@ class Access extends LDAPUtility { $this->connection->resetConnectionResource(); $cr = $this->connection->getConnectionResource(); - if(!$this->ldap->isResource($cr)) { + if (!$this->ldap->isResource($cr)) { // Seems like we didn't find any resource. \OCP\Util::writeLog('user_ldap', "Could not $command, because resource is missing.", ILogger::DEBUG); throw $e; @@ -1162,13 +1161,13 @@ class Access extends LDAPUtility { * @throws ServerNotAvailableException */ private function executeSearch($filter, $base, &$attr = null, $limit = null, $offset = null) { - if(!is_null($attr) && !is_array($attr)) { + if (!is_null($attr) && !is_array($attr)) { $attr = [mb_strtolower($attr, 'UTF-8')]; } // See if we have a resource, in case not cancel with message $cr = $this->connection->getConnectionResource(); - if(!$this->ldap->isResource($cr)) { + if (!$this->ldap->isResource($cr)) { // Seems like we didn't find any resource. // Return an empty array just like before. \OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', ILogger::DEBUG); @@ -1182,7 +1181,7 @@ class Access extends LDAPUtility { $sr = $this->invokeLDAPMethod('search', $linkResources, $base, $filter, $attr); // cannot use $cr anymore, might have changed in the previous call! $error = $this->ldap->errno($this->connection->getConnectionResource()); - if(!is_array($sr) || $error !== 0) { + if (!is_array($sr) || $error !== 0) { \OCP\Util::writeLog('user_ldap', 'Attempt for Paging? '.print_r($pagedSearchOK, true), ILogger::ERROR); return false; } @@ -1207,26 +1206,26 @@ class Access extends LDAPUtility { */ private function processPagedSearchStatus($sr, $filter, $base, $iFoundItems, $limit, $offset, $pagedSearchOK, $skipHandling) { $cookie = null; - if($pagedSearchOK) { + if ($pagedSearchOK) { $cr = $this->connection->getConnectionResource(); - foreach($sr as $key => $res) { - if($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) { + foreach ($sr as $key => $res) { + if ($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) { $this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie); } } //browsing through prior pages to get the cookie for the new one - if($skipHandling) { + if ($skipHandling) { return false; } // if count is bigger, then the server does not support // paged search. Instead, he did a normal search. We set a // flag here, so the callee knows how to deal with it. - if($iFoundItems <= $limit) { + if ($iFoundItems <= $limit) { $this->pagedSearchedSuccessful = true; } } else { - if(!is_null($limit) && (int)$this->connection->ldapPagingSize !== 0) { + if (!is_null($limit) && (int)$this->connection->ldapPagingSize !== 0) { \OC::$server->getLogger()->debug( 'Paged search was not available', [ 'app' => 'user_ldap' ] @@ -1259,7 +1258,7 @@ class Access extends LDAPUtility { \OCP\Util::writeLog('user_ldap', 'Count filter: '.print_r($filter, true), ILogger::DEBUG); $limitPerPage = (int)$this->connection->ldapPagingSize; - if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) { + if (!is_null($limit) && $limit < $limitPerPage && $limit > 0) { $limitPerPage = $limit; } @@ -1269,7 +1268,7 @@ class Access extends LDAPUtility { do { $search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset); - if($search === false) { + if ($search === false) { return $counter > 0 ? $counter : false; } list($sr, $pagedSearchOK) = $search; @@ -1288,7 +1287,7 @@ class Access extends LDAPUtility { * Continue now depends on $hasMorePages value */ $continue = $pagedSearchOK && $hasMorePages; - } while($continue && (is_null($limit) || $limit <= 0 || $limit > $counter)); + } while ($continue && (is_null($limit) || $limit <= 0 || $limit > $counter)); return $counter; } @@ -1301,7 +1300,7 @@ class Access extends LDAPUtility { private function countEntriesInSearchResults($searchResults) { $counter = 0; - foreach($searchResults as $res) { + foreach ($searchResults as $res) { $count = (int)$this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $res); $counter += $count; } @@ -1323,7 +1322,7 @@ class Access extends LDAPUtility { */ public function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) { $limitPerPage = (int)$this->connection->ldapPagingSize; - if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) { + if (!is_null($limit) && $limit < $limitPerPage && $limit > 0) { $limitPerPage = $limit; } @@ -1337,13 +1336,13 @@ class Access extends LDAPUtility { $savedoffset = $offset; do { $search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset); - if($search === false) { + if ($search === false) { return []; } list($sr, $pagedSearchOK) = $search; $cr = $this->connection->getConnectionResource(); - if($skipHandling) { + if ($skipHandling) { //i.e. result do not need to be fetched, we just need the cookie //thus pass 1 or any other value as $iFoundItems because it is not //used @@ -1354,7 +1353,7 @@ class Access extends LDAPUtility { } $iFoundItems = 0; - foreach($sr as $res) { + foreach ($sr as $res) { $findings = array_merge($findings, $this->invokeLDAPMethod('getEntries', $cr, $res)); $iFoundItems = max($iFoundItems, $findings['count']); unset($findings['count']); @@ -1370,27 +1369,27 @@ class Access extends LDAPUtility { // if we're here, probably no connection resource is returned. // to make Nextcloud behave nicely, we simply give back an empty array. - if(is_null($findings)) { + if (is_null($findings)) { return []; } - if(!is_null($attr)) { + if (!is_null($attr)) { $selection = []; $i = 0; - foreach($findings as $item) { - if(!is_array($item)) { + foreach ($findings as $item) { + if (!is_array($item)) { continue; } $item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8'); - foreach($attr as $key) { - if(isset($item[$key])) { - if(is_array($item[$key]) && isset($item[$key]['count'])) { + foreach ($attr as $key) { + if (isset($item[$key])) { + if (is_array($item[$key]) && isset($item[$key]['count'])) { unset($item[$key]['count']); } - if($key !== 'dn') { - if($this->resemblesDN($key)) { + if ($key !== 'dn') { + if ($this->resemblesDN($key)) { $selection[$i][$key] = $this->helper->sanitizeDN($item[$key]); - } elseif($key === 'objectguid' || $key === 'guid') { + } elseif ($key === 'objectguid' || $key === 'guid') { $selection[$i][$key] = [$this->convertObjectGUID2Str($item[$key][0])]; } else { $selection[$i][$key] = $item[$key]; @@ -1399,7 +1398,6 @@ class Access extends LDAPUtility { $selection[$i][$key] = [$this->helper->sanitizeDN($item[$key])]; } } - } $i++; } @@ -1408,7 +1406,7 @@ class Access extends LDAPUtility { //we slice the findings, when //a) paged search unsuccessful, though attempted //b) no paged search, but limit set - if((!$this->getPagedSearchResultState() + if ((!$this->getPagedSearchResultState() && $pagedSearchOK) || ( !$pagedSearchOK @@ -1428,13 +1426,13 @@ class Access extends LDAPUtility { public function sanitizeUsername($name) { $name = trim($name); - if($this->connection->ldapIgnoreNamingRules) { + if ($this->connection->ldapIgnoreNamingRules) { return $name; } // Transliteration to ASCII $transliterated = @iconv('UTF-8', 'ASCII//TRANSLIT', $name); - if($transliterated !== false) { + if ($transliterated !== false) { // depending on system config iconv can work or not $name = $transliterated; } @@ -1445,7 +1443,7 @@ class Access extends LDAPUtility { // Every remaining disallowed characters will be removed $name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name); - if($name === '') { + if ($name === '') { throw new \InvalidArgumentException('provided name template for username does not contain any allowed characters'); } @@ -1460,7 +1458,7 @@ class Access extends LDAPUtility { */ public function escapeFilterPart($input, $allowAsterisk = false) { $asterisk = ''; - if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') { + if ($allowAsterisk && strlen($input) > 0 && $input[0] === '*') { $asterisk = '*'; $input = mb_substr($input, 1, null, 'UTF-8'); } @@ -1496,7 +1494,7 @@ class Access extends LDAPUtility { */ private function combineFilter($filters, $operator) { $combinedFilter = '('.$operator; - foreach($filters as $filter) { + foreach ($filters as $filter) { if ($filter !== '' && $filter[0] !== '(') { $filter = '('.$filter.')'; } @@ -1538,16 +1536,16 @@ class Access extends LDAPUtility { * @throws \Exception */ private function getAdvancedFilterPartForSearch($search, $searchAttributes) { - if(!is_array($searchAttributes) || count($searchAttributes) < 2) { + if (!is_array($searchAttributes) || count($searchAttributes) < 2) { throw new \Exception('searchAttributes must be an array with at least two string'); } $searchWords = explode(' ', trim($search)); $wordFilters = []; - foreach($searchWords as $word) { + foreach ($searchWords as $word) { $word = $this->prepareSearchTerm($word); //every word needs to appear at least once $wordMatchOneAttrFilters = []; - foreach($searchAttributes as $attr) { + foreach ($searchAttributes as $attr) { $wordMatchOneAttrFilters[] = $attr . '=' . $word; } $wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters); @@ -1566,10 +1564,10 @@ class Access extends LDAPUtility { private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) { $filter = []; $haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0); - if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) { + if ($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) { try { return $this->getAdvancedFilterPartForSearch($search, $searchAttributes); - } catch(\Exception $e) { + } catch (\Exception $e) { \OCP\Util::writeLog( 'user_ldap', 'Creating advanced filter for search failed, falling back to simple method.', @@ -1579,17 +1577,17 @@ class Access extends LDAPUtility { } $search = $this->prepareSearchTerm($search); - if(!is_array($searchAttributes) || count($searchAttributes) === 0) { + if (!is_array($searchAttributes) || count($searchAttributes) === 0) { if ($fallbackAttribute === '') { return ''; } $filter[] = $fallbackAttribute . '=' . $search; } else { - foreach($searchAttributes as $attribute) { + foreach ($searchAttributes as $attribute) { $filter[] = $attribute . '=' . $search; } } - if(count($filter) === 1) { + if (count($filter) === 1) { return '('.$filter[0].')'; } return $this->combineFilterWithOr($filter); @@ -1640,7 +1638,7 @@ class Access extends LDAPUtility { 'ldapAgentName' => $name, 'ldapAgentPassword' => $password ]; - if(!$testConnection->setConfiguration($credentials)) { + if (!$testConnection->setConfiguration($credentials)) { return false; } return $testConnection->bind(); @@ -1662,30 +1660,30 @@ class Access extends LDAPUtility { // Sacrebleu! The UUID attribute is unknown :( We need first an // existing DN to be able to reliably detect it. $result = $this->search($filter, $base, ['dn'], 1); - if(!isset($result[0]) || !isset($result[0]['dn'])) { + if (!isset($result[0]) || !isset($result[0]['dn'])) { throw new \Exception('Cannot determine UUID attribute'); } $dn = $result[0]['dn'][0]; - if(!$this->detectUuidAttribute($dn, true)) { + if (!$this->detectUuidAttribute($dn, true)) { throw new \Exception('Cannot determine UUID attribute'); } } else { // The UUID attribute is either known or an override is given. // By calling this method we ensure that $this->connection->$uuidAttr // is definitely set - if(!$this->detectUuidAttribute('', true)) { + if (!$this->detectUuidAttribute('', true)) { throw new \Exception('Cannot determine UUID attribute'); } } $uuidAttr = $this->connection->ldapUuidUserAttribute; - if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') { + if ($uuidAttr === 'guid' || $uuidAttr === 'objectguid') { $uuid = $this->formatGuid2ForFilterUser($uuid); } $filter = $uuidAttr . '=' . $uuid; $result = $this->searchUsers($filter, ['dn'], 2); - if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) { + if (is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) { // we put the count into account to make sure that this is // really unique return $result[0]['dn'][0]; @@ -1705,7 +1703,7 @@ class Access extends LDAPUtility { * @throws ServerNotAvailableException */ private function detectUuidAttribute($dn, $isUser = true, $force = false, array $ldapRecord = null) { - if($isUser) { + if ($isUser) { $uuidAttr = 'ldapUuidUserAttribute'; $uuidOverride = $this->connection->ldapExpertUUIDUserAttr; } else { @@ -1713,8 +1711,8 @@ class Access extends LDAPUtility { $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr; } - if(!$force) { - if($this->connection->$uuidAttr !== 'auto') { + if (!$force) { + if ($this->connection->$uuidAttr !== 'auto') { return true; } elseif (is_string($uuidOverride) && trim($uuidOverride) !== '') { $this->connection->$uuidAttr = $uuidOverride; @@ -1722,23 +1720,23 @@ class Access extends LDAPUtility { } $attribute = $this->connection->getFromCache($uuidAttr); - if(!$attribute === null) { + if (!$attribute === null) { $this->connection->$uuidAttr = $attribute; return true; } } - foreach(self::UUID_ATTRIBUTES as $attribute) { - if($ldapRecord !== null) { + foreach (self::UUID_ATTRIBUTES as $attribute) { + if ($ldapRecord !== null) { // we have the info from LDAP already, we don't need to talk to the server again - if(isset($ldapRecord[$attribute])) { + if (isset($ldapRecord[$attribute])) { $this->connection->$uuidAttr = $attribute; return true; } } $value = $this->readAttribute($dn, $attribute); - if(is_array($value) && isset($value[0]) && !empty($value[0])) { + if (is_array($value) && isset($value[0]) && !empty($value[0])) { \OC::$server->getLogger()->debug( 'Setting {attribute} as {subject}', [ @@ -1765,7 +1763,7 @@ class Access extends LDAPUtility { * @throws ServerNotAvailableException */ public function getUUID($dn, $isUser = true, $ldapRecord = null) { - if($isUser) { + if ($isUser) { $uuidAttr = 'ldapUuidUserAttribute'; $uuidOverride = $this->connection->ldapExpertUUIDUserAttr; } else { @@ -1774,18 +1772,17 @@ class Access extends LDAPUtility { } $uuid = false; - if($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) { + if ($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) { $attr = $this->connection->$uuidAttr; $uuid = isset($ldapRecord[$attr]) ? $ldapRecord[$attr] : $this->readAttribute($dn, $attr); - if(!is_array($uuid) + if (!is_array($uuid) && $uuidOverride !== '' - && $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord)) - { + && $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord)) { $uuid = isset($ldapRecord[$this->connection->$uuidAttr]) ? $ldapRecord[$this->connection->$uuidAttr] : $this->readAttribute($dn, $this->connection->$uuidAttr); } - if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) { + if (is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) { $uuid = $uuid[0]; } } @@ -1802,15 +1799,15 @@ class Access extends LDAPUtility { private function convertObjectGUID2Str($oguid) { $hex_guid = bin2hex($oguid); $hex_guid_to_guid_str = ''; - for($k = 1; $k <= 4; ++$k) { + for ($k = 1; $k <= 4; ++$k) { $hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2); } $hex_guid_to_guid_str .= '-'; - for($k = 1; $k <= 2; ++$k) { + for ($k = 1; $k <= 2; ++$k) { $hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2); } $hex_guid_to_guid_str .= '-'; - for($k = 1; $k <= 2; ++$k) { + for ($k = 1; $k <= 2; ++$k) { $hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2); } $hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4); @@ -1831,11 +1828,11 @@ class Access extends LDAPUtility { * @return string */ public function formatGuid2ForFilterUser($guid) { - if(!is_string($guid)) { + if (!is_string($guid)) { throw new \InvalidArgumentException('String expected'); } $blocks = explode('-', $guid); - if(count($blocks) !== 5) { + if (count($blocks) !== 5) { /* * Why not throw an Exception instead? This method is a utility * called only when trying to figure out whether a "missing" known @@ -1854,12 +1851,12 @@ class Access extends LDAPUtility { ); return $guid; } - for($i=0; $i < 3; $i++) { + for ($i=0; $i < 3; $i++) { $pairs = str_split($blocks[$i], 2); $pairs = array_reverse($pairs); $blocks[$i] = implode('', $pairs); } - for($i=0; $i < 5; $i++) { + for ($i=0; $i < 5; $i++) { $pairs = str_split($blocks[$i], 2); $blocks[$i] = '\\' . implode('\\', $pairs); } @@ -1877,12 +1874,12 @@ class Access extends LDAPUtility { $domainDN = $this->getDomainDNFromDN($dn); $cacheKey = 'getSID-'.$domainDN; $sid = $this->connection->getFromCache($cacheKey); - if(!is_null($sid)) { + if (!is_null($sid)) { return $sid; } $objectSid = $this->readAttribute($domainDN, 'objectsid'); - if(!is_array($objectSid) || empty($objectSid)) { + if (!is_array($objectSid) || empty($objectSid)) { $this->connection->writeToCache($cacheKey, false); return false; } @@ -1940,12 +1937,12 @@ class Access extends LDAPUtility { $belongsToBase = false; $bases = $this->helper->sanitizeDN($bases); - foreach($bases as $base) { + foreach ($bases as $base) { $belongsToBase = true; - if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) { + if (mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) { $belongsToBase = false; } - if($belongsToBase) { + if ($belongsToBase) { break; } } @@ -1974,16 +1971,16 @@ class Access extends LDAPUtility { * @return string containing the key or empty if none is cached */ private function getPagedResultCookie($base, $filter, $limit, $offset) { - if($offset === 0) { + if ($offset === 0) { return ''; } $offset -= $limit; //we work with cache here $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset; $cookie = ''; - if(isset($this->cookies[$cacheKey])) { + if (isset($this->cookies[$cacheKey])) { $cookie = $this->cookies[$cacheKey]; - if(is_null($cookie)) { + if (is_null($cookie)) { $cookie = ''; } } @@ -2001,7 +1998,7 @@ class Access extends LDAPUtility { * @return bool */ public function hasMoreResults() { - if(empty($this->lastCookie) && $this->lastCookie !== '0') { + if (empty($this->lastCookie) && $this->lastCookie !== '0') { // as in RFC 2696, when all results are returned, the cookie will // be empty. return false; @@ -2021,7 +2018,7 @@ class Access extends LDAPUtility { */ private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) { // allow '0' for 389ds - if(!empty($cookie) || $cookie === '0') { + if (!empty($cookie) || $cookie === '0') { $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset; $this->cookies[$cacheKey] = $cookie; $this->lastCookie = $cookie; @@ -2058,10 +2055,9 @@ class Access extends LDAPUtility { .' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset, ILogger::DEBUG); //get the cookie from the search for the previous search, required by LDAP - foreach($bases as $base) { - + foreach ($bases as $base) { $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset); - if(empty($cookie) && $cookie !== "0" && ($offset > 0)) { + if (empty($cookie) && $cookie !== "0" && ($offset > 0)) { // no cookie known from a potential previous search. We need // to start from 0 to come to the desired page. cookie value // of '0' is valid, because 389ds @@ -2071,17 +2067,17 @@ class Access extends LDAPUtility { //still no cookie? obviously, the server does not like us. Let's skip paging efforts. // '0' is valid, because 389ds //TODO: remember this, probably does not change in the next request... - if(empty($cookie) && $cookie !== '0') { + if (empty($cookie) && $cookie !== '0') { $cookie = null; } } - if(!is_null($cookie)) { + if (!is_null($cookie)) { //since offset = 0, this is a new search. We abandon other searches that might be ongoing. $this->abandonPagedSearch(); $pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult', $this->connection->getConnectionResource(), $limit, false, $cookie); - if(!$pagedSearchOK) { + if (!$pagedSearchOK) { return false; } \OCP\Util::writeLog('user_ldap', 'Ready for a paged search', ILogger::DEBUG); @@ -2089,14 +2085,13 @@ class Access extends LDAPUtility { $e = new \Exception('No paged search possible, Limit '.$limit.' Offset '.$offset); \OC::$server->getLogger()->logException($e, ['level' => ILogger::DEBUG]); } - } - /* ++ Fixing RHDS searches with pages with zero results ++ - * We coudn't get paged searches working with our RHDS for login ($limit = 0), - * due to pages with zero results. - * So we added "&& !empty($this->lastCookie)" to this test to ignore pagination - * if we don't have a previous paged search. - */ + /* ++ Fixing RHDS searches with pages with zero results ++ + * We coudn't get paged searches working with our RHDS for login ($limit = 0), + * due to pages with zero results. + * So we added "&& !empty($this->lastCookie)" to this test to ignore pagination + * if we don't have a previous paged search. + */ } elseif ($limit === 0 && !empty($this->lastCookie)) { // a search without limit was requested. However, if we do use // Paged Search once, we always must do it. This requires us to @@ -2125,5 +2120,4 @@ class Access extends LDAPUtility { } return false; } - } diff --git a/apps/user_ldap/lib/AccessFactory.php b/apps/user_ldap/lib/AccessFactory.php index 04d72a16f29..a85823a4564 100644 --- a/apps/user_ldap/lib/AccessFactory.php +++ b/apps/user_ldap/lib/AccessFactory.php @@ -44,8 +44,7 @@ class AccessFactory { Manager $userManager, Helper $helper, IConfig $config, - IUserManager $ncUserManager) - { + IUserManager $ncUserManager) { $this->ldap = $ldap; $this->userManager = $userManager; $this->helper = $helper; diff --git a/apps/user_ldap/lib/Command/CheckUser.php b/apps/user_ldap/lib/Command/CheckUser.php index 5b837e47b8e..430e9c35960 100644 --- a/apps/user_ldap/lib/Command/CheckUser.php +++ b/apps/user_ldap/lib/Command/CheckUser.php @@ -92,9 +92,9 @@ class CheckUser extends Command { $this->isAllowed($input->getOption('force')); $this->confirmUserIsMapped($uid); $exists = $this->backend->userExistsOnLDAP($uid); - if($exists === true) { + if ($exists === true) { $output->writeln('The user is still available on LDAP.'); - if($input->getOption('update')) { + if ($input->getOption('update')) { $this->updateUser($uid, $output); } return; @@ -130,7 +130,7 @@ class CheckUser extends Command { * @return true */ protected function isAllowed($force) { - if($this->helper->haveDisabledConfigurations() && !$force) { + if ($this->helper->haveDisabledConfigurations() && !$force) { throw new \Exception('Cannot check user existence, because ' . 'disabled LDAP configurations are present.'); } @@ -163,5 +163,4 @@ class CheckUser extends Command { $output->writeln('<error>Error while trying to lookup and update attributes from LDAP</error>'); } } - } diff --git a/apps/user_ldap/lib/Command/CreateEmptyConfig.php b/apps/user_ldap/lib/Command/CreateEmptyConfig.php index fab9c513141..8b2b19a5175 100644 --- a/apps/user_ldap/lib/Command/CreateEmptyConfig.php +++ b/apps/user_ldap/lib/Command/CreateEmptyConfig.php @@ -63,7 +63,7 @@ class CreateEmptyConfig extends Command { $configHolder->saveConfiguration(); $prose = ''; - if(!$input->getOption('only-print-prefix')) { + if (!$input->getOption('only-print-prefix')) { $prose = 'Created new configuration with configID '; } $output->writeln($prose . "{$configPrefix}"); diff --git a/apps/user_ldap/lib/Command/DeleteConfig.php b/apps/user_ldap/lib/Command/DeleteConfig.php index f62caf2902a..fd075ae70c3 100644 --- a/apps/user_ldap/lib/Command/DeleteConfig.php +++ b/apps/user_ldap/lib/Command/DeleteConfig.php @@ -61,7 +61,7 @@ class DeleteConfig extends Command { $success = $this->helper->deleteServerConfiguration($configPrefix); - if($success) { + if ($success) { $output->writeln("Deleted configuration with configID '{$configPrefix}'"); } else { $output->writeln("Cannot delete configuration with configID '{$configPrefix}'"); diff --git a/apps/user_ldap/lib/Command/Search.php b/apps/user_ldap/lib/Command/Search.php index edd4fa71ba0..3c05d6cc2ee 100644 --- a/apps/user_ldap/lib/Command/Search.php +++ b/apps/user_ldap/lib/Command/Search.php @@ -90,16 +90,16 @@ class Search extends Command { * @throws \InvalidArgumentException */ protected function validateOffsetAndLimit($offset, $limit) { - if($limit < 0) { + if ($limit < 0) { throw new \InvalidArgumentException('limit must be 0 or greater'); } - if($offset < 0) { + if ($offset < 0) { throw new \InvalidArgumentException('offset must be 0 or greater'); } - if($limit === 0 && $offset !== 0) { + if ($limit === 0 && $offset !== 0) { throw new \InvalidArgumentException('offset must be 0 if limit is also set to 0'); } - if($offset > 0 && ($offset % $limit !== 0)) { + if ($offset > 0 && ($offset % $limit !== 0)) { throw new \InvalidArgumentException('offset must be a multiple of limit'); } } @@ -113,7 +113,7 @@ class Search extends Command { $limit = (int)$input->getOption('limit'); $this->validateOffsetAndLimit($offset, $limit); - if($input->getOption('group')) { + if ($input->getOption('group')) { $proxy = new Group_Proxy($configPrefixes, $ldapWrapper, \OC::$server->query('LDAPGroupPluginManager')); $getMethod = 'getGroups'; $printID = false; @@ -136,7 +136,7 @@ class Search extends Command { } $result = $proxy->$getMethod($input->getArgument('search'), $limit, $offset); - foreach($result as $id => $name) { + foreach ($result as $id => $name) { $line = $name . ($printID ? ' ('.$id.')' : ''); $output->writeln($line); } diff --git a/apps/user_ldap/lib/Command/SetConfig.php b/apps/user_ldap/lib/Command/SetConfig.php index a1ddf3a591a..4c8c47b6411 100644 --- a/apps/user_ldap/lib/Command/SetConfig.php +++ b/apps/user_ldap/lib/Command/SetConfig.php @@ -36,7 +36,6 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class SetConfig extends Command { - protected function configure() { $this ->setName('ldap:set-config') @@ -63,7 +62,7 @@ class SetConfig extends Command { $helper = new Helper(\OC::$server->getConfig()); $availableConfigs = $helper->getServerConfigurationPrefixes(); $configID = $input->getArgument('configID'); - if(!in_array($configID, $availableConfigs)) { + if (!in_array($configID, $availableConfigs)) { $output->writeln("Invalid configID"); return; } diff --git a/apps/user_ldap/lib/Command/ShowConfig.php b/apps/user_ldap/lib/Command/ShowConfig.php index f4af798d433..cbd94287f9b 100644 --- a/apps/user_ldap/lib/Command/ShowConfig.php +++ b/apps/user_ldap/lib/Command/ShowConfig.php @@ -69,9 +69,9 @@ class ShowConfig extends Command { protected function execute(InputInterface $input, OutputInterface $output) { $availableConfigs = $this->helper->getServerConfigurationPrefixes(); $configID = $input->getArgument('configID'); - if(!is_null($configID)) { + if (!is_null($configID)) { $configIDs[] = $configID; - if(!in_array($configIDs[0], $availableConfigs)) { + if (!in_array($configIDs[0], $availableConfigs)) { $output->writeln("Invalid configID"); return; } @@ -89,7 +89,7 @@ class ShowConfig extends Command { * @param bool $withPassword Set to TRUE to show plaintext passwords in output */ protected function renderConfigs($configIDs, $output, $withPassword) { - foreach($configIDs as $id) { + foreach ($configIDs as $id) { $configHolder = new Configuration($id); $configuration = $configHolder->getConfiguration(); ksort($configuration); @@ -97,11 +97,11 @@ class ShowConfig extends Command { $table = new Table($output); $table->setHeaders(['Configuration', $id]); $rows = []; - foreach($configuration as $key => $value) { - if($key === 'ldapAgentPassword' && !$withPassword) { + foreach ($configuration as $key => $value) { + if ($key === 'ldapAgentPassword' && !$withPassword) { $value = '***'; } - if(is_array($value)) { + if (is_array($value)) { $value = implode(';', $value); } $rows[] = [$key, $value]; diff --git a/apps/user_ldap/lib/Command/TestConfig.php b/apps/user_ldap/lib/Command/TestConfig.php index 6ddd420e4f0..0973e6245b3 100644 --- a/apps/user_ldap/lib/Command/TestConfig.php +++ b/apps/user_ldap/lib/Command/TestConfig.php @@ -35,7 +35,6 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class TestConfig extends Command { - protected function configure() { $this ->setName('ldap:test-config') @@ -52,17 +51,17 @@ class TestConfig extends Command { $helper = new Helper(\OC::$server->getConfig()); $availableConfigs = $helper->getServerConfigurationPrefixes(); $configID = $input->getArgument('configID'); - if(!in_array($configID, $availableConfigs)) { + if (!in_array($configID, $availableConfigs)) { $output->writeln("Invalid configID"); return; } $result = $this->testConfig($configID); - if($result === 0) { + if ($result === 0) { $output->writeln('The configuration is valid and the connection could be established!'); - } elseif($result === 1) { + } elseif ($result === 1) { $output->writeln('The configuration is invalid. Please have a look at the logs for further details.'); - } elseif($result === 2) { + } elseif ($result === 2) { $output->writeln('The configuration is valid, but the Bind failed. Please check the server settings and credentials.'); } else { $output->writeln('Your LDAP server was kidnapped by aliens.'); @@ -81,12 +80,12 @@ class TestConfig extends Command { //ensure validation is run before we attempt the bind $connection->getConfiguration(); - if(!$connection->setConfiguration([ + if (!$connection->setConfiguration([ 'ldap_configuration_active' => 1, ])) { return 1; } - if($connection->bind()) { + if ($connection->bind()) { return 0; } return 2; diff --git a/apps/user_ldap/lib/Configuration.php b/apps/user_ldap/lib/Configuration.php index ccba7b43586..4076a6e8a3d 100644 --- a/apps/user_ldap/lib/Configuration.php +++ b/apps/user_ldap/lib/Configuration.php @@ -118,7 +118,7 @@ class Configuration { */ public function __construct($configPrefix, $autoRead = true) { $this->configPrefix = $configPrefix; - if($autoRead) { + if ($autoRead) { $this->readConfiguration(); } } @@ -128,7 +128,7 @@ class Configuration { * @return mixed|null */ public function __get($name) { - if(isset($this->config[$name])) { + if (isset($this->config[$name])) { return $this->config[$name]; } return null; @@ -159,22 +159,22 @@ class Configuration { * @return false|null */ public function setConfiguration($config, &$applied = null) { - if(!is_array($config)) { + if (!is_array($config)) { return false; } $cta = $this->getConfigTranslationArray(); - foreach($config as $inputKey => $val) { - if(strpos($inputKey, '_') !== false && array_key_exists($inputKey, $cta)) { + foreach ($config as $inputKey => $val) { + if (strpos($inputKey, '_') !== false && array_key_exists($inputKey, $cta)) { $key = $cta[$inputKey]; - } elseif(array_key_exists($inputKey, $this->config)) { + } elseif (array_key_exists($inputKey, $this->config)) { $key = $inputKey; } else { continue; } $setMethod = 'setValue'; - switch($key) { + switch ($key) { case 'ldapAgentPassword': $setMethod = 'setRawValue'; break; @@ -198,7 +198,7 @@ class Configuration { break; } $this->$setMethod($key, $val); - if(is_array($applied)) { + if (is_array($applied)) { $applied[] = $inputKey; // storing key as index avoids duplication, and as value for simplicity } @@ -208,15 +208,15 @@ class Configuration { } public function readConfiguration() { - if(!$this->configRead && !is_null($this->configPrefix)) { + if (!$this->configRead && !is_null($this->configPrefix)) { $cta = array_flip($this->getConfigTranslationArray()); - foreach($this->config as $key => $val) { - if(!isset($cta[$key])) { + foreach ($this->config as $key => $val) { + if (!isset($cta[$key])) { //some are determined continue; } $dbKey = $cta[$key]; - switch($key) { + switch ($key) { case 'ldapBase': case 'ldapBaseUsers': case 'ldapBaseGroups': @@ -259,7 +259,7 @@ class Configuration { */ public function saveConfiguration() { $cta = array_flip($this->getConfigTranslationArray()); - foreach($this->unsavedChanges as $key) { + foreach ($this->unsavedChanges as $key) { $value = $this->config[$key]; switch ($key) { case 'ldapAgentPassword': @@ -275,7 +275,7 @@ class Configuration { case 'ldapGroupFilterObjectclass': case 'ldapGroupFilterGroups': case 'ldapLoginFilterAttributes': - if(is_array($value)) { + if (is_array($value)) { $value = implode("\n", $value); } break; @@ -285,7 +285,7 @@ class Configuration { case 'ldapUuidGroupAttribute': continue 2; } - if(is_null($value)) { + if (is_null($value)) { $value = ''; } $this->saveValue($cta[$key], $value); @@ -300,7 +300,7 @@ class Configuration { */ protected function getMultiLine($varName) { $value = $this->getValue($varName); - if(empty($value)) { + if (empty($value)) { $value = ''; } else { $value = preg_split('/\r\n|\r|\n/', $value); @@ -316,21 +316,21 @@ class Configuration { * @param array|string $value to set */ protected function setMultiLine($varName, $value) { - if(empty($value)) { + if (empty($value)) { $value = ''; } elseif (!is_array($value)) { $value = preg_split('/\r\n|\r|\n|;/', $value); - if($value === false) { + if ($value === false) { $value = ''; } } - if(!is_array($value)) { + if (!is_array($value)) { $finalValue = trim($value); } else { $finalValue = []; - foreach($value as $key => $val) { - if(is_string($val)) { + foreach ($value as $key => $val) { + if (is_string($val)) { $val = trim($val); if ($val !== '') { //accidental line breaks are not wanted and can cause @@ -377,7 +377,7 @@ class Configuration { */ protected function getValue($varName) { static $defaults; - if(is_null($defaults)) { + if (is_null($defaults)) { $defaults = $this->getDefaults(); } return \OC::$server->getConfig()->getAppValue('user_ldap', @@ -392,7 +392,7 @@ class Configuration { * @param mixed $value to set */ protected function setValue($varName, $value) { - if(is_string($value)) { + if (is_string($value)) { $value = trim($value); } $this->config[$varName] = $value; @@ -554,7 +554,7 @@ class Configuration { * @throws \RuntimeException */ public function resolveRule($rule) { - if($rule === 'avatar') { + if ($rule === 'avatar') { return $this->getAvatarAttributes(); } throw new \RuntimeException('Invalid rule'); @@ -564,20 +564,19 @@ class Configuration { $value = $this->ldapUserAvatarRule ?: self::AVATAR_PREFIX_DEFAULT; $defaultAttributes = ['jpegphoto', 'thumbnailphoto']; - if($value === self::AVATAR_PREFIX_NONE) { + if ($value === self::AVATAR_PREFIX_NONE) { return []; } - if(strpos($value, self::AVATAR_PREFIX_DATA_ATTRIBUTE) === 0) { + if (strpos($value, self::AVATAR_PREFIX_DATA_ATTRIBUTE) === 0) { $attribute = trim(substr($value, strlen(self::AVATAR_PREFIX_DATA_ATTRIBUTE))); - if($attribute === '') { + if ($attribute === '') { return $defaultAttributes; } return [strtolower($attribute)]; } - if($value !== self::AVATAR_PREFIX_DEFAULT) { + if ($value !== self::AVATAR_PREFIX_DEFAULT) { \OC::$server->getLogger()->warning('Invalid config value to ldapUserAvatarRule; falling back to default.'); } return $defaultAttributes; } - } diff --git a/apps/user_ldap/lib/Connection.php b/apps/user_ldap/lib/Connection.php index 51c35c2a665..cec4866b0ea 100644 --- a/apps/user_ldap/lib/Connection.php +++ b/apps/user_ldap/lib/Connection.php @@ -111,7 +111,7 @@ class Connection extends LDAPUtility { $this->configuration = new Configuration($configPrefix, !is_null($configID)); $memcache = \OC::$server->getMemCacheFactory(); - if($memcache->isAvailable()) { + if ($memcache->isAvailable()) { $this->cache = $memcache->createDistributed(); } $helper = new Helper(\OC::$server->getConfig()); @@ -120,7 +120,7 @@ class Connection extends LDAPUtility { } public function __destruct() { - if(!$this->dontDestruct && $this->ldap->isResource($this->ldapConnectionRes)) { + if (!$this->dontDestruct && $this->ldap->isResource($this->ldapConnectionRes)) { @$this->ldap->unbind($this->ldapConnectionRes); $this->bindResult = []; } @@ -132,7 +132,7 @@ class Connection extends LDAPUtility { public function __clone() { $this->configuration = new Configuration($this->configPrefix, !is_null($this->configID)); - if(count($this->bindResult) !== 0 && $this->bindResult['result'] === true) { + if (count($this->bindResult) !== 0 && $this->bindResult['result'] === true) { $this->bindResult = []; } $this->ldapConnectionRes = null; @@ -144,7 +144,7 @@ class Connection extends LDAPUtility { * @return bool|mixed */ public function __get($name) { - if(!$this->configured) { + if (!$this->configured) { $this->readConfiguration(); } @@ -160,7 +160,7 @@ class Connection extends LDAPUtility { $before = $this->configuration->$name; $this->configuration->$name = $value; $after = $this->configuration->$name; - if($before !== $after) { + if ($before !== $after) { if ($this->configID !== '' && $this->configID !== null) { $this->configuration->saveConfiguration(); } @@ -200,13 +200,13 @@ class Connection extends LDAPUtility { * Returns the LDAP handler */ public function getConnectionResource() { - if(!$this->ldapConnectionRes) { + if (!$this->ldapConnectionRes) { $this->init(); - } elseif(!$this->ldap->isResource($this->ldapConnectionRes)) { + } elseif (!$this->ldap->isResource($this->ldapConnectionRes)) { $this->ldapConnectionRes = null; $this->establishConnection(); } - if(is_null($this->ldapConnectionRes)) { + if (is_null($this->ldapConnectionRes)) { \OCP\Util::writeLog('user_ldap', 'No LDAP Connection to server ' . $this->configuration->ldapHost, ILogger::ERROR); throw new ServerNotAvailableException('Connection to LDAP server could not be established'); } @@ -217,7 +217,7 @@ class Connection extends LDAPUtility { * resets the connection resource */ public function resetConnectionResource() { - if(!is_null($this->ldapConnectionRes)) { + if (!is_null($this->ldapConnectionRes)) { @$this->ldap->unbind($this->ldapConnectionRes); $this->ldapConnectionRes = null; $this->bindResult = []; @@ -230,7 +230,7 @@ class Connection extends LDAPUtility { */ private function getCacheKey($key) { $prefix = 'LDAP-'.$this->configID.'-'.$this->configPrefix.'-'; - if(is_null($key)) { + if (is_null($key)) { return $prefix; } return $prefix.hash('sha256', $key); @@ -241,10 +241,10 @@ class Connection extends LDAPUtility { * @return mixed|null */ public function getFromCache($key) { - if(!$this->configured) { + if (!$this->configured) { $this->readConfiguration(); } - if(is_null($this->cache) || !$this->configuration->ldapCacheTTL) { + if (is_null($this->cache) || !$this->configuration->ldapCacheTTL) { return null; } $key = $this->getCacheKey($key); @@ -259,10 +259,10 @@ class Connection extends LDAPUtility { * @return string */ public function writeToCache($key, $value) { - if(!$this->configured) { + if (!$this->configured) { $this->readConfiguration(); } - if(is_null($this->cache) + if (is_null($this->cache) || !$this->configuration->ldapCacheTTL || !$this->configuration->ldapConfigurationActive) { return null; @@ -273,7 +273,7 @@ class Connection extends LDAPUtility { } public function clearCache() { - if(!is_null($this->cache)) { + if (!is_null($this->cache)) { $this->cache->clear($this->getCacheKey(null)); } } @@ -285,7 +285,7 @@ class Connection extends LDAPUtility { * @return null */ private function readConfiguration($force = false) { - if((!$this->configured || $force) && !is_null($this->configID)) { + if ((!$this->configured || $force) && !is_null($this->configID)) { $this->configuration->readConfiguration(); $this->configured = $this->validateConfiguration(); } @@ -298,12 +298,12 @@ class Connection extends LDAPUtility { * @return boolean true if config validates, false otherwise. Check with $setParameters for detailed success on single parameters */ public function setConfiguration($config, &$setParameters = null) { - if(is_null($setParameters)) { + if (is_null($setParameters)) { $setParameters = []; } $this->doNotValidate = false; $this->configuration->setConfiguration($config, $setParameters); - if(count($setParameters) > 0) { + if (count($setParameters) > 0) { $this->configured = $this->validateConfiguration(); } @@ -330,10 +330,10 @@ class Connection extends LDAPUtility { $config = $this->configuration->getConfiguration(); $cta = $this->configuration->getConfigTranslationArray(); $result = []; - foreach($cta as $dbkey => $configkey) { - switch($configkey) { + foreach ($cta as $dbkey => $configkey) { + switch ($configkey) { case 'homeFolderNamingRule': - if(strpos($config[$configkey], 'attr:') === 0) { + if (strpos($config[$configkey], 'attr:') === 0) { $result[$dbkey] = substr($config[$configkey], 5); } else { $result[$dbkey] = ''; @@ -344,7 +344,7 @@ class Connection extends LDAPUtility { case 'ldapBaseGroups': case 'ldapAttributesForUserSearch': case 'ldapAttributesForGroupSearch': - if(is_array($config[$configkey])) { + if (is_array($config[$configkey])) { $result[$dbkey] = implode("\n", $config[$configkey]); break; } //else follows default @@ -357,23 +357,23 @@ class Connection extends LDAPUtility { private function doSoftValidation() { //if User or Group Base are not set, take over Base DN setting - foreach(['ldapBaseUsers', 'ldapBaseGroups'] as $keyBase) { + foreach (['ldapBaseUsers', 'ldapBaseGroups'] as $keyBase) { $val = $this->configuration->$keyBase; - if(empty($val)) { + if (empty($val)) { $this->configuration->$keyBase = $this->configuration->ldapBase; } } - foreach(['ldapExpertUUIDUserAttr' => 'ldapUuidUserAttribute', + foreach (['ldapExpertUUIDUserAttr' => 'ldapUuidUserAttribute', 'ldapExpertUUIDGroupAttr' => 'ldapUuidGroupAttribute'] as $expertSetting => $effectiveSetting) { $uuidOverride = $this->configuration->$expertSetting; - if(!empty($uuidOverride)) { + if (!empty($uuidOverride)) { $this->configuration->$effectiveSetting = $uuidOverride; } else { $uuidAttributes = Access::UUID_ATTRIBUTES; array_unshift($uuidAttributes, 'auto'); - if(!in_array($this->configuration->$effectiveSetting, + if (!in_array($this->configuration->$effectiveSetting, $uuidAttributes) && (!is_null($this->configID))) { $this->configuration->$effectiveSetting = 'auto'; @@ -383,7 +383,6 @@ class Connection extends LDAPUtility { $effectiveSetting.', '.'reset to '. 'autodetect.', ILogger::INFO); } - } } @@ -395,14 +394,14 @@ class Connection extends LDAPUtility { //make sure empty search attributes are saved as simple, empty array $saKeys = ['ldapAttributesForUserSearch', 'ldapAttributesForGroupSearch']; - foreach($saKeys as $key) { + foreach ($saKeys as $key) { $val = $this->configuration->$key; - if(is_array($val) && count($val) === 1 && empty($val[0])) { + if (is_array($val) && count($val) === 1 && empty($val[0])) { $this->configuration->$key = []; } } - if((stripos($this->configuration->ldapHost, 'ldaps://') === 0) + if ((stripos($this->configuration->ldapHost, 'ldaps://') === 0) && $this->configuration->ldapTLS) { $this->configuration->ldapTLS = false; \OCP\Util::writeLog( @@ -424,10 +423,10 @@ class Connection extends LDAPUtility { //options that shall not be empty $options = ['ldapHost', 'ldapPort', 'ldapUserDisplayName', 'ldapGroupDisplayName', 'ldapLoginFilter']; - foreach($options as $key) { + foreach ($options as $key) { $val = $this->configuration->$key; - if(empty($val)) { - switch($key) { + if (empty($val)) { + switch ($key) { case 'ldapHost': $subj = 'LDAP Host'; break; @@ -475,7 +474,7 @@ class Connection extends LDAPUtility { $baseUsers = $this->configuration->ldapBaseUsers; $baseGroups = $this->configuration->ldapBaseGroups; - if(empty($base) && empty($baseUsers) && empty($baseGroups)) { + if (empty($base) && empty($baseUsers) && empty($baseGroups)) { \OCP\Util::writeLog( 'user_ldap', $errorStr.'Not a single Base DN given.', @@ -484,7 +483,7 @@ class Connection extends LDAPUtility { $configurationOK = false; } - if(mb_strpos($this->configuration->ldapLoginFilter, '%uid', 0, 'UTF-8') + if (mb_strpos($this->configuration->ldapLoginFilter, '%uid', 0, 'UTF-8') === false) { \OCP\Util::writeLog( 'user_ldap', @@ -502,8 +501,7 @@ class Connection extends LDAPUtility { * @return bool true if configuration seems OK, false otherwise */ private function validateConfiguration() { - - if($this->doNotValidate) { + if ($this->doNotValidate) { //don't do a validation if it is a new configuration with pure //default values. Will be allowed on changes via __set or //setConfiguration @@ -526,14 +524,14 @@ class Connection extends LDAPUtility { * @throws ServerNotAvailableException */ private function establishConnection() { - if(!$this->configuration->ldapConfigurationActive) { + if (!$this->configuration->ldapConfigurationActive) { return null; } static $phpLDAPinstalled = true; - if(!$phpLDAPinstalled) { + if (!$phpLDAPinstalled) { return false; } - if(!$this->ignoreValidation && !$this->configured) { + if (!$this->ignoreValidation && !$this->configured) { \OCP\Util::writeLog( 'user_ldap', 'Configuration is invalid, cannot connect', @@ -541,8 +539,8 @@ class Connection extends LDAPUtility { ); return false; } - if(!$this->ldapConnectionRes) { - if(!$this->ldap->areLDAPFunctionsAvailable()) { + if (!$this->ldapConnectionRes) { + if (!$this->ldap->areLDAPFunctionsAvailable()) { $phpLDAPinstalled = false; \OCP\Util::writeLog( 'user_ldap', @@ -552,8 +550,8 @@ class Connection extends LDAPUtility { return false; } - if($this->configuration->turnOffCertCheck) { - if(putenv('LDAPTLS_REQCERT=never')) { + if ($this->configuration->turnOffCertCheck) { + if (putenv('LDAPTLS_REQCERT=never')) { \OCP\Util::writeLog('user_ldap', 'Turned off SSL certificate validation successfully.', ILogger::DEBUG); @@ -577,20 +575,20 @@ class Connection extends LDAPUtility { return $this->bind(); } } catch (ServerNotAvailableException $e) { - if(!$isBackupHost) { + if (!$isBackupHost) { throw $e; } } //if LDAP server is not reachable, try the Backup (Replica!) Server - if($isBackupHost || $isOverrideMainServer) { + if ($isBackupHost || $isOverrideMainServer) { $this->doConnect($this->configuration->ldapBackupHost, $this->configuration->ldapBackupPort); $this->bindResult = []; $bindStatus = $this->bind(); $error = $this->ldap->isResource($this->ldapConnectionRes) ? $this->ldap->errno($this->ldapConnectionRes) : -1; - if($bindStatus && $error === 0 && !$this->getFromCache('overrideMainServer')) { + if ($bindStatus && $error === 0 && !$this->getFromCache('overrideMainServer')) { //when bind to backup server succeeded and failed to main server, //skip contacting him until next cache refresh $this->writeToCache('overrideMainServer', true); @@ -615,16 +613,16 @@ class Connection extends LDAPUtility { $this->ldapConnectionRes = $this->ldap->connect($host, $port); - if(!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_PROTOCOL_VERSION, 3)) { + if (!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_PROTOCOL_VERSION, 3)) { throw new ServerNotAvailableException('Could not set required LDAP Protocol version.'); } - if(!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_REFERRALS, 0)) { + if (!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_REFERRALS, 0)) { throw new ServerNotAvailableException('Could not disable LDAP referrals.'); } - if($this->configuration->ldapTLS) { - if(!$this->ldap->startTls($this->ldapConnectionRes)) { + if ($this->configuration->ldapTLS) { + if (!$this->ldap->startTls($this->ldapConnectionRes)) { throw new ServerNotAvailableException('Start TLS failed, when connecting to LDAP host ' . $host . '.'); } } @@ -636,15 +634,15 @@ class Connection extends LDAPUtility { * Binds to LDAP */ public function bind() { - if(!$this->configuration->ldapConfigurationActive) { + if (!$this->configuration->ldapConfigurationActive) { return false; } $cr = $this->ldapConnectionRes; - if(!$this->ldap->isResource($cr)) { + if (!$this->ldap->isResource($cr)) { $cr = $this->getConnectionResource(); } - if( + if ( count($this->bindResult) !== 0 && $this->bindResult['dn'] === $this->configuration->ldapAgentName && \OC::$server->getHasher()->verify( @@ -668,7 +666,7 @@ class Connection extends LDAPUtility { 'result' => $ldapLogin, ]; - if(!$ldapLogin) { + if (!$ldapLogin) { $errno = $this->ldap->errno($cr); \OCP\Util::writeLog('user_ldap', @@ -677,7 +675,7 @@ class Connection extends LDAPUtility { // Set to failure mode, if LDAP error code is not LDAP_SUCCESS or LDAP_INVALID_CREDENTIALS // or (needed for Apple Open Directory:) LDAP_INSUFFICIENT_ACCESS - if($errno !== 0 && $errno !== 49 && $errno !== 50) { + if ($errno !== 0 && $errno !== 49 && $errno !== 50) { $this->ldapConnectionRes = null; } @@ -685,5 +683,4 @@ class Connection extends LDAPUtility { } return true; } - } diff --git a/apps/user_ldap/lib/Controller/ConfigAPIController.php b/apps/user_ldap/lib/Controller/ConfigAPIController.php index fb8451287ef..ec056c651a7 100644 --- a/apps/user_ldap/lib/Controller/ConfigAPIController.php +++ b/apps/user_ldap/lib/Controller/ConfigAPIController.php @@ -151,12 +151,12 @@ class ConfigAPIController extends OCSController { public function delete($configID) { try { $this->ensureConfigIDExists($configID); - if(!$this->ldapHelper->deleteServerConfiguration($configID)) { + if (!$this->ldapHelper->deleteServerConfiguration($configID)) { throw new OCSException('Could not delete configuration'); } - } catch(OCSException $e) { + } catch (OCSException $e) { throw $e; - } catch(\Exception $e) { + } catch (\Exception $e) { $this->logger->logException($e); throw new OCSException('An issue occurred when deleting the config.'); } @@ -191,7 +191,7 @@ class ConfigAPIController extends OCSController { try { $this->ensureConfigIDExists($configID); - if(!is_array($configData)) { + if (!is_array($configData)) { throw new OCSBadRequestException('configData is not properly set'); } @@ -199,14 +199,14 @@ class ConfigAPIController extends OCSController { $configKeys = $configuration->getConfigTranslationArray(); foreach ($configKeys as $i => $key) { - if(isset($configData[$key])) { + if (isset($configData[$key])) { $configuration->$key = $configData[$key]; } } $configuration->saveConfiguration(); $this->connectionFactory->get($configID)->clearCache(); - } catch(OCSException $e) { + } catch (OCSException $e) { throw $e; } catch (\Exception $e) { $this->logger->logException($e); @@ -292,16 +292,16 @@ class ConfigAPIController extends OCSController { $config = new Configuration($configID); $data = $config->getConfiguration(); - if(!(int)$showPassword) { + if (!(int)$showPassword) { $data['ldapAgentPassword'] = '***'; } foreach ($data as $key => $value) { - if(is_array($value)) { + if (is_array($value)) { $value = implode(';', $value); $data[$key] = $value; } } - } catch(OCSException $e) { + } catch (OCSException $e) { throw $e; } catch (\Exception $e) { $this->logger->logException($e); @@ -319,7 +319,7 @@ class ConfigAPIController extends OCSController { */ private function ensureConfigIDExists($configID) { $prefixes = $this->ldapHelper->getServerConfigurationPrefixes(); - if(!in_array($configID, $prefixes, true)) { + if (!in_array($configID, $prefixes, true)) { throw new OCSNotFoundException('Config ID not found'); } } diff --git a/apps/user_ldap/lib/Controller/RenewPasswordController.php b/apps/user_ldap/lib/Controller/RenewPasswordController.php index cc58f79cbd0..499a25e0d28 100644 --- a/apps/user_ldap/lib/Controller/RenewPasswordController.php +++ b/apps/user_ldap/lib/Controller/RenewPasswordController.php @@ -84,7 +84,7 @@ class RenewPasswordController extends Controller { * @return TemplateResponse|RedirectResponse */ public function showRenewPasswordForm($user) { - if($this->config->getUserValue($user, 'user_ldap', 'needsPasswordReset') !== 'true') { + if ($this->config->getUserValue($user, 'user_ldap', 'needsPasswordReset') !== 'true') { return new RedirectResponse($this->urlGenerator->linkToRouteAbsolute('core.login.showLoginForm')); } $parameters = []; @@ -128,7 +128,7 @@ class RenewPasswordController extends Controller { * @return RedirectResponse */ public function tryRenewPassword($user, $oldPassword, $newPassword) { - if($this->config->getUserValue($user, 'user_ldap', 'needsPasswordReset') !== 'true') { + if ($this->config->getUserValue($user, 'user_ldap', 'needsPasswordReset') !== 'true') { return new RedirectResponse($this->urlGenerator->linkToRouteAbsolute('core.login.showLoginForm')); } $args = !is_null($user) ? ['user' => $user] : []; @@ -175,5 +175,4 @@ class RenewPasswordController extends Controller { ]); return new RedirectResponse($this->urlGenerator->linkToRoute('core.login.showLoginForm', $args)); } - } diff --git a/apps/user_ldap/lib/Exceptions/AttributeNotSet.php b/apps/user_ldap/lib/Exceptions/AttributeNotSet.php index c05a0221849..5a4853d1e19 100644 --- a/apps/user_ldap/lib/Exceptions/AttributeNotSet.php +++ b/apps/user_ldap/lib/Exceptions/AttributeNotSet.php @@ -23,4 +23,5 @@ namespace OCA\User_LDAP\Exceptions; -class AttributeNotSet extends \RuntimeException {} +class AttributeNotSet extends \RuntimeException { +} diff --git a/apps/user_ldap/lib/Exceptions/ConstraintViolationException.php b/apps/user_ldap/lib/Exceptions/ConstraintViolationException.php index 2581de127d0..1a462b27781 100644 --- a/apps/user_ldap/lib/Exceptions/ConstraintViolationException.php +++ b/apps/user_ldap/lib/Exceptions/ConstraintViolationException.php @@ -23,4 +23,5 @@ namespace OCA\User_LDAP\Exceptions; -class ConstraintViolationException extends \Exception {} +class ConstraintViolationException extends \Exception { +} diff --git a/apps/user_ldap/lib/Exceptions/NotOnLDAP.php b/apps/user_ldap/lib/Exceptions/NotOnLDAP.php index 8a9ce068b9b..e88fa3b840e 100644 --- a/apps/user_ldap/lib/Exceptions/NotOnLDAP.php +++ b/apps/user_ldap/lib/Exceptions/NotOnLDAP.php @@ -23,4 +23,5 @@ namespace OCA\User_LDAP\Exceptions; -class NotOnLDAP extends \Exception {} +class NotOnLDAP extends \Exception { +} diff --git a/apps/user_ldap/lib/GroupPluginManager.php b/apps/user_ldap/lib/GroupPluginManager.php index 799e290f852..56c4aab9f3b 100644 --- a/apps/user_ldap/lib/GroupPluginManager.php +++ b/apps/user_ldap/lib/GroupPluginManager.php @@ -27,7 +27,6 @@ namespace OCA\User_LDAP; use OCP\GroupInterface; class GroupPluginManager { - private $respondToActions = 0; private $which = [ @@ -54,7 +53,7 @@ class GroupPluginManager { $respondToActions = $plugin->respondToActions(); $this->respondToActions |= $respondToActions; - foreach($this->which as $action => $v) { + foreach ($this->which as $action => $v) { if ((bool)($respondToActions & $action)) { $this->which[$action] = $plugin; \OC::$server->getLogger()->debug("Registered action ".$action." to plugin ".get_class($plugin), ['app' => 'user_ldap']); diff --git a/apps/user_ldap/lib/Group_LDAP.php b/apps/user_ldap/lib/Group_LDAP.php index 246b61b5202..85d9e38e03e 100644 --- a/apps/user_ldap/lib/Group_LDAP.php +++ b/apps/user_ldap/lib/Group_LDAP.php @@ -73,7 +73,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD parent::__construct($access); $filter = $this->access->connection->ldapGroupFilter; $gassoc = $this->access->connection->ldapGroupMemberAssocAttr; - if(!empty($filter) && !empty($gassoc)) { + if (!empty($filter) && !empty($gassoc)) { $this->enabled = true; } @@ -92,25 +92,25 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD * Checks whether the user is member of a group or not. */ public function inGroup($uid, $gid) { - if(!$this->enabled) { + if (!$this->enabled) { return false; } $cacheKey = 'inGroup'.$uid.':'.$gid; $inGroup = $this->access->connection->getFromCache($cacheKey); - if(!is_null($inGroup)) { + if (!is_null($inGroup)) { return (bool)$inGroup; } $userDN = $this->access->username2dn($uid); - if(isset($this->cachedGroupMembers[$gid])) { + if (isset($this->cachedGroupMembers[$gid])) { $isInGroup = in_array($userDN, $this->cachedGroupMembers[$gid]); return $isInGroup; } $cacheKeyMembers = 'inGroup-members:'.$gid; $members = $this->access->connection->getFromCache($cacheKeyMembers); - if(!is_null($members)) { + if (!is_null($members)) { $this->cachedGroupMembers[$gid] = $members; $isInGroup = in_array($userDN, $members, true); $this->access->connection->writeToCache($cacheKey, $isInGroup); @@ -119,34 +119,34 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD $groupDN = $this->access->groupname2dn($gid); // just in case - if(!$groupDN || !$userDN) { + if (!$groupDN || !$userDN) { $this->access->connection->writeToCache($cacheKey, false); return false; } //check primary group first - if($gid === $this->getUserPrimaryGroup($userDN)) { + if ($gid === $this->getUserPrimaryGroup($userDN)) { $this->access->connection->writeToCache($cacheKey, true); return true; } //usually, LDAP attributes are said to be case insensitive. But there are exceptions of course. $members = $this->_groupMembers($groupDN); - if(!is_array($members) || count($members) === 0) { + if (!is_array($members) || count($members) === 0) { $this->access->connection->writeToCache($cacheKey, false); return false; } //extra work if we don't get back user DNs - if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') { + if (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') { $dns = []; $filterParts = []; $bytes = 0; - foreach($members as $mid) { + foreach ($members as $mid) { $filter = str_replace('%uid', $mid, $this->access->connection->ldapLoginFilter); $filterParts[] = $filter; $bytes += strlen($filter); - if($bytes >= 9000000) { + if ($bytes >= 9000000) { // AD has a default input buffer of 10 MB, we do not want // to take even the chance to exceed it $filter = $this->access->combineFilterWithOr($filterParts); @@ -156,7 +156,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD $dns = array_merge($dns, $users); } } - if(count($filterParts) > 0) { + if (count($filterParts) > 0) { $filter = $this->access->combineFilterWithOr($filterParts); $users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts)); $dns = array_merge($dns, $users); @@ -201,7 +201,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD $memberUrlFilter = substr($memberURLs[0], $pos); $foundMembers = $this->access->searchUsers($memberUrlFilter,'dn'); $dynamicMembers = []; - foreach($foundMembers as $value) { + foreach ($foundMembers as $value) { $dynamicMembers[$value['dn'][0]] = 1; } } else { @@ -230,7 +230,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD // used extensively in cron job, caching makes sense for nested groups $cacheKey = '_groupMembers'.$dnGroup; $groupMembers = $this->access->connection->getFromCache($cacheKey); - if($groupMembers !== null) { + if ($groupMembers !== null) { return $groupMembers; } $seen[$dnGroup] = 1; @@ -290,10 +290,10 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD $recordMode = is_array($list) && isset($list[0]) && is_array($list[0]) && isset($list[0]['dn'][0]); if ($nesting !== 1) { - if($recordMode) { + if ($recordMode) { // the keys are numeric, but should hold the DN return array_reduce($list, function ($transformed, $record) use ($dn) { - if($record['dn'][0] != $dn) { + if ($record['dn'][0] != $dn) { $transformed[$record['dn'][0]] = $record; } return $transformed; @@ -326,7 +326,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD public function gidNumber2Name($gid, $dn) { $cacheKey = 'gidNumberToName' . $gid; $groupName = $this->access->connection->getFromCache($cacheKey); - if(!is_null($groupName) && isset($groupName)) { + if (!is_null($groupName) && isset($groupName)) { return $groupName; } @@ -337,7 +337,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD $this->access->connection->ldapGidNumber . '=' . $gid ]); $result = $this->access->searchGroups($filter, ['dn'], 1); - if(empty($result)) { + if (empty($result)) { return false; } $dn = $result[0]['dn'][0]; @@ -360,7 +360,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD */ private function getEntryGidNumber($dn, $attribute) { $value = $this->access->readAttribute($dn, $attribute); - if(is_array($value) && !empty($value)) { + if (is_array($value) && !empty($value)) { return $value[0]; } return false; @@ -382,9 +382,9 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD */ public function getUserGidNumber($dn) { $gidNumber = false; - if($this->access->connection->hasGidNumber) { + if ($this->access->connection->hasGidNumber) { $gidNumber = $this->getEntryGidNumber($dn, $this->access->connection->ldapGidNumber); - if($gidNumber === false) { + if ($gidNumber === false) { $this->access->connection->hasGidNumber = false; } } @@ -401,7 +401,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD */ private function prepareFilterForUsersHasGidNumber($groupDN, $search = '') { $groupID = $this->getGroupGidNumber($groupDN); - if($groupID === false) { + if ($groupID === false) { throw new \Exception('Not a valid group'); } @@ -465,9 +465,9 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD */ public function getUserGroupByGid($dn) { $groupID = $this->getUserGidNumber($dn); - if($groupID !== false) { + if ($groupID !== false) { $groupName = $this->gidNumber2Name($groupID, $dn); - if($groupName !== false) { + if ($groupName !== false) { return $groupName; } } @@ -484,12 +484,12 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD public function primaryGroupID2Name($gid, $dn) { $cacheKey = 'primaryGroupIDtoName'; $groupNames = $this->access->connection->getFromCache($cacheKey); - if(!is_null($groupNames) && isset($groupNames[$gid])) { + if (!is_null($groupNames) && isset($groupNames[$gid])) { return $groupNames[$gid]; } $domainObjectSid = $this->access->getSID($dn); - if($domainObjectSid === false) { + if ($domainObjectSid === false) { return false; } @@ -499,7 +499,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD 'objectsid=' . $domainObjectSid . '-' . $gid ]); $result = $this->access->searchGroups($filter, ['dn'], 1); - if(empty($result)) { + if (empty($result)) { return false; } $dn = $result[0]['dn'][0]; @@ -522,7 +522,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD */ private function getEntryGroupID($dn, $attribute) { $value = $this->access->readAttribute($dn, $attribute); - if(is_array($value) && !empty($value)) { + if (is_array($value) && !empty($value)) { return $value[0]; } return false; @@ -544,9 +544,9 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD */ public function getUserPrimaryGroupIDs($dn) { $primaryGroupID = false; - if($this->access->connection->hasPrimaryGroups) { + if ($this->access->connection->hasPrimaryGroups) { $primaryGroupID = $this->getEntryGroupID($dn, 'primaryGroupID'); - if($primaryGroupID === false) { + if ($primaryGroupID === false) { $this->access->connection->hasPrimaryGroups = false; } } @@ -563,7 +563,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD */ private function prepareFilterForUsersInPrimaryGroup($groupDN, $search = '') { $groupID = $this->getGroupPrimaryGroupID($groupDN); - if($groupID === false) { + if ($groupID === false) { throw new \Exception('Not a valid group'); } @@ -627,9 +627,9 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD */ public function getUserPrimaryGroup($dn) { $groupID = $this->getUserPrimaryGroupIDs($dn); - if($groupID !== false) { + if ($groupID !== false) { $groupName = $this->primaryGroupID2Name($groupID, $dn); - if($groupName !== false) { + if ($groupName !== false) { return $groupName; } } @@ -648,16 +648,16 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD * This function includes groups based on dynamic group membership. */ public function getUserGroups($uid) { - if(!$this->enabled) { + if (!$this->enabled) { return []; } $cacheKey = 'getUserGroups'.$uid; $userGroups = $this->access->connection->getFromCache($cacheKey); - if(!is_null($userGroups)) { + if (!is_null($userGroups)) { return $userGroups; } $userDN = $this->access->username2dn($uid); - if(!$userDN) { + if (!$userDN) { $this->access->connection->writeToCache($cacheKey, []); return []; } @@ -672,7 +672,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD // look through dynamic groups to add them to the result array if needed $groupsToMatch = $this->access->fetchListOfGroups( $this->access->connection->ldapGroupFilter,['dn',$dynamicGroupMemberURL]); - foreach($groupsToMatch as $dynamicGroup) { + foreach ($groupsToMatch as $dynamicGroup) { if (!array_key_exists($dynamicGroupMemberURL, $dynamicGroup)) { continue; } @@ -689,7 +689,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD if ($userMatch !== false) { // match found so this user is in this group $groupName = $this->access->dn2groupname($dynamicGroup['dn'][0]); - if(is_string($groupName)) { + if (is_string($groupName)) { // be sure to never return false if the dn could not be // resolved to a name, for whatever reason. $groups[] = $groupName; @@ -705,7 +705,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD // if possible, read out membership via memberOf. It's far faster than // performing a search, which still is a fallback later. // memberof doesn't support memberuid, so skip it here. - if((int)$this->access->connection->hasMemberOfFilterSupport === 1 + if ((int)$this->access->connection->hasMemberOfFilterSupport === 1 && (int)$this->access->connection->useMemberOfToDetectMembership === 1 && strtolower($this->access->connection->ldapGroupMemberAssocAttr) !== 'memberuid' ) { @@ -713,7 +713,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD if (is_array($groupDNs)) { foreach ($groupDNs as $dn) { $groupName = $this->access->dn2groupname($dn); - if(is_string($groupName)) { + if (is_string($groupName)) { // be sure to never return false if the dn could not be // resolved to a name, for whatever reason. $groups[] = $groupName; @@ -721,10 +721,10 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD } } - if($primaryGroup !== false) { + if ($primaryGroup !== false) { $groups[] = $primaryGroup; } - if($gidGroupName !== false) { + if ($gidGroupName !== false) { $groups[] = $gidGroupName; } $this->access->connection->writeToCache($cacheKey, $groups); @@ -732,11 +732,11 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD } //uniqueMember takes DN, memberuid the uid, so we need to distinguish - if((strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'uniquemember') + if ((strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'uniquemember') || (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'member') ) { $uid = $userDN; - } elseif(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') { + } elseif (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') { $result = $this->access->readAttribute($userDN, 'uid'); if ($result === false) { \OCP\Util::writeLog('user_ldap', 'No uid attribute found for DN ' . $userDN . ' on '. @@ -750,7 +750,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD $uid = $userDN; } - if($uid !== false) { + if ($uid !== false) { if (isset($this->cachedGroupsByMember[$uid])) { $groups = array_merge($groups, $this->cachedGroupsByMember[$uid]); } else { @@ -761,10 +761,10 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD } } - if($primaryGroup !== false) { + if ($primaryGroup !== false) { $groups[] = $primaryGroup; } - if($gidGroupName !== false) { + if ($gidGroupName !== false) { $groups[] = $gidGroupName; } @@ -794,7 +794,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD [$this->access->connection->ldapGroupDisplayName, 'dn']); if (is_array($groups)) { $fetcher = function ($dn, &$seen) { - if(is_array($dn) && isset($dn['dn'][0])) { + if (is_array($dn) && isset($dn['dn'][0])) { $dn = $dn['dn'][0]; } return $this->getGroupsByMember($dn, $seen); @@ -816,33 +816,33 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD * @throws \Exception */ public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) { - if(!$this->enabled) { + if (!$this->enabled) { return []; } - if(!$this->groupExists($gid)) { + if (!$this->groupExists($gid)) { return []; } $search = $this->access->escapeFilterPart($search, true); $cacheKey = 'usersInGroup-'.$gid.'-'.$search.'-'.$limit.'-'.$offset; // check for cache of the exact query $groupUsers = $this->access->connection->getFromCache($cacheKey); - if(!is_null($groupUsers)) { + if (!is_null($groupUsers)) { return $groupUsers; } // check for cache of the query without limit and offset $groupUsers = $this->access->connection->getFromCache('usersInGroup-'.$gid.'-'.$search); - if(!is_null($groupUsers)) { + if (!is_null($groupUsers)) { $groupUsers = array_slice($groupUsers, $offset, $limit); $this->access->connection->writeToCache($cacheKey, $groupUsers); return $groupUsers; } - if($limit === -1) { + if ($limit === -1) { $limit = null; } $groupDN = $this->access->groupname2dn($gid); - if(!$groupDN) { + if (!$groupDN) { // group couldn't be found, return empty resultset $this->access->connection->writeToCache($cacheKey, []); return []; @@ -851,7 +851,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD $primaryUsers = $this->getUsersInPrimaryGroup($groupDN, $search, $limit, $offset); $posixGroupUsers = $this->getUsersInGidNumber($groupDN, $search, $limit, $offset); $members = $this->_groupMembers($groupDN); - if(!$members && empty($posixGroupUsers) && empty($primaryUsers)) { + if (!$members && empty($posixGroupUsers) && empty($primaryUsers)) { //in case users could not be retrieved, return empty result set $this->access->connection->writeToCache($cacheKey, []); return []; @@ -860,8 +860,8 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD $groupUsers = []; $isMemberUid = (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid'); $attrs = $this->access->userManager->getAttributes(true); - foreach($members as $member) { - if($isMemberUid) { + foreach ($members as $member) { + if ($isMemberUid) { //we got uids, need to get their DNs to 'translate' them to user names $filter = $this->access->combineFilterWithAnd([ str_replace('%uid', trim($member), $this->access->connection->ldapLoginFilter), @@ -871,31 +871,30 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD ]) ]); $ldap_users = $this->access->fetchListOfUsers($filter, $attrs, 1); - if(count($ldap_users) < 1) { + if (count($ldap_users) < 1) { continue; } $groupUsers[] = $this->access->dn2username($ldap_users[0]['dn'][0]); } else { //we got DNs, check if we need to filter by search or we can give back all of them $uid = $this->access->dn2username($member); - if(!$uid) { + if (!$uid) { continue; } $cacheKey = 'userExistsOnLDAP' . $uid; $userExists = $this->access->connection->getFromCache($cacheKey); - if($userExists === false) { + if ($userExists === false) { continue; } - if($userExists === null || $search !== '') { + if ($userExists === null || $search !== '') { if (!$this->access->readAttribute($member, $this->access->connection->ldapUserDisplayName, $this->access->combineFilterWithAnd([ $this->access->getFilterPartForUserSearch($search), $this->access->connection->ldapUserFilter - ]))) - { - if($search === '') { + ]))) { + if ($search === '') { $this->access->connection->writeToCache($cacheKey, false); } continue; @@ -928,16 +927,16 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD } $cacheKey = 'countUsersInGroup-'.$gid.'-'.$search; - if(!$this->enabled || !$this->groupExists($gid)) { + if (!$this->enabled || !$this->groupExists($gid)) { return false; } $groupUsers = $this->access->connection->getFromCache($cacheKey); - if(!is_null($groupUsers)) { + if (!is_null($groupUsers)) { return $groupUsers; } $groupDN = $this->access->groupname2dn($gid); - if(!$groupDN) { + if (!$groupDN) { // group couldn't be found, return empty result set $this->access->connection->writeToCache($cacheKey, false); return false; @@ -945,7 +944,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD $members = $this->_groupMembers($groupDN); $primaryUserCount = $this->countUsersInPrimaryGroup($groupDN, ''); - if(!$members && $primaryUserCount === 0) { + if (!$members && $primaryUserCount === 0) { //in case users could not be retrieved, return empty result set $this->access->connection->writeToCache($cacheKey, false); return false; @@ -970,27 +969,27 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD //For now this is not important, because the only use of this method //does not supply a search string $groupUsers = []; - foreach($members as $member) { - if($isMemberUid) { + foreach ($members as $member) { + if ($isMemberUid) { //we got uids, need to get their DNs to 'translate' them to user names $filter = $this->access->combineFilterWithAnd([ str_replace('%uid', $member, $this->access->connection->ldapLoginFilter), $this->access->getFilterPartForUserSearch($search) ]); $ldap_users = $this->access->fetchListOfUsers($filter, 'dn', 1); - if(count($ldap_users) < 1) { + if (count($ldap_users) < 1) { continue; } $groupUsers[] = $this->access->dn2username($ldap_users[0]); } else { //we need to apply the search filter now - if(!$this->access->readAttribute($member, + if (!$this->access->readAttribute($member, $this->access->connection->ldapUserDisplayName, $this->access->getFilterPartForUserSearch($search))) { continue; } // dn2username will also check if the users belong to the allowed base - if($ocname = $this->access->dn2username($member)) { + if ($ocname = $this->access->dn2username($member)) { $groupUsers[] = $ocname; } } @@ -1013,7 +1012,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD * Returns a list with all groups (used by getGroups) */ protected function getGroupsChunk($search = '', $limit = -1, $offset = 0) { - if(!$this->enabled) { + if (!$this->enabled) { return []; } $cacheKey = 'getGroups-'.$search.'-'.$limit.'-'.$offset; @@ -1021,13 +1020,13 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD //Check cache before driving unnecessary searches \OCP\Util::writeLog('user_ldap', 'getGroups '.$cacheKey, ILogger::DEBUG); $ldap_groups = $this->access->connection->getFromCache($cacheKey); - if(!is_null($ldap_groups)) { + if (!is_null($ldap_groups)) { return $ldap_groups; } // if we'd pass -1 to LDAP search, we'd end up in a Protocol // error. With a limit of 0, we get 0 results. So we pass null. - if($limit <= 0) { + if ($limit <= 0) { $limit = null; } $filter = $this->access->combineFilterWithAnd([ @@ -1059,7 +1058,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD * (active directory has a limit of 1000 by default) */ public function getGroups($search = '', $limit = -1, $offset = 0) { - if(!$this->enabled) { + if (!$this->enabled) { return []; } $search = $this->access->escapeFilterPart($search, true); @@ -1069,9 +1068,9 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD } $maxGroups = 100000; // limit max results (just for safety reasons) if ($limit > -1) { - $overallLimit = min($limit + $offset, $maxGroups); + $overallLimit = min($limit + $offset, $maxGroups); } else { - $overallLimit = $maxGroups; + $overallLimit = $maxGroups; } $chunkOffset = $offset; $allGroups = []; @@ -1106,20 +1105,20 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD */ public function groupExists($gid) { $groupExists = $this->access->connection->getFromCache('groupExists'.$gid); - if(!is_null($groupExists)) { + if (!is_null($groupExists)) { return (bool)$groupExists; } //getting dn, if false the group does not exist. If dn, it may be mapped //only, requires more checking. $dn = $this->access->groupname2dn($gid); - if(!$dn) { + if (!$dn) { $this->access->connection->writeToCache('groupExists'.$gid, false); return false; } //if group really still exists, we will be able to read its objectclass - if(!is_array($this->access->readAttribute($dn, ''))) { + if (!is_array($this->access->readAttribute($dn, ''))) { $this->access->connection->writeToCache('groupExists'.$gid, false); return false; } @@ -1160,7 +1159,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD if ($dn = $this->groupPluginManager->createGroup($gid)) { //updates group mapping $uuid = $this->access->getUUID($dn, false); - if(is_string($uuid)) { + if (is_string($uuid)) { $this->access->mapAndAnnounceIfApplicable( $this->access->getGroupMapper(), $dn, diff --git a/apps/user_ldap/lib/Group_Proxy.php b/apps/user_ldap/lib/Group_Proxy.php index b492e965307..3bd0cc4c400 100644 --- a/apps/user_ldap/lib/Group_Proxy.php +++ b/apps/user_ldap/lib/Group_Proxy.php @@ -40,10 +40,10 @@ class Group_Proxy extends Proxy implements \OCP\GroupInterface, IGroupLDAP, IGet */ public function __construct($serverConfigPrefixes, ILDAPWrapper $ldap, GroupPluginManager $groupPluginManager) { parent::__construct($ldap); - foreach($serverConfigPrefixes as $configPrefix) { + foreach ($serverConfigPrefixes as $configPrefix) { $this->backends[$configPrefix] = new \OCA\User_LDAP\Group_LDAP($this->getAccess($configPrefix), $groupPluginManager); - if(is_null($this->refBackend)) { + if (is_null($this->refBackend)) { $this->refBackend = &$this->backends[$configPrefix]; } } @@ -58,8 +58,8 @@ class Group_Proxy extends Proxy implements \OCP\GroupInterface, IGroupLDAP, IGet */ protected function walkBackends($gid, $method, $parameters) { $cacheKey = $this->getGroupCacheKey($gid); - foreach($this->backends as $configPrefix => $backend) { - if($result = call_user_func_array([$backend, $method], $parameters)) { + foreach ($this->backends as $configPrefix => $backend) { + if ($result = call_user_func_array([$backend, $method], $parameters)) { $this->writeToCache($cacheKey, $configPrefix); return $result; } @@ -79,17 +79,17 @@ class Group_Proxy extends Proxy implements \OCP\GroupInterface, IGroupLDAP, IGet $cacheKey = $this->getGroupCacheKey($gid); $prefix = $this->getFromCache($cacheKey); //in case the uid has been found in the past, try this stored connection first - if(!is_null($prefix)) { - if(isset($this->backends[$prefix])) { + if (!is_null($prefix)) { + if (isset($this->backends[$prefix])) { $result = call_user_func_array([$this->backends[$prefix], $method], $parameters); - if($result === $passOnWhen) { + if ($result === $passOnWhen) { //not found here, reset cache to null if group vanished //because sometimes methods return false with a reason $groupExists = call_user_func_array( [$this->backends[$prefix], 'groupExists'], [$gid] ); - if(!$groupExists) { + if (!$groupExists) { $this->writeToCache($cacheKey, null); } } @@ -122,7 +122,7 @@ class Group_Proxy extends Proxy implements \OCP\GroupInterface, IGroupLDAP, IGet public function getUserGroups($uid) { $groups = []; - foreach($this->backends as $backend) { + foreach ($this->backends as $backend) { $backendGroups = $backend->getUserGroups($uid); if (is_array($backendGroups)) { $groups = array_merge($groups, $backendGroups); @@ -139,7 +139,7 @@ class Group_Proxy extends Proxy implements \OCP\GroupInterface, IGroupLDAP, IGet public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) { $users = []; - foreach($this->backends as $backend) { + foreach ($this->backends as $backend) { $backendUsers = $backend->usersInGroup($gid, $search, $limit, $offset); if (is_array($backendUsers)) { $users = array_merge($users, $backendUsers); @@ -224,7 +224,7 @@ class Group_Proxy extends Proxy implements \OCP\GroupInterface, IGroupLDAP, IGet public function getGroups($search = '', $limit = -1, $offset = 0) { $groups = []; - foreach($this->backends as $backend) { + foreach ($this->backends as $backend) { $backendGroups = $backend->getGroups($search, $limit, $offset); if (is_array($backendGroups)) { $groups = array_merge($groups, $backendGroups); diff --git a/apps/user_ldap/lib/Handler/ExtStorageConfigHandler.php b/apps/user_ldap/lib/Handler/ExtStorageConfigHandler.php index af9bc7aba84..13d20a42a17 100644 --- a/apps/user_ldap/lib/Handler/ExtStorageConfigHandler.php +++ b/apps/user_ldap/lib/Handler/ExtStorageConfigHandler.php @@ -42,22 +42,22 @@ class ExtStorageConfigHandler extends UserContext implements IConfigHandler { $this->placeholder = 'home'; $user = $this->getUser(); - if($user === null) { + if ($user === null) { return $optionValue; } $backend = $user->getBackend(); - if(!$backend instanceof User_Proxy) { + if (!$backend instanceof User_Proxy) { return $optionValue; } $access = $backend->getLDAPAccess($user->getUID()); - if(!$access) { + if (!$access) { return $optionValue; } $attribute = $access->connection->ldapExtStorageHomeAttribute; - if(empty($attribute)) { + if (empty($attribute)) { return $optionValue; } diff --git a/apps/user_ldap/lib/Helper.php b/apps/user_ldap/lib/Helper.php index 19797d8a98b..90fa3d05892 100644 --- a/apps/user_ldap/lib/Helper.php +++ b/apps/user_ldap/lib/Helper.php @@ -101,7 +101,7 @@ class Helper { $keys = $this->getServersConfig($referenceConfigkey); $result = []; - foreach($keys as $key) { + foreach ($keys as $key) { $len = strlen($key) - strlen($referenceConfigkey); $prefix = substr($key, 0, $len); $result[$prefix] = $this->config->getAppValue('user_ldap', $key); @@ -118,7 +118,7 @@ class Helper { public function getNextServerConfigurationPrefix() { $serverConnections = $this->getServerConfigurationPrefixes(); - if(count($serverConnections) === 0) { + if (count($serverConnections) === 0) { return 's01'; } @@ -148,12 +148,12 @@ class Helper { * @return bool true on success, false otherwise */ public function deleteServerConfiguration($prefix) { - if(!in_array($prefix, self::getServerConfigurationPrefixes())) { + if (!in_array($prefix, self::getServerConfigurationPrefixes())) { return false; } $saveOtherConfigurations = ''; - if(empty($prefix)) { + if (empty($prefix)) { $saveOtherConfigurations = 'AND `configkey` NOT LIKE \'s%\''; } @@ -167,11 +167,11 @@ class Helper { '); $delRows = $query->execute([$prefix.'%']); - if($delRows === null) { + if ($delRows === null) { return false; } - if($delRows === 0) { + if ($delRows === 0) { return false; } @@ -187,7 +187,7 @@ class Helper { $all = $this->getServerConfigurationPrefixes(false); $active = $this->getServerConfigurationPrefixes(true); - if(!is_array($all) || !is_array($active)) { + if (!is_array($all) || !is_array($active)) { throw new \Exception('Unexpected Return Value'); } @@ -201,14 +201,14 @@ class Helper { */ public function getDomainFromURL($url) { $uinfo = parse_url($url); - if(!is_array($uinfo)) { + if (!is_array($uinfo)) { return false; } $domain = false; - if(isset($uinfo['host'])) { + if (isset($uinfo['host'])) { $domain = $uinfo['host']; - } elseif(isset($uinfo['path'])) { + } elseif (isset($uinfo['path'])) { $domain = $uinfo['path']; } @@ -222,7 +222,7 @@ class Helper { */ public function setLDAPProvider() { $current = \OC::$server->getConfig()->getSystemValue('ldapProviderFactory', null); - if(is_null($current)) { + if (is_null($current)) { \OC::$server->getConfig()->setSystemValue('ldapProviderFactory', LDAPProviderFactory::class); } } @@ -234,9 +234,9 @@ class Helper { */ public function sanitizeDN($dn) { //treating multiple base DNs - if(is_array($dn)) { + if (is_array($dn)) { $result = []; - foreach($dn as $singleDN) { + foreach ($dn as $singleDN) { $result[] = $this->sanitizeDN($singleDN); } return $result; @@ -287,7 +287,7 @@ class Helper { * @throws \Exception */ public static function loginName2UserName($param) { - if(!isset($param['uid'])) { + if (!isset($param['uid'])) { throw new \Exception('key uid is expected to be set in $param'); } @@ -306,7 +306,7 @@ class Helper { $configPrefixes, $ldapWrapper, $ocConfig, $notificationManager, $userSession, $userPluginManager ); $uid = $userBackend->loginName2UserName($param['uid']); - if($uid !== false) { + if ($uid !== false) { $param['uid'] = $uid; } } diff --git a/apps/user_ldap/lib/IGroupLDAP.php b/apps/user_ldap/lib/IGroupLDAP.php index 7b2b5301e29..c84b899f5c0 100644 --- a/apps/user_ldap/lib/IGroupLDAP.php +++ b/apps/user_ldap/lib/IGroupLDAP.php @@ -40,5 +40,4 @@ interface IGroupLDAP { * @return resource of the LDAP connection */ public function getNewLDAPConnection($gid); - } diff --git a/apps/user_ldap/lib/ILDAPGroupPlugin.php b/apps/user_ldap/lib/ILDAPGroupPlugin.php index 3a5accece26..3c9baeab65c 100644 --- a/apps/user_ldap/lib/ILDAPGroupPlugin.php +++ b/apps/user_ldap/lib/ILDAPGroupPlugin.php @@ -81,5 +81,4 @@ interface ILDAPGroupPlugin { * @return array|false */ public function getGroupDetails($gid); - } diff --git a/apps/user_ldap/lib/ILDAPUserPlugin.php b/apps/user_ldap/lib/ILDAPUserPlugin.php index 29397b6c205..e4858d0688f 100644 --- a/apps/user_ldap/lib/ILDAPUserPlugin.php +++ b/apps/user_ldap/lib/ILDAPUserPlugin.php @@ -89,5 +89,4 @@ interface ILDAPUserPlugin { * @return int|bool */ public function countUsers(); - } diff --git a/apps/user_ldap/lib/ILDAPWrapper.php b/apps/user_ldap/lib/ILDAPWrapper.php index 586cfa18f8d..aa67dd596f1 100644 --- a/apps/user_ldap/lib/ILDAPWrapper.php +++ b/apps/user_ldap/lib/ILDAPWrapper.php @@ -212,5 +212,4 @@ interface ILDAPWrapper { * @return bool true if it is a resource, false otherwise */ public function isResource($resource); - } diff --git a/apps/user_ldap/lib/Jobs/CleanUp.php b/apps/user_ldap/lib/Jobs/CleanUp.php index 052ae72b663..996df67b1d2 100644 --- a/apps/user_ldap/lib/Jobs/CleanUp.php +++ b/apps/user_ldap/lib/Jobs/CleanUp.php @@ -83,19 +83,19 @@ class CleanUp extends TimedJob { //pass in app.php we do add here, except something else is passed e.g. //in tests. - if(isset($arguments['helper'])) { + if (isset($arguments['helper'])) { $this->ldapHelper = $arguments['helper']; } else { $this->ldapHelper = new Helper(\OC::$server->getConfig()); } - if(isset($arguments['ocConfig'])) { + if (isset($arguments['ocConfig'])) { $this->ocConfig = $arguments['ocConfig']; } else { $this->ocConfig = \OC::$server->getConfig(); } - if(isset($arguments['userBackend'])) { + if (isset($arguments['userBackend'])) { $this->userBackend = $arguments['userBackend']; } else { $this->userBackend = new User_Proxy( @@ -108,19 +108,19 @@ class CleanUp extends TimedJob { ); } - if(isset($arguments['db'])) { + if (isset($arguments['db'])) { $this->db = $arguments['db']; } else { $this->db = \OC::$server->getDatabaseConnection(); } - if(isset($arguments['mapping'])) { + if (isset($arguments['mapping'])) { $this->mapping = $arguments['mapping']; } else { $this->mapping = new UserMapping($this->db); } - if(isset($arguments['deletedUsersIndex'])) { + if (isset($arguments['deletedUsersIndex'])) { $this->dui = $arguments['deletedUsersIndex']; } else { $this->dui = new DeletedUsersIndex( @@ -135,11 +135,11 @@ class CleanUp extends TimedJob { public function run($argument) { $this->setArguments($argument); - if(!$this->isCleanUpAllowed()) { + if (!$this->isCleanUpAllowed()) { return; } $users = $this->mapping->getList($this->getOffset(), $this->getChunkSize()); - if(!is_array($users)) { + if (!is_array($users)) { //something wrong? Let's start from the beginning next time and //abort $this->setOffset(true); @@ -165,7 +165,7 @@ class CleanUp extends TimedJob { */ public function isCleanUpAllowed() { try { - if($this->ldapHelper->haveDisabledConfigurations()) { + if ($this->ldapHelper->haveDisabledConfigurations()) { return false; } } catch (\Exception $e) { @@ -189,7 +189,7 @@ class CleanUp extends TimedJob { * @param array $users result from getMappedUsers() */ private function checkUsers(array $users) { - foreach($users as $user) { + foreach ($users as $user) { $this->checkUser($user); } } @@ -199,7 +199,7 @@ class CleanUp extends TimedJob { * @param string[] $user */ private function checkUser(array $user) { - if($this->userBackend->userExistsOnLDAP($user['name'])) { + if ($this->userBackend->userExistsOnLDAP($user['name'])) { //still available, all good return; @@ -231,10 +231,9 @@ class CleanUp extends TimedJob { * @return int */ public function getChunkSize() { - if($this->limit === null) { + if ($this->limit === null) { $this->limit = (int)$this->ocConfig->getAppValue('user_ldap', 'cleanUpJobChunkSize', 50); } return $this->limit; } - } diff --git a/apps/user_ldap/lib/Jobs/Sync.php b/apps/user_ldap/lib/Jobs/Sync.php index e095ba41bef..1ef2d16e7c2 100644 --- a/apps/user_ldap/lib/Jobs/Sync.php +++ b/apps/user_ldap/lib/Jobs/Sync.php @@ -122,20 +122,20 @@ class Sync extends TimedJob { $isBackgroundJobModeAjax = $this->config ->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax'; - if($isBackgroundJobModeAjax) { + if ($isBackgroundJobModeAjax) { return; } $cycleData = $this->getCycle(); - if($cycleData === null) { + if ($cycleData === null) { $cycleData = $this->determineNextCycle(); - if($cycleData === null) { + if ($cycleData === null) { $this->updateInterval(); return; } } - if(!$this->qualifiesToRun($cycleData)) { + if (!$this->qualifiesToRun($cycleData)) { $this->updateInterval(); return; } @@ -175,7 +175,7 @@ class Sync extends TimedJob { true ); - if((int)$connection->ldapPagingSize === 0) { + if ((int)$connection->ldapPagingSize === 0) { return false; } return count($results) >= (int)$connection->ldapPagingSize; @@ -189,7 +189,7 @@ class Sync extends TimedJob { */ public function getCycle() { $prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true); - if(count($prefixes) === 0) { + if (count($prefixes) === 0) { return null; } @@ -198,7 +198,7 @@ class Sync extends TimedJob { 'offset' => (int)$this->config->getAppValue('user_ldap', 'background_sync_offset', 0), ]; - if( + if ( $cycleData['prefix'] !== null && in_array($cycleData['prefix'], $prefixes) ) { @@ -227,14 +227,14 @@ class Sync extends TimedJob { */ public function determineNextCycle(array $cycleData = null) { $prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true); - if(count($prefixes) === 0) { + if (count($prefixes) === 0) { return null; } // get the next prefix in line and remember it $oldPrefix = $cycleData === null ? null : $cycleData['prefix']; $prefix = $this->getNextPrefix($oldPrefix); - if($prefix === null) { + if ($prefix === null) { return null; } $cycleData['prefix'] = $prefix; @@ -253,7 +253,7 @@ class Sync extends TimedJob { */ public function qualifiesToRun($cycleData) { $lastChange = $this->config->getAppValue('user_ldap', $cycleData['prefix'] . '_lastChange', 0); - if((time() - $lastChange) > 60 * 30) { + if ((time() - $lastChange) > 60 * 30) { return true; } return false; @@ -279,17 +279,17 @@ class Sync extends TimedJob { protected function getNextPrefix($lastPrefix) { $prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true); $noOfPrefixes = count($prefixes); - if($noOfPrefixes === 0) { + if ($noOfPrefixes === 0) { return null; } $i = $lastPrefix === null ? false : array_search($lastPrefix, $prefixes, true); - if($i === false) { + if ($i === false) { $i = -1; } else { $i++; } - if(!isset($prefixes[$i])) { + if (!isset($prefixes[$i])) { $i = 0; } return $prefixes[$i]; @@ -301,49 +301,49 @@ class Sync extends TimedJob { * @param array $argument */ public function setArgument($argument) { - if(isset($argument['config'])) { + if (isset($argument['config'])) { $this->config = $argument['config']; } else { $this->config = \OC::$server->getConfig(); } - if(isset($argument['helper'])) { + if (isset($argument['helper'])) { $this->ldapHelper = $argument['helper']; } else { $this->ldapHelper = new Helper($this->config); } - if(isset($argument['ldapWrapper'])) { + if (isset($argument['ldapWrapper'])) { $this->ldap = $argument['ldapWrapper']; } else { $this->ldap = new LDAP(); } - if(isset($argument['avatarManager'])) { + if (isset($argument['avatarManager'])) { $this->avatarManager = $argument['avatarManager']; } else { $this->avatarManager = \OC::$server->getAvatarManager(); } - if(isset($argument['dbc'])) { + if (isset($argument['dbc'])) { $this->dbc = $argument['dbc']; } else { $this->dbc = \OC::$server->getDatabaseConnection(); } - if(isset($argument['ncUserManager'])) { + if (isset($argument['ncUserManager'])) { $this->ncUserManager = $argument['ncUserManager']; } else { $this->ncUserManager = \OC::$server->getUserManager(); } - if(isset($argument['notificationManager'])) { + if (isset($argument['notificationManager'])) { $this->notificationManager = $argument['notificationManager']; } else { $this->notificationManager = \OC::$server->getNotificationManager(); } - if(isset($argument['userManager'])) { + if (isset($argument['userManager'])) { $this->userManager = $argument['userManager']; } else { $this->userManager = new Manager( @@ -358,19 +358,19 @@ class Sync extends TimedJob { ); } - if(isset($argument['mapper'])) { + if (isset($argument['mapper'])) { $this->mapper = $argument['mapper']; } else { $this->mapper = new UserMapping($this->dbc); } - if(isset($argument['connectionFactory'])) { + if (isset($argument['connectionFactory'])) { $this->connectionFactory = $argument['connectionFactory']; } else { $this->connectionFactory = new ConnectionFactory($this->ldap); } - if(isset($argument['accessFactory'])) { + if (isset($argument['accessFactory'])) { $this->accessFactory = $argument['accessFactory']; } else { $this->accessFactory = new AccessFactory( diff --git a/apps/user_ldap/lib/Jobs/UpdateGroups.php b/apps/user_ldap/lib/Jobs/UpdateGroups.php index 71a2ea8c69e..19981a69bd2 100644 --- a/apps/user_ldap/lib/Jobs/UpdateGroups.php +++ b/apps/user_ldap/lib/Jobs/UpdateGroups.php @@ -67,7 +67,7 @@ class UpdateGroups extends \OC\BackgroundJob\TimedJob { $knownGroups = array_keys(self::getKnownGroups()); $actualGroups = self::getGroupBE()->getGroups(); - if(empty($actualGroups) && empty($knownGroups)) { + if (empty($actualGroups) && empty($knownGroups)) { \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.', ILogger::INFO); @@ -99,26 +99,26 @@ class UpdateGroups extends \OC\BackgroundJob\TimedJob { SET `owncloudusers` = ? WHERE `owncloudname` = ? '); - foreach($groups as $group) { + foreach ($groups as $group) { //we assume, that self::$groupsFromDB has been retrieved already $knownUsers = unserialize(self::$groupsFromDB[$group]['owncloudusers']); $actualUsers = self::getGroupBE()->usersInGroup($group); $hasChanged = false; - foreach(array_diff($knownUsers, $actualUsers) as $removedUser) { + foreach (array_diff($knownUsers, $actualUsers) as $removedUser) { \OCP\Util::emitHook('OC_User', 'post_removeFromGroup', ['uid' => $removedUser, 'gid' => $group]); \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – "'.$removedUser.'" removed from "'.$group.'".', ILogger::INFO); $hasChanged = true; } - foreach(array_diff($actualUsers, $knownUsers) as $addedUser) { + foreach (array_diff($actualUsers, $knownUsers) as $addedUser) { \OCP\Util::emitHook('OC_User', 'post_addToGroup', ['uid' => $addedUser, 'gid' => $group]); \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – "'.$addedUser.'" added to "'.$group.'".', ILogger::INFO); $hasChanged = true; } - if($hasChanged) { + if ($hasChanged) { $query->execute([serialize($actualUsers), $group]); } } @@ -137,7 +137,7 @@ class UpdateGroups extends \OC\BackgroundJob\TimedJob { INTO `*PREFIX*ldap_group_members` (`owncloudname`, `owncloudusers`) VALUES (?, ?) '); - foreach($createdGroups as $createdGroup) { + foreach ($createdGroups as $createdGroup) { \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – new group "'.$createdGroup.'" found.', ILogger::INFO); @@ -159,7 +159,7 @@ class UpdateGroups extends \OC\BackgroundJob\TimedJob { FROM `*PREFIX*ldap_group_members` WHERE `owncloudname` = ? '); - foreach($removedGroups as $removedGroup) { + foreach ($removedGroups as $removedGroup) { \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – group "'.$removedGroup.'" was removed.', ILogger::INFO); @@ -174,13 +174,13 @@ class UpdateGroups extends \OC\BackgroundJob\TimedJob { * @return \OCA\User_LDAP\Group_LDAP|\OCA\User_LDAP\Group_Proxy */ static private function getGroupBE() { - if(!is_null(self::$groupBE)) { + if (!is_null(self::$groupBE)) { return self::$groupBE; } $helper = new Helper(\OC::$server->getConfig()); $configPrefixes = $helper->getServerConfigurationPrefixes(true); $ldapWrapper = new LDAP(); - if(count($configPrefixes) === 1) { + if (count($configPrefixes) === 1) { //avoid the proxy when there is only one LDAP server configured $dbc = \OC::$server->getDatabaseConnection(); $userManager = new Manager( @@ -210,7 +210,7 @@ class UpdateGroups extends \OC\BackgroundJob\TimedJob { * @return array */ static private function getKnownGroups() { - if(is_array(self::$groupsFromDB)) { + if (is_array(self::$groupsFromDB)) { return self::$groupsFromDB; } $query = \OC_DB::prepare(' @@ -219,7 +219,7 @@ class UpdateGroups extends \OC\BackgroundJob\TimedJob { '); $result = $query->execute()->fetchAll(); self::$groupsFromDB = []; - foreach($result as $dataset) { + foreach ($result as $dataset) { self::$groupsFromDB[$dataset['owncloudname']] = $dataset; } diff --git a/apps/user_ldap/lib/LDAP.php b/apps/user_ldap/lib/LDAP.php index c4a30770566..409c6ab2b09 100644 --- a/apps/user_ldap/lib/LDAP.php +++ b/apps/user_ldap/lib/LDAP.php @@ -54,10 +54,10 @@ class LDAP implements ILDAPWrapper { * @return mixed */ public function connect($host, $port) { - if(strpos($host, '://') === false) { + if (strpos($host, '://') === false) { $host = 'ldap://' . $host; } - if(strpos($host, ':', strpos($host, '://') + 1) === false) { + if (strpos($host, ':', strpos($host, '://') + 1) === false) { //ldap_connect ignores port parameter when URLs are passed $host .= ':' . $port; } @@ -195,7 +195,7 @@ class LDAP implements ILDAPWrapper { */ public function search($link, $baseDN, $filter, $attr, $attrsOnly = 0, $limit = 0) { $oldHandler = set_error_handler(function ($no, $message, $file, $line) use (&$oldHandler) { - if(strpos($message, 'Partial search results returned: Sizelimit exceeded') !== false) { + if (strpos($message, 'Partial search results returned: Sizelimit exceeded') !== false) { return true; } $oldHandler($no, $message, $file, $line); @@ -285,13 +285,13 @@ class LDAP implements ILDAPWrapper { * @return bool */ protected function isResultFalse($result) { - if($result === false) { + if ($result === false) { return true; } - if($this->curFunc === 'ldap_search' && is_array($result)) { + if ($this->curFunc === 'ldap_search' && is_array($result)) { foreach ($result as $singleResult) { - if($singleResult === false) { + if ($singleResult === false) { return true; } } @@ -306,7 +306,7 @@ class LDAP implements ILDAPWrapper { protected function invokeLDAPMethod() { $arguments = func_get_args(); $func = 'ldap_' . array_shift($arguments); - if(function_exists($func)) { + if (function_exists($func)) { $this->preFunctionCall($func, $arguments); $result = call_user_func_array($func, $arguments); if ($this->isResultFalse($result)) { @@ -336,12 +336,12 @@ class LDAP implements ILDAPWrapper { */ private function processLDAPError($resource) { $errorCode = ldap_errno($resource); - if($errorCode === 0) { + if ($errorCode === 0) { return; } $errorMsg = ldap_error($resource); - if($this->curFunc === 'ldap_get_entries' + if ($this->curFunc === 'ldap_get_entries' && $errorCode === -4) { } elseif ($errorCode === 32) { //for now @@ -373,9 +373,9 @@ class LDAP implements ILDAPWrapper { * @throw \Exception */ private function postFunctionCall() { - if($this->isResource($this->curArgs[0])) { + if ($this->isResource($this->curArgs[0])) { $resource = $this->curArgs[0]; - } elseif( + } elseif ( $this->curFunc === 'ldap_search' && is_array($this->curArgs[0]) && $this->isResource($this->curArgs[0][0]) diff --git a/apps/user_ldap/lib/LDAPProvider.php b/apps/user_ldap/lib/LDAPProvider.php index 75267165cdf..5b91a52f546 100644 --- a/apps/user_ldap/lib/LDAPProvider.php +++ b/apps/user_ldap/lib/LDAPProvider.php @@ -37,7 +37,6 @@ use OCP\LDAP\ILDAPProvider; * LDAP provider for pulic access to the LDAP backend. */ class LDAPProvider implements ILDAPProvider, IDeletionFlagSupport { - private $userBackend; private $groupBackend; private $logger; @@ -57,7 +56,7 @@ class LDAPProvider implements ILDAPProvider, IDeletionFlagSupport { $this->deletedUsersIndex = $deletedUsersIndex; $userBackendFound = false; $groupBackendFound = false; - foreach ($serverContainer->getUserManager()->getBackends() as $backend){ + foreach ($serverContainer->getUserManager()->getBackends() as $backend) { $this->logger->debug('instance '.get_class($backend).' user backend.', ['app' => 'user_ldap']); if ($backend instanceof IUserLDAP) { $this->userBackend = $backend; @@ -65,7 +64,7 @@ class LDAPProvider implements ILDAPProvider, IDeletionFlagSupport { break; } } - foreach ($serverContainer->getGroupManager()->getBackends() as $backend){ + foreach ($serverContainer->getGroupManager()->getBackends() as $backend) { $this->logger->debug('instance '.get_class($backend).' group backend.', ['app' => 'user_ldap']); if ($backend instanceof IGroupLDAP) { $this->groupBackend = $backend; @@ -86,11 +85,11 @@ class LDAPProvider implements ILDAPProvider, IDeletionFlagSupport { * @throws \Exception if translation was unsuccessful */ public function getUserDN($uid) { - if(!$this->userBackend->userExists($uid)){ + if (!$this->userBackend->userExists($uid)) { throw new \Exception('User id not found in LDAP'); } $result = $this->userBackend->getLDAPAccess($uid)->username2dn($uid); - if(!$result){ + if (!$result) { throw new \Exception('Translation to LDAP DN unsuccessful'); } return $result; @@ -103,11 +102,11 @@ class LDAPProvider implements ILDAPProvider, IDeletionFlagSupport { * @throws \Exception */ public function getGroupDN($gid) { - if(!$this->groupBackend->groupExists($gid)){ + if (!$this->groupBackend->groupExists($gid)) { throw new \Exception('Group id not found in LDAP'); } $result = $this->groupBackend->getLDAPAccess($gid)->groupname2dn($gid); - if(!$result){ + if (!$result) { throw new \Exception('Translation to LDAP DN unsuccessful'); } return $result; @@ -122,7 +121,7 @@ class LDAPProvider implements ILDAPProvider, IDeletionFlagSupport { */ public function getUserName($dn) { $result = $this->userBackend->dn2UserName($dn); - if(!$result){ + if (!$result) { throw new \Exception('Translation to internal user name unsuccessful'); } return $result; @@ -154,7 +153,7 @@ class LDAPProvider implements ILDAPProvider, IDeletionFlagSupport { * @throws \Exception if user id was not found in LDAP */ public function getLDAPConnection($uid) { - if(!$this->userBackend->userExists($uid)){ + if (!$this->userBackend->userExists($uid)) { throw new \Exception('User id not found in LDAP'); } return $this->userBackend->getNewLDAPConnection($uid); @@ -168,7 +167,7 @@ class LDAPProvider implements ILDAPProvider, IDeletionFlagSupport { * @throws \Exception if group id was not found in LDAP */ public function getGroupLDAPConnection($gid) { - if(!$this->groupBackend->groupExists($gid)){ + if (!$this->groupBackend->groupExists($gid)) { throw new \Exception('Group id not found in LDAP'); } return $this->groupBackend->getNewLDAPConnection($gid); @@ -181,14 +180,14 @@ class LDAPProvider implements ILDAPProvider, IDeletionFlagSupport { * @throws \Exception if user id was not found in LDAP */ public function getLDAPBaseUsers($uid) { - if(!$this->userBackend->userExists($uid)){ + if (!$this->userBackend->userExists($uid)) { throw new \Exception('User id not found in LDAP'); } $access = $this->userBackend->getLDAPAccess($uid); $bases = $access->getConnection()->ldapBaseUsers; $dn = $this->getUserDN($uid); foreach ($bases as $base) { - if($access->isDNPartOfBase($dn, [$base])) { + if ($access->isDNPartOfBase($dn, [$base])) { return $base; } } @@ -211,7 +210,7 @@ class LDAPProvider implements ILDAPProvider, IDeletionFlagSupport { * @throws \Exception if user id was not found in LDAP */ public function getLDAPBaseGroups($uid) { - if(!$this->userBackend->userExists($uid)){ + if (!$this->userBackend->userExists($uid)) { throw new \Exception('User id not found in LDAP'); } $bases = $this->userBackend->getLDAPAccess($uid)->getConnection()->ldapBaseGroups; @@ -224,7 +223,7 @@ class LDAPProvider implements ILDAPProvider, IDeletionFlagSupport { * @throws \Exception if user id was not found in LDAP */ public function clearCache($uid) { - if(!$this->userBackend->userExists($uid)){ + if (!$this->userBackend->userExists($uid)) { throw new \Exception('User id not found in LDAP'); } $this->userBackend->getLDAPAccess($uid)->getConnection()->clearCache(); @@ -237,7 +236,7 @@ class LDAPProvider implements ILDAPProvider, IDeletionFlagSupport { * @throws \Exception if user id was not found in LDAP */ public function clearGroupCache($gid) { - if(!$this->groupBackend->groupExists($gid)){ + if (!$this->groupBackend->groupExists($gid)) { throw new \Exception('Group id not found in LDAP'); } $this->groupBackend->getLDAPAccess($gid)->getConnection()->clearCache(); @@ -276,7 +275,7 @@ class LDAPProvider implements ILDAPProvider, IDeletionFlagSupport { * @throws \Exception if user id was not found in LDAP */ public function getLDAPDisplayNameField($uid) { - if(!$this->userBackend->userExists($uid)){ + if (!$this->userBackend->userExists($uid)) { throw new \Exception('User id not found in LDAP'); } return $this->userBackend->getLDAPAccess($uid)->getConnection()->getConfiguration()['ldap_display_name']; @@ -289,7 +288,7 @@ class LDAPProvider implements ILDAPProvider, IDeletionFlagSupport { * @throws \Exception if user id was not found in LDAP */ public function getLDAPEmailField($uid) { - if(!$this->userBackend->userExists($uid)){ + if (!$this->userBackend->userExists($uid)) { throw new \Exception('User id not found in LDAP'); } return $this->userBackend->getLDAPAccess($uid)->getConnection()->getConfiguration()['ldap_email_attr']; @@ -302,10 +301,9 @@ class LDAPProvider implements ILDAPProvider, IDeletionFlagSupport { * @throws \Exception if group id was not found in LDAP */ public function getLDAPGroupMemberAssoc($gid) { - if(!$this->groupBackend->groupExists($gid)){ + if (!$this->groupBackend->groupExists($gid)) { throw new \Exception('Group id not found in LDAP'); } return $this->groupBackend->getLDAPAccess($gid)->getConnection()->getConfiguration()['ldap_group_member_assoc_attribute']; } - } diff --git a/apps/user_ldap/lib/Mapping/AbstractMapping.php b/apps/user_ldap/lib/Mapping/AbstractMapping.php index 5d445af6b7e..e14c9a572de 100644 --- a/apps/user_ldap/lib/Mapping/AbstractMapping.php +++ b/apps/user_ldap/lib/Mapping/AbstractMapping.php @@ -55,7 +55,7 @@ abstract class AbstractMapping { * @return bool */ public function isColNameValid($col) { - switch($col) { + switch ($col) { case 'ldap_dn': case 'owncloud_name': case 'directory_uuid': @@ -74,7 +74,7 @@ abstract class AbstractMapping { * @return string|false */ protected function getXbyY($fetchCol, $compareCol, $search) { - if(!$this->isColNameValid($fetchCol)) { + if (!$this->isColNameValid($fetchCol)) { //this is used internally only, but we don't want to risk //having SQL injection at all. throw new \Exception('Invalid Column Name'); @@ -86,7 +86,7 @@ abstract class AbstractMapping { '); $res = $query->execute([$search]); - if($res !== false) { + if ($res !== false) { return $query->fetchColumn(); } @@ -174,8 +174,8 @@ abstract class AbstractMapping { $res = $query->execute([$prefixMatch.$this->dbc->escapeLikeParameter($search).$postfixMatch]); $names = []; - if($res !== false) { - while($row = $query->fetch()) { + if ($res !== false) { + while ($row = $query->fetch()) { $names[] = $row['owncloud_name']; } } @@ -230,7 +230,7 @@ abstract class AbstractMapping { * @return bool */ public function map($fdn, $name, $uuid) { - if(mb_strlen($fdn) > 255) { + if (mb_strlen($fdn) > 255) { \OC::$server->getLogger()->error( 'Cannot map, because the DN exceeds 255 characters: {dn}', [ @@ -295,9 +295,9 @@ abstract class AbstractMapping { ->from($this->getTableName()); $cursor = $picker->execute(); $result = true; - while($id = $cursor->fetchColumn(0)) { + while ($id = $cursor->fetchColumn(0)) { $preCallback($id); - if($isUnmapped = $this->unmap($id)) { + if ($isUnmapped = $this->unmap($id)) { $postCallback($id); } $result &= $isUnmapped; diff --git a/apps/user_ldap/lib/Mapping/GroupMapping.php b/apps/user_ldap/lib/Mapping/GroupMapping.php index cc779817f1a..b2c1b9c99af 100644 --- a/apps/user_ldap/lib/Mapping/GroupMapping.php +++ b/apps/user_ldap/lib/Mapping/GroupMapping.php @@ -36,5 +36,4 @@ class GroupMapping extends AbstractMapping { protected function getTableName() { return '*PREFIX*ldap_group_mapping'; } - } diff --git a/apps/user_ldap/lib/Mapping/UserMapping.php b/apps/user_ldap/lib/Mapping/UserMapping.php index 31ac8a05326..556f7ecf1a4 100644 --- a/apps/user_ldap/lib/Mapping/UserMapping.php +++ b/apps/user_ldap/lib/Mapping/UserMapping.php @@ -36,5 +36,4 @@ class UserMapping extends AbstractMapping { protected function getTableName() { return '*PREFIX*ldap_user_mapping'; } - } diff --git a/apps/user_ldap/lib/Migration/UUIDFix.php b/apps/user_ldap/lib/Migration/UUIDFix.php index f6359c2e882..f7e399a51bd 100644 --- a/apps/user_ldap/lib/Migration/UUIDFix.php +++ b/apps/user_ldap/lib/Migration/UUIDFix.php @@ -37,14 +37,14 @@ abstract class UUIDFix extends QueuedJob { public function run($argument) { $isUser = $this->proxy instanceof User_Proxy; - foreach($argument['records'] as $record) { + foreach ($argument['records'] as $record) { $access = $this->proxy->getLDAPAccess($record['name']); $uuid = $access->getUUID($record['dn'], $isUser); - if($uuid === false) { + if ($uuid === false) { // record not found, no prob, continue with the next continue; } - if($uuid !== $record['uuid']) { + if ($uuid !== $record['uuid']) { $this->mapper->setUUIDbyDN($uuid, $record['dn']); } } diff --git a/apps/user_ldap/lib/Migration/UUIDFixInsert.php b/apps/user_ldap/lib/Migration/UUIDFixInsert.php index 1674882803a..873c8bcd98e 100644 --- a/apps/user_ldap/lib/Migration/UUIDFixInsert.php +++ b/apps/user_ldap/lib/Migration/UUIDFixInsert.php @@ -72,7 +72,7 @@ class UUIDFixInsert implements IRepairStep { */ public function run(IOutput $output) { $installedVersion = $this->config->getAppValue('user_ldap', 'installed_version', '1.2.1'); - if(version_compare($installedVersion, '1.2.1') !== -1) { + if (version_compare($installedVersion, '1.2.1') !== -1) { return; } @@ -83,20 +83,19 @@ class UUIDFixInsert implements IRepairStep { do { $retry = false; $records = $mapper->getList($offset, $batchSize); - if(count($records) === 0){ + if (count($records) === 0) { continue; } try { $this->jobList->add($jobClass, ['records' => $records]); $offset += $batchSize; } catch (\InvalidArgumentException $e) { - if(strpos($e->getMessage(), 'Background job arguments can\'t exceed 4000') !== false) { + if (strpos($e->getMessage(), 'Background job arguments can\'t exceed 4000') !== false) { $batchSize = (int)floor(count($records) * 0.8); $retry = true; } } } while (count($records) === $batchSize || $retry); } - } } diff --git a/apps/user_ldap/lib/Notification/Notifier.php b/apps/user_ldap/lib/Notification/Notifier.php index 167f282beb7..d380e38a486 100644 --- a/apps/user_ldap/lib/Notification/Notifier.php +++ b/apps/user_ldap/lib/Notification/Notifier.php @@ -37,7 +37,7 @@ class Notifier implements INotifier { /** * @param IFactory $l10nFactory */ - public function __construct(\OCP\L10N\IFactory $l10nFactory) { + public function __construct(\OCP\L10N\IFactory $l10nFactory) { $this->l10nFactory = $l10nFactory; } diff --git a/apps/user_ldap/lib/Proxy.php b/apps/user_ldap/lib/Proxy.php index b077b0d5a86..7698895eaf0 100644 --- a/apps/user_ldap/lib/Proxy.php +++ b/apps/user_ldap/lib/Proxy.php @@ -50,7 +50,7 @@ abstract class Proxy { public function __construct(ILDAPWrapper $ldap) { $this->ldap = $ldap; $memcache = \OC::$server->getMemCacheFactory(); - if($memcache->isAvailable()) { + if ($memcache->isAvailable()) { $this->cache = $memcache->createDistributed(); } } @@ -68,7 +68,7 @@ abstract class Proxy { static $db; static $coreUserManager; static $coreNotificationManager; - if($fs === null) { + if ($fs === null) { $ocConfig = \OC::$server->getConfig(); $fs = new FilesystemHelper(); $log = new LogWrapper(); @@ -94,7 +94,7 @@ abstract class Proxy { * @return mixed */ protected function getAccess($configPrefix) { - if(!isset(self::$accesses[$configPrefix])) { + if (!isset(self::$accesses[$configPrefix])) { $this->addAccess($configPrefix); } return self::$accesses[$configPrefix]; @@ -149,7 +149,7 @@ abstract class Proxy { */ protected function handleRequest($id, $method, $parameters, $passOnWhen = false) { $result = $this->callOnLastSeenOn($id, $method, $parameters, $passOnWhen); - if($result === $passOnWhen) { + if ($result === $passOnWhen) { $result = $this->walkBackends($id, $method, $parameters); } return $result; @@ -161,7 +161,7 @@ abstract class Proxy { */ private function getCacheKey($key) { $prefix = 'LDAP-Proxy-'; - if($key === null) { + if ($key === null) { return $prefix; } return $prefix.hash('sha256', $key); @@ -172,7 +172,7 @@ abstract class Proxy { * @return mixed|null */ public function getFromCache($key) { - if($this->cache === null) { + if ($this->cache === null) { return null; } @@ -190,7 +190,7 @@ abstract class Proxy { * @param mixed $value */ public function writeToCache($key, $value) { - if($this->cache === null) { + if ($this->cache === null) { return; } $key = $this->getCacheKey($key); @@ -199,7 +199,7 @@ abstract class Proxy { } public function clearCache() { - if($this->cache === null) { + if ($this->cache === null) { return; } $this->cache->clear($this->getCacheKey(null)); diff --git a/apps/user_ldap/lib/Settings/Admin.php b/apps/user_ldap/lib/Settings/Admin.php index e9c883bd20d..f043d179e80 100644 --- a/apps/user_ldap/lib/Settings/Admin.php +++ b/apps/user_ldap/lib/Settings/Admin.php @@ -49,7 +49,7 @@ class Admin implements ISettings { public function getForm() { $helper = new Helper(\OC::$server->getConfig()); $prefixes = $helper->getServerConfigurationPrefixes(); - if(count($prefixes) === 0) { + if (count($prefixes) === 0) { $newPrefix = $helper->getNextServerConfigurationPrefix(); $config = new Configuration($newPrefix, false); $config->setConfiguration($config->getDefaults()); @@ -70,11 +70,11 @@ class Admin implements ISettings { $parameters['wizardControls'] = $wControls; // assign default values - if(!isset($config)) { + if (!isset($config)) { $config = new Configuration('', false); } $defaults = $config->getDefaults(); - foreach($defaults as $key => $default) { + foreach ($defaults as $key => $default) { $parameters[$key.'_default'] = $default; } diff --git a/apps/user_ldap/lib/User/DeletedUsersIndex.php b/apps/user_ldap/lib/User/DeletedUsersIndex.php index 98de28b6925..fee2b02d2c3 100644 --- a/apps/user_ldap/lib/User/DeletedUsersIndex.php +++ b/apps/user_ldap/lib/User/DeletedUsersIndex.php @@ -71,7 +71,7 @@ class DeletedUsersIndex { 'user_ldap', 'isDeleted', '1'); $userObjects = []; - foreach($deletedUsers as $user) { + foreach ($deletedUsers as $user) { $userObjects[] = new OfflineUser($user, $this->config, $this->db, $this->mapping); } $this->deletedUsers = $userObjects; @@ -84,7 +84,7 @@ class DeletedUsersIndex { * @return \OCA\User_LDAP\User\OfflineUser[] */ public function getUsers() { - if(is_array($this->deletedUsers)) { + if (is_array($this->deletedUsers)) { return $this->deletedUsers; } return $this->fetchDeletedUsers(); @@ -95,7 +95,7 @@ class DeletedUsersIndex { * @return bool */ public function hasUsers() { - if(!is_array($this->deletedUsers)) { + if (!is_array($this->deletedUsers)) { $this->fetchDeletedUsers(); } return is_array($this->deletedUsers) && (count($this->deletedUsers) > 0); @@ -109,7 +109,7 @@ class DeletedUsersIndex { */ public function markUser($ocName) { $curValue = $this->config->getUserValue($ocName, 'user_ldap', 'isDeleted', '0'); - if($curValue === '1') { + if ($curValue === '1') { // the user is already marked, do not write to DB again return; } diff --git a/apps/user_ldap/lib/User/Manager.php b/apps/user_ldap/lib/User/Manager.php index f3729f2458e..a62aa3b39ac 100644 --- a/apps/user_ldap/lib/User/Manager.php +++ b/apps/user_ldap/lib/User/Manager.php @@ -97,7 +97,6 @@ class Manager { IAvatarManager $avatarManager, Image $image, IDBConnection $db, IUserManager $userManager, INotificationManager $notificationManager) { - $this->ocConfig = $ocConfig; $this->ocFilesystem = $ocFilesystem; $this->ocLog = $ocLog; @@ -142,7 +141,7 @@ class Manager { * @param $uid */ public function invalidate($uid) { - if(!isset($this->usersByUid[$uid])) { + if (!isset($this->usersByUid[$uid])) { return; } $dn = $this->usersByUid[$uid]->getDN(); @@ -156,7 +155,7 @@ class Manager { * @return null */ private function checkAccess() { - if(is_null($this->access)) { + if (is_null($this->access)) { throw new \Exception('LDAP Access instance must be set first'); } } @@ -181,11 +180,11 @@ class Manager { ]; $homeRule = $this->access->getConnection()->homeFolderNamingRule; - if(strpos($homeRule, 'attr:') === 0) { + if (strpos($homeRule, 'attr:') === 0) { $attributes[] = substr($homeRule, strlen('attr:')); } - if(!$minimal) { + if (!$minimal) { // attributes that are not really important but may come with big // payload. $attributes = array_merge( @@ -197,7 +196,7 @@ class Manager { $attributes = array_reduce($attributes, function ($list, $attribute) { $attribute = strtolower(trim((string)$attribute)); - if(!empty($attribute) && !in_array($attribute, $list)) { + if (!empty($attribute) && !in_array($attribute, $list)) { $list[] = $attribute; } @@ -240,11 +239,11 @@ class Manager { */ protected function createInstancyByUserName($id) { //most likely a uid. Check whether it is a deleted user - if($this->isDeletedUser($id)) { + if ($this->isDeletedUser($id)) { return $this->getDeletedUser($id); } $dn = $this->access->username2dn($id); - if($dn !== false) { + if ($dn !== false) { return $this->createAndCache($dn, $id); } return null; @@ -258,20 +257,19 @@ class Manager { */ public function get($id) { $this->checkAccess(); - if(isset($this->usersByDN[$id])) { + if (isset($this->usersByDN[$id])) { return $this->usersByDN[$id]; - } elseif(isset($this->usersByUid[$id])) { + } elseif (isset($this->usersByUid[$id])) { return $this->usersByUid[$id]; } - if($this->access->stringResemblesDN($id)) { + if ($this->access->stringResemblesDN($id)) { $uid = $this->access->dn2username($id); - if($uid !== false) { + if ($uid !== false) { return $this->createAndCache($id, $uid); } } return $this->createInstancyByUserName($id); } - } diff --git a/apps/user_ldap/lib/User/OfflineUser.php b/apps/user_ldap/lib/User/OfflineUser.php index 60a39e95022..72d29dd5441 100644 --- a/apps/user_ldap/lib/User/OfflineUser.php +++ b/apps/user_ldap/lib/User/OfflineUser.php @@ -203,7 +203,7 @@ class OfflineUser { 'email' => 'settings', 'lastLogin' => 'login', ]; - foreach($properties as $property => $app) { + foreach ($properties as $property => $app) { $this->$property = $this->config->getUserValue($this->ocName, $app, $property, ''); } @@ -226,7 +226,7 @@ class OfflineUser { ', 1); $query->execute([$this->ocName]); $sResult = $query->fetchColumn(0); - if((int)$sResult === 1) { + if ((int)$sResult === 1) { $this->hasActiveShares = true; return; } @@ -238,7 +238,7 @@ class OfflineUser { ', 1); $query->execute([$this->ocName]); $sResult = $query->fetchColumn(0); - if((int)$sResult === 1) { + if ((int)$sResult === 1) { $this->hasActiveShares = true; return; } diff --git a/apps/user_ldap/lib/User/User.php b/apps/user_ldap/lib/User/User.php index 28eeddccef0..724db063659 100644 --- a/apps/user_ldap/lib/User/User.php +++ b/apps/user_ldap/lib/User/User.php @@ -127,7 +127,6 @@ class User { IConfig $config, FilesystemHelper $fs, Image $image, LogWrapper $log, IAvatarManager $avatarManager, IUserManager $userManager, INotificationManager $notificationManager) { - if ($username === null) { $log->log("uid for '$dn' must not be null!", ILogger::ERROR); throw new \InvalidArgumentException('uid must not be null!'); @@ -156,17 +155,17 @@ class User { * @return null */ public function update() { - if(is_null($this->dn)) { + if (is_null($this->dn)) { return null; } $hasLoggedIn = $this->config->getUserValue($this->uid, 'user_ldap', self::USER_PREFKEY_FIRSTLOGIN, 0); - if($this->needsRefresh()) { + if ($this->needsRefresh()) { $this->updateEmail(); $this->updateQuota(); - if($hasLoggedIn !== 0) { + if ($hasLoggedIn !== 0) { //we do not need to try it, when the user has not been logged in //before, because the file system will not be ready. $this->updateAvatar(); @@ -184,7 +183,7 @@ class User { */ public function markUser() { $curValue = $this->config->getUserValue($this->getUsername(), 'user_ldap', 'isDeleted', '0'); - if($curValue === '1') { + if ($curValue === '1') { // the user is already marked, do not write to DB again return; } @@ -200,7 +199,7 @@ class User { $this->markRefreshTime(); //Quota $attr = strtolower($this->connection->ldapQuotaAttribute); - if(isset($ldapEntry[$attr])) { + if (isset($ldapEntry[$attr])) { $this->updateQuota($ldapEntry[$attr][0]); } else { if ($this->connection->ldapQuotaDefault !== '') { @@ -212,11 +211,11 @@ class User { //displayName $displayName = $displayName2 = ''; $attr = strtolower($this->connection->ldapUserDisplayName); - if(isset($ldapEntry[$attr])) { + if (isset($ldapEntry[$attr])) { $displayName = (string)$ldapEntry[$attr][0]; } $attr = strtolower($this->connection->ldapUserDisplayName2); - if(isset($ldapEntry[$attr])) { + if (isset($ldapEntry[$attr])) { $displayName2 = (string)$ldapEntry[$attr][0]; } if ($displayName !== '') { @@ -233,22 +232,22 @@ class User { //email must be stored after displayname, because it would cause a user //change event that will trigger fetching the display name again $attr = strtolower($this->connection->ldapEmailAttribute); - if(isset($ldapEntry[$attr])) { + if (isset($ldapEntry[$attr])) { $this->updateEmail($ldapEntry[$attr][0]); } unset($attr); // LDAP Username, needed for s2s sharing - if(isset($ldapEntry['uid'])) { + if (isset($ldapEntry['uid'])) { $this->storeLDAPUserName($ldapEntry['uid'][0]); - } elseif(isset($ldapEntry['samaccountname'])) { + } elseif (isset($ldapEntry['samaccountname'])) { $this->storeLDAPUserName($ldapEntry['samaccountname'][0]); } //homePath - if(strpos($this->connection->homeFolderNamingRule, 'attr:') === 0) { + if (strpos($this->connection->homeFolderNamingRule, 'attr:') === 0) { $attr = strtolower(substr($this->connection->homeFolderNamingRule, strlen('attr:'))); - if(isset($ldapEntry[$attr])) { + if (isset($ldapEntry[$attr])) { $this->access->cacheUserHome( $this->getUsername(), $this->getHomePath($ldapEntry[$attr][0])); } @@ -257,14 +256,14 @@ class User { //memberOf groups $cacheKey = 'getMemberOf'.$this->getUsername(); $groups = false; - if(isset($ldapEntry['memberof'])) { + if (isset($ldapEntry['memberof'])) { $groups = $ldapEntry['memberof']; } $this->connection->writeToCache($cacheKey, $groups); //external storage var $attr = strtolower($this->connection->ldapExtStorageHomeAttribute); - if(isset($ldapEntry[$attr])) { + if (isset($ldapEntry[$attr])) { $this->updateExtStorageHome($ldapEntry[$attr][0]); } unset($attr); @@ -273,8 +272,8 @@ class User { /** @var Connection $connection */ $connection = $this->access->getConnection(); $attributes = $connection->resolveRule('avatar'); - foreach ($attributes as $attribute) { - if(isset($ldapEntry[$attribute])) { + foreach ($attributes as $attribute) { + if (isset($ldapEntry[$attribute])) { $this->avatarImage = $ldapEntry[$attribute][0]; // the call to the method that saves the avatar in the file // system must be postponed after the login. It is to ensure @@ -314,8 +313,7 @@ class User { if (is_null($valueFromLDAP) && strpos($this->access->connection->homeFolderNamingRule, 'attr:') === 0 - && $this->access->connection->homeFolderNamingRule !== 'attr:') - { + && $this->access->connection->homeFolderNamingRule !== 'attr:') { $attr = substr($this->access->connection->homeFolderNamingRule, strlen('attr:')); $homedir = $this->access->readAttribute( $this->access->username2dn($this->getUsername()), $attr); @@ -327,7 +325,7 @@ class User { if ($path !== '') { //if attribute's value is an absolute path take this, otherwise append it to data dir //check for / at the beginning or pattern c:\ resp. c:/ - if('/' !== $path[0] + if ('/' !== $path[0] && !(3 < strlen($path) && ctype_alpha($path[0]) && $path[1] === ':' && ('\\' === $path[2] || '/' === $path[2])) ) { @@ -342,7 +340,7 @@ class User { return $path; } - if(!is_null($attr) + if (!is_null($attr) && $this->config->getAppValue('user_ldap', 'enforce_home_folder_naming_rule', true) ) { // a naming rule attribute is defined, but it doesn't exist for that LDAP user @@ -357,7 +355,7 @@ class User { public function getMemberOfGroups() { $cacheKey = 'getMemberOf'.$this->getUsername(); $memberOfGroups = $this->connection->getFromCache($cacheKey); - if(!is_null($memberOfGroups)) { + if (!is_null($memberOfGroups)) { return $memberOfGroups; } $groupDNs = $this->access->readAttribute($this->getDN(), 'memberOf'); @@ -370,7 +368,7 @@ class User { * @return string data (provided by LDAP) | false */ public function getAvatarImage() { - if(!is_null($this->avatarImage)) { + if (!is_null($this->avatarImage)) { return $this->avatarImage; } @@ -378,9 +376,9 @@ class User { /** @var Connection $connection */ $connection = $this->access->getConnection(); $attributes = $connection->resolveRule('avatar'); - foreach($attributes as $attribute) { + foreach ($attributes as $attribute) { $result = $this->access->readAttribute($this->dn, $attribute); - if($result !== false && is_array($result) && isset($result[0])) { + if ($result !== false && is_array($result) && isset($result[0])) { $this->avatarImage = $result[0]; break; } @@ -417,7 +415,7 @@ class User { $lastChecked = $this->config->getUserValue($this->uid, 'user_ldap', self::USER_PREFKEY_LASTREFRESH, 0); - if((time() - (int)$lastChecked) < (int)$this->config->getAppValue('user_ldap', 'updateAttributesInterval', 86400)) { + if ((time() - (int)$lastChecked) < (int)$this->config->getAppValue('user_ldap', 'updateAttributesInterval', 86400)) { return false; } return true; @@ -443,11 +441,11 @@ class User { */ public function composeAndStoreDisplayName($displayName, $displayName2 = '') { $displayName2 = (string)$displayName2; - if($displayName2 !== '') { + if ($displayName2 !== '') { $displayName .= ' (' . $displayName2 . ')'; } $oldName = $this->config->getUserValue($this->uid, 'user_ldap', 'displayName', null); - if ($oldName !== $displayName) { + if ($oldName !== $displayName) { $this->store('displayName', $displayName); $user = $this->userManager->get($this->getUsername()); if (!empty($oldName) && $user instanceof \OC\User\User) { @@ -475,7 +473,7 @@ class User { * @return bool */ private function wasRefreshed($feature) { - if(isset($this->refreshedFeatures[$feature])) { + if (isset($this->refreshedFeatures[$feature])) { return true; } $this->refreshedFeatures[$feature] = 1; @@ -488,15 +486,15 @@ class User { * @return null */ public function updateEmail($valueFromLDAP = null) { - if($this->wasRefreshed('email')) { + if ($this->wasRefreshed('email')) { return; } $email = (string)$valueFromLDAP; - if(is_null($valueFromLDAP)) { + if (is_null($valueFromLDAP)) { $emailAttribute = $this->connection->ldapEmailAttribute; if ($emailAttribute !== '') { $aEmail = $this->access->readAttribute($this->dn, $emailAttribute); - if(is_array($aEmail) && (count($aEmail) > 0)) { + if (is_array($aEmail) && (count($aEmail) > 0)) { $email = (string)$aEmail[0]; } } @@ -533,22 +531,22 @@ class User { * @return null */ public function updateQuota($valueFromLDAP = null) { - if($this->wasRefreshed('quota')) { + if ($this->wasRefreshed('quota')) { return; } $quotaAttribute = $this->connection->ldapQuotaAttribute; $defaultQuota = $this->connection->ldapQuotaDefault; - if($quotaAttribute === '' && $defaultQuota === '') { + if ($quotaAttribute === '' && $defaultQuota === '') { return; } $quota = false; - if(is_null($valueFromLDAP) && $quotaAttribute !== '') { + if (is_null($valueFromLDAP) && $quotaAttribute !== '') { $aQuota = $this->access->readAttribute($this->dn, $quotaAttribute); - if($aQuota && (count($aQuota) > 0) && $this->verifyQuotaValue($aQuota[0])) { + if ($aQuota && (count($aQuota) > 0) && $this->verifyQuotaValue($aQuota[0])) { $quota = $aQuota[0]; - } elseif(is_array($aQuota) && isset($aQuota[0])) { + } elseif (is_array($aQuota) && isset($aQuota[0])) { $this->log->log('no suitable LDAP quota found for user ' . $this->uid . ': [' . $aQuota[0] . ']', ILogger::DEBUG); } } elseif ($this->verifyQuotaValue($valueFromLDAP)) { @@ -560,7 +558,7 @@ class User { if ($quota === false && $this->verifyQuotaValue($defaultQuota)) { // quota not found using the LDAP attribute (or not parseable). Try the default quota $quota = $defaultQuota; - } elseif($quota === false) { + } elseif ($quota === false) { $this->log->log('no suitable default quota found for user ' . $this->uid . ': [' . $defaultQuota . ']', ILogger::DEBUG); return; } @@ -583,7 +581,7 @@ class User { * @param array $params */ public function updateAvatarPostLogin($params) { - if(isset($params['uid']) && $params['uid'] === $this->getUsername()) { + if (isset($params['uid']) && $params['uid'] === $this->getUsername()) { $this->updateAvatar(); } } @@ -593,29 +591,29 @@ class User { * @return bool */ public function updateAvatar($force = false) { - if(!$force && $this->wasRefreshed('avatar')) { + if (!$force && $this->wasRefreshed('avatar')) { return false; } $avatarImage = $this->getAvatarImage(); - if($avatarImage === false) { + if ($avatarImage === false) { //not set, nothing left to do; return false; } - if(!$this->image->loadFromBase64(base64_encode($avatarImage))) { + if (!$this->image->loadFromBase64(base64_encode($avatarImage))) { return false; } // use the checksum before modifications $checksum = md5($this->image->data()); - if($checksum === $this->config->getUserValue($this->uid, 'user_ldap', 'lastAvatarChecksum', '')) { + if ($checksum === $this->config->getUserValue($this->uid, 'user_ldap', 'lastAvatarChecksum', '')) { return true; } $isSet = $this->setOwnCloudAvatar(); - if($isSet) { + if ($isSet) { // save checksum only after successful setting $this->config->setUserValue($this->uid, 'user_ldap', 'lastAvatarChecksum', $checksum); } @@ -628,7 +626,7 @@ class User { * @return bool */ private function setOwnCloudAvatar() { - if(!$this->image->valid()) { + if (!$this->image->valid()) { $this->log->log('avatar image data from LDAP invalid for '.$this->dn, ILogger::ERROR); return false; } @@ -636,12 +634,12 @@ class User { //make sure it is a square and not bigger than 128x128 $size = min([$this->image->width(), $this->image->height(), 128]); - if(!$this->image->centerCrop($size)) { + if (!$this->image->centerCrop($size)) { $this->log->log('croping image for avatar failed for '.$this->dn, ILogger::ERROR); return false; } - if(!$this->fs->isLoaded()) { + if (!$this->fs->isLoaded()) { $this->fs->setup($this->uid); } @@ -717,7 +715,7 @@ class User { if (array_key_exists('pwdpolicysubentry', $result[0])) { $pwdPolicySubentry = $result[0]['pwdpolicysubentry']; - if ($pwdPolicySubentry && (count($pwdPolicySubentry) > 0)){ + if ($pwdPolicySubentry && (count($pwdPolicySubentry) > 0)) { $ppolicyDN = $pwdPolicySubentry[0];//custom ppolicy DN } } @@ -729,7 +727,7 @@ class User { //retrieve relevant password policy attributes $cacheKey = 'ppolicyAttributes' . $ppolicyDN; $result = $this->connection->getFromCache($cacheKey); - if(is_null($result)) { + if (is_null($result)) { $result = $this->access->search('objectclass=*', [$ppolicyDN], ['pwdgraceauthnlimit', 'pwdmaxage', 'pwdexpirewarning']); $this->connection->writeToCache($cacheKey, $result); } @@ -764,7 +762,7 @@ class User { && !empty($pwdExpireWarning)) { $pwdMaxAgeInt = (int)$pwdMaxAge[0]; $pwdExpireWarningInt = (int)$pwdExpireWarning[0]; - if ($pwdMaxAgeInt > 0 && $pwdExpireWarningInt > 0){ + if ($pwdMaxAgeInt > 0 && $pwdExpireWarningInt > 0) { $pwdChangedTimeDt = \DateTime::createFromFormat('YmdHisZ', $pwdChangedTime[0]); $pwdChangedTimeDt->add(new \DateInterval('PT'.$pwdMaxAgeInt.'S')); $currentDateTime = new \DateTime(); diff --git a/apps/user_ldap/lib/UserPluginManager.php b/apps/user_ldap/lib/UserPluginManager.php index f240d4493c3..2d99d887604 100644 --- a/apps/user_ldap/lib/UserPluginManager.php +++ b/apps/user_ldap/lib/UserPluginManager.php @@ -28,7 +28,6 @@ namespace OCA\User_LDAP; use OC\User\Backend; class UserPluginManager { - public $test = false; private $respondToActions = 0; @@ -60,7 +59,7 @@ class UserPluginManager { $respondToActions = $plugin->respondToActions(); $this->respondToActions |= $respondToActions; - foreach($this->which as $action => $v) { + foreach ($this->which as $action => $v) { if (is_int($action) && (bool)($respondToActions & $action)) { $this->which[$action] = $plugin; \OC::$server->getLogger()->debug("Registered action ".$action." to plugin ".get_class($plugin), ['app' => 'user_ldap']); diff --git a/apps/user_ldap/lib/User_LDAP.php b/apps/user_ldap/lib/User_LDAP.php index 08b0464cc50..4e5af690387 100644 --- a/apps/user_ldap/lib/User_LDAP.php +++ b/apps/user_ldap/lib/User_LDAP.php @@ -87,16 +87,16 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn return $this->userPluginManager->canChangeAvatar($uid); } - if(!$this->implementsActions(Backend::PROVIDE_AVATAR)) { + if (!$this->implementsActions(Backend::PROVIDE_AVATAR)) { return true; } $user = $this->access->userManager->get($uid); - if(!$user instanceof User) { + if (!$user instanceof User) { return false; } $imageData = $user->getAvatarImage(); - if($imageData === false) { + if ($imageData === false) { return true; } return !$user->updateAvatar(true); @@ -156,7 +156,7 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn //find out dn of the user name $attrs = $this->access->userManager->getAttributes(); $users = $this->access->fetchUsersByLoginName($loginName, $attrs); - if(count($users) < 1) { + if (count($users) < 1) { throw new NotOnLDAP('No user available for the given login name on ' . $this->access->connection->ldapHost . ':' . $this->access->connection->ldapPort); } @@ -173,23 +173,23 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn public function checkPassword($uid, $password) { try { $ldapRecord = $this->getLDAPUserByLoginName($uid); - } catch(NotOnLDAP $e) { + } catch (NotOnLDAP $e) { \OC::$server->getLogger()->logException($e, ['app' => 'user_ldap', 'level' => ILogger::DEBUG]); return false; } $dn = $ldapRecord['dn'][0]; $user = $this->access->userManager->get($dn); - if(!$user instanceof User) { + if (!$user instanceof User) { Util::writeLog('user_ldap', 'LDAP Login: Could not get user object for DN ' . $dn . '. Maybe the LDAP entry has no set display name attribute?', ILogger::WARN); return false; } - if($user->getUsername() !== false) { + if ($user->getUsername() !== false) { //are the credentials OK? - if(!$this->access->areCredentialsValid($dn, $password)) { + if (!$this->access->areCredentialsValid($dn, $password)) { return false; } @@ -216,11 +216,11 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn $user = $this->access->userManager->get($uid); - if(!$user instanceof User) { + if (!$user instanceof User) { throw new \Exception('LDAP setPassword: Could not get user object for uid ' . $uid . '. Maybe the LDAP entry has no set display name attribute?'); } - if($user->getUsername() !== false && $this->access->setPassword($user->getDN(), $password)) { + if ($user->getUsername() !== false && $this->access->setPassword($user->getDN(), $password)) { $ldapDefaultPPolicyDN = $this->access->connection->ldapDefaultPPolicyDN; $turnOnPasswordChange = $this->access->connection->turnOnPasswordChange; if (!empty($ldapDefaultPPolicyDN) && ((int)$turnOnPasswordChange === 1)) { @@ -252,13 +252,13 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn //check if users are cached, if so return $ldap_users = $this->access->connection->getFromCache($cachekey); - if(!is_null($ldap_users)) { + if (!is_null($ldap_users)) { return $ldap_users; } // if we'd pass -1 to LDAP search, we'd end up in a Protocol // error. With a limit of 0, we get 0 results. So we pass null. - if($limit <= 0) { + if ($limit <= 0) { $limit = null; } $filter = $this->access->combineFilterWithAnd([ @@ -292,22 +292,22 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn * @throws \OC\ServerNotAvailableException */ public function userExistsOnLDAP($user) { - if(is_string($user)) { + if (is_string($user)) { $user = $this->access->userManager->get($user); } - if(is_null($user)) { + if (is_null($user)) { return false; } $uid = $user instanceof User ? $user->getUsername() : $user->getOCName(); $cacheKey = 'userExistsOnLDAP' . $uid; $userExists = $this->access->connection->getFromCache($cacheKey); - if(!is_null($userExists)) { + if (!is_null($userExists)) { return (bool)$userExists; } $dn = $user->getDN(); //check if user really still exists by reading its entry - if(!is_array($this->access->readAttribute($dn, '', $this->access->connection->ldapUserFilter))) { + if (!is_array($this->access->readAttribute($dn, '', $this->access->connection->ldapUserFilter))) { try { $uuid = $this->access->getUserMapper()->getUUIDByDN($dn); if (!$uuid) { @@ -331,7 +331,7 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn } } - if($user instanceof OfflineUser) { + if ($user instanceof OfflineUser) { $user->unmark(); } @@ -347,13 +347,13 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn */ public function userExists($uid) { $userExists = $this->access->connection->getFromCache('userExists'.$uid); - if(!is_null($userExists)) { + if (!is_null($userExists)) { return (bool)$userExists; } //getting dn, if false the user does not exist. If dn, he may be mapped only, requires more checking. $user = $this->access->userManager->get($uid); - if(is_null($user)) { + if (is_null($user)) { Util::writeLog('user_ldap', 'No DN found for '.$uid.' on '. $this->access->connection->ldapHost, ILogger::DEBUG); $this->access->connection->writeToCache('userExists'.$uid, false); @@ -373,13 +373,13 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn public function deleteUser($uid) { if ($this->userPluginManager->canDeleteUser()) { $status = $this->userPluginManager->deleteUser($uid); - if($status === false) { + if ($status === false) { return false; } } $marked = $this->ocConfig->getUserValue($uid, 'user_ldap', 'isDeleted', 0); - if((int)$marked === 0) { + if ((int)$marked === 0) { \OC::$server->getLogger()->notice( 'User '.$uid . ' is not marked as deleted, not cleaning up.', ['app' => 'user_ldap']); @@ -403,7 +403,7 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn */ public function getHome($uid) { // user Exists check required as it is not done in user proxy! - if(!$this->userExists($uid)) { + if (!$this->userExists($uid)) { return false; } @@ -413,13 +413,13 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn $cacheKey = 'getHome'.$uid; $path = $this->access->connection->getFromCache($cacheKey); - if(!is_null($path)) { + if (!is_null($path)) { return $path; } // early return path if it is a deleted user $user = $this->access->userManager->get($uid); - if($user instanceof User || $user instanceof OfflineUser) { + if ($user instanceof User || $user instanceof OfflineUser) { $path = $user->getHomePath() ?: false; } else { throw new NoUserException($uid . ' is not a valid user anymore'); @@ -439,12 +439,12 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn return $this->userPluginManager->getDisplayName($uid); } - if(!$this->userExists($uid)) { + if (!$this->userExists($uid)) { return false; } $cacheKey = 'getDisplayName'.$uid; - if(!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) { + if (!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) { return $displayName; } @@ -461,10 +461,10 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn $this->access->username2dn($uid), $this->access->connection->ldapUserDisplayName); - if($displayName && (count($displayName) > 0)) { + if ($displayName && (count($displayName) > 0)) { $displayName = $displayName[0]; - if (is_array($displayName2)){ + if (is_array($displayName2)) { $displayName2 = count($displayName2) > 0 ? $displayName2[0] : ''; } @@ -508,7 +508,7 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn */ public function getDisplayNames($search = '', $limit = null, $offset = null) { $cacheKey = 'getDisplayNames-'.$search.'-'.$limit.'-'.$offset; - if(!is_null($displayNames = $this->access->connection->getFromCache($cacheKey))) { + if (!is_null($displayNames = $this->access->connection->getFromCache($cacheKey))) { return $displayNames; } @@ -559,7 +559,7 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn $filter = $this->access->getFilterForUserCount(); $cacheKey = 'countUsers-'.$filter; - if(!is_null($entries = $this->access->connection->getFromCache($cacheKey))) { + if (!is_null($entries = $this->access->connection->getFromCache($cacheKey))) { return $entries; } $entries = $this->access->countUsers($filter); @@ -609,7 +609,7 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn if (is_string($dn)) { // the NC user creation work flow requires a know user id up front $uuid = $this->access->getUUID($dn, true); - if(is_string($uuid)) { + if (is_string($uuid)) { $this->access->mapAndAnnounceIfApplicable( $this->access->getUserMapper(), $dn, @@ -635,5 +635,4 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn } return false; } - } diff --git a/apps/user_ldap/lib/User_Proxy.php b/apps/user_ldap/lib/User_Proxy.php index 27e8c42ae73..e9ff92d03eb 100644 --- a/apps/user_ldap/lib/User_Proxy.php +++ b/apps/user_ldap/lib/User_Proxy.php @@ -60,11 +60,11 @@ class User_Proxy extends Proxy implements \OCP\IUserBackend, \OCP\UserInterface, UserPluginManager $userPluginManager ) { parent::__construct($ldap); - foreach($serverConfigPrefixes as $configPrefix) { + foreach ($serverConfigPrefixes as $configPrefix) { $this->backends[$configPrefix] = new User_LDAP($this->getAccess($configPrefix), $ocConfig, $notificationManager, $userSession, $userPluginManager); - if(is_null($this->refBackend)) { + if (is_null($this->refBackend)) { $this->refBackend = &$this->backends[$configPrefix]; } } @@ -79,13 +79,13 @@ class User_Proxy extends Proxy implements \OCP\IUserBackend, \OCP\UserInterface, */ protected function walkBackends($uid, $method, $parameters) { $cacheKey = $this->getUserCacheKey($uid); - foreach($this->backends as $configPrefix => $backend) { + foreach ($this->backends as $configPrefix => $backend) { $instance = $backend; - if(!method_exists($instance, $method) + if (!method_exists($instance, $method) && method_exists($this->getAccess($configPrefix), $method)) { $instance = $this->getAccess($configPrefix); } - if($result = call_user_func_array([$instance, $method], $parameters)) { + if ($result = call_user_func_array([$instance, $method], $parameters)) { $this->writeToCache($cacheKey, $configPrefix); return $result; } @@ -105,22 +105,22 @@ class User_Proxy extends Proxy implements \OCP\IUserBackend, \OCP\UserInterface, $cacheKey = $this->getUserCacheKey($uid); $prefix = $this->getFromCache($cacheKey); //in case the uid has been found in the past, try this stored connection first - if(!is_null($prefix)) { - if(isset($this->backends[$prefix])) { + if (!is_null($prefix)) { + if (isset($this->backends[$prefix])) { $instance = $this->backends[$prefix]; - if(!method_exists($instance, $method) + if (!method_exists($instance, $method) && method_exists($this->getAccess($prefix), $method)) { $instance = $this->getAccess($prefix); } $result = call_user_func_array([$instance, $method], $parameters); - if($result === $passOnWhen) { + if ($result === $passOnWhen) { //not found here, reset cache to null if user vanished //because sometimes methods return false with a reason $userExists = call_user_func_array( [$this->backends[$prefix], 'userExistsOnLDAP'], [$uid] ); - if(!$userExists) { + if (!$userExists) { $this->writeToCache($cacheKey, null); } } @@ -162,7 +162,7 @@ class User_Proxy extends Proxy implements \OCP\IUserBackend, \OCP\UserInterface, public function getUsers($search = '', $limit = 10, $offset = 0) { //we do it just as the /OC_User implementation: do not play around with limit and offset but ask all backends $users = []; - foreach($this->backends as $backend) { + foreach ($this->backends as $backend) { $backendUsers = $backend->getUsers($search, $limit, $offset); if (is_array($backendUsers)) { $users = array_merge($users, $backendUsers); @@ -179,13 +179,13 @@ class User_Proxy extends Proxy implements \OCP\IUserBackend, \OCP\UserInterface, public function userExists($uid) { $existsOnLDAP = false; $existsLocally = $this->handleRequest($uid, 'userExists', [$uid]); - if($existsLocally) { + if ($existsLocally) { $existsOnLDAP = $this->userExistsOnLDAP($uid); } - if($existsLocally && !$existsOnLDAP) { + if ($existsLocally && !$existsOnLDAP) { try { $user = $this->getLDAPAccess($uid)->userManager->get($uid); - if($user instanceof User) { + if ($user instanceof User) { $user->markUser(); } } catch (\Exception $e) { @@ -288,7 +288,7 @@ class User_Proxy extends Proxy implements \OCP\IUserBackend, \OCP\UserInterface, public function getDisplayNames($search = '', $limit = null, $offset = null) { //we do it just as the /OC_User implementation: do not play around with limit and offset but ask all backends $users = []; - foreach($this->backends as $backend) { + foreach ($this->backends as $backend) { $backendUsers = $backend->getDisplayNames($search, $limit, $offset); if (is_array($backendUsers)) { $users = $users + $backendUsers; @@ -332,7 +332,7 @@ class User_Proxy extends Proxy implements \OCP\IUserBackend, \OCP\UserInterface, */ public function countUsers() { $users = false; - foreach($this->backends as $backend) { + foreach ($this->backends as $backend) { $backendUsers = $backend->countUsers(); if ($backendUsers !== false) { $users += $backendUsers; diff --git a/apps/user_ldap/lib/Wizard.php b/apps/user_ldap/lib/Wizard.php index a0dcd0febbf..01a9e19076d 100644 --- a/apps/user_ldap/lib/Wizard.php +++ b/apps/user_ldap/lib/Wizard.php @@ -72,7 +72,7 @@ class Wizard extends LDAPUtility { public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) { parent::__construct($ldap); $this->configuration = $configuration; - if(is_null(Wizard::$l)) { + if (is_null(Wizard::$l)) { Wizard::$l = \OC::$server->getL10N('user_ldap'); } $this->access = $access; @@ -80,7 +80,7 @@ class Wizard extends LDAPUtility { } public function __destruct() { - if($this->result->hasChanges()) { + if ($this->result->hasChanges()) { $this->configuration->saveConfiguration(); } } @@ -95,18 +95,18 @@ class Wizard extends LDAPUtility { */ public function countEntries(string $filter, string $type): int { $reqs = ['ldapHost', 'ldapPort', 'ldapBase']; - if($type === 'users') { + if ($type === 'users') { $reqs[] = 'ldapUserFilter'; } - if(!$this->checkRequirements($reqs)) { + if (!$this->checkRequirements($reqs)) { throw new \Exception('Requirements not met', 400); } $attr = ['dn']; // default $limit = 1001; - if($type === 'groups') { + if ($type === 'groups') { $result = $this->access->countGroups($filter, $attr, $limit); - } elseif($type === 'users') { + } elseif ($type === 'users') { $result = $this->access->countUsers($filter, $attr, $limit); } elseif ($type === 'objects') { $result = $this->access->countObjects($limit); @@ -125,7 +125,7 @@ class Wizard extends LDAPUtility { * @return string */ private function formatCountResult(int $count): string { - if($count > 1000) { + if ($count > 1000) { return '> 1000'; } return (string)$count; @@ -134,7 +134,7 @@ class Wizard extends LDAPUtility { public function countGroups() { $filter = $this->configuration->ldapGroupFilter; - if(empty($filter)) { + if (empty($filter)) { $output = self::$l->n('%s group found', '%s groups found', 0, [0]); $this->result->addChange('ldap_group_count', $output); return $this->result; @@ -144,7 +144,7 @@ class Wizard extends LDAPUtility { $groupsTotal = $this->countEntries($filter, 'groups'); } catch (\Exception $e) { //400 can be ignored, 500 is forwarded - if($e->getCode() === 500) { + if ($e->getCode() === 500) { throw $e; } return false; @@ -186,7 +186,7 @@ class Wizard extends LDAPUtility { public function countInBaseDN() { // we don't need to provide a filter in this case $total = $this->countEntries('', 'objects'); - if($total === false) { + if ($total === false) { throw new \Exception('invalid results received'); } $this->result->addChange('ldap_test_base', $total); @@ -200,7 +200,7 @@ class Wizard extends LDAPUtility { * @return int|bool */ public function countUsersWithAttribute($attr, $existsCheck = false) { - if(!$this->checkRequirements(['ldapHost', + if (!$this->checkRequirements(['ldapHost', 'ldapPort', 'ldapBase', 'ldapUserFilter', @@ -225,7 +225,7 @@ class Wizard extends LDAPUtility { * @throws \Exception */ public function detectUserDisplayNameAttribute() { - if(!$this->checkRequirements(['ldapHost', + if (!$this->checkRequirements(['ldapHost', 'ldapPort', 'ldapBase', 'ldapUserFilter', @@ -238,7 +238,7 @@ class Wizard extends LDAPUtility { // most likely not the default value with upper case N, // verify it still produces a result $count = (int)$this->countUsersWithAttribute($attr, true); - if($count > 0) { + if ($count > 0) { //no change, but we sent it back to make sure the user interface //is still correct, even if the ajax call was cancelled meanwhile $this->result->addChange('ldap_display_name', $attr); @@ -251,7 +251,7 @@ class Wizard extends LDAPUtility { foreach ($displayNameAttrs as $attr) { $count = (int)$this->countUsersWithAttribute($attr, true); - if($count > 0) { + if ($count > 0) { $this->applyFind('ldap_display_name', $attr); return $this->result; } @@ -267,7 +267,7 @@ class Wizard extends LDAPUtility { * @return WizardResult|bool */ public function detectEmailAttribute() { - if(!$this->checkRequirements(['ldapHost', + if (!$this->checkRequirements(['ldapHost', 'ldapPort', 'ldapBase', 'ldapUserFilter', @@ -278,7 +278,7 @@ class Wizard extends LDAPUtility { $attr = $this->configuration->ldapEmailAttribute; if ($attr !== '') { $count = (int)$this->countUsersWithAttribute($attr, true); - if($count > 0) { + if ($count > 0) { return false; } $writeLog = true; @@ -289,17 +289,17 @@ class Wizard extends LDAPUtility { $emailAttributes = ['mail', 'mailPrimaryAddress']; $winner = ''; $maxUsers = 0; - foreach($emailAttributes as $attr) { + foreach ($emailAttributes as $attr) { $count = $this->countUsersWithAttribute($attr); - if($count > $maxUsers) { + if ($count > $maxUsers) { $maxUsers = $count; $winner = $attr; } } - if($winner !== '') { + if ($winner !== '') { $this->applyFind('ldap_email_attr', $winner); - if($writeLog) { + if ($writeLog) { \OCP\Util::writeLog('user_ldap', 'The mail attribute has ' . 'automatically been reset, because the original value ' . 'did not return any results.', ILogger::INFO); @@ -314,7 +314,7 @@ class Wizard extends LDAPUtility { * @throws \Exception */ public function determineAttributes() { - if(!$this->checkRequirements(['ldapHost', + if (!$this->checkRequirements(['ldapHost', 'ldapPort', 'ldapBase', 'ldapUserFilter', @@ -330,7 +330,7 @@ class Wizard extends LDAPUtility { $this->result->addOptions('ldap_loginfilter_attributes', $attributes); $selected = $this->configuration->ldapLoginFilterAttributes; - if(is_array($selected) && !empty($selected)) { + if (is_array($selected) && !empty($selected)) { $this->result->addChange('ldap_loginfilter_attributes', $selected); } @@ -343,7 +343,7 @@ class Wizard extends LDAPUtility { * @throws \Exception */ private function getUserAttributes() { - if(!$this->checkRequirements(['ldapHost', + if (!$this->checkRequirements(['ldapHost', 'ldapPort', 'ldapBase', 'ldapUserFilter', @@ -351,20 +351,20 @@ class Wizard extends LDAPUtility { return false; } $cr = $this->getConnection(); - if(!$cr) { + if (!$cr) { throw new \Exception('Could not connect to LDAP'); } $base = $this->configuration->ldapBase[0]; $filter = $this->configuration->ldapUserFilter; $rr = $this->ldap->search($cr, $base, $filter, [], 1, 1); - if(!$this->ldap->isResource($rr)) { + if (!$this->ldap->isResource($rr)) { return false; } $er = $this->ldap->firstEntry($cr, $rr); $attributes = $this->ldap->getAttributes($cr, $er); $pureAttributes = []; - for($i = 0; $i < $attributes['count']; $i++) { + for ($i = 0; $i < $attributes['count']; $i++) { $pureAttributes[] = $attributes[$i]; } @@ -399,23 +399,23 @@ class Wizard extends LDAPUtility { * @throws \Exception */ private function determineGroups($dbKey, $confKey, $testMemberOf = true) { - if(!$this->checkRequirements(['ldapHost', + if (!$this->checkRequirements(['ldapHost', 'ldapPort', 'ldapBase', ])) { return false; } $cr = $this->getConnection(); - if(!$cr) { + if (!$cr) { throw new \Exception('Could not connect to LDAP'); } $this->fetchGroups($dbKey, $confKey); - if($testMemberOf) { + if ($testMemberOf) { $this->configuration->hasMemberOfFilterSupport = $this->testMemberOf(); $this->result->markChange(); - if(!$this->configuration->hasMemberOfFilterSupport) { + if (!$this->configuration->hasMemberOfFilterSupport) { throw new \Exception('memberOf is not supported by the server'); } } @@ -435,7 +435,7 @@ class Wizard extends LDAPUtility { $obclasses = ['posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames', 'groupOfUniqueNames']; $filterParts = []; - foreach($obclasses as $obclass) { + foreach ($obclasses as $obclass) { $filterParts[] = 'objectclass='.$obclass; } //we filter for everything @@ -452,8 +452,8 @@ class Wizard extends LDAPUtility { // we need to request dn additionally here, otherwise memberOf // detection will fail later $result = $this->access->searchGroups($filter, ['cn', 'dn'], $limit, $offset); - foreach($result as $item) { - if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) { + foreach ($result as $item) { + if (!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) { // just in case - no issue known continue; } @@ -463,7 +463,7 @@ class Wizard extends LDAPUtility { $offset += $limit; } while ($this->access->hasMoreResults()); - if(count($groupNames) > 0) { + if (count($groupNames) > 0) { natsort($groupNames); $this->result->addOptions($dbKey, array_values($groupNames)); } else { @@ -471,7 +471,7 @@ class Wizard extends LDAPUtility { } $setFeatures = $this->configuration->$confKey; - if(is_array($setFeatures) && !empty($setFeatures)) { + if (is_array($setFeatures) && !empty($setFeatures)) { //something is already configured? pre-select it. $this->result->addChange($dbKey, $setFeatures); } @@ -479,14 +479,14 @@ class Wizard extends LDAPUtility { } public function determineGroupMemberAssoc() { - if(!$this->checkRequirements(['ldapHost', + if (!$this->checkRequirements(['ldapHost', 'ldapPort', 'ldapGroupFilter', ])) { return false; } $attribute = $this->detectGroupMemberAssoc(); - if($attribute === false) { + if ($attribute === false) { return false; } $this->configuration->setConfiguration(['ldapGroupMemberAssocAttr' => $attribute]); @@ -501,14 +501,14 @@ class Wizard extends LDAPUtility { * @throws \Exception */ public function determineGroupObjectClasses() { - if(!$this->checkRequirements(['ldapHost', + if (!$this->checkRequirements(['ldapHost', 'ldapPort', 'ldapBase', ])) { return false; } $cr = $this->getConnection(); - if(!$cr) { + if (!$cr) { throw new \Exception('Could not connect to LDAP'); } @@ -528,14 +528,14 @@ class Wizard extends LDAPUtility { * @throws \Exception */ public function determineUserObjectClasses() { - if(!$this->checkRequirements(['ldapHost', + if (!$this->checkRequirements(['ldapHost', 'ldapPort', 'ldapBase', ])) { return false; } $cr = $this->getConnection(); - if(!$cr) { + if (!$cr) { throw new \Exception('Could not connect to LDAP'); } @@ -558,7 +558,7 @@ class Wizard extends LDAPUtility { * @throws \Exception */ public function getGroupFilter() { - if(!$this->checkRequirements(['ldapHost', + if (!$this->checkRequirements(['ldapHost', 'ldapPort', 'ldapBase', ])) { @@ -582,7 +582,7 @@ class Wizard extends LDAPUtility { * @throws \Exception */ public function getUserListFilter() { - if(!$this->checkRequirements(['ldapHost', + if (!$this->checkRequirements(['ldapHost', 'ldapPort', 'ldapBase', ])) { @@ -595,7 +595,7 @@ class Wizard extends LDAPUtility { $this->applyFind('ldap_display_name', $d['ldap_display_name']); } $filter = $this->composeLdapFilter(self::LFILTER_USER_LIST); - if(!$filter) { + if (!$filter) { throw new \Exception('Cannot create filter'); } @@ -608,7 +608,7 @@ class Wizard extends LDAPUtility { * @throws \Exception */ public function getUserLoginFilter() { - if(!$this->checkRequirements(['ldapHost', + if (!$this->checkRequirements(['ldapHost', 'ldapPort', 'ldapBase', 'ldapUserFilter', @@ -617,7 +617,7 @@ class Wizard extends LDAPUtility { } $filter = $this->composeLdapFilter(self::LFILTER_LOGIN); - if(!$filter) { + if (!$filter) { throw new \Exception('Cannot create filter'); } @@ -631,7 +631,7 @@ class Wizard extends LDAPUtility { * @throws \Exception */ public function testLoginName($loginName) { - if(!$this->checkRequirements(['ldapHost', + if (!$this->checkRequirements(['ldapHost', 'ldapPort', 'ldapBase', 'ldapLoginFilter', @@ -640,17 +640,17 @@ class Wizard extends LDAPUtility { } $cr = $this->access->connection->getConnectionResource(); - if(!$this->ldap->isResource($cr)) { + if (!$this->ldap->isResource($cr)) { throw new \Exception('connection error'); } - if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8') + if (mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8') === false) { throw new \Exception('missing placeholder'); } $users = $this->access->countUsersByLoginName($loginName); - if($this->ldap->errno($cr) !== 0) { + if ($this->ldap->errno($cr) !== 0) { throw new \Exception($this->ldap->error($cr)); } $filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter); @@ -665,19 +665,19 @@ class Wizard extends LDAPUtility { * @throws \Exception */ public function guessPortAndTLS() { - if(!$this->checkRequirements(['ldapHost', + if (!$this->checkRequirements(['ldapHost', ])) { return false; } $this->checkHost(); $portSettings = $this->getPortSettingsToTry(); - if(!is_array($portSettings)) { + if (!is_array($portSettings)) { throw new \Exception(print_r($portSettings, true)); } //proceed from the best configuration and return on first success - foreach($portSettings as $setting) { + foreach ($portSettings as $setting) { $p = $setting['port']; $t = $setting['tls']; \OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, ILogger::DEBUG); @@ -690,7 +690,7 @@ class Wizard extends LDAPUtility { // any reply other than -1 (= cannot connect) is already okay, // because then we found the server // unavailable startTLS returns -11 - if($e->getCode() > 0) { + if ($e->getCode() > 0) { $settingsFound = true; } else { throw $e; @@ -718,7 +718,7 @@ class Wizard extends LDAPUtility { * @return WizardResult|false WizardResult on success, false otherwise */ public function guessBaseDN() { - if(!$this->checkRequirements(['ldapHost', + if (!$this->checkRequirements(['ldapHost', 'ldapPort', ])) { return false; @@ -727,9 +727,9 @@ class Wizard extends LDAPUtility { //check whether a DN is given in the agent name (99.9% of all cases) $base = null; $i = stripos($this->configuration->ldapAgentName, 'dc='); - if($i !== false) { + if ($i !== false) { $base = substr($this->configuration->ldapAgentName, $i); - if($this->testBaseDN($base)) { + if ($this->testBaseDN($base)) { $this->applyFind('ldap_base', $base); return $this->result; } @@ -740,12 +740,12 @@ class Wizard extends LDAPUtility { //a base DN $helper = new Helper(\OC::$server->getConfig()); $domain = $helper->getDomainFromURL($this->configuration->ldapHost); - if(!$domain) { + if (!$domain) { return false; } $dparts = explode('.', $domain); - while(count($dparts) > 0) { + while (count($dparts) > 0) { $base2 = 'dc=' . implode(',dc=', $dparts); if ($base !== $base2 && $this->testBaseDN($base2)) { $this->applyFind('ldap_base', $base2); @@ -779,7 +779,7 @@ class Wizard extends LDAPUtility { $hostInfo = parse_url($host); //removes Port from Host - if(is_array($hostInfo) && isset($hostInfo['port'])) { + if (is_array($hostInfo) && isset($hostInfo['port'])) { $port = $hostInfo['port']; $host = str_replace(':'.$port, '', $host); $this->applyFind('ldap_host', $host); @@ -796,30 +796,30 @@ class Wizard extends LDAPUtility { private function detectGroupMemberAssoc() { $possibleAttrs = ['uniqueMember', 'memberUid', 'member', 'gidNumber']; $filter = $this->configuration->ldapGroupFilter; - if(empty($filter)) { + if (empty($filter)) { return false; } $cr = $this->getConnection(); - if(!$cr) { + if (!$cr) { throw new \Exception('Could not connect to LDAP'); } $base = $this->configuration->ldapBaseGroups[0] ?: $this->configuration->ldapBase[0]; $rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000); - if(!$this->ldap->isResource($rr)) { + if (!$this->ldap->isResource($rr)) { return false; } $er = $this->ldap->firstEntry($cr, $rr); - while(is_resource($er)) { + while (is_resource($er)) { $this->ldap->getDN($cr, $er); $attrs = $this->ldap->getAttributes($cr, $er); $result = []; $possibleAttrsCount = count($possibleAttrs); - for($i = 0; $i < $possibleAttrsCount; $i++) { - if(isset($attrs[$possibleAttrs[$i]])) { + for ($i = 0; $i < $possibleAttrsCount; $i++) { + if (isset($attrs[$possibleAttrs[$i]])) { $result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count']; } } - if(!empty($result)) { + if (!empty($result)) { natsort($result); return key($result); } @@ -838,14 +838,14 @@ class Wizard extends LDAPUtility { */ private function testBaseDN($base) { $cr = $this->getConnection(); - if(!$cr) { + if (!$cr) { throw new \Exception('Could not connect to LDAP'); } //base is there, let's validate it. If we search for anything, we should //get a result set > 0 on a proper base $rr = $this->ldap->search($cr, $base, 'objectClass=*', ['dn'], 0, 1); - if(!$this->ldap->isResource($rr)) { + if (!$this->ldap->isResource($rr)) { $errorNo = $this->ldap->errno($cr); $errorMsg = $this->ldap->error($cr); \OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base. @@ -867,11 +867,11 @@ class Wizard extends LDAPUtility { */ private function testMemberOf() { $cr = $this->getConnection(); - if(!$cr) { + if (!$cr) { throw new \Exception('Could not connect to LDAP'); } $result = $this->access->countUsers('memberOf=*', ['memberOf'], 1); - if(is_int($result) && $result > 0) { + if (is_int($result) && $result > 0) { return true; } return false; @@ -892,27 +892,27 @@ class Wizard extends LDAPUtility { case self::LFILTER_USER_LIST: $objcs = $this->configuration->ldapUserFilterObjectclass; //glue objectclasses - if(is_array($objcs) && count($objcs) > 0) { + if (is_array($objcs) && count($objcs) > 0) { $filter .= '(|'; - foreach($objcs as $objc) { + foreach ($objcs as $objc) { $filter .= '(objectclass=' . $objc . ')'; } $filter .= ')'; $parts++; } //glue group memberships - if($this->configuration->hasMemberOfFilterSupport) { + if ($this->configuration->hasMemberOfFilterSupport) { $cns = $this->configuration->ldapUserFilterGroups; - if(is_array($cns) && count($cns) > 0) { + if (is_array($cns) && count($cns) > 0) { $filter .= '(|'; $cr = $this->getConnection(); - if(!$cr) { + if (!$cr) { throw new \Exception('Could not connect to LDAP'); } $base = $this->configuration->ldapBase[0]; - foreach($cns as $cn) { + foreach ($cns as $cn) { $rr = $this->ldap->search($cr, $base, 'cn=' . $cn, ['dn', 'primaryGroupToken']); - if(!$this->ldap->isResource($rr)) { + if (!$this->ldap->isResource($rr)) { continue; } $er = $this->ldap->firstEntry($cr, $rr); @@ -922,7 +922,7 @@ class Wizard extends LDAPUtility { continue; } $filterPart = '(memberof=' . $dn . ')'; - if(isset($attrs['primaryGroupToken'])) { + if (isset($attrs['primaryGroupToken'])) { $pgt = $attrs['primaryGroupToken'][0]; $primaryFilterPart = '(primaryGroupID=' . $pgt .')'; $filterPart = '(|' . $filterPart . $primaryFilterPart . ')'; @@ -934,7 +934,7 @@ class Wizard extends LDAPUtility { $parts++; } //wrap parts in AND condition - if($parts > 1) { + if ($parts > 1) { $filter = '(&' . $filter . ')'; } if ($filter === '') { @@ -945,9 +945,9 @@ class Wizard extends LDAPUtility { case self::LFILTER_GROUP_LIST: $objcs = $this->configuration->ldapGroupFilterObjectclass; //glue objectclasses - if(is_array($objcs) && count($objcs) > 0) { + if (is_array($objcs) && count($objcs) > 0) { $filter .= '(|'; - foreach($objcs as $objc) { + foreach ($objcs as $objc) { $filter .= '(objectclass=' . $objc . ')'; } $filter .= ')'; @@ -955,16 +955,16 @@ class Wizard extends LDAPUtility { } //glue group memberships $cns = $this->configuration->ldapGroupFilterGroups; - if(is_array($cns) && count($cns) > 0) { + if (is_array($cns) && count($cns) > 0) { $filter .= '(|'; - foreach($cns as $cn) { + foreach ($cns as $cn) { $filter .= '(cn=' . $cn . ')'; } $filter .= ')'; } $parts++; //wrap parts in AND condition - if($parts > 1) { + if ($parts > 1) { $filter = '(&' . $filter . ')'; } break; @@ -977,13 +977,13 @@ class Wizard extends LDAPUtility { $userAttributes = array_change_key_case(array_flip($userAttributes)); $parts = 0; - if($this->configuration->ldapLoginFilterUsername === '1') { + if ($this->configuration->ldapLoginFilterUsername === '1') { $attr = ''; - if(isset($userAttributes['uid'])) { + if (isset($userAttributes['uid'])) { $attr = 'uid'; - } elseif(isset($userAttributes['samaccountname'])) { + } elseif (isset($userAttributes['samaccountname'])) { $attr = 'samaccountname'; - } elseif(isset($userAttributes['cn'])) { + } elseif (isset($userAttributes['cn'])) { //fallback $attr = 'cn'; } @@ -994,16 +994,16 @@ class Wizard extends LDAPUtility { } $filterEmail = ''; - if($this->configuration->ldapLoginFilterEmail === '1') { + if ($this->configuration->ldapLoginFilterEmail === '1') { $filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))'; $parts++; } $filterAttributes = ''; $attrsToFilter = $this->configuration->ldapLoginFilterAttributes; - if(is_array($attrsToFilter) && count($attrsToFilter) > 0) { + if (is_array($attrsToFilter) && count($attrsToFilter) > 0) { $filterAttributes = '(|'; - foreach($attrsToFilter as $attribute) { + foreach ($attrsToFilter as $attribute) { $filterAttributes .= '(' . $attribute . $loginpart . ')'; } $filterAttributes .= ')'; @@ -1011,13 +1011,13 @@ class Wizard extends LDAPUtility { } $filterLogin = ''; - if($parts > 1) { + if ($parts > 1) { $filterLogin = '(|'; } $filterLogin .= $filterUsername; $filterLogin .= $filterEmail; $filterLogin .= $filterAttributes; - if($parts > 1) { + if ($parts > 1) { $filterLogin .= ')'; } @@ -1042,12 +1042,12 @@ class Wizard extends LDAPUtility { //connect, does not really trigger any server communication $host = $this->configuration->ldapHost; $hostInfo = parse_url($host); - if(!$hostInfo) { + if (!$hostInfo) { throw new \Exception(self::$l->t('Invalid Host')); } \OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', ILogger::DEBUG); $cr = $this->ldap->connect($host, $port); - if(!is_resource($cr)) { + if (!is_resource($cr)) { throw new \Exception(self::$l->t('Invalid Host')); } @@ -1057,9 +1057,9 @@ class Wizard extends LDAPUtility { $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT); try { - if($tls) { + if ($tls) { $isTlsWorking = @$this->ldap->startTls($cr); - if(!$isTlsWorking) { + if (!$isTlsWorking) { return false; } } @@ -1073,17 +1073,17 @@ class Wizard extends LDAPUtility { $errNo = $this->ldap->errno($cr); $error = ldap_error($cr); $this->ldap->unbind($cr); - } catch(ServerNotAvailableException $e) { + } catch (ServerNotAvailableException $e) { return false; } - if($login === true) { + if ($login === true) { $this->ldap->unbind($cr); \OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . (int)$tls, ILogger::DEBUG); return true; } - if($errNo === -1) { + if ($errNo === -1) { //host, port or TLS wrong return false; } @@ -1111,9 +1111,9 @@ class Wizard extends LDAPUtility { */ private function checkRequirements($reqs) { $this->checkAgentRequirements(); - foreach($reqs as $option) { + foreach ($reqs as $option) { $value = $this->configuration->$option; - if(empty($value)) { + if (empty($value)) { return false; } } @@ -1135,33 +1135,33 @@ class Wizard extends LDAPUtility { $dnRead = []; $foundItems = []; $maxEntries = 0; - if(!is_array($this->configuration->ldapBase) + if (!is_array($this->configuration->ldapBase) || !isset($this->configuration->ldapBase[0])) { return false; } $base = $this->configuration->ldapBase[0]; $cr = $this->getConnection(); - if(!$this->ldap->isResource($cr)) { + if (!$this->ldap->isResource($cr)) { return false; } $lastFilter = null; - if(isset($filters[count($filters)-1])) { + if (isset($filters[count($filters)-1])) { $lastFilter = $filters[count($filters)-1]; } - foreach($filters as $filter) { - if($lastFilter === $filter && count($foundItems) > 0) { + foreach ($filters as $filter) { + if ($lastFilter === $filter && count($foundItems) > 0) { //skip when the filter is a wildcard and results were found continue; } // 20k limit for performance and reason $rr = $this->ldap->search($cr, $base, $filter, [$attr], 0, 20000); - if(!$this->ldap->isResource($rr)) { + if (!$this->ldap->isResource($rr)) { continue; } $entries = $this->ldap->countEntries($cr, $rr); $getEntryFunc = 'firstEntry'; - if(($entries !== false) && ($entries > 0)) { - if(!is_null($maxF) && $entries > $maxEntries) { + if (($entries !== false) && ($entries > 0)) { + if (!is_null($maxF) && $entries > $maxEntries) { $maxEntries = $entries; $maxF = $filter; } @@ -1169,13 +1169,13 @@ class Wizard extends LDAPUtility { do { $entry = $this->ldap->$getEntryFunc($cr, $rr); $getEntryFunc = 'nextEntry'; - if(!$this->ldap->isResource($entry)) { + if (!$this->ldap->isResource($entry)) { continue 2; } $rr = $entry; //will be expected by nextEntry next round $attributes = $this->ldap->getAttributes($cr, $entry); $dn = $this->ldap->getDN($cr, $entry); - if($dn === false || in_array($dn, $dnRead)) { + if ($dn === false || in_array($dn, $dnRead)) { continue; } $newItems = []; @@ -1186,7 +1186,7 @@ class Wizard extends LDAPUtility { $foundItems = array_merge($foundItems, $newItems); $this->resultCache[$dn][$attr] = $newItems; $dnRead[] = $dn; - } while(($state === self::LRESULT_PROCESSED_SKIP + } while (($state === self::LRESULT_PROCESSED_SKIP || $this->ldap->isResource($entry)) && ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit)); } @@ -1209,11 +1209,11 @@ class Wizard extends LDAPUtility { */ private function determineFeature($objectclasses, $attr, $dbkey, $confkey, $po = false) { $cr = $this->getConnection(); - if(!$cr) { + if (!$cr) { throw new \Exception('Could not connect to LDAP'); } $p = 'objectclass='; - foreach($objectclasses as $key => $value) { + foreach ($objectclasses as $key => $value) { $objectclasses[$key] = $p.$value; } $maxEntryObjC = ''; @@ -1225,7 +1225,7 @@ class Wizard extends LDAPUtility { $availableFeatures = $this->cumulativeSearchOnAttribute($objectclasses, $attr, $dig, $maxEntryObjC); - if(is_array($availableFeatures) + if (is_array($availableFeatures) && count($availableFeatures) > 0) { natcasesort($availableFeatures); //natcasesort keeps indices, but we must get rid of them for proper @@ -1236,7 +1236,7 @@ class Wizard extends LDAPUtility { } $setFeatures = $this->configuration->$confkey; - if(is_array($setFeatures) && !empty($setFeatures)) { + if (is_array($setFeatures) && !empty($setFeatures)) { //something is already configured? pre-select it. $this->result->addChange($dbkey, $setFeatures); } elseif ($po && $maxEntryObjC !== '') { @@ -1258,7 +1258,7 @@ class Wizard extends LDAPUtility { * LRESULT_PROCESSED_INVALID or LRESULT_PROCESSED_SKIP */ private function getAttributeValuesFromEntry($result, $attribute, &$known) { - if(!is_array($result) + if (!is_array($result) || !isset($result['count']) || !$result['count'] > 0) { return self::LRESULT_PROCESSED_INVALID; @@ -1267,12 +1267,12 @@ class Wizard extends LDAPUtility { // strtolower on all keys for proper comparison $result = \OCP\Util::mb_array_change_key_case($result); $attribute = strtolower($attribute); - if(isset($result[$attribute])) { - foreach($result[$attribute] as $key => $val) { - if($key === 'count') { + if (isset($result[$attribute])) { + foreach ($result[$attribute] as $key => $val) { + if ($key === 'count') { continue; } - if(!in_array($val, $known)) { + if (!in_array($val, $known)) { $known[] = $val; } } @@ -1286,7 +1286,7 @@ class Wizard extends LDAPUtility { * @return bool|mixed */ private function getConnection() { - if(!is_null($this->cr)) { + if (!is_null($this->cr)) { return $this->cr; } @@ -1298,14 +1298,14 @@ class Wizard extends LDAPUtility { $this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3); $this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0); $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT); - if($this->configuration->ldapTLS === 1) { + if ($this->configuration->ldapTLS === 1) { $this->ldap->startTls($cr); } $lo = @$this->ldap->bind($cr, $this->configuration->ldapAgentName, $this->configuration->ldapAgentPassword); - if($lo === true) { + if ($lo === true) { $this->$cr = $cr; return $cr; } @@ -1340,9 +1340,9 @@ class Wizard extends LDAPUtility { $portSettings = []; //In case the port is already provided, we will check this first - if($port > 0) { + if ($port > 0) { $hostInfo = parse_url($host); - if(!(is_array($hostInfo) + if (!(is_array($hostInfo) && isset($hostInfo['scheme']) && stripos($hostInfo['scheme'], 'ldaps') !== false)) { $portSettings[] = ['port' => $port, 'tls' => true]; @@ -1356,6 +1356,4 @@ class Wizard extends LDAPUtility { return $portSettings; } - - } diff --git a/apps/user_ldap/lib/WizardResult.php b/apps/user_ldap/lib/WizardResult.php index 4c0c555ca53..3c8f638736e 100644 --- a/apps/user_ldap/lib/WizardResult.php +++ b/apps/user_ldap/lib/WizardResult.php @@ -52,7 +52,7 @@ class WizardResult { * @param array|string $values */ public function addOptions($key, $values) { - if(!is_array($values)) { + if (!is_array($values)) { $values = [$values]; } $this->options[$key] = $values; @@ -71,7 +71,7 @@ class WizardResult { public function getResultArray() { $result = []; $result['changes'] = $this->changes; - if(count($this->options) > 0) { + if (count($this->options) > 0) { $result['options'] = $this->options; } return $result; |