]> git.mxchange.org Git - friendica.git/blob - src/Model/User.php
Measures against several warnings and errors in the log
[friendica.git] / src / Model / User.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Model;
23
24 use DivineOmega\DOFileCachePSR6\CacheItemPool;
25 use DivineOmega\PasswordExposed;
26 use ErrorException;
27 use Exception;
28 use Friendica\Content\Pager;
29 use Friendica\Core\Hook;
30 use Friendica\Core\L10n;
31 use Friendica\Core\Logger;
32 use Friendica\Core\Protocol;
33 use Friendica\Core\Search;
34 use Friendica\Core\System;
35 use Friendica\Core\Worker;
36 use Friendica\Database\DBA;
37 use Friendica\DI;
38 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
39 use Friendica\Security\TwoFactor\Model\AppSpecificPassword;
40 use Friendica\Network\HTTPException;
41 use Friendica\Object\Image;
42 use Friendica\Util\Crypto;
43 use Friendica\Util\DateTimeFormat;
44 use Friendica\Util\Images;
45 use Friendica\Util\Network;
46 use Friendica\Util\Proxy;
47 use Friendica\Util\Strings;
48 use Friendica\Worker\Delivery;
49 use ImagickException;
50 use LightOpenID;
51
52 /**
53  * This class handles User related functions
54  */
55 class User
56 {
57         /**
58          * Page/profile types
59          *
60          * PAGE_FLAGS_NORMAL is a typical personal profile account
61          * PAGE_FLAGS_SOAPBOX automatically approves all friend requests as Contact::SHARING, (readonly)
62          * PAGE_FLAGS_COMMUNITY automatically approves all friend requests as Contact::SHARING, but with
63          *      write access to wall and comments (no email and not included in page owner's ACL lists)
64          * PAGE_FLAGS_FREELOVE automatically approves all friend requests as full friends (Contact::FRIEND).
65          *
66          * @{
67          */
68         const PAGE_FLAGS_NORMAL    = 0;
69         const PAGE_FLAGS_SOAPBOX   = 1;
70         const PAGE_FLAGS_COMMUNITY = 2;
71         const PAGE_FLAGS_FREELOVE  = 3;
72         const PAGE_FLAGS_BLOG      = 4;
73         const PAGE_FLAGS_PRVGROUP  = 5;
74         /**
75          * @}
76          */
77
78         /**
79          * Account types
80          *
81          * ACCOUNT_TYPE_PERSON - the account belongs to a person
82          *      Associated page types: PAGE_FLAGS_NORMAL, PAGE_FLAGS_SOAPBOX, PAGE_FLAGS_FREELOVE
83          *
84          * ACCOUNT_TYPE_ORGANISATION - the account belongs to an organisation
85          *      Associated page type: PAGE_FLAGS_SOAPBOX
86          *
87          * ACCOUNT_TYPE_NEWS - the account is a news reflector
88          *      Associated page type: PAGE_FLAGS_SOAPBOX
89          *
90          * ACCOUNT_TYPE_COMMUNITY - the account is community forum
91          *      Associated page types: PAGE_COMMUNITY, PAGE_FLAGS_PRVGROUP
92          *
93          * ACCOUNT_TYPE_RELAY - the account is a relay
94          *      This will only be assigned to contacts, not to user accounts
95          * @{
96          */
97         const ACCOUNT_TYPE_PERSON =       0;
98         const ACCOUNT_TYPE_ORGANISATION = 1;
99         const ACCOUNT_TYPE_NEWS =         2;
100         const ACCOUNT_TYPE_COMMUNITY =    3;
101         const ACCOUNT_TYPE_RELAY =        4;
102         const ACCOUNT_TYPE_DELETED =    127;
103         /**
104          * @}
105          */
106
107         private static $owner;
108
109         /**
110          * Returns the numeric account type by their string
111          *
112          * @param string $accounttype as string constant
113          * @return int|null Numeric account type - or null when not set
114          */
115         public static function getAccountTypeByString(string $accounttype)
116         {
117                 switch ($accounttype) {
118                         case 'person':
119                                 return User::ACCOUNT_TYPE_PERSON;
120
121                         case 'organisation':
122                                 return User::ACCOUNT_TYPE_ORGANISATION;
123
124                         case 'news':
125                                 return User::ACCOUNT_TYPE_NEWS;
126
127                         case 'community':
128                                 return User::ACCOUNT_TYPE_COMMUNITY;
129
130                 }
131                 return null;
132         }
133
134         /**
135          * Fetch the system account
136          *
137          * @return array system account
138          */
139         public static function getSystemAccount(): array
140         {
141                 $system = Contact::selectFirst([], ['self' => true, 'uid' => 0]);
142                 if (!DBA::isResult($system)) {
143                         self::createSystemAccount();
144                         $system = Contact::selectFirst([], ['self' => true, 'uid' => 0]);
145                         if (!DBA::isResult($system)) {
146                                 return [];
147                         }
148                 }
149
150                 $system['sprvkey'] = $system['uprvkey'] = $system['prvkey'];
151                 $system['spubkey'] = $system['upubkey'] = $system['pubkey'];
152                 $system['nickname'] = $system['nick'];
153                 $system['page-flags'] = User::PAGE_FLAGS_SOAPBOX;
154                 $system['account-type'] = $system['contact-type'];
155                 $system['guid'] = '';
156                 $system['picdate'] = '';
157                 $system['theme'] = '';
158                 $system['publish'] = false;
159                 $system['net-publish'] = false;
160                 $system['hide-friends'] = true;
161                 $system['hidewall'] = true;
162                 $system['prv_keywords'] = '';
163                 $system['pub_keywords'] = '';
164                 $system['address'] = '';
165                 $system['locality'] = '';
166                 $system['region'] = '';
167                 $system['postal-code'] = '';
168                 $system['country-name'] = '';
169                 $system['homepage'] = DI::baseUrl()->get();
170                 $system['dob'] = '0000-00-00';
171
172                 // Ensure that the user contains data
173                 $user = DBA::selectFirst('user', ['prvkey', 'guid'], ['uid' => 0]);
174                 if (empty($user['prvkey']) || empty($user['guid'])) {
175                         $fields = [
176                                 'username' => $system['name'],
177                                 'nickname' => $system['nick'],
178                                 'register_date' => $system['created'],
179                                 'pubkey' => $system['pubkey'],
180                                 'prvkey' => $system['prvkey'],
181                                 'spubkey' => $system['spubkey'],
182                                 'sprvkey' => $system['sprvkey'],
183                                 'guid' => System::createUUID(),
184                                 'verified' => true,
185                                 'page-flags' => User::PAGE_FLAGS_SOAPBOX,
186                                 'account-type' => User::ACCOUNT_TYPE_RELAY,
187                         ];
188
189                         DBA::update('user', $fields, ['uid' => 0]);
190
191                         $system['guid'] = $fields['guid'];
192                 } else {
193                         $system['guid'] = $user['guid'];
194                 }
195
196                 return $system;
197         }
198
199         /**
200          * Create the system account
201          *
202          * @return void
203          */
204         private static function createSystemAccount()
205         {
206                 $system_actor_name = self::getActorName();
207                 if (empty($system_actor_name)) {
208                         return;
209                 }
210
211                 $keys = Crypto::newKeypair(4096);
212                 if ($keys === false) {
213                         throw new Exception(DI::l10n()->t('SERIOUS ERROR: Generation of security keys failed.'));
214                 }
215
216                 $system = [
217                         'uid'          => 0,
218                         'created'      => DateTimeFormat::utcNow(),
219                         'self'         => true,
220                         'network'      => Protocol::ACTIVITYPUB,
221                         'name'         => 'System Account',
222                         'addr'         => $system_actor_name . '@' . DI::baseUrl()->getHostname(),
223                         'nick'         => $system_actor_name,
224                         'url'          => DI::baseUrl() . '/friendica',
225                         'pubkey'       => $keys['pubkey'],
226                         'prvkey'       => $keys['prvkey'],
227                         'blocked'      => 0,
228                         'pending'      => 0,
229                         'contact-type' => Contact::TYPE_RELAY, // In AP this is translated to 'Application'
230                         'name-date'    => DateTimeFormat::utcNow(),
231                         'uri-date'     => DateTimeFormat::utcNow(),
232                         'avatar-date'  => DateTimeFormat::utcNow(),
233                         'closeness'    => 0,
234                         'baseurl'      => DI::baseUrl(),
235                 ];
236
237                 $system['avatar'] = $system['photo'] = Contact::getDefaultAvatar($system, Proxy::SIZE_SMALL);
238                 $system['thumb']  = Contact::getDefaultAvatar($system, Proxy::SIZE_THUMB);
239                 $system['micro']  = Contact::getDefaultAvatar($system, Proxy::SIZE_MICRO);
240                 $system['nurl']   = Strings::normaliseLink($system['url']);
241                 $system['gsid']   = GServer::getID($system['baseurl']);
242
243                 Contact::insert($system);
244         }
245
246         /**
247          * Detect a usable actor name
248          *
249          * @return string actor account name
250          */
251         public static function getActorName(): string
252         {
253                 $system_actor_name = DI::config()->get('system', 'actor_name');
254                 if (!empty($system_actor_name)) {
255                         $self = Contact::selectFirst(['nick'], ['uid' => 0, 'self' => true]);
256                         if (!empty($self['nick'])) {
257                                 if ($self['nick'] != $system_actor_name) {
258                                         // Reset the actor name to the already used name
259                                         DI::config()->set('system', 'actor_name', $self['nick']);
260                                         $system_actor_name = $self['nick'];
261                                 }
262                         }
263                         return $system_actor_name;
264                 }
265
266                 // List of possible actor names
267                 $possible_accounts = ['friendica', 'actor', 'system', 'internal'];
268                 foreach ($possible_accounts as $name) {
269                         if (!DBA::exists('user', ['nickname' => $name, 'account_removed' => false, 'account_expired' => false]) &&
270                                 !DBA::exists('userd', ['username' => $name])) {
271                                 DI::config()->set('system', 'actor_name', $name);
272                                 return $name;
273                         }
274                 }
275                 return '';
276         }
277
278         /**
279          * Returns true if a user record exists with the provided id
280          *
281          * @param  int $uid
282          *
283          * @return boolean
284          * @throws Exception
285          */
286         public static function exists(int $uid): bool
287         {
288                 return DBA::exists('user', ['uid' => $uid]);
289         }
290
291         /**
292          * @param  integer       $uid
293          * @param array          $fields
294          * @return array|boolean User record if it exists, false otherwise
295          * @throws Exception
296          */
297         public static function getById(int $uid, array $fields = [])
298         {
299                 return !empty($uid) ? DBA::selectFirst('user', $fields, ['uid' => $uid]) : [];
300         }
301
302         /**
303          * Returns a user record based on it's GUID
304          *
305          * @param string $guid   The guid of the user
306          * @param array  $fields The fields to retrieve
307          * @param bool   $active True, if only active records are searched
308          *
309          * @return array|boolean User record if it exists, false otherwise
310          * @throws Exception
311          */
312         public static function getByGuid(string $guid, array $fields = [], bool $active = true)
313         {
314                 if ($active) {
315                         $cond = ['guid' => $guid, 'account_expired' => false, 'account_removed' => false];
316                 } else {
317                         $cond = ['guid' => $guid];
318                 }
319
320                 return DBA::selectFirst('user', $fields, $cond);
321         }
322
323         /**
324          * @param  string        $nickname
325          * @param array          $fields
326          * @return array|boolean User record if it exists, false otherwise
327          * @throws Exception
328          */
329         public static function getByNickname(string $nickname, array $fields = [])
330         {
331                 return DBA::selectFirst('user', $fields, ['nickname' => $nickname]);
332         }
333
334         /**
335          * Returns the user id of a given profile URL
336          *
337          * @param string $url
338          *
339          * @return integer user id
340          * @throws Exception
341          */
342         public static function getIdForURL(string $url): int
343         {
344                 // Avoid database queries when the local node hostname isn't even part of the url.
345                 if (!Contact::isLocal($url)) {
346                         return 0;
347                 }
348
349                 $self = Contact::selectFirst(['uid'], ['self' => true, 'nurl' => Strings::normaliseLink($url)]);
350                 if (!empty($self['uid'])) {
351                         return $self['uid'];
352                 }
353
354                 $self = Contact::selectFirst(['uid'], ['self' => true, 'addr' => $url]);
355                 if (!empty($self['uid'])) {
356                         return $self['uid'];
357                 }
358
359                 $self = Contact::selectFirst(['uid'], ['self' => true, 'alias' => [$url, Strings::normaliseLink($url)]]);
360                 if (!empty($self['uid'])) {
361                         return $self['uid'];
362                 }
363
364                 return 0;
365         }
366
367         /**
368          * Get a user based on its email
369          *
370          * @param string $email
371          * @param array  $fields
372          * @return array|boolean User record if it exists, false otherwise
373          * @throws Exception
374          */
375         public static function getByEmail(string $email, array $fields = [])
376         {
377                 return DBA::selectFirst('user', $fields, ['email' => $email]);
378         }
379
380         /**
381          * Fetch the user array of the administrator. The first one if there are several.
382          *
383          * @param array $fields
384          * @return array user
385          * @throws Exception
386          */
387         public static function getFirstAdmin(array $fields = []) : array
388         {
389                 if (!empty(DI::config()->get('config', 'admin_nickname'))) {
390                         return self::getByNickname(DI::config()->get('config', 'admin_nickname'), $fields);
391                 }
392
393                 return self::getAdminList()[0] ?? [];
394         }
395
396         /**
397          * Get owner data by user id
398          *
399          * @param int     $uid
400          * @param boolean $repairMissing Repair the owner data if it's missing
401          * @return boolean|array
402          * @throws Exception
403          */
404         public static function getOwnerDataById(int $uid, bool $repairMissing = true)
405         {
406                 if ($uid == 0) {
407                         return self::getSystemAccount();
408                 }
409
410                 if (!empty(self::$owner[$uid])) {
411                         return self::$owner[$uid];
412                 }
413
414                 $owner = DBA::selectFirst('owner-view', [], ['uid' => $uid]);
415                 if (!DBA::isResult($owner)) {
416                         if (!self::exists($uid) || !$repairMissing) {
417                                 return false;
418                         }
419                         if (!DBA::exists('profile', ['uid' => $uid])) {
420                                 DBA::insert('profile', ['uid' => $uid]);
421                         }
422                         if (!DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
423                                 Contact::createSelfFromUserId($uid);
424                         }
425                         $owner = self::getOwnerDataById($uid, false);
426                 }
427
428                 if (empty($owner['nickname'])) {
429                         return false;
430                 }
431
432                 if (!$repairMissing || $owner['account_expired']) {
433                         return $owner;
434                 }
435
436                 // Check if the returned data is valid, otherwise fix it. See issue #6122
437
438                 // Check for correct url and normalised nurl
439                 $url = DI::baseUrl() . '/profile/' . $owner['nickname'];
440                 $repair = empty($owner['network']) || ($owner['url'] != $url) || ($owner['nurl'] != Strings::normaliseLink($owner['url']));
441
442                 if (!$repair) {
443                         // Check if "addr" is present and correct
444                         $addr = $owner['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
445                         $repair = ($addr != $owner['addr']) || empty($owner['prvkey']) || empty($owner['pubkey']);
446                 }
447
448                 if (!$repair) {
449                         // Check if the avatar field is filled and the photo directs to the correct path
450                         $avatar = Photo::selectFirst(['resource-id'], ['uid' => $uid, 'profile' => true]);
451                         if (DBA::isResult($avatar)) {
452                                 $repair = empty($owner['avatar']) || !strpos($owner['photo'], $avatar['resource-id']);
453                         }
454                 }
455
456                 if ($repair) {
457                         Contact::updateSelfFromUserID($uid);
458                         // Return the corrected data and avoid a loop
459                         $owner = self::getOwnerDataById($uid, false);
460                 }
461
462                 self::$owner[$uid] = $owner;
463                 return $owner;
464         }
465
466         /**
467          * Get owner data by nick name
468          *
469          * @param int $nick
470          * @return boolean|array
471          * @throws Exception
472          */
473         public static function getOwnerDataByNick(string $nick)
474         {
475                 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nick]);
476
477                 if (!DBA::isResult($user)) {
478                         return false;
479                 }
480
481                 return self::getOwnerDataById($user['uid']);
482         }
483
484         /**
485          * Returns the default group for a given user and network
486          *
487          * @param int $uid User id
488          *
489          * @return int group id
490          * @throws Exception
491          */
492         public static function getDefaultGroup(int $uid): int
493         {
494                 $user = DBA::selectFirst('user', ['def_gid'], ['uid' => $uid]);
495                 if (DBA::isResult($user)) {
496                         $default_group = $user["def_gid"];
497                 } else {
498                         $default_group = 0;
499                 }
500
501                 return $default_group;
502         }
503
504         /**
505          * Authenticate a user with a clear text password
506          *
507          * Returns the user id associated with a successful password authentication
508          *
509          * @param mixed  $user_info
510          * @param string $password
511          * @param bool   $third_party
512          * @return int User Id if authentication is successful
513          * @throws HTTPException\ForbiddenException
514          * @throws HTTPException\NotFoundException
515          */
516         public static function getIdFromPasswordAuthentication($user_info, string $password, bool $third_party = false): int
517         {
518                 // Addons registered with the "authenticate" hook may create the user on the
519                 // fly. `getAuthenticationInfo` will fail if the user doesn't exist yet. If
520                 // the user doesn't exist, we should give the addons a chance to create the
521                 // user in our database, if applicable, before re-throwing the exception if
522                 // they fail.
523                 try {
524                         $user = self::getAuthenticationInfo($user_info);
525                 } catch (Exception $e) {
526                         $username = (is_string($user_info) ? $user_info : $user_info['nickname'] ?? '');
527
528                         // Addons can create users, and since this 'catch' branch should only
529                         // execute if getAuthenticationInfo can't find an existing user, that's
530                         // exactly what will happen here. Creating a numeric username would create
531                         // abiguity with user IDs, possibly opening up an attack vector.
532                         // So let's be very careful about that.
533                         if (empty($username) || is_numeric($username)) {
534                                 throw $e;
535                         }
536
537                         return self::getIdFromAuthenticateHooks($username, $password);
538                 }
539
540                 if ($third_party && DI::pConfig()->get($user['uid'], '2fa', 'verified')) {
541                         // Third-party apps can't verify two-factor authentication, we use app-specific passwords instead
542                         if (AppSpecificPassword::authenticateUser($user['uid'], $password)) {
543                                 return $user['uid'];
544                         }
545                 } elseif (strpos($user['password'], '$') === false) {
546                         //Legacy hash that has not been replaced by a new hash yet
547                         if (self::hashPasswordLegacy($password) === $user['password']) {
548                                 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
549
550                                 return $user['uid'];
551                         }
552                 } elseif (!empty($user['legacy_password'])) {
553                         //Legacy hash that has been double-hashed and not replaced by a new hash yet
554                         //Warning: `legacy_password` is not necessary in sync with the content of `password`
555                         if (password_verify(self::hashPasswordLegacy($password), $user['password'])) {
556                                 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
557
558                                 return $user['uid'];
559                         }
560                 } elseif (password_verify($password, $user['password'])) {
561                         //New password hash
562                         if (password_needs_rehash($user['password'], PASSWORD_DEFAULT)) {
563                                 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
564                         }
565
566                         return $user['uid'];
567                 } else {
568                         return self::getIdFromAuthenticateHooks($user['nickname'], $password); // throws
569                 }
570
571                 throw new HTTPException\ForbiddenException(DI::l10n()->t('Login failed'));
572         }
573
574         /**
575          * Try to obtain a user ID via "authenticate" hook addons
576          *
577          * Returns the user id associated with a successful password authentication
578          *
579          * @param string $username
580          * @param string $password
581          * @return int User Id if authentication is successful
582          * @throws HTTPException\ForbiddenException
583          */
584         public static function getIdFromAuthenticateHooks(string $username, string $password): int
585         {
586                 $addon_auth = [
587                         'username'      => $username,
588                         'password'      => $password,
589                         'authenticated' => 0,
590                         'user_record'   => null
591                 ];
592
593                 /*
594                  * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
595                  * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
596                  * and later addons should not interfere with an earlier one that succeeded.
597                  */
598                 Hook::callAll('authenticate', $addon_auth);
599
600                 if ($addon_auth['authenticated'] && $addon_auth['user_record']) {
601                         return $addon_auth['user_record']['uid'];
602                 }
603
604                 throw new HTTPException\ForbiddenException(DI::l10n()->t('Login failed'));
605         }
606
607         /**
608          * Returns authentication info from various parameters types
609          *
610          * User info can be any of the following:
611          * - User DB object
612          * - User Id
613          * - User email or username or nickname
614          * - User array with at least the uid and the hashed password
615          *
616          * @param mixed $user_info
617          * @return array|null Null if not found/determined
618          * @throws HTTPException\NotFoundException
619          */
620         public static function getAuthenticationInfo($user_info)
621         {
622                 $user = null;
623
624                 if (is_object($user_info) || is_array($user_info)) {
625                         if (is_object($user_info)) {
626                                 $user = (array) $user_info;
627                         } else {
628                                 $user = $user_info;
629                         }
630
631                         if (
632                                 !isset($user['uid'])
633                                 || !isset($user['password'])
634                                 || !isset($user['legacy_password'])
635                         ) {
636                                 throw new Exception(DI::l10n()->t('Not enough information to authenticate'));
637                         }
638                 } elseif (is_int($user_info) || is_string($user_info)) {
639                         if (is_int($user_info)) {
640                                 $user = DBA::selectFirst(
641                                         'user',
642                                         ['uid', 'nickname', 'password', 'legacy_password'],
643                                         [
644                                                 'uid' => $user_info,
645                                                 'blocked' => 0,
646                                                 'account_expired' => 0,
647                                                 'account_removed' => 0,
648                                                 'verified' => 1
649                                         ]
650                                 );
651                         } else {
652                                 $fields = ['uid', 'nickname', 'password', 'legacy_password'];
653                                 $condition = [
654                                         "(`email` = ? OR `username` = ? OR `nickname` = ?)
655                                         AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified`",
656                                         $user_info, $user_info, $user_info
657                                 ];
658                                 $user = DBA::selectFirst('user', $fields, $condition);
659                         }
660
661                         if (!DBA::isResult($user)) {
662                                 throw new HTTPException\NotFoundException(DI::l10n()->t('User not found'));
663                         }
664                 }
665
666                 return $user;
667         }
668
669         /**
670          * Update the day of the last activity of the given user
671          *
672          * @param integer $uid
673          * @return void
674          */
675         public static function updateLastActivity(int $uid)
676         {
677                 $user = User::getById($uid, ['last-activity']);
678                 if (empty($user)) {
679                         return;
680                 }
681
682                 $current_day = DateTimeFormat::utcNow('Y-m-d');
683
684                 if ($user['last-activity'] != $current_day) {
685                         User::update(['last-activity' => $current_day], $uid);
686                         // Set the last actitivy for all identities of the user
687                         DBA::update('user', ['last-activity' => $current_day], ['parent-uid' => $uid, 'account_removed' => false]);
688                 }
689         }
690
691         /**
692          * Generates a human-readable random password
693          *
694          * @return string
695          * @throws Exception
696          */
697         public static function generateNewPassword(): string
698         {
699                 return ucfirst(Strings::getRandomName(8)) . random_int(1000, 9999);
700         }
701
702         /**
703          * Checks if the provided plaintext password has been exposed or not
704          *
705          * @param string $password
706          * @return bool
707          * @throws Exception
708          */
709         public static function isPasswordExposed(string $password): bool
710         {
711                 $cache = new CacheItemPool();
712                 $cache->changeConfig([
713                         'cacheDirectory' => System::getTempPath() . '/password-exposed-cache/',
714                 ]);
715
716                 try {
717                         $passwordExposedChecker = new PasswordExposed\PasswordExposedChecker(null, $cache);
718
719                         return $passwordExposedChecker->passwordExposed($password) === PasswordExposed\PasswordStatus::EXPOSED;
720                 } catch (Exception $e) {
721                         Logger::error('Password Exposed Exception: ' . $e->getMessage(), [
722                                 'code' => $e->getCode(),
723                                 'file' => $e->getFile(),
724                                 'line' => $e->getLine(),
725                                 'trace' => $e->getTraceAsString()
726                         ]);
727
728                         return false;
729                 }
730         }
731
732         /**
733          * Legacy hashing function, kept for password migration purposes
734          *
735          * @param string $password
736          * @return string
737          */
738         private static function hashPasswordLegacy(string $password): string
739         {
740                 return hash('whirlpool', $password);
741         }
742
743         /**
744          * Global user password hashing function
745          *
746          * @param string $password
747          * @return string
748          * @throws Exception
749          */
750         public static function hashPassword(string $password): string
751         {
752                 if (!trim($password)) {
753                         throw new Exception(DI::l10n()->t('Password can\'t be empty'));
754                 }
755
756                 return password_hash($password, PASSWORD_DEFAULT);
757         }
758
759         /**
760          * Allowed characters are a-z, A-Z, 0-9 and special characters except white spaces, accentuated letters and colon (:).
761          *
762          * Password length is limited to 72 characters if the current default password hashing algorithm is Blowfish.
763          * From the manual: "Using the PASSWORD_BCRYPT as the algorithm, will result in the password parameter being
764          * truncated to a maximum length of 72 bytes."
765          *
766          * @see https://www.php.net/manual/en/function.password-hash.php#refsect1-function.password-hash-parameters
767          *
768          * @param string|null $delimiter Whether the regular expression is meant to be wrapper in delimiter characters
769          * @return string
770          */
771         public static function getPasswordRegExp(string $delimiter = null): string
772         {
773                 $allowed_characters = '!"#$%&\'()*+,-./;<=>?@[\]^_`{|}~';
774
775                 if ($delimiter) {
776                         $allowed_characters = preg_quote($allowed_characters, $delimiter);
777                 }
778
779                 return '^[a-zA-Z0-9' . $allowed_characters . ']' . (PASSWORD_DEFAULT !== PASSWORD_BCRYPT ? '{1,72}' : '+') . '$';
780         }
781
782         /**
783          * Updates a user row with a new plaintext password
784          *
785          * @param int    $uid
786          * @param string $password
787          * @return bool
788          * @throws Exception
789          */
790         public static function updatePassword(int $uid, string $password): bool
791         {
792                 $password = trim($password);
793
794                 if (empty($password)) {
795                         throw new Exception(DI::l10n()->t('Empty passwords are not allowed.'));
796                 }
797
798                 if (!DI::config()->get('system', 'disable_password_exposed', false) && self::isPasswordExposed($password)) {
799                         throw new Exception(DI::l10n()->t('The new password has been exposed in a public data dump, please choose another.'));
800                 }
801
802                 if (PASSWORD_DEFAULT === PASSWORD_BCRYPT && strlen($password) > 72) {
803                         throw new Exception(DI::l10n()->t('The password length is limited to 72 characters.'));
804                 }
805
806                 if (!preg_match('/' . self::getPasswordRegExp('/') . '/', $password)) {
807                         throw new Exception(DI::l10n()->t('The password can\'t contain accentuated letters, white spaces or colons (:)'));
808                 }
809
810                 return self::updatePasswordHashed($uid, self::hashPassword($password));
811         }
812
813         /**
814          * Updates a user row with a new hashed password.
815          * Empties the password reset token field just in case.
816          *
817          * @param int    $uid
818          * @param string $pasword_hashed
819          * @return bool
820          * @throws Exception
821          */
822         private static function updatePasswordHashed(int $uid, string $pasword_hashed): bool
823         {
824                 $fields = [
825                         'password' => $pasword_hashed,
826                         'pwdreset' => null,
827                         'pwdreset_time' => null,
828                         'legacy_password' => false
829                 ];
830                 return DBA::update('user', $fields, ['uid' => $uid]);
831         }
832
833         /**
834          * Checks if a nickname is in the list of the forbidden nicknames
835          *
836          * Check if a nickname is forbidden from registration on the node by the
837          * admin. Forbidden nicknames (e.g. role namess) can be configured in the
838          * admin panel.
839          *
840          * @param string $nickname The nickname that should be checked
841          * @return boolean True is the nickname is blocked on the node
842          */
843         public static function isNicknameBlocked(string $nickname): bool
844         {
845                 $forbidden_nicknames = DI::config()->get('system', 'forbidden_nicknames', '');
846                 if (!empty($forbidden_nicknames)) {
847                         $forbidden = explode(',', $forbidden_nicknames);
848                         $forbidden = array_map('trim', $forbidden);
849                 } else {
850                         $forbidden = [];
851                 }
852
853                 // Add the name of the internal actor to the "forbidden" list
854                 $actor_name = self::getActorName();
855                 if (!empty($actor_name)) {
856                         $forbidden[] = $actor_name;
857                 }
858
859                 if (empty($forbidden)) {
860                         return false;
861                 }
862
863                 // check if the nickname is in the list of blocked nicknames
864                 if (in_array(strtolower($nickname), $forbidden)) {
865                         return true;
866                 }
867
868                 // else return false
869                 return false;
870         }
871
872         /**
873          * Get avatar link for given user
874          *
875          * @param array  $user
876          * @param string $size One of the Proxy::SIZE_* constants
877          * @return string avatar link
878          * @throws Exception
879          */
880         public static function getAvatarUrl(array $user, string $size = ''): string
881         {
882                 if (empty($user['nickname'])) {
883                         DI::logger()->warning('Missing user nickname key', ['trace' => System::callstack(20)]);
884                 }
885
886                 $url = DI::baseUrl() . '/photo/';
887
888                 switch ($size) {
889                         case Proxy::SIZE_MICRO:
890                                 $url .= 'micro/';
891                                 $scale = 6;
892                                 break;
893                         case Proxy::SIZE_THUMB:
894                                 $url .= 'avatar/';
895                                 $scale = 5;
896                                 break;
897                         default:
898                                 $url .= 'profile/';
899                                 $scale = 4;
900                                 break;
901                 }
902
903                 $updated  =  '';
904                 $mimetype = '';
905
906                 $photo = Photo::selectFirst(['type', 'created', 'edited', 'updated'], ["scale" => $scale, 'uid' => $user['uid'], 'profile' => true]);
907                 if (!empty($photo)) {
908                         $updated  = max($photo['created'], $photo['edited'], $photo['updated']);
909                         $mimetype = $photo['type'];
910                 }
911
912                 return $url . $user['nickname'] . Images::getExtensionByMimeType($mimetype) . ($updated ? '?ts=' . strtotime($updated) : '');
913         }
914
915         /**
916          * Get banner link for given user
917          *
918          * @param array  $user
919          * @return string banner link
920          * @throws Exception
921          */
922         public static function getBannerUrl(array $user): string
923         {
924                 if (empty($user['nickname'])) {
925                         DI::logger()->warning('Missing user nickname key', ['trace' => System::callstack(20)]);
926                 }
927
928                 $url = DI::baseUrl() . '/photo/banner/';
929
930                 $updated  = '';
931                 $mimetype = '';
932
933                 $photo = Photo::selectFirst(['type', 'created', 'edited', 'updated'], ["scale" => 3, 'uid' => $user['uid'], 'photo-type' => Photo::USER_BANNER]);
934                 if (!empty($photo)) {
935                         $updated  = max($photo['created'], $photo['edited'], $photo['updated']);
936                         $mimetype = $photo['type'];
937                 } else {
938                         // Only for the RC phase: Don't return an image link for the default picture
939                         return '';
940                 }
941
942                 return $url . $user['nickname'] . Images::getExtensionByMimeType($mimetype) . ($updated ? '?ts=' . strtotime($updated) : '');
943         }
944
945         /**
946          * Catch-all user creation function
947          *
948          * Creates a user from the provided data array, either form fields or OpenID.
949          * Required: { username, nickname, email } or { openid_url }
950          *
951          * Performs the following:
952          * - Sends to the OpenId auth URL (if relevant)
953          * - Creates new key pairs for crypto
954          * - Create self-contact
955          * - Create profile image
956          *
957          * @param  array $data
958          * @return array
959          * @throws ErrorException
960          * @throws HTTPException\InternalServerErrorException
961          * @throws ImagickException
962          * @throws Exception
963          */
964         public static function create(array $data): array
965         {
966                 $return = ['user' => null, 'password' => ''];
967
968                 $using_invites = DI::config()->get('system', 'invitation_only');
969
970                 $invite_id  = !empty($data['invite_id'])  ? trim($data['invite_id'])  : '';
971                 $username   = !empty($data['username'])   ? trim($data['username'])   : '';
972                 $nickname   = !empty($data['nickname'])   ? trim($data['nickname'])   : '';
973                 $email      = !empty($data['email'])      ? trim($data['email'])      : '';
974                 $openid_url = !empty($data['openid_url']) ? trim($data['openid_url']) : '';
975                 $photo      = !empty($data['photo'])      ? trim($data['photo'])      : '';
976                 $password   = !empty($data['password'])   ? trim($data['password'])   : '';
977                 $password1  = !empty($data['password1'])  ? trim($data['password1'])  : '';
978                 $confirm    = !empty($data['confirm'])    ? trim($data['confirm'])    : '';
979                 $blocked    = !empty($data['blocked']);
980                 $verified   = !empty($data['verified']);
981                 $language   = !empty($data['language'])   ? trim($data['language'])   : 'en';
982
983                 $netpublish = $publish = !empty($data['profile_publish_reg']);
984
985                 if ($password1 != $confirm) {
986                         throw new Exception(DI::l10n()->t('Passwords do not match. Password unchanged.'));
987                 } elseif ($password1 != '') {
988                         $password = $password1;
989                 }
990
991                 if ($using_invites) {
992                         if (!$invite_id) {
993                                 throw new Exception(DI::l10n()->t('An invitation is required.'));
994                         }
995
996                         if (!Register::existsByHash($invite_id)) {
997                                 throw new Exception(DI::l10n()->t('Invitation could not be verified.'));
998                         }
999                 }
1000
1001                 /// @todo Check if this part is really needed. We should have fetched all this data in advance
1002                 if (empty($username) || empty($email) || empty($nickname)) {
1003                         if ($openid_url) {
1004                                 if (!Network::isUrlValid($openid_url)) {
1005                                         throw new Exception(DI::l10n()->t('Invalid OpenID url'));
1006                                 }
1007                                 $_SESSION['register'] = 1;
1008                                 $_SESSION['openid'] = $openid_url;
1009
1010                                 $openid = new LightOpenID(DI::baseUrl()->getHostname());
1011                                 $openid->identity = $openid_url;
1012                                 $openid->returnUrl = DI::baseUrl() . '/openid';
1013                                 $openid->required = ['namePerson/friendly', 'contact/email', 'namePerson'];
1014                                 $openid->optional = ['namePerson/first', 'media/image/aspect11', 'media/image/default'];
1015                                 try {
1016                                         $authurl = $openid->authUrl();
1017                                 } catch (Exception $e) {
1018                                         throw new Exception(DI::l10n()->t('We encountered a problem while logging in with the OpenID you provided. Please check the correct spelling of the ID.') . '<br />' . DI::l10n()->t('The error message was:') . $e->getMessage(), 0, $e);
1019                                 }
1020                                 System::externalRedirect($authurl);
1021                                 // NOTREACHED
1022                         }
1023
1024                         throw new Exception(DI::l10n()->t('Please enter the required information.'));
1025                 }
1026
1027                 if (!Network::isUrlValid($openid_url)) {
1028                         $openid_url = '';
1029                 }
1030
1031                 // collapse multiple spaces in name
1032                 $username = preg_replace('/ +/', ' ', $username);
1033
1034                 $username_min_length = max(1, min(64, intval(DI::config()->get('system', 'username_min_length', 3))));
1035                 $username_max_length = max(1, min(64, intval(DI::config()->get('system', 'username_max_length', 48))));
1036
1037                 if ($username_min_length > $username_max_length) {
1038                         Logger::error(DI::l10n()->t('system.username_min_length (%s) and system.username_max_length (%s) are excluding each other, swapping values.', $username_min_length, $username_max_length));
1039                         $tmp = $username_min_length;
1040                         $username_min_length = $username_max_length;
1041                         $username_max_length = $tmp;
1042                 }
1043
1044                 if (mb_strlen($username) < $username_min_length) {
1045                         throw new Exception(DI::l10n()->tt('Username should be at least %s character.', 'Username should be at least %s characters.', $username_min_length));
1046                 }
1047
1048                 if (mb_strlen($username) > $username_max_length) {
1049                         throw new Exception(DI::l10n()->tt('Username should be at most %s character.', 'Username should be at most %s characters.', $username_max_length));
1050                 }
1051
1052                 // So now we are just looking for a space in the full name.
1053                 $loose_reg = DI::config()->get('system', 'no_regfullname');
1054                 if (!$loose_reg) {
1055                         $username = mb_convert_case($username, MB_CASE_TITLE, 'UTF-8');
1056                         if (strpos($username, ' ') === false) {
1057                                 throw new Exception(DI::l10n()->t("That doesn't appear to be your full (First Last) name."));
1058                         }
1059                 }
1060
1061                 if (!Network::isEmailDomainAllowed($email)) {
1062                         throw new Exception(DI::l10n()->t('Your email domain is not among those allowed on this site.'));
1063                 }
1064
1065                 if (!filter_var($email, FILTER_VALIDATE_EMAIL) || !Network::isEmailDomainValid($email)) {
1066                         throw new Exception(DI::l10n()->t('Not a valid email address.'));
1067                 }
1068                 if (self::isNicknameBlocked($nickname)) {
1069                         throw new Exception(DI::l10n()->t('The nickname was blocked from registration by the nodes admin.'));
1070                 }
1071
1072                 if (DI::config()->get('system', 'block_extended_register', false) && DBA::exists('user', ['email' => $email])) {
1073                         throw new Exception(DI::l10n()->t('Cannot use that email.'));
1074                 }
1075
1076                 // Disallow somebody creating an account using openid that uses the admin email address,
1077                 // since openid bypasses email verification. We'll allow it if there is not yet an admin account.
1078                 if (strlen($openid_url) && in_array(strtolower($email), self::getAdminEmailList())) {
1079                         throw new Exception(DI::l10n()->t('Cannot use that email.'));
1080                 }
1081
1082                 $nickname = $data['nickname'] = strtolower($nickname);
1083
1084                 if (!preg_match('/^[a-z0-9][a-z0-9_]*$/', $nickname)) {
1085                         throw new Exception(DI::l10n()->t('Your nickname can only contain a-z, 0-9 and _.'));
1086                 }
1087
1088                 // Check existing and deleted accounts for this nickname.
1089                 if (
1090                         DBA::exists('user', ['nickname' => $nickname])
1091                         || DBA::exists('userd', ['username' => $nickname])
1092                 ) {
1093                         throw new Exception(DI::l10n()->t('Nickname is already registered. Please choose another.'));
1094                 }
1095
1096                 $new_password = strlen($password) ? $password : User::generateNewPassword();
1097                 $new_password_encoded = self::hashPassword($new_password);
1098
1099                 $return['password'] = $new_password;
1100
1101                 $keys = Crypto::newKeypair(4096);
1102                 if ($keys === false) {
1103                         throw new Exception(DI::l10n()->t('SERIOUS ERROR: Generation of security keys failed.'));
1104                 }
1105
1106                 $prvkey = $keys['prvkey'];
1107                 $pubkey = $keys['pubkey'];
1108
1109                 // Create another keypair for signing/verifying salmon protocol messages.
1110                 $sres = Crypto::newKeypair(512);
1111                 $sprvkey = $sres['prvkey'];
1112                 $spubkey = $sres['pubkey'];
1113
1114                 $insert_result = DBA::insert('user', [
1115                         'guid'     => System::createUUID(),
1116                         'username' => $username,
1117                         'password' => $new_password_encoded,
1118                         'email'    => $email,
1119                         'openid'   => $openid_url,
1120                         'nickname' => $nickname,
1121                         'pubkey'   => $pubkey,
1122                         'prvkey'   => $prvkey,
1123                         'spubkey'  => $spubkey,
1124                         'sprvkey'  => $sprvkey,
1125                         'verified' => $verified,
1126                         'blocked'  => $blocked,
1127                         'language' => $language,
1128                         'timezone' => 'UTC',
1129                         'register_date' => DateTimeFormat::utcNow(),
1130                         'default-location' => ''
1131                 ]);
1132
1133                 if ($insert_result) {
1134                         $uid = DBA::lastInsertId();
1135                         $user = DBA::selectFirst('user', [], ['uid' => $uid]);
1136                 } else {
1137                         throw new Exception(DI::l10n()->t('An error occurred during registration. Please try again.'));
1138                 }
1139
1140                 if (!$uid) {
1141                         throw new Exception(DI::l10n()->t('An error occurred during registration. Please try again.'));
1142                 }
1143
1144                 // if somebody clicked submit twice very quickly, they could end up with two accounts
1145                 // due to race condition. Remove this one.
1146                 $user_count = DBA::count('user', ['nickname' => $nickname]);
1147                 if ($user_count > 1) {
1148                         DBA::delete('user', ['uid' => $uid]);
1149
1150                         throw new Exception(DI::l10n()->t('Nickname is already registered. Please choose another.'));
1151                 }
1152
1153                 $insert_result = DBA::insert('profile', [
1154                         'uid' => $uid,
1155                         'name' => $username,
1156                         'photo' => self::getAvatarUrl($user),
1157                         'thumb' => self::getAvatarUrl($user, Proxy::SIZE_THUMB),
1158                         'publish' => $publish,
1159                         'net-publish' => $netpublish,
1160                 ]);
1161                 if (!$insert_result) {
1162                         DBA::delete('user', ['uid' => $uid]);
1163
1164                         throw new Exception(DI::l10n()->t('An error occurred creating your default profile. Please try again.'));
1165                 }
1166
1167                 // Create the self contact
1168                 if (!Contact::createSelfFromUserId($uid)) {
1169                         DBA::delete('user', ['uid' => $uid]);
1170
1171                         throw new Exception(DI::l10n()->t('An error occurred creating your self contact. Please try again.'));
1172                 }
1173
1174                 // Create a group with no members. This allows somebody to use it
1175                 // right away as a default group for new contacts.
1176                 $def_gid = Group::create($uid, DI::l10n()->t('Friends'));
1177                 if (!$def_gid) {
1178                         DBA::delete('user', ['uid' => $uid]);
1179
1180                         throw new Exception(DI::l10n()->t('An error occurred creating your default contact group. Please try again.'));
1181                 }
1182
1183                 $fields = ['def_gid' => $def_gid];
1184                 if (DI::config()->get('system', 'newuser_private') && $def_gid) {
1185                         $fields['allow_gid'] = '<' . $def_gid . '>';
1186                 }
1187
1188                 DBA::update('user', $fields, ['uid' => $uid]);
1189
1190                 // if we have no OpenID photo try to look up an avatar
1191                 if (!strlen($photo)) {
1192                         $photo = Network::lookupAvatarByEmail($email);
1193                 }
1194
1195                 // unless there is no avatar-addon loaded
1196                 if (strlen($photo)) {
1197                         $photo_failure = false;
1198
1199                         $filename = basename($photo);
1200                         $curlResult = DI::httpClient()->get($photo, HttpClientAccept::IMAGE);
1201                         if ($curlResult->isSuccess()) {
1202                                 Logger::debug('Got picture', ['Content-Type' => $curlResult->getHeader('Content-Type'), 'url' => $photo]);
1203                                 $img_str = $curlResult->getBody();
1204                                 $type = $curlResult->getContentType();
1205                         } else {
1206                                 $img_str = '';
1207                                 $type = '';
1208                         }
1209
1210                         $type = Images::getMimeTypeByData($img_str, $photo, $type);
1211
1212                         $image = new Image($img_str, $type);
1213                         if ($image->isValid()) {
1214                                 $image->scaleToSquare(300);
1215
1216                                 $resource_id = Photo::newResource();
1217
1218                                 // Not using Photo::PROFILE_PHOTOS here, so that it is discovered as translateble string
1219                                 $profile_album = DI::l10n()->t('Profile Photos');
1220
1221                                 $r = Photo::store($image, $uid, 0, $resource_id, $filename, $profile_album, 4);
1222
1223                                 if ($r === false) {
1224                                         $photo_failure = true;
1225                                 }
1226
1227                                 $image->scaleDown(80);
1228
1229                                 $r = Photo::store($image, $uid, 0, $resource_id, $filename, $profile_album, 5);
1230
1231                                 if ($r === false) {
1232                                         $photo_failure = true;
1233                                 }
1234
1235                                 $image->scaleDown(48);
1236
1237                                 $r = Photo::store($image, $uid, 0, $resource_id, $filename, $profile_album, 6);
1238
1239                                 if ($r === false) {
1240                                         $photo_failure = true;
1241                                 }
1242
1243                                 if (!$photo_failure) {
1244                                         Photo::update(['profile' => true, 'photo-type' => Photo::USER_AVATAR], ['resource-id' => $resource_id]);
1245                                 }
1246                         }
1247
1248                         Contact::updateSelfFromUserID($uid, true);
1249                 }
1250
1251                 Hook::callAll('register_account', $uid);
1252
1253                 $return['user'] = $user;
1254                 return $return;
1255         }
1256
1257         /**
1258          * Update a user entry and distribute the changes if needed
1259          *
1260          * @param array $fields
1261          * @param integer $uid
1262          * @return boolean
1263          */
1264         public static function update(array $fields, int $uid): bool
1265         {
1266                 $old_owner = self::getOwnerDataById($uid);
1267                 if (empty($old_owner)) {
1268                         return false;
1269                 }
1270
1271                 if (!DBA::update('user', $fields, ['uid' => $uid])) {
1272                         return false;
1273                 }
1274
1275                 $update = Contact::updateSelfFromUserID($uid);
1276
1277                 $owner = self::getOwnerDataById($uid);
1278                 if (empty($owner)) {
1279                         return false;
1280                 }
1281
1282                 if ($old_owner['name'] != $owner['name']) {
1283                         Profile::update(['name' => $owner['name']], $uid);
1284                 }
1285
1286                 if ($update) {
1287                         Profile::publishUpdate($uid);
1288                 }
1289
1290                 return true;
1291         }
1292
1293         /**
1294          * Sets block state for a given user
1295          *
1296          * @param int  $uid   The user id
1297          * @param bool $block Block state (default is true)
1298          *
1299          * @return bool True, if successfully blocked
1300
1301          * @throws Exception
1302          */
1303         public static function block(int $uid, bool $block = true): bool
1304         {
1305                 return DBA::update('user', ['blocked' => $block], ['uid' => $uid]);
1306         }
1307
1308         /**
1309          * Allows a registration based on a hash
1310          *
1311          * @param string $hash
1312          *
1313          * @return bool True, if the allow was successful
1314          *
1315          * @throws HTTPException\InternalServerErrorException
1316          * @throws Exception
1317          */
1318         public static function allow(string $hash): bool
1319         {
1320                 $register = Register::getByHash($hash);
1321                 if (!DBA::isResult($register)) {
1322                         return false;
1323                 }
1324
1325                 $user = User::getById($register['uid']);
1326                 if (!DBA::isResult($user)) {
1327                         return false;
1328                 }
1329
1330                 Register::deleteByHash($hash);
1331
1332                 DBA::update('user', ['blocked' => false, 'verified' => true], ['uid' => $register['uid']]);
1333
1334                 $profile = DBA::selectFirst('profile', ['net-publish'], ['uid' => $register['uid']]);
1335
1336                 if (DBA::isResult($profile) && $profile['net-publish'] && Search::getGlobalDirectory()) {
1337                         $url = DI::baseUrl() . '/profile/' . $user['nickname'];
1338                         Worker::add(Worker::PRIORITY_LOW, "Directory", $url);
1339                 }
1340
1341                 $l10n = DI::l10n()->withLang($register['language']);
1342
1343                 return User::sendRegisterOpenEmail(
1344                         $l10n,
1345                         $user,
1346                         DI::config()->get('config', 'sitename'),
1347                         DI::baseUrl()->get(),
1348                         ($register['password'] ?? '') ?: 'Sent in a previous email'
1349                 );
1350         }
1351
1352         /**
1353          * Denys a pending registration
1354          *
1355          * @param string $hash The hash of the pending user
1356          *
1357          * This does not have to go through user_remove() and save the nickname
1358          * permanently against re-registration, as the person was not yet
1359          * allowed to have friends on this system
1360          *
1361          * @return bool True, if the deny was successfull
1362          * @throws Exception
1363          */
1364         public static function deny(string $hash): bool
1365         {
1366                 $register = Register::getByHash($hash);
1367                 if (!DBA::isResult($register)) {
1368                         return false;
1369                 }
1370
1371                 $user = User::getById($register['uid']);
1372                 if (!DBA::isResult($user)) {
1373                         return false;
1374                 }
1375
1376                 // Delete the avatar
1377                 Photo::delete(['uid' => $register['uid']]);
1378
1379                 return DBA::delete('user', ['uid' => $register['uid']]) &&
1380                        Register::deleteByHash($register['hash']);
1381         }
1382
1383         /**
1384          * Creates a new user based on a minimal set and sends an email to this user
1385          *
1386          * @param string $name  The user's name
1387          * @param string $email The user's email address
1388          * @param string $nick  The user's nick name
1389          * @param string $lang  The user's language (default is english)
1390          * @return bool True, if the user was created successfully
1391          * @throws HTTPException\InternalServerErrorException
1392          * @throws ErrorException
1393          * @throws ImagickException
1394          */
1395         public static function createMinimal(string $name, string $email, string $nick, string $lang = L10n::DEFAULT): bool
1396         {
1397                 if (empty($name) ||
1398                     empty($email) ||
1399                     empty($nick)) {
1400                         throw new HTTPException\InternalServerErrorException('Invalid arguments.');
1401                 }
1402
1403                 $result = self::create([
1404                         'username' => $name,
1405                         'email' => $email,
1406                         'nickname' => $nick,
1407                         'verified' => 1,
1408                         'language' => $lang
1409                 ]);
1410
1411                 $user = $result['user'];
1412                 $preamble = Strings::deindent(DI::l10n()->t('
1413                 Dear %1$s,
1414                         the administrator of %2$s has set up an account for you.'));
1415                 $body = Strings::deindent(DI::l10n()->t('
1416                 The login details are as follows:
1417
1418                 Site Location:  %1$s
1419                 Login Name:             %2$s
1420                 Password:               %3$s
1421
1422                 You may change your password from your account "Settings" page after logging
1423                 in.
1424
1425                 Please take a few moments to review the other account settings on that page.
1426
1427                 You may also wish to add some basic information to your default profile
1428                 (on the "Profiles" page) so that other people can easily find you.
1429
1430                 We recommend setting your full name, adding a profile photo,
1431                 adding some profile "keywords" (very useful in making new friends) - and
1432                 perhaps what country you live in; if you do not wish to be more specific
1433                 than that.
1434
1435                 We fully respect your right to privacy, and none of these items are necessary.
1436                 If you are new and do not know anybody here, they may help
1437                 you to make some new and interesting friends.
1438
1439                 If you ever want to delete your account, you can do so at %1$s/settings/removeme
1440
1441                 Thank you and welcome to %4$s.'));
1442
1443                 $preamble = sprintf($preamble, $user['username'], DI::config()->get('config', 'sitename'));
1444                 $body = sprintf($body, DI::baseUrl()->get(), $user['nickname'], $result['password'], DI::config()->get('config', 'sitename'));
1445
1446                 $email = DI::emailer()
1447                         ->newSystemMail()
1448                         ->withMessage(DI::l10n()->t('Registration details for %s', DI::config()->get('config', 'sitename')), $preamble, $body)
1449                         ->forUser($user)
1450                         ->withRecipient($user['email'])
1451                         ->build();
1452                 return DI::emailer()->send($email);
1453         }
1454
1455         /**
1456          * Sends pending registration confirmation email
1457          *
1458          * @param array  $user     User record array
1459          * @param string $sitename
1460          * @param string $siteurl
1461          * @param string $password Plaintext password
1462          * @return NULL|boolean from notification() and email() inherited
1463          * @throws HTTPException\InternalServerErrorException
1464          */
1465         public static function sendRegisterPendingEmail(array $user, string $sitename, string $siteurl, string $password)
1466         {
1467                 $body = Strings::deindent(DI::l10n()->t(
1468                         '
1469                         Dear %1$s,
1470                                 Thank you for registering at %2$s. Your account is pending for approval by the administrator.
1471
1472                         Your login details are as follows:
1473
1474                         Site Location:  %3$s
1475                         Login Name:             %4$s
1476                         Password:               %5$s
1477                 ',
1478                         $user['username'],
1479                         $sitename,
1480                         $siteurl,
1481                         $user['nickname'],
1482                         $password
1483                 ));
1484
1485                 $email = DI::emailer()
1486                         ->newSystemMail()
1487                         ->withMessage(DI::l10n()->t('Registration at %s', $sitename), $body)
1488                         ->forUser($user)
1489                         ->withRecipient($user['email'])
1490                         ->build();
1491                 return DI::emailer()->send($email);
1492         }
1493
1494         /**
1495          * Sends registration confirmation
1496          *
1497          * It's here as a function because the mail is sent from different parts
1498          *
1499          * @param L10n   $l10n     The used language
1500          * @param array  $user     User record array
1501          * @param string $sitename
1502          * @param string $siteurl
1503          * @param string $password Plaintext password
1504          *
1505          * @return NULL|boolean from notification() and email() inherited
1506          * @throws HTTPException\InternalServerErrorException
1507          */
1508         public static function sendRegisterOpenEmail(L10n $l10n, array $user, string $sitename, string $siteurl, string $password)
1509         {
1510                 $preamble = Strings::deindent($l10n->t(
1511                         '
1512                                 Dear %1$s,
1513                                 Thank you for registering at %2$s. Your account has been created.
1514                         ',
1515                         $user['username'],
1516                         $sitename
1517                 ));
1518                 $body = Strings::deindent($l10n->t(
1519                         '
1520                         The login details are as follows:
1521
1522                         Site Location:  %3$s
1523                         Login Name:             %1$s
1524                         Password:               %5$s
1525
1526                         You may change your password from your account "Settings" page after logging
1527                         in.
1528
1529                         Please take a few moments to review the other account settings on that page.
1530
1531                         You may also wish to add some basic information to your default profile
1532                         ' . "\x28" . 'on the "Profiles" page' . "\x29" . ' so that other people can easily find you.
1533
1534                         We recommend setting your full name, adding a profile photo,
1535                         adding some profile "keywords" ' . "\x28" . 'very useful in making new friends' . "\x29" . ' - and
1536                         perhaps what country you live in; if you do not wish to be more specific
1537                         than that.
1538
1539                         We fully respect your right to privacy, and none of these items are necessary.
1540                         If you are new and do not know anybody here, they may help
1541                         you to make some new and interesting friends.
1542
1543                         If you ever want to delete your account, you can do so at %3$s/settings/removeme
1544
1545                         Thank you and welcome to %2$s.',
1546                         $user['nickname'],
1547                         $sitename,
1548                         $siteurl,
1549                         $user['username'],
1550                         $password
1551                 ));
1552
1553                 $email = DI::emailer()
1554                         ->newSystemMail()
1555                         ->withMessage(DI::l10n()->t('Registration details for %s', $sitename), $preamble, $body)
1556                         ->forUser($user)
1557                         ->withRecipient($user['email'])
1558                         ->build();
1559                 return DI::emailer()->send($email);
1560         }
1561
1562         /**
1563          * @param int $uid user to remove
1564          * @return bool
1565          * @throws HTTPException\InternalServerErrorException
1566          */
1567         public static function remove(int $uid): bool
1568         {
1569                 if (empty($uid)) {
1570                         return false;
1571                 }
1572
1573                 Logger::notice('Removing user', ['user' => $uid]);
1574
1575                 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
1576
1577                 Hook::callAll('remove_user', $user);
1578
1579                 // save username (actually the nickname as it is guaranteed
1580                 // unique), so it cannot be re-registered in the future.
1581                 DBA::insert('userd', ['username' => $user['nickname']]);
1582
1583                 // Remove all personal settings, especially connector settings
1584                 DBA::delete('pconfig', ['uid' => $uid]);
1585
1586                 // The user and related data will be deleted in Friendica\Worker\ExpireAndRemoveUsers
1587                 DBA::update('user', ['account_removed' => true, 'account_expires_on' => DateTimeFormat::utc('now + 7 day')], ['uid' => $uid]);
1588                 Worker::add(Worker::PRIORITY_HIGH, 'Notifier', Delivery::REMOVAL, $uid);
1589
1590                 // Send an update to the directory
1591                 $self = DBA::selectFirst('contact', ['url'], ['uid' => $uid, 'self' => true]);
1592                 Worker::add(Worker::PRIORITY_LOW, 'Directory', $self['url']);
1593
1594                 // Remove the user relevant data
1595                 Worker::add(Worker::PRIORITY_NEGLIGIBLE, 'RemoveUser', $uid);
1596
1597                 return true;
1598         }
1599
1600         /**
1601          * Return all identities to a user
1602          *
1603          * @param int $uid The user id
1604          * @return array All identities for this user
1605          *
1606          * Example for a return:
1607          *    [
1608          *        [
1609          *            'uid' => 1,
1610          *            'username' => 'maxmuster',
1611          *            'nickname' => 'Max Mustermann'
1612          *        ],
1613          *        [
1614          *            'uid' => 2,
1615          *            'username' => 'johndoe',
1616          *            'nickname' => 'John Doe'
1617          *        ]
1618          *    ]
1619          * @throws Exception
1620          */
1621         public static function identities(int $uid): array
1622         {
1623                 if (empty($uid)) {
1624                         return [];
1625                 }
1626
1627                 $identities = [];
1628
1629                 $user = DBA::selectFirst('user', ['uid', 'nickname', 'username', 'parent-uid'], ['uid' => $uid]);
1630                 if (!DBA::isResult($user)) {
1631                         return $identities;
1632                 }
1633
1634                 if ($user['parent-uid'] == 0) {
1635                         // First add our own entry
1636                         $identities = [[
1637                                 'uid' => $user['uid'],
1638                                 'username' => $user['username'],
1639                                 'nickname' => $user['nickname']
1640                         ]];
1641
1642                         // Then add all the children
1643                         $r = DBA::select(
1644                                 'user',
1645                                 ['uid', 'username', 'nickname'],
1646                                 ['parent-uid' => $user['uid'], 'account_removed' => false]
1647                         );
1648                         if (DBA::isResult($r)) {
1649                                 $identities = array_merge($identities, DBA::toArray($r));
1650                         }
1651                 } else {
1652                         // First entry is our parent
1653                         $r = DBA::select(
1654                                 'user',
1655                                 ['uid', 'username', 'nickname'],
1656                                 ['uid' => $user['parent-uid'], 'account_removed' => false]
1657                         );
1658                         if (DBA::isResult($r)) {
1659                                 $identities = DBA::toArray($r);
1660                         }
1661
1662                         // Then add all siblings
1663                         $r = DBA::select(
1664                                 'user',
1665                                 ['uid', 'username', 'nickname'],
1666                                 ['parent-uid' => $user['parent-uid'], 'account_removed' => false]
1667                         );
1668                         if (DBA::isResult($r)) {
1669                                 $identities = array_merge($identities, DBA::toArray($r));
1670                         }
1671                 }
1672
1673                 $r = DBA::p(
1674                         "SELECT `user`.`uid`, `user`.`username`, `user`.`nickname`
1675                         FROM `manage`
1676                         INNER JOIN `user` ON `manage`.`mid` = `user`.`uid`
1677                         WHERE `user`.`account_removed` = 0 AND `manage`.`uid` = ?",
1678                         $user['uid']
1679                 );
1680                 if (DBA::isResult($r)) {
1681                         $identities = array_merge($identities, DBA::toArray($r));
1682                 }
1683
1684                 return $identities;
1685         }
1686
1687         /**
1688          * Check if the given user id has delegations or is delegated
1689          *
1690          * @param int $uid
1691          * @return bool
1692          */
1693         public static function hasIdentities(int $uid): bool
1694         {
1695                 if (empty($uid)) {
1696                         return false;
1697                 }
1698
1699                 $user = DBA::selectFirst('user', ['parent-uid'], ['uid' => $uid, 'account_removed' => false]);
1700                 if (!DBA::isResult($user)) {
1701                         return false;
1702                 }
1703
1704                 if ($user['parent-uid'] != 0) {
1705                         return true;
1706                 }
1707
1708                 if (DBA::exists('user', ['parent-uid' => $uid, 'account_removed' => false])) {
1709                         return true;
1710                 }
1711
1712                 if (DBA::exists('manage', ['uid' => $uid])) {
1713                         return true;
1714                 }
1715
1716                 return false;
1717         }
1718
1719         /**
1720          * Returns statistical information about the current users of this node
1721          *
1722          * @return array
1723          *
1724          * @throws Exception
1725          */
1726         public static function getStatistics(): array
1727         {
1728                 $statistics = [
1729                         'total_users'           => 0,
1730                         'active_users_halfyear' => 0,
1731                         'active_users_monthly'  => 0,
1732                         'active_users_weekly'   => 0,
1733                 ];
1734
1735                 $userStmt = DBA::select('owner-view', ['uid', 'last-activity', 'last-item'],
1736                         ["`verified` AND `last-activity` > ? AND NOT `blocked`
1737                         AND NOT `account_removed` AND NOT `account_expired`",
1738                         DBA::NULL_DATETIME]);
1739                 if (!DBA::isResult($userStmt)) {
1740                         return $statistics;
1741                 }
1742
1743                 $halfyear = time() - (180 * 24 * 60 * 60);
1744                 $month = time() - (30 * 24 * 60 * 60);
1745                 $week = time() - (7 * 24 * 60 * 60);
1746
1747                 while ($user = DBA::fetch($userStmt)) {
1748                         $statistics['total_users']++;
1749
1750                         if ((strtotime($user['last-activity']) > $halfyear) || (strtotime($user['last-item']) > $halfyear)
1751                         ) {
1752                                 $statistics['active_users_halfyear']++;
1753                         }
1754
1755                         if ((strtotime($user['last-activity']) > $month) || (strtotime($user['last-item']) > $month)
1756                         ) {
1757                                 $statistics['active_users_monthly']++;
1758                         }
1759
1760                         if ((strtotime($user['last-activity']) > $week) || (strtotime($user['last-item']) > $week)
1761                         ) {
1762                                 $statistics['active_users_weekly']++;
1763                         }
1764                 }
1765                 DBA::close($userStmt);
1766
1767                 return $statistics;
1768         }
1769
1770         /**
1771          * Get all users of the current node
1772          *
1773          * @param int    $start Start count (Default is 0)
1774          * @param int    $count Count of the items per page (Default is @see Pager::ITEMS_PER_PAGE)
1775          * @param string $type  The type of users, which should get (all, bocked, removed)
1776          * @param string $order Order of the user list (Default is 'contact.name')
1777          * @param bool   $descending Order direction (Default is ascending)
1778          * @return array|bool The list of the users
1779          * @throws Exception
1780          */
1781         public static function getList(int $start = 0, int $count = Pager::ITEMS_PER_PAGE, string $type = 'all', string $order = 'name', bool $descending = false)
1782         {
1783                 $param = ['limit' => [$start, $count], 'order' => [$order => $descending]];
1784                 $condition = [];
1785                 switch ($type) {
1786                         case 'active':
1787                                 $condition['account_removed'] = false;
1788                                 $condition['blocked'] = false;
1789                                 break;
1790
1791                         case 'blocked':
1792                                 $condition['account_removed'] = false;
1793                                 $condition['blocked'] = true;
1794                                 $condition['verified'] = true;
1795                                 break;
1796
1797                         case 'removed':
1798                                 $condition['account_removed'] = true;
1799                                 break;
1800                 }
1801
1802                 return DBA::selectToArray('owner-view', [], $condition, $param);
1803         }
1804
1805         /**
1806          * Returns a list of lowercase admin email addresses from the comma-separated list in the config
1807          *
1808          * @return array
1809          */
1810         public static function getAdminEmailList(): array
1811         {
1812                 $adminEmails = strtolower(str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1813                 if (!$adminEmails) {
1814                         return [];
1815                 }
1816
1817                 return explode(',', $adminEmails);
1818         }
1819
1820         /**
1821          * Returns the complete list of admin user accounts
1822          *
1823          * @param array $fields
1824          * @return array
1825          * @throws Exception
1826          */
1827         public static function getAdminList(array $fields = []): array
1828         {
1829                 $condition = [
1830                         'email'           => self::getAdminEmailList(),
1831                         'parent-uid'      => 0,
1832                         'blocked'         => 0,
1833                         'verified'        => true,
1834                         'account_removed' => false,
1835                         'account_expired' => false,
1836                 ];
1837
1838                 return DBA::selectToArray('user', $fields, $condition, ['order' => ['uid']]);
1839         }
1840
1841         /**
1842          * Return a list of admin user accounts where each unique email address appears only once.
1843          *
1844          * This method is meant for admin notifications that do not need to be sent multiple times to the same email address.
1845          *
1846          * @param array $fields
1847          * @return array
1848          * @throws Exception
1849          */
1850         public static function getAdminListForEmailing(array $fields = []): array
1851         {
1852                 return array_filter(self::getAdminList($fields), function ($user) {
1853                         static $emails = [];
1854
1855                         if (in_array($user['email'], $emails)) {
1856                                 return false;
1857                         }
1858
1859                         $emails[] = $user['email'];
1860
1861                         return true;
1862                 });
1863         }
1864 }