Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

685 lines
19 KiB

4 years ago
4 years ago
4 years ago
  1. <?php
  2. /**
  3. * @file src/Model/User.php
  4. * @brief This file includes the User class with user related database functions
  5. */
  6. namespace Friendica\Model;
  7. use DivineOmega\PasswordExposed\PasswordStatus;
  8. use Friendica\Core\Addon;
  9. use Friendica\Core\Config;
  10. use Friendica\Core\L10n;
  11. use Friendica\Core\PConfig;
  12. use Friendica\Core\System;
  13. use Friendica\Core\Worker;
  14. use Friendica\Database\DBM;
  15. use Friendica\Model\Contact;
  16. use Friendica\Model\Group;
  17. use Friendica\Model\Photo;
  18. use Friendica\Object\Image;
  19. use Friendica\Util\Crypto;
  20. use Friendica\Util\DateTimeFormat;
  21. use Friendica\Util\Network;
  22. use dba;
  23. use Exception;
  24. use LightOpenID;
  25. use function password_exposed;
  26. require_once 'boot.php';
  27. require_once 'include/dba.php';
  28. require_once 'include/enotify.php';
  29. require_once 'include/text.php';
  30. /**
  31. * @brief This class handles User related functions
  32. */
  33. class User
  34. {
  35. /**
  36. * @brief Get owner data by user id
  37. *
  38. * @param int $uid
  39. * @return boolean|array
  40. */
  41. public static function getOwnerDataById($uid) {
  42. $r = dba::fetch_first("SELECT
  43. `contact`.*,
  44. `user`.`prvkey` AS `uprvkey`,
  45. `user`.`timezone`,
  46. `user`.`nickname`,
  47. `user`.`sprvkey`,
  48. `user`.`spubkey`,
  49. `user`.`page-flags`,
  50. `user`.`account-type`,
  51. `user`.`prvnets`
  52. FROM `contact`
  53. INNER JOIN `user`
  54. ON `user`.`uid` = `contact`.`uid`
  55. WHERE `contact`.`uid` = ?
  56. AND `contact`.`self`
  57. LIMIT 1",
  58. $uid
  59. );
  60. if (!DBM::is_result($r)) {
  61. return false;
  62. }
  63. return $r;
  64. }
  65. /**
  66. * @brief Returns the default group for a given user and network
  67. *
  68. * @param int $uid User id
  69. * @param string $network network name
  70. *
  71. * @return int group id
  72. */
  73. public static function getDefaultGroup($uid, $network = '')
  74. {
  75. $default_group = 0;
  76. if ($network == NETWORK_OSTATUS) {
  77. $default_group = PConfig::get($uid, "ostatus", "default_group");
  78. }
  79. if ($default_group != 0) {
  80. return $default_group;
  81. }
  82. $user = dba::selectFirst('user', ['def_gid'], ['uid' => $uid]);
  83. if (DBM::is_result($user)) {
  84. $default_group = $user["def_gid"];
  85. }
  86. return $default_group;
  87. }
  88. /**
  89. * Authenticate a user with a clear text password
  90. *
  91. * @brief Authenticate a user with a clear text password
  92. * @param mixed $user_info
  93. * @param string $password
  94. * @return int|boolean
  95. * @deprecated since version 3.6
  96. * @see User::getIdFromPasswordAuthentication()
  97. */
  98. public static function authenticate($user_info, $password)
  99. {
  100. try {
  101. return self::getIdFromPasswordAuthentication($user_info, $password);
  102. } catch (Exception $ex) {
  103. return false;
  104. }
  105. }
  106. /**
  107. * Returns the user id associated with a successful password authentication
  108. *
  109. * @brief Authenticate a user with a clear text password
  110. * @param mixed $user_info
  111. * @param string $password
  112. * @return int User Id if authentication is successful
  113. * @throws Exception
  114. */
  115. public static function getIdFromPasswordAuthentication($user_info, $password)
  116. {
  117. $user = self::getAuthenticationInfo($user_info);
  118. if (strpos($user['password'], '$') === false) {
  119. if (self::hashPasswordLegacy($password) === $user['password']) {
  120. self::updatePassword($user['uid'], $password);
  121. return $user['uid'];
  122. }
  123. } elseif (password_verify($password, $user['password'])) {
  124. if (password_needs_rehash($user['password'], PASSWORD_DEFAULT)) {
  125. self::updatePassword($user['uid'], $password);
  126. }
  127. return $user['uid'];
  128. }
  129. throw new Exception(L10n::t('Login failed'));
  130. }
  131. /**
  132. * Returns authentication info from various parameters types
  133. *
  134. * User info can be any of the following:
  135. * - User DB object
  136. * - User Id
  137. * - User email or username or nickname
  138. * - User array with at least the uid and the hashed password
  139. *
  140. * @param mixed $user_info
  141. * @return array
  142. * @throws Exception
  143. */
  144. private static function getAuthenticationInfo($user_info)
  145. {
  146. $user = null;
  147. if (is_object($user_info) || is_array($user_info)) {
  148. if (is_object($user_info)) {
  149. $user = (array) $user_info;
  150. } else {
  151. $user = $user_info;
  152. }
  153. if (!isset($user['uid'])
  154. || !isset($user['password'])
  155. ) {
  156. throw new Exception(L10n::t('Not enough information to authenticate'));
  157. }
  158. } elseif (is_int($user_info) || is_string($user_info)) {
  159. if (is_int($user_info)) {
  160. $user = dba::selectFirst('user', ['uid', 'password'],
  161. [
  162. 'uid' => $user_info,
  163. 'blocked' => 0,
  164. 'account_expired' => 0,
  165. 'account_removed' => 0,
  166. 'verified' => 1
  167. ]
  168. );
  169. } else {
  170. $user = dba::fetch_first('SELECT `uid`, `password`
  171. FROM `user`
  172. WHERE (`email` = ? OR `username` = ? OR `nickname` = ?)
  173. AND `blocked` = 0
  174. AND `account_expired` = 0
  175. AND `account_removed` = 0
  176. AND `verified` = 1
  177. LIMIT 1',
  178. $user_info,
  179. $user_info,
  180. $user_info
  181. );
  182. }
  183. if (!DBM::is_result($user)) {
  184. throw new Exception(L10n::t('User not found'));
  185. }
  186. }
  187. return $user;
  188. }
  189. /**
  190. * Generates a human-readable random password
  191. *
  192. * @return string
  193. */
  194. public static function generateNewPassword()
  195. {
  196. return autoname(6) . mt_rand(100, 9999);
  197. }
  198. /**
  199. * Checks if the provided plaintext password has been exposed or not
  200. *
  201. * @param string $password
  202. * @return bool
  203. */
  204. public static function isPasswordExposed($password)
  205. {
  206. return password_exposed($password) === PasswordStatus::EXPOSED;
  207. }
  208. /**
  209. * Legacy hashing function, kept for password migration purposes
  210. *
  211. * @param string $password
  212. * @return string
  213. */
  214. private static function hashPasswordLegacy($password)
  215. {
  216. return hash('whirlpool', $password);
  217. }
  218. /**
  219. * Global user password hashing function
  220. *
  221. * @param string $password
  222. * @return string
  223. */
  224. public static function hashPassword($password)
  225. {
  226. return password_hash($password, PASSWORD_DEFAULT);
  227. }
  228. /**
  229. * Updates a user row with a new plaintext password
  230. *
  231. * @param int $uid
  232. * @param string $password
  233. * @return bool
  234. */
  235. public static function updatePassword($uid, $password)
  236. {
  237. return self::updatePasswordHashed($uid, self::hashPassword($password));
  238. }
  239. /**
  240. * Updates a user row with a new hashed password.
  241. * Empties the password reset token field just in case.
  242. *
  243. * @param int $uid
  244. * @param string $pasword_hashed
  245. * @return bool
  246. */
  247. private static function updatePasswordHashed($uid, $pasword_hashed)
  248. {
  249. $fields = [
  250. 'password' => $pasword_hashed,
  251. 'pwdreset' => null,
  252. 'pwdreset_time' => null,
  253. ];
  254. return dba::update('user', $fields, ['uid' => $uid]);
  255. }
  256. /**
  257. * @brief Catch-all user creation function
  258. *
  259. * Creates a user from the provided data array, either form fields or OpenID.
  260. * Required: { username, nickname, email } or { openid_url }
  261. *
  262. * Performs the following:
  263. * - Sends to the OpenId auth URL (if relevant)
  264. * - Creates new key pairs for crypto
  265. * - Create self-contact
  266. * - Create profile image
  267. *
  268. * @param array $data
  269. * @return string
  270. * @throw Exception
  271. */
  272. public static function create(array $data)
  273. {
  274. $a = get_app();
  275. $return = ['user' => null, 'password' => ''];
  276. $using_invites = Config::get('system', 'invitation_only');
  277. $num_invites = Config::get('system', 'number_invites');
  278. $invite_id = x($data, 'invite_id') ? notags(trim($data['invite_id'])) : '';
  279. $username = x($data, 'username') ? notags(trim($data['username'])) : '';
  280. $nickname = x($data, 'nickname') ? notags(trim($data['nickname'])) : '';
  281. $email = x($data, 'email') ? notags(trim($data['email'])) : '';
  282. $openid_url = x($data, 'openid_url') ? notags(trim($data['openid_url'])) : '';
  283. $photo = x($data, 'photo') ? notags(trim($data['photo'])) : '';
  284. $password = x($data, 'password') ? trim($data['password']) : '';
  285. $password1 = x($data, 'password1') ? trim($data['password1']) : '';
  286. $confirm = x($data, 'confirm') ? trim($data['confirm']) : '';
  287. $blocked = x($data, 'blocked') ? intval($data['blocked']) : 0;
  288. $verified = x($data, 'verified') ? intval($data['verified']) : 0;
  289. $publish = x($data, 'profile_publish_reg') && intval($data['profile_publish_reg']) ? 1 : 0;
  290. $netpublish = strlen(Config::get('system', 'directory')) ? $publish : 0;
  291. if ($password1 != $confirm) {
  292. throw new Exception(L10n::t('Passwords do not match. Password unchanged.'));
  293. } elseif ($password1 != '') {
  294. $password = $password1;
  295. }
  296. if ($using_invites) {
  297. if (!$invite_id) {
  298. throw new Exception(L10n::t('An invitation is required.'));
  299. }
  300. if (!dba::exists('register', ['hash' => $invite_id])) {
  301. throw new Exception(L10n::t('Invitation could not be verified.'));
  302. }
  303. }
  304. if (!x($username) || !x($email) || !x($nickname)) {
  305. if ($openid_url) {
  306. if (!Network::isUrlValid($openid_url)) {
  307. throw new Exception(L10n::t('Invalid OpenID url'));
  308. }
  309. $_SESSION['register'] = 1;
  310. $_SESSION['openid'] = $openid_url;
  311. $openid = new LightOpenID;
  312. $openid->identity = $openid_url;
  313. $openid->returnUrl = System::baseUrl() . '/openid';
  314. $openid->required = ['namePerson/friendly', 'contact/email', 'namePerson'];
  315. $openid->optional = ['namePerson/first', 'media/image/aspect11', 'media/image/default'];
  316. try {
  317. $authurl = $openid->authUrl();
  318. } catch (Exception $e) {
  319. 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);
  320. }
  321. goaway($authurl);
  322. // NOTREACHED
  323. }
  324. throw new Exception(L10n::t('Please enter the required information.'));
  325. }
  326. if (!Network::isUrlValid($openid_url)) {
  327. $openid_url = '';
  328. }
  329. $err = '';
  330. // collapse multiple spaces in name
  331. $username = preg_replace('/ +/', ' ', $username);
  332. if (mb_strlen($username) > 48) {
  333. throw new Exception(L10n::t('Please use a shorter name.'));
  334. }
  335. if (mb_strlen($username) < 3) {
  336. throw new Exception(L10n::t('Name too short.'));
  337. }
  338. // So now we are just looking for a space in the full name.
  339. $loose_reg = Config::get('system', 'no_regfullname');
  340. if (!$loose_reg) {
  341. $username = mb_convert_case($username, MB_CASE_TITLE, 'UTF-8');
  342. if (!strpos($username, ' ')) {
  343. throw new Exception(L10n::t("That doesn't appear to be your full \x28First Last\x29 name."));
  344. }
  345. }
  346. if (!Network::isEmailDomainAllowed($email)) {
  347. throw new Exception(L10n::t('Your email domain is not among those allowed on this site.'));
  348. }
  349. if (!valid_email($email) || !Network::isEmailDomainValid($email)) {
  350. throw new Exception(L10n::t('Not a valid email address.'));
  351. }
  352. if (Config::get('system', 'block_extended_register', false) && dba::exists('user', ['email' => $email])) {
  353. throw new Exception(L10n::t('Cannot use that email.'));
  354. }
  355. // Disallow somebody creating an account using openid that uses the admin email address,
  356. // since openid bypasses email verification. We'll allow it if there is not yet an admin account.
  357. if (x($a->config, 'admin_email') && strlen($openid_url)) {
  358. $adminlist = explode(',', str_replace(' ', '', strtolower($a->config['admin_email'])));
  359. if (in_array(strtolower($email), $adminlist)) {
  360. throw new Exception(L10n::t('Cannot use that email.'));
  361. }
  362. }
  363. $nickname = $data['nickname'] = strtolower($nickname);
  364. if (!preg_match('/^[a-z0-9][a-z0-9\_]*$/', $nickname)) {
  365. throw new Exception(L10n::t('Your nickname can only contain a-z, 0-9 and _.'));
  366. }
  367. // Check existing and deleted accounts for this nickname.
  368. if (dba::exists('user', ['nickname' => $nickname])
  369. || dba::exists('userd', ['username' => $nickname])
  370. ) {
  371. throw new Exception(L10n::t('Nickname is already registered. Please choose another.'));
  372. }
  373. $new_password = strlen($password) ? $password : User::generateNewPassword();
  374. $new_password_encoded = self::hashPassword($new_password);
  375. $return['password'] = $new_password;
  376. $keys = Crypto::newKeypair(4096);
  377. if ($keys === false) {
  378. throw new Exception(L10n::t('SERIOUS ERROR: Generation of security keys failed.'));
  379. }
  380. $prvkey = $keys['prvkey'];
  381. $pubkey = $keys['pubkey'];
  382. // Create another keypair for signing/verifying salmon protocol messages.
  383. $sres = Crypto::newKeypair(512);
  384. $sprvkey = $sres['prvkey'];
  385. $spubkey = $sres['pubkey'];
  386. $insert_result = dba::insert('user', [
  387. 'guid' => generate_user_guid(),
  388. 'username' => $username,
  389. 'password' => $new_password_encoded,
  390. 'email' => $email,
  391. 'openid' => $openid_url,
  392. 'nickname' => $nickname,
  393. 'pubkey' => $pubkey,
  394. 'prvkey' => $prvkey,
  395. 'spubkey' => $spubkey,
  396. 'sprvkey' => $sprvkey,
  397. 'verified' => $verified,
  398. 'blocked' => $blocked,
  399. 'timezone' => 'UTC',
  400. 'register_date' => DateTimeFormat::utcNow(),
  401. 'default-location' => ''
  402. ]);
  403. if ($insert_result) {
  404. $uid = dba::lastInsertId();
  405. $user = dba::selectFirst('user', [], ['uid' => $uid]);
  406. } else {
  407. throw new Exception(L10n::t('An error occurred during registration. Please try again.'));
  408. }
  409. if (!$uid) {
  410. throw new Exception(L10n::t('An error occurred during registration. Please try again.'));
  411. }
  412. // if somebody clicked submit twice very quickly, they could end up with two accounts
  413. // due to race condition. Remove this one.
  414. $user_count = dba::count('user', ['nickname' => $nickname]);
  415. if ($user_count > 1) {
  416. dba::delete('user', ['uid' => $uid]);
  417. throw new Exception(L10n::t('Nickname is already registered. Please choose another.'));
  418. }
  419. $insert_result = dba::insert('profile', [
  420. 'uid' => $uid,
  421. 'name' => $username,
  422. 'photo' => System::baseUrl() . "/photo/profile/{$uid}.jpg",
  423. 'thumb' => System::baseUrl() . "/photo/avatar/{$uid}.jpg",
  424. 'publish' => $publish,
  425. 'is-default' => 1,
  426. 'net-publish' => $netpublish,
  427. 'profile-name' => L10n::t('default')
  428. ]);
  429. if (!$insert_result) {
  430. dba::delete('user', ['uid' => $uid]);
  431. throw new Exception(L10n::t('An error occurred creating your default profile. Please try again.'));
  432. }
  433. // Create the self contact
  434. if (!Contact::createSelfFromUserId($uid)) {
  435. dba::delete('user', ['uid' => $uid]);
  436. throw new Exception(L10n::t('An error occurred creating your self contact. Please try again.'));
  437. }
  438. // Create a group with no members. This allows somebody to use it
  439. // right away as a default group for new contacts.
  440. $def_gid = Group::create($uid, L10n::t('Friends'));
  441. if (!$def_gid) {
  442. dba::delete('user', ['uid' => $uid]);
  443. throw new Exception(L10n::t('An error occurred creating your default contact group. Please try again.'));
  444. }
  445. $fields = ['def_gid' => $def_gid];
  446. if (Config::get('system', 'newuser_private') && $def_gid) {
  447. $fields['allow_gid'] = '<' . $def_gid . '>';
  448. }
  449. dba::update('user', $fields, ['uid' => $uid]);
  450. // if we have no OpenID photo try to look up an avatar
  451. if (!strlen($photo)) {
  452. $photo = Network::lookupAvatarByEmail($email);
  453. }
  454. // unless there is no avatar-addon loaded
  455. if (strlen($photo)) {
  456. $photo_failure = false;
  457. $filename = basename($photo);
  458. $img_str = Network::fetchUrl($photo, true);
  459. // guess mimetype from headers or filename
  460. $type = Image::guessType($photo, true);
  461. $Image = new Image($img_str, $type);
  462. if ($Image->isValid()) {
  463. $Image->scaleToSquare(175);
  464. $hash = Photo::newResource();
  465. $r = Photo::store($Image, $uid, 0, $hash, $filename, L10n::t('Profile Photos'), 4);
  466. if ($r === false) {
  467. $photo_failure = true;
  468. }
  469. $Image->scaleDown(80);
  470. $r = Photo::store($Image, $uid, 0, $hash, $filename, L10n::t('Profile Photos'), 5);
  471. if ($r === false) {
  472. $photo_failure = true;
  473. }
  474. $Image->scaleDown(48);
  475. $r = Photo::store($Image, $uid, 0, $hash, $filename, L10n::t('Profile Photos'), 6);
  476. if ($r === false) {
  477. $photo_failure = true;
  478. }
  479. if (!$photo_failure) {
  480. dba::update('photo', ['profile' => 1], ['resource-id' => $hash]);
  481. }
  482. }
  483. }
  484. Addon::callHooks('register_account', $uid);
  485. $return['user'] = $user;
  486. return $return;
  487. }
  488. /**
  489. * @brief Sends pending registration confiŕmation email
  490. *
  491. * @param string $email
  492. * @param string $sitename
  493. * @param string $username
  494. * @return NULL|boolean from notification() and email() inherited
  495. */
  496. public static function sendRegisterPendingEmail($email, $sitename, $username)
  497. {
  498. $body = deindent(L10n::t('
  499. Dear %1$s,
  500. Thank you for registering at %2$s. Your account is pending for approval by the administrator.
  501. '));
  502. $body = sprintf($body, $username, $sitename);
  503. return notification([
  504. 'type' => SYSTEM_EMAIL,
  505. 'to_email' => $email,
  506. 'subject'=> L10n::t('Registration at %s', $sitename),
  507. 'body' => $body]);
  508. }
  509. /**
  510. * @brief Sends registration confirmation
  511. *
  512. * It's here as a function because the mail is sent from different parts
  513. *
  514. * @param string $email
  515. * @param string $sitename
  516. * @param string $siteurl
  517. * @param string $username
  518. * @param string $password
  519. * @return NULL|boolean from notification() and email() inherited
  520. */
  521. public static function sendRegisterOpenEmail($email, $sitename, $siteurl, $username, $password)
  522. {
  523. $preamble = deindent(L10n::t('
  524. Dear %1$s,
  525. Thank you for registering at %2$s. Your account has been created.
  526. '));
  527. $body = deindent(L10n::t('
  528. The login details are as follows:
  529. Site Location: %3$s
  530. Login Name: %1$s
  531. Password: %5$s
  532. You may change your password from your account "Settings" page after logging
  533. in.
  534. Please take a few moments to review the other account settings on that page.
  535. You may also wish to add some basic information to your default profile
  536. ' . "\x28" . 'on the "Profiles" page' . "\x29" . ' so that other people can easily find you.
  537. We recommend setting your full name, adding a profile photo,
  538. adding some profile "keywords" ' . "\x28" . 'very useful in making new friends' . "\x29" . ' - and
  539. perhaps what country you live in; if you do not wish to be more specific
  540. than that.
  541. We fully respect your right to privacy, and none of these items are necessary.
  542. If you are new and do not know anybody here, they may help
  543. you to make some new and interesting friends.
  544. If you ever want to delete your account, you can do so at %3$s/removeme
  545. Thank you and welcome to %2$s.'));
  546. $preamble = sprintf($preamble, $username, $sitename);
  547. $body = sprintf($body, $email, $sitename, $siteurl, $username, $password);
  548. return notification([
  549. 'type' => SYSTEM_EMAIL,
  550. 'to_email' => $email,
  551. 'subject'=> L10n::t('Registration details for %s', $sitename),
  552. 'preamble'=> $preamble,
  553. 'body' => $body]);
  554. }
  555. /**
  556. * @param object $uid user to remove
  557. * @return void
  558. */
  559. public static function remove($uid)
  560. {
  561. if (!$uid) {
  562. return;
  563. }
  564. logger('Removing user: ' . $uid);
  565. $user = dba::selectFirst('user', [], ['uid' => $uid]);
  566. Addon::callHooks('remove_user', $user);
  567. // save username (actually the nickname as it is guaranteed
  568. // unique), so it cannot be re-registered in the future.
  569. dba::insert('userd', ['username' => $user['nickname']]);
  570. // The user and related data will be deleted in "cron_expire_and_remove_users" (cronjobs.php)
  571. dba::update('user', ['account_removed' => true, 'account_expires_on' => DateTimeFormat::utcNow()], ['uid' => $uid]);
  572. Worker::add(PRIORITY_HIGH, "Notifier", "removeme", $uid);
  573. // Send an update to the directory
  574. Worker::add(PRIORITY_LOW, "Directory", $user['url']);
  575. if ($uid == local_user()) {
  576. unset($_SESSION['authenticated']);
  577. unset($_SESSION['uid']);
  578. goaway(System::baseUrl());
  579. }
  580. }
  581. }