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