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