]> git.mxchange.org Git - friendica.git/blob - src/Model/User.php
e7f2f89ad6f09bddcdb568fef7372710a0220f59
[friendica.git] / src / Model / User.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
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\PasswordExposed;
25 use Exception;
26 use Friendica\Content\Pager;
27 use Friendica\Core\Hook;
28 use Friendica\Core\L10n;
29 use Friendica\Core\Logger;
30 use Friendica\Core\Protocol;
31 use Friendica\Core\System;
32 use Friendica\Core\Worker;
33 use Friendica\Database\DBA;
34 use Friendica\DI;
35 use Friendica\Model\TwoFactor\AppSpecificPassword;
36 use Friendica\Network\HTTPException\InternalServerErrorException;
37 use Friendica\Object\Image;
38 use Friendica\Util\Crypto;
39 use Friendica\Util\DateTimeFormat;
40 use Friendica\Util\Images;
41 use Friendica\Util\Network;
42 use Friendica\Util\Strings;
43 use Friendica\Worker\Delivery;
44 use LightOpenID;
45
46 /**
47  * This class handles User related functions
48  */
49 class User
50 {
51         /**
52          * Page/profile types
53          *
54          * PAGE_FLAGS_NORMAL is a typical personal profile account
55          * PAGE_FLAGS_SOAPBOX automatically approves all friend requests as Contact::SHARING, (readonly)
56          * PAGE_FLAGS_COMMUNITY automatically approves all friend requests as Contact::SHARING, but with
57          *      write access to wall and comments (no email and not included in page owner's ACL lists)
58          * PAGE_FLAGS_FREELOVE automatically approves all friend requests as full friends (Contact::FRIEND).
59          *
60          * @{
61          */
62         const PAGE_FLAGS_NORMAL    = 0;
63         const PAGE_FLAGS_SOAPBOX   = 1;
64         const PAGE_FLAGS_COMMUNITY = 2;
65         const PAGE_FLAGS_FREELOVE  = 3;
66         const PAGE_FLAGS_BLOG      = 4;
67         const PAGE_FLAGS_PRVGROUP  = 5;
68         /**
69          * @}
70          */
71
72         /**
73          * Account types
74          *
75          * ACCOUNT_TYPE_PERSON - the account belongs to a person
76          *      Associated page types: PAGE_FLAGS_NORMAL, PAGE_FLAGS_SOAPBOX, PAGE_FLAGS_FREELOVE
77          *
78          * ACCOUNT_TYPE_ORGANISATION - the account belongs to an organisation
79          *      Associated page type: PAGE_FLAGS_SOAPBOX
80          *
81          * ACCOUNT_TYPE_NEWS - the account is a news reflector
82          *      Associated page type: PAGE_FLAGS_SOAPBOX
83          *
84          * ACCOUNT_TYPE_COMMUNITY - the account is community forum
85          *      Associated page types: PAGE_COMMUNITY, PAGE_FLAGS_PRVGROUP
86          *
87          * ACCOUNT_TYPE_RELAY - the account is a relay
88          *      This will only be assigned to contacts, not to user accounts
89          * @{
90          */
91         const ACCOUNT_TYPE_PERSON =       0;
92         const ACCOUNT_TYPE_ORGANISATION = 1;
93         const ACCOUNT_TYPE_NEWS =         2;
94         const ACCOUNT_TYPE_COMMUNITY =    3;
95         const ACCOUNT_TYPE_RELAY =        4;
96         /**
97          * @}
98          */
99
100         /**
101          * Returns true if a user record exists with the provided id
102          *
103          * @param  integer $uid
104          * @return boolean
105          * @throws Exception
106          */
107         public static function exists($uid)
108         {
109                 return DBA::exists('user', ['uid' => $uid]);
110         }
111
112         /**
113          * @param  integer       $uid
114          * @param array          $fields
115          * @return array|boolean User record if it exists, false otherwise
116          * @throws Exception
117          */
118         public static function getById($uid, array $fields = [])
119         {
120                 return DBA::selectFirst('user', $fields, ['uid' => $uid]);
121         }
122
123         /**
124          * Returns a user record based on it's GUID
125          *
126          * @param string $guid   The guid of the user
127          * @param array  $fields The fields to retrieve
128          * @param bool   $active True, if only active records are searched
129          *
130          * @return array|boolean User record if it exists, false otherwise
131          * @throws Exception
132          */
133         public static function getByGuid(string $guid, array $fields = [], bool $active = true)
134         {
135                 if ($active) {
136                         $cond = ['guid' => $guid, 'account_expired' => false, 'account_removed' => false];
137                 } else {
138                         $cond = ['guid' => $guid];
139                 }
140
141                 return DBA::selectFirst('user', $fields, $cond);
142         }
143
144         /**
145          * @param  string        $nickname
146          * @param array          $fields
147          * @return array|boolean User record if it exists, false otherwise
148          * @throws Exception
149          */
150         public static function getByNickname($nickname, array $fields = [])
151         {
152                 return DBA::selectFirst('user', $fields, ['nickname' => $nickname]);
153         }
154
155         /**
156          * Returns the user id of a given profile URL
157          *
158          * @param string $url
159          *
160          * @return integer user id
161          * @throws Exception
162          */
163         public static function getIdForURL($url)
164         {
165                 $self = DBA::selectFirst('contact', ['uid'], ['nurl' => Strings::normaliseLink($url), 'self' => true]);
166                 if (!DBA::isResult($self)) {
167                         return false;
168                 } else {
169                         return $self['uid'];
170                 }
171         }
172
173         /**
174          * Get a user based on its email
175          *
176          * @param string        $email
177          * @param array          $fields
178          *
179          * @return array|boolean User record if it exists, false otherwise
180          *
181          * @throws Exception
182          */
183         public static function getByEmail($email, array $fields = [])
184         {
185                 return DBA::selectFirst('user', $fields, ['email' => $email]);
186         }
187
188         /**
189          * Get owner data by user id
190          *
191          * @param int $uid
192          * @param boolean $check_valid Test if data is invalid and correct it
193          * @return boolean|array
194          * @throws Exception
195          */
196         public static function getOwnerDataById($uid, $check_valid = true)
197         {
198                 $owner = DBA::selectFirst('owner-view', [], ['uid' => $uid]);
199                 if (!DBA::isResult($owner)) {
200                         return false;
201                 }
202
203                 if (empty($owner['nickname'])) {
204                         return false;
205                 }
206
207                 if (!$check_valid) {
208                         return $owner;
209                 }
210
211                 // Check if the returned data is valid, otherwise fix it. See issue #6122
212
213                 // Check for correct url and normalised nurl
214                 $url = DI::baseUrl() . '/profile/' . $owner['nickname'];
215                 $repair = ($owner['url'] != $url) || ($owner['nurl'] != Strings::normaliseLink($owner['url']));
216
217                 if (!$repair) {
218                         // Check if "addr" is present and correct
219                         $addr = $owner['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
220                         $repair = ($addr != $owner['addr']);
221                 }
222
223                 if (!$repair) {
224                         // Check if the avatar field is filled and the photo directs to the correct path
225                         $avatar = Photo::selectFirst(['resource-id'], ['uid' => $uid, 'profile' => true]);
226                         if (DBA::isResult($avatar)) {
227                                 $repair = empty($owner['avatar']) || !strpos($owner['photo'], $avatar['resource-id']);
228                         }
229                 }
230
231                 if ($repair) {
232                         Contact::updateSelfFromUserID($uid);
233                         // Return the corrected data and avoid a loop
234                         $owner = self::getOwnerDataById($uid, false);
235                 }
236
237                 return $owner;
238         }
239
240         /**
241          * Get owner data by nick name
242          *
243          * @param int $nick
244          * @return boolean|array
245          * @throws Exception
246          */
247         public static function getOwnerDataByNick($nick)
248         {
249                 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nick]);
250
251                 if (!DBA::isResult($user)) {
252                         return false;
253                 }
254
255                 return self::getOwnerDataById($user['uid']);
256         }
257
258         /**
259          * Returns the default group for a given user and network
260          *
261          * @param int $uid User id
262          * @param string $network network name
263          *
264          * @return int group id
265          * @throws InternalServerErrorException
266          */
267         public static function getDefaultGroup($uid, $network = '')
268         {
269                 $default_group = 0;
270
271                 if ($network == Protocol::OSTATUS) {
272                         $default_group = DI::pConfig()->get($uid, "ostatus", "default_group");
273                 }
274
275                 if ($default_group != 0) {
276                         return $default_group;
277                 }
278
279                 $user = DBA::selectFirst('user', ['def_gid'], ['uid' => $uid]);
280
281                 if (DBA::isResult($user)) {
282                         $default_group = $user["def_gid"];
283                 }
284
285                 return $default_group;
286         }
287
288
289         /**
290          * Authenticate a user with a clear text password
291          *
292          * @param mixed  $user_info
293          * @param string $password
294          * @param bool   $third_party
295          * @return int|boolean
296          * @deprecated since version 3.6
297          * @see        User::getIdFromPasswordAuthentication()
298          */
299         public static function authenticate($user_info, $password, $third_party = false)
300         {
301                 try {
302                         return self::getIdFromPasswordAuthentication($user_info, $password, $third_party);
303                 } catch (Exception $ex) {
304                         return false;
305                 }
306         }
307
308         /**
309          * Authenticate a user with a clear text password
310          *
311          * Returns the user id associated with a successful password authentication
312          *
313          * @param mixed  $user_info
314          * @param string $password
315          * @param bool   $third_party
316          * @return int User Id if authentication is successful
317          * @throws Exception
318          */
319         public static function getIdFromPasswordAuthentication($user_info, $password, $third_party = false)
320         {
321                 $user = self::getAuthenticationInfo($user_info);
322
323                 if ($third_party && DI::pConfig()->get($user['uid'], '2fa', 'verified')) {
324                         // Third-party apps can't verify two-factor authentication, we use app-specific passwords instead
325                         if (AppSpecificPassword::authenticateUser($user['uid'], $password)) {
326                                 return $user['uid'];
327                         }
328                 } elseif (strpos($user['password'], '$') === false) {
329                         //Legacy hash that has not been replaced by a new hash yet
330                         if (self::hashPasswordLegacy($password) === $user['password']) {
331                                 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
332
333                                 return $user['uid'];
334                         }
335                 } elseif (!empty($user['legacy_password'])) {
336                         //Legacy hash that has been double-hashed and not replaced by a new hash yet
337                         //Warning: `legacy_password` is not necessary in sync with the content of `password`
338                         if (password_verify(self::hashPasswordLegacy($password), $user['password'])) {
339                                 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
340
341                                 return $user['uid'];
342                         }
343                 } elseif (password_verify($password, $user['password'])) {
344                         //New password hash
345                         if (password_needs_rehash($user['password'], PASSWORD_DEFAULT)) {
346                                 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
347                         }
348
349                         return $user['uid'];
350                 }
351
352                 throw new Exception(DI::l10n()->t('Login failed'));
353         }
354
355         /**
356          * Returns authentication info from various parameters types
357          *
358          * User info can be any of the following:
359          * - User DB object
360          * - User Id
361          * - User email or username or nickname
362          * - User array with at least the uid and the hashed password
363          *
364          * @param mixed $user_info
365          * @return array
366          * @throws Exception
367          */
368         private static function getAuthenticationInfo($user_info)
369         {
370                 $user = null;
371
372                 if (is_object($user_info) || is_array($user_info)) {
373                         if (is_object($user_info)) {
374                                 $user = (array) $user_info;
375                         } else {
376                                 $user = $user_info;
377                         }
378
379                         if (
380                                 !isset($user['uid'])
381                                 || !isset($user['password'])
382                                 || !isset($user['legacy_password'])
383                         ) {
384                                 throw new Exception(DI::l10n()->t('Not enough information to authenticate'));
385                         }
386                 } elseif (is_int($user_info) || is_string($user_info)) {
387                         if (is_int($user_info)) {
388                                 $user = DBA::selectFirst(
389                                         'user',
390                                         ['uid', 'password', 'legacy_password'],
391                                         [
392                                                 'uid' => $user_info,
393                                                 'blocked' => 0,
394                                                 'account_expired' => 0,
395                                                 'account_removed' => 0,
396                                                 'verified' => 1
397                                         ]
398                                 );
399                         } else {
400                                 $fields = ['uid', 'password', 'legacy_password'];
401                                 $condition = [
402                                         "(`email` = ? OR `username` = ? OR `nickname` = ?)
403                                         AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified`",
404                                         $user_info, $user_info, $user_info
405                                 ];
406                                 $user = DBA::selectFirst('user', $fields, $condition);
407                         }
408
409                         if (!DBA::isResult($user)) {
410                                 throw new Exception(DI::l10n()->t('User not found'));
411                         }
412                 }
413
414                 return $user;
415         }
416
417         /**
418          * Generates a human-readable random password
419          *
420          * @return string
421          */
422         public static function generateNewPassword()
423         {
424                 return ucfirst(Strings::getRandomName(8)) . random_int(1000, 9999);
425         }
426
427         /**
428          * Checks if the provided plaintext password has been exposed or not
429          *
430          * @param string $password
431          * @return bool
432          * @throws Exception
433          */
434         public static function isPasswordExposed($password)
435         {
436                 $cache = new \DivineOmega\DOFileCachePSR6\CacheItemPool();
437                 $cache->changeConfig([
438                         'cacheDirectory' => get_temppath() . '/password-exposed-cache/',
439                 ]);
440
441                 try {
442                         $passwordExposedChecker = new PasswordExposed\PasswordExposedChecker(null, $cache);
443
444                         return $passwordExposedChecker->passwordExposed($password) === PasswordExposed\PasswordStatus::EXPOSED;
445                 } catch (\Exception $e) {
446                         Logger::error('Password Exposed Exception: ' . $e->getMessage(), [
447                                 'code' => $e->getCode(),
448                                 'file' => $e->getFile(),
449                                 'line' => $e->getLine(),
450                                 'trace' => $e->getTraceAsString()
451                         ]);
452
453                         return false;
454                 }
455         }
456
457         /**
458          * Legacy hashing function, kept for password migration purposes
459          *
460          * @param string $password
461          * @return string
462          */
463         private static function hashPasswordLegacy($password)
464         {
465                 return hash('whirlpool', $password);
466         }
467
468         /**
469          * Global user password hashing function
470          *
471          * @param string $password
472          * @return string
473          * @throws Exception
474          */
475         public static function hashPassword($password)
476         {
477                 if (!trim($password)) {
478                         throw new Exception(DI::l10n()->t('Password can\'t be empty'));
479                 }
480
481                 return password_hash($password, PASSWORD_DEFAULT);
482         }
483
484         /**
485          * Updates a user row with a new plaintext password
486          *
487          * @param int    $uid
488          * @param string $password
489          * @return bool
490          * @throws Exception
491          */
492         public static function updatePassword($uid, $password)
493         {
494                 $password = trim($password);
495
496                 if (empty($password)) {
497                         throw new Exception(DI::l10n()->t('Empty passwords are not allowed.'));
498                 }
499
500                 if (!DI::config()->get('system', 'disable_password_exposed', false) && self::isPasswordExposed($password)) {
501                         throw new Exception(DI::l10n()->t('The new password has been exposed in a public data dump, please choose another.'));
502                 }
503
504                 $allowed_characters = '!"#$%&\'()*+,-./;<=>?@[\]^_`{|}~';
505
506                 if (!preg_match('/^[a-z0-9' . preg_quote($allowed_characters, '/') . ']+$/i', $password)) {
507                         throw new Exception(DI::l10n()->t('The password can\'t contain accentuated letters, white spaces or colons (:)'));
508                 }
509
510                 return self::updatePasswordHashed($uid, self::hashPassword($password));
511         }
512
513         /**
514          * Updates a user row with a new hashed password.
515          * Empties the password reset token field just in case.
516          *
517          * @param int    $uid
518          * @param string $pasword_hashed
519          * @return bool
520          * @throws Exception
521          */
522         private static function updatePasswordHashed($uid, $pasword_hashed)
523         {
524                 $fields = [
525                         'password' => $pasword_hashed,
526                         'pwdreset' => null,
527                         'pwdreset_time' => null,
528                         'legacy_password' => false
529                 ];
530                 return DBA::update('user', $fields, ['uid' => $uid]);
531         }
532
533         /**
534          * Checks if a nickname is in the list of the forbidden nicknames
535          *
536          * Check if a nickname is forbidden from registration on the node by the
537          * admin. Forbidden nicknames (e.g. role namess) can be configured in the
538          * admin panel.
539          *
540          * @param string $nickname The nickname that should be checked
541          * @return boolean True is the nickname is blocked on the node
542          * @throws InternalServerErrorException
543          */
544         public static function isNicknameBlocked($nickname)
545         {
546                 $forbidden_nicknames = DI::config()->get('system', 'forbidden_nicknames', '');
547
548                 // if the config variable is empty return false
549                 if (empty($forbidden_nicknames)) {
550                         return false;
551                 }
552
553                 // check if the nickname is in the list of blocked nicknames
554                 $forbidden = explode(',', $forbidden_nicknames);
555                 $forbidden = array_map('trim', $forbidden);
556                 if (in_array(strtolower($nickname), $forbidden)) {
557                         return true;
558                 }
559
560                 // else return false
561                 return false;
562         }
563
564         /**
565          * Catch-all user creation function
566          *
567          * Creates a user from the provided data array, either form fields or OpenID.
568          * Required: { username, nickname, email } or { openid_url }
569          *
570          * Performs the following:
571          * - Sends to the OpenId auth URL (if relevant)
572          * - Creates new key pairs for crypto
573          * - Create self-contact
574          * - Create profile image
575          *
576          * @param  array $data
577          * @return array
578          * @throws \ErrorException
579          * @throws InternalServerErrorException
580          * @throws \ImagickException
581          * @throws Exception
582          */
583         public static function create(array $data)
584         {
585                 $return = ['user' => null, 'password' => ''];
586
587                 $using_invites = DI::config()->get('system', 'invitation_only');
588
589                 $invite_id  = !empty($data['invite_id'])  ? Strings::escapeTags(trim($data['invite_id']))  : '';
590                 $username   = !empty($data['username'])   ? Strings::escapeTags(trim($data['username']))   : '';
591                 $nickname   = !empty($data['nickname'])   ? Strings::escapeTags(trim($data['nickname']))   : '';
592                 $email      = !empty($data['email'])      ? Strings::escapeTags(trim($data['email']))      : '';
593                 $openid_url = !empty($data['openid_url']) ? Strings::escapeTags(trim($data['openid_url'])) : '';
594                 $photo      = !empty($data['photo'])      ? Strings::escapeTags(trim($data['photo']))      : '';
595                 $password   = !empty($data['password'])   ? trim($data['password'])           : '';
596                 $password1  = !empty($data['password1'])  ? trim($data['password1'])          : '';
597                 $confirm    = !empty($data['confirm'])    ? trim($data['confirm'])            : '';
598                 $blocked    = !empty($data['blocked']);
599                 $verified   = !empty($data['verified']);
600                 $language   = !empty($data['language'])   ? Strings::escapeTags(trim($data['language']))   : 'en';
601
602                 $netpublish = $publish = !empty($data['profile_publish_reg']);
603
604                 if ($password1 != $confirm) {
605                         throw new Exception(DI::l10n()->t('Passwords do not match. Password unchanged.'));
606                 } elseif ($password1 != '') {
607                         $password = $password1;
608                 }
609
610                 if ($using_invites) {
611                         if (!$invite_id) {
612                                 throw new Exception(DI::l10n()->t('An invitation is required.'));
613                         }
614
615                         if (!Register::existsByHash($invite_id)) {
616                                 throw new Exception(DI::l10n()->t('Invitation could not be verified.'));
617                         }
618                 }
619
620                 /// @todo Check if this part is really needed. We should have fetched all this data in advance
621                 if (empty($username) || empty($email) || empty($nickname)) {
622                         if ($openid_url) {
623                                 if (!Network::isUrlValid($openid_url)) {
624                                         throw new Exception(DI::l10n()->t('Invalid OpenID url'));
625                                 }
626                                 $_SESSION['register'] = 1;
627                                 $_SESSION['openid'] = $openid_url;
628
629                                 $openid = new LightOpenID(DI::baseUrl()->getHostname());
630                                 $openid->identity = $openid_url;
631                                 $openid->returnUrl = DI::baseUrl() . '/openid';
632                                 $openid->required = ['namePerson/friendly', 'contact/email', 'namePerson'];
633                                 $openid->optional = ['namePerson/first', 'media/image/aspect11', 'media/image/default'];
634                                 try {
635                                         $authurl = $openid->authUrl();
636                                 } catch (Exception $e) {
637                                         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.') . EOL . EOL . DI::l10n()->t('The error message was:') . $e->getMessage(), 0, $e);
638                                 }
639                                 System::externalRedirect($authurl);
640                                 // NOTREACHED
641                         }
642
643                         throw new Exception(DI::l10n()->t('Please enter the required information.'));
644                 }
645
646                 if (!Network::isUrlValid($openid_url)) {
647                         $openid_url = '';
648                 }
649
650                 // collapse multiple spaces in name
651                 $username = preg_replace('/ +/', ' ', $username);
652
653                 $username_min_length = max(1, min(64, intval(DI::config()->get('system', 'username_min_length', 3))));
654                 $username_max_length = max(1, min(64, intval(DI::config()->get('system', 'username_max_length', 48))));
655
656                 if ($username_min_length > $username_max_length) {
657                         Logger::log(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), Logger::WARNING);
658                         $tmp = $username_min_length;
659                         $username_min_length = $username_max_length;
660                         $username_max_length = $tmp;
661                 }
662
663                 if (mb_strlen($username) < $username_min_length) {
664                         throw new Exception(DI::l10n()->tt('Username should be at least %s character.', 'Username should be at least %s characters.', $username_min_length));
665                 }
666
667                 if (mb_strlen($username) > $username_max_length) {
668                         throw new Exception(DI::l10n()->tt('Username should be at most %s character.', 'Username should be at most %s characters.', $username_max_length));
669                 }
670
671                 // So now we are just looking for a space in the full name.
672                 $loose_reg = DI::config()->get('system', 'no_regfullname');
673                 if (!$loose_reg) {
674                         $username = mb_convert_case($username, MB_CASE_TITLE, 'UTF-8');
675                         if (strpos($username, ' ') === false) {
676                                 throw new Exception(DI::l10n()->t("That doesn't appear to be your full (First Last) name."));
677                         }
678                 }
679
680                 if (!Network::isEmailDomainAllowed($email)) {
681                         throw new Exception(DI::l10n()->t('Your email domain is not among those allowed on this site.'));
682                 }
683
684                 if (!filter_var($email, FILTER_VALIDATE_EMAIL) || !Network::isEmailDomainValid($email)) {
685                         throw new Exception(DI::l10n()->t('Not a valid email address.'));
686                 }
687                 if (self::isNicknameBlocked($nickname)) {
688                         throw new Exception(DI::l10n()->t('The nickname was blocked from registration by the nodes admin.'));
689                 }
690
691                 if (DI::config()->get('system', 'block_extended_register', false) && DBA::exists('user', ['email' => $email])) {
692                         throw new Exception(DI::l10n()->t('Cannot use that email.'));
693                 }
694
695                 // Disallow somebody creating an account using openid that uses the admin email address,
696                 // since openid bypasses email verification. We'll allow it if there is not yet an admin account.
697                 if (DI::config()->get('config', 'admin_email') && strlen($openid_url)) {
698                         $adminlist = explode(',', str_replace(' ', '', strtolower(DI::config()->get('config', 'admin_email'))));
699                         if (in_array(strtolower($email), $adminlist)) {
700                                 throw new Exception(DI::l10n()->t('Cannot use that email.'));
701                         }
702                 }
703
704                 $nickname = $data['nickname'] = strtolower($nickname);
705
706                 if (!preg_match('/^[a-z0-9][a-z0-9\_]*$/', $nickname)) {
707                         throw new Exception(DI::l10n()->t('Your nickname can only contain a-z, 0-9 and _.'));
708                 }
709
710                 // Check existing and deleted accounts for this nickname.
711                 if (
712                         DBA::exists('user', ['nickname' => $nickname])
713                         || DBA::exists('userd', ['username' => $nickname])
714                 ) {
715                         throw new Exception(DI::l10n()->t('Nickname is already registered. Please choose another.'));
716                 }
717
718                 $new_password = strlen($password) ? $password : User::generateNewPassword();
719                 $new_password_encoded = self::hashPassword($new_password);
720
721                 $return['password'] = $new_password;
722
723                 $keys = Crypto::newKeypair(4096);
724                 if ($keys === false) {
725                         throw new Exception(DI::l10n()->t('SERIOUS ERROR: Generation of security keys failed.'));
726                 }
727
728                 $prvkey = $keys['prvkey'];
729                 $pubkey = $keys['pubkey'];
730
731                 // Create another keypair for signing/verifying salmon protocol messages.
732                 $sres = Crypto::newKeypair(512);
733                 $sprvkey = $sres['prvkey'];
734                 $spubkey = $sres['pubkey'];
735
736                 $insert_result = DBA::insert('user', [
737                         'guid'     => System::createUUID(),
738                         'username' => $username,
739                         'password' => $new_password_encoded,
740                         'email'    => $email,
741                         'openid'   => $openid_url,
742                         'nickname' => $nickname,
743                         'pubkey'   => $pubkey,
744                         'prvkey'   => $prvkey,
745                         'spubkey'  => $spubkey,
746                         'sprvkey'  => $sprvkey,
747                         'verified' => $verified,
748                         'blocked'  => $blocked,
749                         'language' => $language,
750                         'timezone' => 'UTC',
751                         'register_date' => DateTimeFormat::utcNow(),
752                         'default-location' => ''
753                 ]);
754
755                 if ($insert_result) {
756                         $uid = DBA::lastInsertId();
757                         $user = DBA::selectFirst('user', [], ['uid' => $uid]);
758                 } else {
759                         throw new Exception(DI::l10n()->t('An error occurred during registration. Please try again.'));
760                 }
761
762                 if (!$uid) {
763                         throw new Exception(DI::l10n()->t('An error occurred during registration. Please try again.'));
764                 }
765
766                 // if somebody clicked submit twice very quickly, they could end up with two accounts
767                 // due to race condition. Remove this one.
768                 $user_count = DBA::count('user', ['nickname' => $nickname]);
769                 if ($user_count > 1) {
770                         DBA::delete('user', ['uid' => $uid]);
771
772                         throw new Exception(DI::l10n()->t('Nickname is already registered. Please choose another.'));
773                 }
774
775                 $insert_result = DBA::insert('profile', [
776                         'uid' => $uid,
777                         'name' => $username,
778                         'photo' => DI::baseUrl() . "/photo/profile/{$uid}.jpg",
779                         'thumb' => DI::baseUrl() . "/photo/avatar/{$uid}.jpg",
780                         'publish' => $publish,
781                         'net-publish' => $netpublish,
782                 ]);
783                 if (!$insert_result) {
784                         DBA::delete('user', ['uid' => $uid]);
785
786                         throw new Exception(DI::l10n()->t('An error occurred creating your default profile. Please try again.'));
787                 }
788
789                 // Create the self contact
790                 if (!Contact::createSelfFromUserId($uid)) {
791                         DBA::delete('user', ['uid' => $uid]);
792
793                         throw new Exception(DI::l10n()->t('An error occurred creating your self contact. Please try again.'));
794                 }
795
796                 // Create a group with no members. This allows somebody to use it
797                 // right away as a default group for new contacts.
798                 $def_gid = Group::create($uid, DI::l10n()->t('Friends'));
799                 if (!$def_gid) {
800                         DBA::delete('user', ['uid' => $uid]);
801
802                         throw new Exception(DI::l10n()->t('An error occurred creating your default contact group. Please try again.'));
803                 }
804
805                 $fields = ['def_gid' => $def_gid];
806                 if (DI::config()->get('system', 'newuser_private') && $def_gid) {
807                         $fields['allow_gid'] = '<' . $def_gid . '>';
808                 }
809
810                 DBA::update('user', $fields, ['uid' => $uid]);
811
812                 // if we have no OpenID photo try to look up an avatar
813                 if (!strlen($photo)) {
814                         $photo = Network::lookupAvatarByEmail($email);
815                 }
816
817                 // unless there is no avatar-addon loaded
818                 if (strlen($photo)) {
819                         $photo_failure = false;
820
821                         $filename = basename($photo);
822                         $curlResult = Network::curl($photo, true);
823                         if ($curlResult->isSuccess()) {
824                                 $img_str = $curlResult->getBody();
825                                 $type = $curlResult->getContentType();
826                         } else {
827                                 $img_str = '';
828                                 $type = '';
829                         }
830
831                         $type = Images::getMimeTypeByData($img_str, $photo, $type);
832
833                         $Image = new Image($img_str, $type);
834                         if ($Image->isValid()) {
835                                 $Image->scaleToSquare(300);
836
837                                 $resource_id = Photo::newResource();
838
839                                 $r = Photo::store($Image, $uid, 0, $resource_id, $filename, DI::l10n()->t('Profile Photos'), 4);
840
841                                 if ($r === false) {
842                                         $photo_failure = true;
843                                 }
844
845                                 $Image->scaleDown(80);
846
847                                 $r = Photo::store($Image, $uid, 0, $resource_id, $filename, DI::l10n()->t('Profile Photos'), 5);
848
849                                 if ($r === false) {
850                                         $photo_failure = true;
851                                 }
852
853                                 $Image->scaleDown(48);
854
855                                 $r = Photo::store($Image, $uid, 0, $resource_id, $filename, DI::l10n()->t('Profile Photos'), 6);
856
857                                 if ($r === false) {
858                                         $photo_failure = true;
859                                 }
860
861                                 if (!$photo_failure) {
862                                         Photo::update(['profile' => 1], ['resource-id' => $resource_id]);
863                                 }
864                         }
865                 }
866
867                 Hook::callAll('register_account', $uid);
868
869                 $return['user'] = $user;
870                 return $return;
871         }
872
873         /**
874          * Sets block state for a given user
875          *
876          * @param int  $uid   The user id
877          * @param bool $block Block state (default is true)
878          *
879          * @return bool True, if successfully blocked
880
881          * @throws Exception
882          */
883         public static function block(int $uid, bool $block = true)
884         {
885                 return DBA::update('user', ['blocked' => $block], ['uid' => $uid]);
886         }
887
888         /**
889          * Allows a registration based on a hash
890          *
891          * @param string $hash
892          *
893          * @return bool True, if the allow was successful
894          *
895          * @throws InternalServerErrorException
896          * @throws Exception
897          */
898         public static function allow(string $hash)
899         {
900                 $register = Register::getByHash($hash);
901                 if (!DBA::isResult($register)) {
902                         return false;
903                 }
904
905                 $user = User::getById($register['uid']);
906                 if (!DBA::isResult($user)) {
907                         return false;
908                 }
909
910                 Register::deleteByHash($hash);
911
912                 DBA::update('user', ['blocked' => false, 'verified' => true], ['uid' => $register['uid']]);
913
914                 $profile = DBA::selectFirst('profile', ['net-publish'], ['uid' => $register['uid']]);
915
916                 if (DBA::isResult($profile) && $profile['net-publish'] && DI::config()->get('system', 'directory')) {
917                         $url = DI::baseUrl() . '/profile/' . $user['nickname'];
918                         Worker::add(PRIORITY_LOW, "Directory", $url);
919                 }
920
921                 $l10n = DI::l10n()->withLang($register['language']);
922
923                 return User::sendRegisterOpenEmail(
924                         $l10n,
925                         $user,
926                         DI::config()->get('config', 'sitename'),
927                         DI::baseUrl()->get(),
928                         ($register['password'] ?? '') ?: 'Sent in a previous email'
929                 );
930         }
931
932         /**
933          * Denys a pending registration
934          *
935          * @param string $hash The hash of the pending user
936          *
937          * This does not have to go through user_remove() and save the nickname
938          * permanently against re-registration, as the person was not yet
939          * allowed to have friends on this system
940          *
941          * @return bool True, if the deny was successfull
942          * @throws Exception
943          */
944         public static function deny(string $hash)
945         {
946                 $register = Register::getByHash($hash);
947                 if (!DBA::isResult($register)) {
948                         return false;
949                 }
950
951                 $user = User::getById($register['uid']);
952                 if (!DBA::isResult($user)) {
953                         return false;
954                 }
955
956                 return DBA::delete('user', ['uid' => $register['uid']]) &&
957                        Register::deleteByHash($register['hash']);
958         }
959
960         /**
961          * Creates a new user based on a minimal set and sends an email to this user
962          *
963          * @param string $name  The user's name
964          * @param string $email The user's email address
965          * @param string $nick  The user's nick name
966          * @param string $lang  The user's language (default is english)
967          *
968          * @return bool True, if the user was created successfully
969          * @throws InternalServerErrorException
970          * @throws \ErrorException
971          * @throws \ImagickException
972          */
973         public static function createMinimal(string $name, string $email, string $nick, string $lang = L10n::DEFAULT)
974         {
975                 if (empty($name) ||
976                     empty($email) ||
977                     empty($nick)) {
978                         throw new InternalServerErrorException('Invalid arguments.');
979                 }
980
981                 $result = self::create([
982                         'username' => $name,
983                         'email' => $email,
984                         'nickname' => $nick,
985                         'verified' => 1,
986                         'language' => $lang
987                 ]);
988
989                 $user = $result['user'];
990                 $preamble = Strings::deindent(DI::l10n()->t('
991                 Dear %1$s,
992                         the administrator of %2$s has set up an account for you.'));
993                 $body = Strings::deindent(DI::l10n()->t('
994                 The login details are as follows:
995
996                 Site Location:  %1$s
997                 Login Name:             %2$s
998                 Password:               %3$s
999
1000                 You may change your password from your account "Settings" page after logging
1001                 in.
1002
1003                 Please take a few moments to review the other account settings on that page.
1004
1005                 You may also wish to add some basic information to your default profile
1006                 (on the "Profiles" page) so that other people can easily find you.
1007
1008                 We recommend setting your full name, adding a profile photo,
1009                 adding some profile "keywords" (very useful in making new friends) - and
1010                 perhaps what country you live in; if you do not wish to be more specific
1011                 than that.
1012
1013                 We fully respect your right to privacy, and none of these items are necessary.
1014                 If you are new and do not know anybody here, they may help
1015                 you to make some new and interesting friends.
1016
1017                 If you ever want to delete your account, you can do so at %1$s/removeme
1018
1019                 Thank you and welcome to %4$s.'));
1020
1021                 $preamble = sprintf($preamble, $user['username'], DI::config()->get('config', 'sitename'));
1022                 $body = sprintf($body, DI::baseUrl()->get(), $user['nickname'], $result['password'], DI::config()->get('config', 'sitename'));
1023
1024                 $email = DI::emailer()
1025                         ->newSystemMail()
1026                         ->withMessage(DI::l10n()->t('Registration details for %s', DI::config()->get('config', 'sitename')), $preamble, $body)
1027                         ->forUser($user)
1028                         ->withRecipient($user['email'])
1029                         ->build();
1030                 return DI::emailer()->send($email);
1031         }
1032
1033         /**
1034          * Sends pending registration confirmation email
1035          *
1036          * @param array  $user     User record array
1037          * @param string $sitename
1038          * @param string $siteurl
1039          * @param string $password Plaintext password
1040          * @return NULL|boolean from notification() and email() inherited
1041          * @throws InternalServerErrorException
1042          */
1043         public static function sendRegisterPendingEmail($user, $sitename, $siteurl, $password)
1044         {
1045                 $body = Strings::deindent(DI::l10n()->t(
1046                         '
1047                         Dear %1$s,
1048                                 Thank you for registering at %2$s. Your account is pending for approval by the administrator.
1049
1050                         Your login details are as follows:
1051
1052                         Site Location:  %3$s
1053                         Login Name:             %4$s
1054                         Password:               %5$s
1055                 ',
1056                         $user['username'],
1057                         $sitename,
1058                         $siteurl,
1059                         $user['nickname'],
1060                         $password
1061                 ));
1062
1063                 $email = DI::emailer()
1064                         ->newSystemMail()
1065                         ->withMessage(DI::l10n()->t('Registration at %s', $sitename), $body)
1066                         ->forUser($user)
1067                         ->withRecipient($user['email'])
1068                         ->build();
1069                 return DI::emailer()->send($email);
1070         }
1071
1072         /**
1073          * Sends registration confirmation
1074          *
1075          * It's here as a function because the mail is sent from different parts
1076          *
1077          * @param \Friendica\Core\L10n $l10n     The used language
1078          * @param array                $user     User record array
1079          * @param string               $sitename
1080          * @param string               $siteurl
1081          * @param string               $password Plaintext password
1082          *
1083          * @return NULL|boolean from notification() and email() inherited
1084          * @throws InternalServerErrorException
1085          */
1086         public static function sendRegisterOpenEmail(\Friendica\Core\L10n $l10n, $user, $sitename, $siteurl, $password)
1087         {
1088                 $preamble = Strings::deindent($l10n->t(
1089                         '
1090                                 Dear %1$s,
1091                                 Thank you for registering at %2$s. Your account has been created.
1092                         ',
1093                         $user['username'],
1094                         $sitename
1095                 ));
1096                 $body = Strings::deindent($l10n->t(
1097                         '
1098                         The login details are as follows:
1099
1100                         Site Location:  %3$s
1101                         Login Name:             %1$s
1102                         Password:               %5$s
1103
1104                         You may change your password from your account "Settings" page after logging
1105                         in.
1106
1107                         Please take a few moments to review the other account settings on that page.
1108
1109                         You may also wish to add some basic information to your default profile
1110                         ' . "\x28" . 'on the "Profiles" page' . "\x29" . ' so that other people can easily find you.
1111
1112                         We recommend setting your full name, adding a profile photo,
1113                         adding some profile "keywords" ' . "\x28" . 'very useful in making new friends' . "\x29" . ' - and
1114                         perhaps what country you live in; if you do not wish to be more specific
1115                         than that.
1116
1117                         We fully respect your right to privacy, and none of these items are necessary.
1118                         If you are new and do not know anybody here, they may help
1119                         you to make some new and interesting friends.
1120
1121                         If you ever want to delete your account, you can do so at %3$s/removeme
1122
1123                         Thank you and welcome to %2$s.',
1124                         $user['nickname'],
1125                         $sitename,
1126                         $siteurl,
1127                         $user['username'],
1128                         $password
1129                 ));
1130
1131                 $email = DI::emailer()
1132                         ->newSystemMail()
1133                         ->withMessage(DI::l10n()->t('Registration details for %s', $sitename), $preamble, $body)
1134                         ->forUser($user)
1135                         ->withRecipient($user['email'])
1136                         ->build();
1137                 return DI::emailer()->send($email);
1138         }
1139
1140         /**
1141          * @param int $uid user to remove
1142          * @return bool
1143          * @throws InternalServerErrorException
1144          */
1145         public static function remove(int $uid)
1146         {
1147                 if (!$uid) {
1148                         return false;
1149                 }
1150
1151                 Logger::log('Removing user: ' . $uid);
1152
1153                 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
1154
1155                 Hook::callAll('remove_user', $user);
1156
1157                 // save username (actually the nickname as it is guaranteed
1158                 // unique), so it cannot be re-registered in the future.
1159                 DBA::insert('userd', ['username' => $user['nickname']]);
1160
1161                 // The user and related data will be deleted in "cron_expire_and_remove_users" (cronjobs.php)
1162                 DBA::update('user', ['account_removed' => true, 'account_expires_on' => DateTimeFormat::utc('now + 7 day')], ['uid' => $uid]);
1163                 Worker::add(PRIORITY_HIGH, 'Notifier', Delivery::REMOVAL, $uid);
1164
1165                 // Send an update to the directory
1166                 $self = DBA::selectFirst('contact', ['url'], ['uid' => $uid, 'self' => true]);
1167                 Worker::add(PRIORITY_LOW, 'Directory', $self['url']);
1168
1169                 // Remove the user relevant data
1170                 Worker::add(PRIORITY_NEGLIGIBLE, 'RemoveUser', $uid);
1171
1172                 return true;
1173         }
1174
1175         /**
1176          * Return all identities to a user
1177          *
1178          * @param int $uid The user id
1179          * @return array All identities for this user
1180          *
1181          * Example for a return:
1182          *    [
1183          *        [
1184          *            'uid' => 1,
1185          *            'username' => 'maxmuster',
1186          *            'nickname' => 'Max Mustermann'
1187          *        ],
1188          *        [
1189          *            'uid' => 2,
1190          *            'username' => 'johndoe',
1191          *            'nickname' => 'John Doe'
1192          *        ]
1193          *    ]
1194          * @throws Exception
1195          */
1196         public static function identities($uid)
1197         {
1198                 $identities = [];
1199
1200                 $user = DBA::selectFirst('user', ['uid', 'nickname', 'username', 'parent-uid'], ['uid' => $uid]);
1201                 if (!DBA::isResult($user)) {
1202                         return $identities;
1203                 }
1204
1205                 if ($user['parent-uid'] == 0) {
1206                         // First add our own entry
1207                         $identities = [[
1208                                 'uid' => $user['uid'],
1209                                 'username' => $user['username'],
1210                                 'nickname' => $user['nickname']
1211                         ]];
1212
1213                         // Then add all the children
1214                         $r = DBA::select(
1215                                 'user',
1216                                 ['uid', 'username', 'nickname'],
1217                                 ['parent-uid' => $user['uid'], 'account_removed' => false]
1218                         );
1219                         if (DBA::isResult($r)) {
1220                                 $identities = array_merge($identities, DBA::toArray($r));
1221                         }
1222                 } else {
1223                         // First entry is our parent
1224                         $r = DBA::select(
1225                                 'user',
1226                                 ['uid', 'username', 'nickname'],
1227                                 ['uid' => $user['parent-uid'], 'account_removed' => false]
1228                         );
1229                         if (DBA::isResult($r)) {
1230                                 $identities = DBA::toArray($r);
1231                         }
1232
1233                         // Then add all siblings
1234                         $r = DBA::select(
1235                                 'user',
1236                                 ['uid', 'username', 'nickname'],
1237                                 ['parent-uid' => $user['parent-uid'], 'account_removed' => false]
1238                         );
1239                         if (DBA::isResult($r)) {
1240                                 $identities = array_merge($identities, DBA::toArray($r));
1241                         }
1242                 }
1243
1244                 $r = DBA::p(
1245                         "SELECT `user`.`uid`, `user`.`username`, `user`.`nickname`
1246                         FROM `manage`
1247                         INNER JOIN `user` ON `manage`.`mid` = `user`.`uid`
1248                         WHERE `user`.`account_removed` = 0 AND `manage`.`uid` = ?",
1249                         $user['uid']
1250                 );
1251                 if (DBA::isResult($r)) {
1252                         $identities = array_merge($identities, DBA::toArray($r));
1253                 }
1254
1255                 return $identities;
1256         }
1257
1258         /**
1259          * Returns statistical information about the current users of this node
1260          *
1261          * @return array
1262          *
1263          * @throws Exception
1264          */
1265         public static function getStatistics()
1266         {
1267                 $statistics = [
1268                         'total_users'           => 0,
1269                         'active_users_halfyear' => 0,
1270                         'active_users_monthly'  => 0,
1271                 ];
1272
1273                 $userStmt = DBA::select('owner-view', ['uid', 'login_date', 'last-item'],
1274                         ["`verified` AND `login_date` > ? AND NOT `blocked`
1275                         AND NOT `account_removed` AND NOT `account_expired`",
1276                         DBA::NULL_DATETIME]);
1277                 if (!DBA::isResult($userStmt)) {
1278                         return $statistics;
1279                 }
1280
1281                 $halfyear = time() - (180 * 24 * 60 * 60);
1282                 $month = time() - (30 * 24 * 60 * 60);
1283
1284                 while ($user = DBA::fetch($userStmt)) {
1285                         $statistics['total_users']++;
1286
1287                         if ((strtotime($user['login_date']) > $halfyear) || (strtotime($user['last-item']) > $halfyear)
1288                         ) {
1289                                 $statistics['active_users_halfyear']++;
1290                         }
1291
1292                         if ((strtotime($user['login_date']) > $month) || (strtotime($user['last-item']) > $month)
1293                         ) {
1294                                 $statistics['active_users_monthly']++;
1295                         }
1296                 }
1297
1298                 return $statistics;
1299         }
1300
1301         /**
1302          * Get all users of the current node
1303          *
1304          * @param int    $start Start count (Default is 0)
1305          * @param int    $count Count of the items per page (Default is @see Pager::ITEMS_PER_PAGE)
1306          * @param string $type  The type of users, which should get (all, bocked, removed)
1307          * @param string $order Order of the user list (Default is 'contact.name')
1308          * @param bool   $descending Order direction (Default is ascending)
1309          *
1310          * @return array The list of the users
1311          * @throws Exception
1312          */
1313         public static function getList($start = 0, $count = Pager::ITEMS_PER_PAGE, $type = 'all', $order = 'name', bool $descending = false)
1314         {
1315                 $param = ['limit' => [$start, $count], 'order' => [$order => $descending]];
1316                 $condition = [];
1317                 switch ($type) {
1318                         case 'active':
1319                                 $condition['blocked'] = false;
1320                                 break;
1321                         case 'blocked':
1322                                 $condition['blocked'] = true;
1323                                 break;
1324                         case 'removed':
1325                                 $condition['account_removed'] = true;
1326                                 break;
1327                 }
1328
1329                 return DBA::selectToArray('owner-view', [], $condition, $param);
1330         }
1331 }