Completed
Push — stable8.2 ( 2160d9...accf28 )
by Thomas
20:31
created

USER_LDAP::getBackendName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 0
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @author Arthur Schiwon <[email protected]>
4
 * @author Bart Visscher <[email protected]>
5
 * @author Dominik Schmidt <[email protected]>
6
 * @author Jörn Friedrich Dreyer <[email protected]>
7
 * @author Lukas Reschke <[email protected]>
8
 * @author Morris Jobke <[email protected]>
9
 * @author Robin Appelman <[email protected]>
10
 * @author Robin McCorkell <[email protected]>
11
 * @author Thomas Müller <[email protected]>
12
 * @author Tom Needham <[email protected]>
13
 *
14
 * @copyright Copyright (c) 2015, ownCloud, Inc.
15
 * @license AGPL-3.0
16
 *
17
 * This code is free software: you can redistribute it and/or modify
18
 * it under the terms of the GNU Affero General Public License, version 3,
19
 * as published by the Free Software Foundation.
20
 *
21
 * This program is distributed in the hope that it will be useful,
22
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24
 * GNU Affero General Public License for more details.
25
 *
26
 * You should have received a copy of the GNU Affero General Public License, version 3,
27
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
28
 *
29
 */
30
31
namespace OCA\user_ldap;
32
33
use OC\User\NoUserException;
34
use OCA\user_ldap\lib\BackendUtility;
35
use OCA\user_ldap\lib\Access;
36
use OCA\user_ldap\lib\user\OfflineUser;
37
use OCA\User_LDAP\lib\User\User;
38
use OCP\IConfig;
39
40
class USER_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserInterface {
41
	/** @var string[] $homesToKill */
42
	protected $homesToKill = array();
43
44
	/** @var \OCP\IConfig */
45
	protected $ocConfig;
46
47
	/**
48
	 * @param \OCA\user_ldap\lib\Access $access
49
	 * @param \OCP\IConfig $ocConfig
50
	 */
51 34
	public function __construct(Access $access, IConfig $ocConfig) {
52 34
		parent::__construct($access);
53 34
		$this->ocConfig = $ocConfig;
54 34
	}
55
56
	/**
57
	 * checks whether the user is allowed to change his avatar in ownCloud
58
	 * @param string $uid the ownCloud user name
59
	 * @return boolean either the user can or cannot
60
	 */
61
	public function canChangeAvatar($uid) {
62
		$user = $this->access->userManager->get($uid);
63
		if(!$user instanceof User) {
64
			return false;
65
		}
66
		if($user->getAvatarImage() === false) {
67
			return true;
68
		}
69
70
		return false;
71
	}
72
73
	/**
74
	 * returns the username for the given login name, if available
75
	 *
76
	 * @param string $loginName
77
	 * @return string|false
78
	 */
79
	public function loginName2UserName($loginName) {
80
		try {
81
			$ldapRecord = $this->getLDAPUserByLoginName($loginName);
82
			$user = $this->access->userManager->get($ldapRecord['dn'][0]);
83
			if($user instanceof OfflineUser) {
84
				return false;
85
			}
86
			return $user->getUsername();
87
		} catch (\Exception $e) {
88
			return false;
89
		}
90
	}
91
92
	/**
93
	 * returns an LDAP record based on a given login name
94
	 *
95
	 * @param string $loginName
96
	 * @return array
97
	 * @throws \Exception
98
	 */
99 7
	public function getLDAPUserByLoginName($loginName) {
100
		//find out dn of the user name
101 7
		$attrs = $this->access->userManager->getAttributes();
102 7
		$users = $this->access->fetchUsersByLoginName($loginName, $attrs, 1);
0 ignored issues
show
Unused Code introduced by
The call to Access::fetchUsersByLoginName() has too many arguments starting with 1.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
103 7
		if(count($users) < 1) {
104 2
			throw new \Exception('No user available for the given login name.');
105
		}
106 5
		return $users[0];
107
	}
108
109
	/**
110
	 * Check if the password is correct
111
	 * @param string $uid The username
112
	 * @param string $password The password
113
	 * @return false|string
114
	 *
115
	 * Check if the password is correct without logging in the user
116
	 */
117 17
	public function checkPassword($uid, $password) {
118
		try {
119 7
			$ldapRecord = $this->getLDAPUserByLoginName($uid);
120 7
		} catch(\Exception $e) {
121 2
			\OC::$server->getLogger()->logException($e, ['app' => 'user_ldap']);
122 2
			return false;
123
		}
124 5
		$dn = $ldapRecord['dn'][0];
125 5
		$user = $this->access->userManager->get($dn);
126
127 5
		if(!$user instanceof User) {
128 1
			\OCP\Util::writeLog('user_ldap',
129 1
				'LDAP Login: Could not get user object for DN ' . $dn .
130 1
				'. Maybe the LDAP entry has no set display name attribute?',
131 1
				\OCP\Util::WARN);
132 1
			return false;
133
		}
134 4
		if($user->getUsername() !== false) {
135
			//are the credentials OK?
136 4
			if(!$this->access->areCredentialsValid($dn, $password)) {
137 2
				return false;
138
			}
139
140 17
			$this->access->cacheUserExists($user->getUsername());
141 17
			$user->processAttributes($ldapRecord);
142 17
			$user->markLogin();
143
144 2
			return $user->getUsername();
145
		}
146
147
		return false;
148 2
	}
149
150
	/**
151
	 * Get a list of all users
152
	 *
153
	 * @param string $search
154
	 * @param null|int $limit
155
	 * @param null|int $offset
156
	 * @return string[] an array of all uids
157
	 */
158 12
	public function getUsers($search = '', $limit = 10, $offset = 0) {
159 10
		$search = $this->access->escapeFilterPart($search, true);
160 10
		$cachekey = 'getUsers-'.$search.'-'.$limit.'-'.$offset;
161
162
		//check if users are cached, if so return
163 12
		$ldap_users = $this->access->connection->getFromCache($cachekey);
164 10
		if(!is_null($ldap_users)) {
165
			return $ldap_users;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $ldap_users; (object|integer|double|string|array|boolean) is incompatible with the return type declared by the interface OC_User_Interface::getUsers of type string[].

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
166
		}
167
168
		// if we'd pass -1 to LDAP search, we'd end up in a Protocol
169
		// error. With a limit of 0, we get 0 results. So we pass null.
170 10
		if($limit <= 0) {
171 3
			$limit = null;
172 3
		}
173 10
		$filter = $this->access->combineFilterWithAnd(array(
174 10
			$this->access->connection->ldapUserFilter,
175 10
			$this->access->connection->ldapUserDisplayName . '=*',
176 10
			$this->access->getFilterPartForUserSearch($search)
177 10
		));
178 10
		$attrs = array($this->access->connection->ldapUserDisplayName, 'dn');
179 10
		$additionalAttribute = $this->access->connection->ldapUserDisplayName2;
180
		if(!empty($additionalAttribute)) {
181
			$attrs[] = $additionalAttribute;
182
		}
183 10
184 10
		\OCP\Util::writeLog('user_ldap',
185 10
			'getUsers: Options: search '.$search.' limit '.$limit.' offset '.$offset.' Filter: '.$filter,
186
			\OCP\Util::DEBUG);
187 10
		//do the search and translate results to owncloud names
188 10
		$ldap_users = $this->access->fetchListOfUsers(
189 12
			$filter,
190 10
			$this->access->userManager->getAttributes(true),
191 10
			$limit, $offset);
192 10
		$ldap_users = $this->access->ownCloudUserNames($ldap_users);
193
		\OCP\Util::writeLog('user_ldap', 'getUsers: '.count($ldap_users). ' Users found', \OCP\Util::DEBUG);
194 10
195 10
		$this->access->connection->writeToCache($cachekey, $ldap_users);
196
		return $ldap_users;
197
	}
198
199
	/**
200
	 * checks whether a user is still available on LDAP
201
	 *
202
	 * @param string|\OCA\User_LDAP\lib\user\User $user either the ownCloud user
203
	 * name or an instance of that user
204
	 * @return bool
205
	 * @throws \Exception
206
	 * @throws \OC\ServerNotAvailableException
207 10
	 */
208 10
	public function userExistsOnLDAP($user) {
209
		if(is_string($user)) {
210
			$user = $this->access->userManager->get($user);
211 10
		}
212 1
		if(is_null($user)) {
213
			return false;
214
		}
215 9
216
		$dn = $user->getDN();
217 9
		//check if user really still exists by reading its entry
218 5
		if(!is_array($this->access->readAttribute($dn, '', $this->access->connection->ldapUserFilter))) {
219 5
			$lcr = $this->access->connection->getConnectionResource();
220 3
			if(is_null($lcr)) {
221
				throw new \Exception('No LDAP Connection to server ' . $this->access->connection->ldapHost);
0 ignored issues
show
Documentation introduced by
The property ldapHost does not exist on object<OCA\user_ldap\lib\Connection>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
222
			}
223
224 2
			try {
225 2
				$uuid = $this->access->getUserMapper()->getUUIDByDN($dn);
226 2
				if(!$uuid) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $uuid of type string|false is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
227
					return false;
228
				}
229
				$newDn = $this->access->getUserDnByUuid($uuid);
230
				//check if renamed user is still valid by reapplying the ldap filter
231 View Code Duplication
				if(!is_array($this->access->readAttribute($newDn, '', $this->access->connection->ldapUserFilter))) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
232
					return false;
233
				}
234
235
				$this->access->getUserMapper()->setDNbyUUID($newDn, $uuid);
236 6
				return true;
237
			} catch (\Exception $e) {
238
				return false;
239
			}
240 6
		}
241
242
		if($user instanceof OfflineUser) {
243
			$user->unmark();
244
		}
245
246
		return true;
247
	}
248
249 12
	/**
250 12
	 * check if a user exists
251
	 * @param string $uid the username
252
	 * @return boolean
253
	 * @throws \Exception when connection could not be established
254 12
	 */
255
	public function userExists($uid) {
256 12
		$userExists = $this->access->connection->getFromCache('userExists'.$uid);
257 2
		if(!is_null($userExists)) {
258 2
			return (bool)$userExists;
259 2
		}
260 2
		//getting dn, if false the user does not exist. If dn, he may be mapped only, requires more checking.
261 10
		$user = $this->access->userManager->get($uid);
262
263
		if(is_null($user)) {
264 1
			\OCP\Util::writeLog('user_ldap', 'No DN found for '.$uid.' on '.
265
				$this->access->connection->ldapHost, \OCP\Util::DEBUG);
0 ignored issues
show
Documentation introduced by
The property ldapHost does not exist on object<OCA\user_ldap\lib\Connection>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
266
			$this->access->connection->writeToCache('userExists'.$uid, false);
267 9
			return false;
268 6
		} else if($user instanceof OfflineUser) {
269 6
			//express check for users marked as deleted. Returning true is
270 6
			//necessary for cleanup
271 6
			return true;
272 6
		}
273
274
		$result = $this->userExistsOnLDAP($user);
275
		$this->access->connection->writeToCache('userExists'.$uid, $result);
276
		if($result === true) {
277
			$user->update();
278
		}
279
		return $result;
280
	}
281 3
282 3
	/**
283 3
	* returns whether a user was deleted in LDAP
284 2
	*
285 2
	* @param string $uid The username of the user to delete
286 2
	* @return bool
287 2
	*/
288
	public function deleteUser($uid) {
289 1
		$marked = $this->ocConfig->getUserValue($uid, 'user_ldap', 'isDeleted', 0);
290 1 View Code Duplication
		if(intval($marked) === 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
291
			\OC::$server->getLogger()->notice(
292
				'User '.$uid . ' is not marked as deleted, not cleaning up.',
293
				array('app' => 'user_ldap'));
294 1
			return false;
295 1
		}
296 1
		\OC::$server->getLogger()->info('Cleaning up after user ' . $uid,
297
			array('app' => 'user_ldap'));
298 1
299
		//Get Home Directory out of user preferences so we can return it later,
300
		//necessary for removing directories as done by OC_User.
301
		$home = $this->ocConfig->getUserValue($uid, 'user_ldap', 'homePath', '');
302
		$this->homesToKill[$uid] = $home;
303
		$this->access->getUserMapper()->unmap($uid);
304
305
		return true;
306
	}
307
308
	/**
309 5
	 * get the user's home directory
310 5
	 *
311
	 * @param string $uid the username
312 1
	 * @return bool|string
313
	 * @throws NoUserException
314
	 * @throws \Exception
315
	 */
316 4
	public function getHome($uid) {
317
		if(isset($this->homesToKill[$uid]) && !empty($this->homesToKill[$uid])) {
318
			//a deleted user who needs some clean up
319
			return $this->homesToKill[$uid];
320 3
		}
321 3
322
		// user Exists check required as it is not done in user proxy!
323
		if(!$this->userExists($uid)) {
324
			return false;
325 3
		}
326 3
327 1
		$cacheKey = 'getHome'.$uid;
328
		$path = $this->access->connection->getFromCache($cacheKey);
329 2
		if(!is_null($path)) {
330
			return $path;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $path; (object|integer|double|string|array|boolean) is incompatible with the return type documented by OCA\user_ldap\USER_LDAP::getHome of type boolean|string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
331
		}
332
333
		$user = $this->access->userManager->get($uid);
334
		if(is_null($user) || ($user instanceof OfflineUser && !$this->userExistsOnLDAP($user->getOCName()))) {
335 2
			throw new NoUserException($uid . ' is not a valid user anymore');
336 2
		}
337
		if($user instanceof OfflineUser) {
338 2
			// apparently this user survived the userExistsOnLDAP check,
339
			// we request the user instance again in order to retrieve a User
340
			// instance instead
341
			$user = $this->access->userManager->get($uid);
342
		}
343
		$path = $user->getHomePath();
344
		$this->access->cacheUserHome($uid, $path);
345
346 2
		return $path;
347 2
	}
348 1
349
	/**
350
	 * get display name of the user
351 2
	 * @param string $uid user ID of the user
352 2
	 * @return string|false display name
353
	 */
354
	public function getDisplayName($uid) {
355
		if(!$this->userExists($uid)) {
356
			return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type declared by the interface OC_User_Interface::getDisplayName of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
357 2
		}
358 2
359 2
		$cacheKey = 'getDisplayName'.$uid;
360
		if(!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
361
			return $displayName;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $displayName; (object|integer|double|string|array|boolean) is incompatible with the return type declared by the interface OC_User_Interface::getDisplayName of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
362
		}
363
364
		//Check whether the display name is configured to have a 2nd feature
365 2
		$additionalAttribute = $this->access->connection->ldapUserDisplayName2;
366 2
		$displayName2 = '';
367 2
		if(!empty($additionalAttribute)) {
368
			$displayName2 = $this->access->readAttribute(
369 2
				$this->access->username2dn($uid),
0 ignored issues
show
Security Bug introduced by
It seems like $this->access->username2dn($uid) targeting OCA\user_ldap\lib\Access::username2dn() can also be of type false; however, OCA\user_ldap\lib\Access::readAttribute() does only seem to accept string, did you maybe forget to handle an error condition?
Loading history...
370 2
				$additionalAttribute);
371
		}
372 2
373
		$displayName = $this->access->readAttribute(
374
			$this->access->username2dn($uid),
0 ignored issues
show
Security Bug introduced by
It seems like $this->access->username2dn($uid) targeting OCA\user_ldap\lib\Access::username2dn() can also be of type false; however, OCA\user_ldap\lib\Access::readAttribute() does only seem to accept string, did you maybe forget to handle an error condition?
Loading history...
375
			$this->access->connection->ldapUserDisplayName);
376 2
377 2
		if($displayName && (count($displayName) > 0)) {
378 2
			$displayName = $displayName[0];
379 2
380
			if(is_array($displayName2) && (count($displayName2) > 0)) {
381
				$displayName2 = $displayName2[0];
382
			}
383
384
			$user = $this->access->userManager->get($uid);
385
			$displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
0 ignored issues
show
Bug introduced by
The method composeAndStoreDisplayName does only exist in OCA\user_ldap\lib\user\User, but not in OCA\user_ldap\lib\user\OfflineUser.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
386
			$this->access->connection->writeToCache($cacheKey, $displayName);
387
			return $displayName;
388
		}
389
390
		return null;
391
	}
392
393
	/**
394
	 * Get a list of all display names
395
	 *
396
	 * @param string $search
397
	 * @param string|null $limit
398
	 * @param string|null $offset
399
	 * @return array an array of all displayNames (value) and the corresponding uids (key)
400
	 */
401
	public function getDisplayNames($search = '', $limit = null, $offset = null) {
402
		$cacheKey = 'getDisplayNames-'.$search.'-'.$limit.'-'.$offset;
403
		if(!is_null($displayNames = $this->access->connection->getFromCache($cacheKey))) {
404
			return $displayNames;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $displayNames; (object|integer|double|string|array|boolean) is incompatible with the return type declared by the interface OC_User_Interface::getDisplayNames of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
405
		}
406
407
		$displayNames = array();
408
		$users = $this->getUsers($search, $limit, $offset);
409
		foreach ($users as $user) {
0 ignored issues
show
Bug introduced by
The expression $users of type object|integer|double|string|array|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
410
			$displayNames[$user] = $this->getDisplayName($user);
411
		}
412
		$this->access->connection->writeToCache($cacheKey, $displayNames);
413
		return $displayNames;
414
	}
415
416 4
	/**
417
	* Check if backend implements actions
418 4
	* @param int $actions bitwise-or'ed actions
419 4
	* @return boolean
420 4
	*
421 4
	* Returns the supported actions as int to be
422 4
	* compared with OC_USER_BACKEND_CREATE_USER etc.
423
	*/
424
	public function implementsActions($actions) {
425
		return (bool)((\OC_User_Backend::CHECK_PASSWORD
426
			| \OC_User_Backend::GET_HOME
427
			| \OC_User_Backend::GET_DISPLAYNAME
428
			| \OC_User_Backend::PROVIDE_AVATAR
429
			| \OC_User_Backend::COUNT_USERS)
430
			& $actions);
431
	}
432
433
	/**
434
	 * @return bool
435
	 */
436
	public function hasUserListings() {
437 2
		return true;
438 2
	}
439 2
440 2
	/**
441
	 * counts the users in LDAP
442
	 *
443 2
	 * @return int|bool
444 2
	 */
445 2
	public function countUsers() {
446
		$filter = $this->access->getFilterForUserCount();
447
		$cacheKey = 'countUsers-'.$filter;
448
		if(!is_null($entries = $this->access->connection->getFromCache($cacheKey))) {
449
			return $entries;
450
		}
451
		$entries = $this->access->countUsers($filter);
452
		$this->access->connection->writeToCache($cacheKey, $entries);
453
		return $entries;
454
	}
455
456
	/**
457
	 * Backend name to be shown in user management
458
	 * @return string the name of the backend to be shown
459
	 */
460
	public function getBackendName(){
461
		return 'LDAP';
462
	}
463
464
}
465