Completed
Push — master ( e1e4d1...65b4e2 )
by Blizzz
18:07
created

Manager::createUser()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 22
Code Lines 12

Duplication

Lines 11
Ratio 50 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 12
nc 10
nop 2
dl 11
loc 22
rs 8.6737
c 1
b 0
f 0
1
<?php
2
/**
3
 * @copyright Copyright (c) 2016, ownCloud, Inc.
4
 *
5
 * @author Arthur Schiwon <[email protected]>
6
 * @author Joas Schilling <[email protected]>
7
 * @author Jörn Friedrich Dreyer <[email protected]>
8
 * @author Lukas Reschke <[email protected]>
9
 * @author Michael U <[email protected]>
10
 * @author Morris Jobke <[email protected]>
11
 * @author Robin Appelman <[email protected]>
12
 * @author Robin McCorkell <[email protected]>
13
 * @author Roeland Jago Douma <[email protected]>
14
 * @author Thomas Müller <[email protected]>
15
 * @author Vincent Chan <[email protected]>
16
 * @author Volkan Gezer <[email protected]>
17
 *
18
 * @license AGPL-3.0
19
 *
20
 * This code is free software: you can redistribute it and/or modify
21
 * it under the terms of the GNU Affero General Public License, version 3,
22
 * as published by the Free Software Foundation.
23
 *
24
 * This program is distributed in the hope that it will be useful,
25
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
26
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27
 * GNU Affero General Public License for more details.
28
 *
29
 * You should have received a copy of the GNU Affero General Public License, version 3,
30
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
31
 *
32
 */
33
34
namespace OC\User;
35
36
use OC\Hooks\PublicEmitter;
37
use OCP\IUser;
38
use OCP\IUserBackend;
39
use OCP\IUserManager;
40
use OCP\IConfig;
41
use OCP\UserInterface;
42
43
/**
44
 * Class Manager
45
 *
46
 * Hooks available in scope \OC\User:
47
 * - preSetPassword(\OC\User\User $user, string $password, string $recoverPassword)
48
 * - postSetPassword(\OC\User\User $user, string $password, string $recoverPassword)
49
 * - preDelete(\OC\User\User $user)
50
 * - postDelete(\OC\User\User $user)
51
 * - preCreateUser(string $uid, string $password)
52
 * - postCreateUser(\OC\User\User $user, string $password)
53
 * - change(\OC\User\User $user)
54
 *
55
 * @package OC\User
56
 */
57
class Manager extends PublicEmitter implements IUserManager {
58
	/**
59
	 * @var \OCP\UserInterface[] $backends
60
	 */
61
	private $backends = array();
62
63
	/**
64
	 * @var \OC\User\User[] $cachedUsers
65
	 */
66
	private $cachedUsers = array();
67
68
	/**
69
	 * @var \OCP\IConfig $config
70
	 */
71
	private $config;
72
73
	/**
74
	 * @param \OCP\IConfig $config
75
	 */
76
	public function __construct(IConfig $config) {
77
		$this->config = $config;
78
		$cachedUsers = &$this->cachedUsers;
79
		$this->listen('\OC\User', 'postDelete', function ($user) use (&$cachedUsers) {
80
			/** @var \OC\User\User $user */
81
			unset($cachedUsers[$user->getUID()]);
82
		});
83
	}
84
85
	/**
86
	 * Get the active backends
87
	 * @return \OCP\UserInterface[]
88
	 */
89
	public function getBackends() {
90
		return $this->backends;
91
	}
92
93
	/**
94
	 * register a user backend
95
	 *
96
	 * @param \OCP\UserInterface $backend
97
	 */
98
	public function registerBackend($backend) {
99
		$this->backends[] = $backend;
100
	}
101
102
	/**
103
	 * remove a user backend
104
	 *
105
	 * @param \OCP\UserInterface $backend
106
	 */
107
	public function removeBackend($backend) {
108
		$this->cachedUsers = array();
109
		if (($i = array_search($backend, $this->backends)) !== false) {
110
			unset($this->backends[$i]);
111
		}
112
	}
113
114
	/**
115
	 * remove all user backends
116
	 */
117
	public function clearBackends() {
118
		$this->cachedUsers = array();
119
		$this->backends = array();
120
	}
121
122
	/**
123
	 * get a user by user id
124
	 *
125
	 * @param string $uid
126
	 * @return \OC\User\User|null Either the user or null if the specified user does not exist
127
	 */
128
	public function get($uid) {
129
		if (isset($this->cachedUsers[$uid])) { //check the cache first to prevent having to loop over the backends
130
			return $this->cachedUsers[$uid];
131
		}
132
		foreach ($this->backends as $backend) {
133
			if ($backend->userExists($uid)) {
134
				return $this->getUserObject($uid, $backend);
135
			}
136
		}
137
		return null;
138
	}
139
140
	/**
141
	 * get or construct the user object
142
	 *
143
	 * @param string $uid
144
	 * @param \OCP\UserInterface $backend
145
	 * @param bool $cacheUser If false the newly created user object will not be cached
146
	 * @return \OC\User\User
147
	 */
148
	protected function getUserObject($uid, $backend, $cacheUser = true) {
149
		if (isset($this->cachedUsers[$uid])) {
150
			return $this->cachedUsers[$uid];
151
		}
152
153
		if (method_exists($backend, 'loginName2UserName')) {
154
			$loginName = $backend->loginName2UserName($uid);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface OCP\UserInterface as the method loginName2UserName() does only exist in the following implementations of said interface: OCA\Testing\AlternativeHomeUserBackend, OCA\User_LDAP\User_LDAP, OCA\User_LDAP\User_Proxy, OC\User\Database.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
155
			if ($loginName !== false) {
156
				$uid = $loginName;
157
			}
158
			if (isset($this->cachedUsers[$uid])) {
159
				return $this->cachedUsers[$uid];
160
			}
161
		}
162
163
		$user = new User($uid, $backend, $this, $this->config);
164
		if ($cacheUser) {
165
			$this->cachedUsers[$uid] = $user;
166
		}
167
		return $user;
168
	}
169
170
	/**
171
	 * check if a user exists
172
	 *
173
	 * @param string $uid
174
	 * @return bool
175
	 */
176
	public function userExists($uid) {
177
		$user = $this->get($uid);
178
		return ($user !== null);
179
	}
180
181
	/**
182
	 * Check if the password is valid for the user
183
	 *
184
	 * @param string $loginName
185
	 * @param string $password
186
	 * @return mixed the User object on success, false otherwise
187
	 */
188
	public function checkPassword($loginName, $password) {
189
		$result = $this->checkPasswordNoLogging($loginName, $password);
190
191
		if ($result === false) {
192
			\OC::$server->getLogger()->warning('Login failed: \''. $loginName .'\' (Remote IP: \''. \OC::$server->getRequest()->getRemoteAddress(). '\')', ['app' => 'core']);
193
		}
194
195
		return $result;
196
	}
197
198
	/**
199
	 * Check if the password is valid for the user
200
	 *
201
	 * @internal
202
	 * @param string $loginName
203
	 * @param string $password
204
	 * @return mixed the User object on success, false otherwise
205
	 */
206
	public function checkPasswordNoLogging($loginName, $password) {
207
		$loginName = str_replace("\0", '', $loginName);
208
		$password = str_replace("\0", '', $password);
209
210 View Code Duplication
		foreach ($this->backends as $backend) {
211
			if ($backend->implementsActions(Backend::CHECK_PASSWORD)) {
212
				$uid = $backend->checkPassword($loginName, $password);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface OCP\UserInterface as the method checkPassword() does only exist in the following implementations of said interface: OCA\Testing\AlternativeHomeUserBackend, OCA\User_LDAP\User_LDAP, OCA\User_LDAP\User_Proxy, OC\User\Database.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
213
				if ($uid !== false) {
214
					return $this->getUserObject($uid, $backend);
215
				}
216
			}
217
		}
218
219
		return false;
220
	}
221
222
	/**
223
	 * search by user id
224
	 *
225
	 * @param string $pattern
226
	 * @param int $limit
227
	 * @param int $offset
228
	 * @return \OC\User\User[]
229
	 */
230 View Code Duplication
	public function search($pattern, $limit = null, $offset = null) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
231
		$users = array();
232
		foreach ($this->backends as $backend) {
233
			$backendUsers = $backend->getUsers($pattern, $limit, $offset);
234
			if (is_array($backendUsers)) {
235
				foreach ($backendUsers as $uid) {
236
					$users[$uid] = $this->getUserObject($uid, $backend);
237
				}
238
			}
239
		}
240
241
		uasort($users, function ($a, $b) {
242
			/**
243
			 * @var \OC\User\User $a
244
			 * @var \OC\User\User $b
245
			 */
246
			return strcmp($a->getUID(), $b->getUID());
247
		});
248
		return $users;
249
	}
250
251
	/**
252
	 * search by displayName
253
	 *
254
	 * @param string $pattern
255
	 * @param int $limit
256
	 * @param int $offset
257
	 * @return \OC\User\User[]
258
	 */
259 View Code Duplication
	public function searchDisplayName($pattern, $limit = null, $offset = null) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
260
		$users = array();
261
		foreach ($this->backends as $backend) {
262
			$backendUsers = $backend->getDisplayNames($pattern, $limit, $offset);
263
			if (is_array($backendUsers)) {
264
				foreach ($backendUsers as $uid => $displayName) {
265
					$users[] = $this->getUserObject($uid, $backend);
266
				}
267
			}
268
		}
269
270
		usort($users, function ($a, $b) {
271
			/**
272
			 * @var \OC\User\User $a
273
			 * @var \OC\User\User $b
274
			 */
275
			return strcmp(strtolower($a->getDisplayName()), strtolower($b->getDisplayName()));
276
		});
277
		return $users;
278
	}
279
280
	/**
281
	 * @param string $uid
282
	 * @param string $password
283
	 * @throws \InvalidArgumentException
284
	 * @return bool|IUser the created user or false
285
	 */
286
	public function createUser($uid, $password) {
287
		$localBackends = [];
288 View Code Duplication
		foreach ($this->backends as $backend) {
289
			if ($backend instanceof Database) {
290
				// First check if there is another user backend
291
				$localBackends[] = $backend;
292
				continue;
293
			}
294
295
			if ($backend->implementsActions(Backend::CREATE_USER)) {
296
				return $this->createUserFromBackend($uid, $password, $backend);
297
			}
298
		}
299
300
		foreach ($localBackends as $backend) {
301
			if ($backend->implementsActions(Backend::CREATE_USER)) {
302
				return $this->createUserFromBackend($uid, $password, $backend);
303
			}
304
		}
305
306
		return false;
307
	}
308
309
	/**
310
	 * @param string $uid
311
	 * @param string $password
312
	 * @param UserInterface $backend
313
	 * @return IUser|null
314
	 * @throws \InvalidArgumentException
315
	 */
316
	public function createUserFromBackend($uid, $password, UserInterface $backend) {
317
		$l = \OC::$server->getL10N('lib');
318
319
		// Check the name for bad characters
320
		// Allowed are: "a-z", "A-Z", "0-9" and "_.@-'"
0 ignored issues
show
Unused Code Comprehensibility introduced by
44% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
321
		if (preg_match('/[^a-zA-Z0-9 _\.@\-\']/', $uid)) {
322
			throw new \InvalidArgumentException($l->t('Only the following characters are allowed in a username:'
323
				. ' "a-z", "A-Z", "0-9", and "_.@-\'"'));
324
		}
325
		// No empty username
326
		if (trim($uid) === '') {
327
			throw new \InvalidArgumentException($l->t('A valid username must be provided'));
328
		}
329
		// No whitespace at the beginning or at the end
330
		if (trim($uid) !== $uid) {
331
			throw new \InvalidArgumentException($l->t('Username contains whitespace at the beginning or at the end'));
332
		}
333
		// Username only consists of 1 or 2 dots (directory traversal)
334
		if ($uid === '.' || $uid === '..') {
335
			throw new \InvalidArgumentException($l->t('Username must not consist of dots only'));
336
		}
337
		// No empty password
338
		if (trim($password) === '') {
339
			throw new \InvalidArgumentException($l->t('A valid password must be provided'));
340
		}
341
342
		// Check if user already exists
343
		if ($this->userExists($uid)) {
344
			throw new \InvalidArgumentException($l->t('The username is already being used'));
345
		}
346
347
		$this->emit('\OC\User', 'preCreateUser', [$uid, $password]);
348
		$backend->createUser($uid, $password);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface OCP\UserInterface as the method createUser() does only exist in the following implementations of said interface: OCA\Testing\AlternativeHomeUserBackend, OC\User\Database.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
349
		$user = $this->getUserObject($uid, $backend);
350
		if ($user instanceof IUser) {
351
			$this->emit('\OC\User', 'postCreateUser', [$user, $password]);
352
		}
353
		return $user;
354
	}
355
356
	/**
357
	 * returns how many users per backend exist (if supported by backend)
358
	 *
359
	 * @param boolean $hasLoggedIn when true only users that have a lastLogin
360
	 *                entry in the preferences table will be affected
361
	 * @return array|int an array of backend class as key and count number as value
362
	 *                if $hasLoggedIn is true only an int is returned
363
	 */
364
	public function countUsers($hasLoggedIn = false) {
365
		if ($hasLoggedIn) {
366
			return $this->countSeenUsers();
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->countSeenUsers(); (integer) is incompatible with the return type declared by the interface OCP\IUserManager::countUsers 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...
367
		}
368
		$userCountStatistics = [];
369
		foreach ($this->backends as $backend) {
370
			if ($backend->implementsActions(Backend::COUNT_USERS)) {
371
				$backendUsers = $backend->countUsers();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface OCP\UserInterface as the method countUsers() does only exist in the following implementations of said interface: OCA\Testing\AlternativeHomeUserBackend, OCA\User_LDAP\User_LDAP, OCA\User_LDAP\User_Proxy, OC\User\Database.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
372
				if($backendUsers !== false) {
373
					if($backend instanceof IUserBackend) {
374
						$name = $backend->getBackendName();
375
					} else {
376
						$name = get_class($backend);
377
					}
378
					if(isset($userCountStatistics[$name])) {
379
						$userCountStatistics[$name] += $backendUsers;
380
					} else {
381
						$userCountStatistics[$name] = $backendUsers;
382
					}
383
				}
384
			}
385
		}
386
		return $userCountStatistics;
387
	}
388
389
	/**
390
	 * The callback is executed for each user on each backend.
391
	 * If the callback returns false no further users will be retrieved.
392
	 *
393
	 * @param \Closure $callback
394
	 * @param string $search
395
	 * @param boolean $onlySeen when true only users that have a lastLogin entry
396
	 *                in the preferences table will be affected
397
	 * @since 9.0.0
398
	 */
399
	public function callForAllUsers(\Closure $callback, $search = '', $onlySeen = false) {
400
		if ($onlySeen) {
401
			$this->callForSeenUsers($callback);
402
		} else {
403
			foreach ($this->getBackends() as $backend) {
404
				$limit = 500;
405
				$offset = 0;
406
				do {
407
					$users = $backend->getUsers($search, $limit, $offset);
408 View Code Duplication
					foreach ($users as $uid) {
409
						if (!$backend->userExists($uid)) {
410
							continue;
411
						}
412
						$user = $this->getUserObject($uid, $backend, false);
413
						$return = $callback($user);
414
						if ($return === false) {
415
							break;
416
						}
417
					}
418
					$offset += $limit;
419
				} while (count($users) >= $limit);
420
			}
421
		}
422
	}
423
424
	/**
425
	 * returns how many users have logged in once
426
	 *
427
	 * @return int
428
	 * @since 12.0.0
429
	 */
430 View Code Duplication
	public function countDisabledUsers() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
431
		$queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
432
		$queryBuilder->select($queryBuilder->createFunction('COUNT(*)'))
433
			->from('preferences')
434
			->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('core')))
435
			->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('enabled')))
436
			->andWhere($queryBuilder->expr()->eq('configvalue', $queryBuilder->createNamedParameter('false')));
437
438
		$query = $queryBuilder->execute();
439
440
		$result = (int)$query->fetchColumn();
441
		$query->closeCursor();
442
443
		return $result;
444
	}
445
446
	/**
447
	 * returns how many users have logged in once
448
	 *
449
	 * @return int
450
	 * @since 11.0.0
451
	 */
452 View Code Duplication
	public function countSeenUsers() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
453
		$queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
454
		$queryBuilder->select($queryBuilder->createFunction('COUNT(*)'))
455
			->from('preferences')
456
			->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('login')))
457
			->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('lastLogin')))
458
			->andWhere($queryBuilder->expr()->isNotNull('configvalue'));
459
460
		$query = $queryBuilder->execute();
461
462
		$result = (int)$query->fetchColumn();
463
		$query->closeCursor();
464
465
		return $result;
466
	}
467
468
	/**
469
	 * @param \Closure $callback
470
	 * @since 11.0.0
471
	 */
472
	public function callForSeenUsers(\Closure $callback) {
473
		$limit = 1000;
474
		$offset = 0;
475
		do {
476
			$userIds = $this->getSeenUserIds($limit, $offset);
477
			$offset += $limit;
478 View Code Duplication
			foreach ($userIds as $userId) {
479
				foreach ($this->backends as $backend) {
480
					if ($backend->userExists($userId)) {
481
						$user = $this->getUserObject($userId, $backend, false);
482
						$return = $callback($user);
483
						if ($return === false) {
484
							return;
485
						}
486
					}
487
				}
488
			}
489
		} while (count($userIds) >= $limit);
490
	}
491
492
	/**
493
	 * Getting all userIds that have a listLogin value requires checking the
494
	 * value in php because on oracle you cannot use a clob in a where clause,
495
	 * preventing us from doing a not null or length(value) > 0 check.
496
	 * 
497
	 * @param int $limit
498
	 * @param int $offset
499
	 * @return string[] with user ids
500
	 */
501
	private function getSeenUserIds($limit = null, $offset = null) {
502
		$queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
503
		$queryBuilder->select(['userid'])
504
			->from('preferences')
505
			->where($queryBuilder->expr()->eq(
506
				'appid', $queryBuilder->createNamedParameter('login'))
507
			)
508
			->andWhere($queryBuilder->expr()->eq(
509
				'configkey', $queryBuilder->createNamedParameter('lastLogin'))
510
			)
511
			->andWhere($queryBuilder->expr()->isNotNull('configvalue')
512
			);
513
514
		if ($limit !== null) {
515
			$queryBuilder->setMaxResults($limit);
516
		}
517
		if ($offset !== null) {
518
			$queryBuilder->setFirstResult($offset);
519
		}
520
		$query = $queryBuilder->execute();
521
		$result = [];
522
523
		while ($row = $query->fetch()) {
524
			$result[] = $row['userid'];
525
		}
526
527
		$query->closeCursor();
528
529
		return $result;
530
	}
531
532
	/**
533
	 * @param string $email
534
	 * @return IUser[]
535
	 * @since 9.1.0
536
	 */
537
	public function getByEmail($email) {
538
		$userIds = $this->config->getUsersForUserValue('settings', 'email', $email);
539
540
		return array_map(function($uid) {
541
			return $this->get($uid);
542
		}, $userIds);
543
	}
544
}
545