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.

894 lines
26KB

  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;
  8. use Exception;
  9. use Friendica\Core\Addon;
  10. use Friendica\Core\Config;
  11. use Friendica\Core\Hook;
  12. use Friendica\Core\L10n;
  13. use Friendica\Core\Logger;
  14. use Friendica\Core\PConfig;
  15. use Friendica\Core\Protocol;
  16. use Friendica\Core\System;
  17. use Friendica\Core\Worker;
  18. use Friendica\Database\DBA;
  19. use Friendica\Object\Image;
  20. use Friendica\Util\Crypto;
  21. use Friendica\Util\DateTimeFormat;
  22. use Friendica\Util\Network;
  23. use Friendica\Util\Strings;
  24. use LightOpenID;
  25. /**
  26. * @brief This class handles User related functions
  27. */
  28. class User
  29. {
  30. /**
  31. * Returns true if a user record exists with the provided id
  32. *
  33. * @param integer $uid
  34. * @return boolean
  35. */
  36. public static function exists($uid)
  37. {
  38. return DBA::exists('user', ['uid' => $uid]);
  39. }
  40. /**
  41. * @param integer $uid
  42. * @return array|boolean User record if it exists, false otherwise
  43. */
  44. public static function getById($uid)
  45. {
  46. return DBA::selectFirst('user', [], ['uid' => $uid]);
  47. }
  48. /**
  49. * @brief Returns the user id of a given profile URL
  50. *
  51. * @param string $url
  52. *
  53. * @return integer user id
  54. */
  55. public static function getIdForURL($url)
  56. {
  57. $self = DBA::selectFirst('contact', ['uid'], ['nurl' => Strings::normaliseLink($url), 'self' => true]);
  58. if (!DBA::isResult($self)) {
  59. return false;
  60. } else {
  61. return $self['uid'];
  62. }
  63. }
  64. /**
  65. * @brief Get owner data by user id
  66. *
  67. * @param int $uid
  68. * @return boolean|array
  69. */
  70. public static function getOwnerDataById($uid) {
  71. $r = DBA::fetchFirst("SELECT
  72. `contact`.*,
  73. `user`.`prvkey` AS `uprvkey`,
  74. `user`.`timezone`,
  75. `user`.`nickname`,
  76. `user`.`sprvkey`,
  77. `user`.`spubkey`,
  78. `user`.`page-flags`,
  79. `user`.`account-type`,
  80. `user`.`prvnets`
  81. FROM `contact`
  82. INNER JOIN `user`
  83. ON `user`.`uid` = `contact`.`uid`
  84. WHERE `contact`.`uid` = ?
  85. AND `contact`.`self`
  86. LIMIT 1",
  87. $uid
  88. );
  89. if (!DBA::isResult($r)) {
  90. return false;
  91. }
  92. if (empty($r['nickname'])) {
  93. return false;
  94. }
  95. // Check if the returned data is valid, otherwise fix it. See issue #6122
  96. $url = System::baseUrl() . '/profile/' . $r['nickname'];
  97. $addr = $r['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
  98. if (($addr != $r['addr']) || ($r['url'] != $url) || ($r['nurl'] != Strings::normaliseLink($r['url']))) {
  99. Contact::updateSelfFromUserID($uid);
  100. }
  101. return $r;
  102. }
  103. /**
  104. * @brief Get owner data by nick name
  105. *
  106. * @param int $nick
  107. * @return boolean|array
  108. */
  109. public static function getOwnerDataByNick($nick)
  110. {
  111. $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nick]);
  112. if (!DBA::isResult($user)) {
  113. return false;
  114. }
  115. return self::getOwnerDataById($user['uid']);
  116. }
  117. /**
  118. * @brief Returns the default group for a given user and network
  119. *
  120. * @param int $uid User id
  121. * @param string $network network name
  122. *
  123. * @return int group id
  124. */
  125. public static function getDefaultGroup($uid, $network = '')
  126. {
  127. $default_group = 0;
  128. if ($network == Protocol::OSTATUS) {
  129. $default_group = PConfig::get($uid, "ostatus", "default_group");
  130. }
  131. if ($default_group != 0) {
  132. return $default_group;
  133. }
  134. $user = DBA::selectFirst('user', ['def_gid'], ['uid' => $uid]);
  135. if (DBA::isResult($user)) {
  136. $default_group = $user["def_gid"];
  137. }
  138. return $default_group;
  139. }
  140. /**
  141. * Authenticate a user with a clear text password
  142. *
  143. * @brief Authenticate a user with a clear text password
  144. * @param mixed $user_info
  145. * @param string $password
  146. * @return int|boolean
  147. * @deprecated since version 3.6
  148. * @see User::getIdFromPasswordAuthentication()
  149. */
  150. public static function authenticate($user_info, $password)
  151. {
  152. try {
  153. return self::getIdFromPasswordAuthentication($user_info, $password);
  154. } catch (Exception $ex) {
  155. return false;
  156. }
  157. }
  158. /**
  159. * Returns the user id associated with a successful password authentication
  160. *
  161. * @brief Authenticate a user with a clear text password
  162. * @param mixed $user_info
  163. * @param string $password
  164. * @return int User Id if authentication is successful
  165. * @throws Exception
  166. */
  167. public static function getIdFromPasswordAuthentication($user_info, $password)
  168. {
  169. $user = self::getAuthenticationInfo($user_info);
  170. if (strpos($user['password'], '$') === false) {
  171. //Legacy hash that has not been replaced by a new hash yet
  172. if (self::hashPasswordLegacy($password) === $user['password']) {
  173. self::updatePassword($user['uid'], $password);
  174. return $user['uid'];
  175. }
  176. } elseif (!empty($user['legacy_password'])) {
  177. //Legacy hash that has been double-hashed and not replaced by a new hash yet
  178. //Warning: `legacy_password` is not necessary in sync with the content of `password`
  179. if (password_verify(self::hashPasswordLegacy($password), $user['password'])) {
  180. self::updatePassword($user['uid'], $password);
  181. return $user['uid'];
  182. }
  183. } elseif (password_verify($password, $user['password'])) {
  184. //New password hash
  185. if (password_needs_rehash($user['password'], PASSWORD_DEFAULT)) {
  186. self::updatePassword($user['uid'], $password);
  187. }
  188. return $user['uid'];
  189. }
  190. throw new Exception(L10n::t('Login failed'));
  191. }
  192. /**
  193. * Returns authentication info from various parameters types
  194. *
  195. * User info can be any of the following:
  196. * - User DB object
  197. * - User Id
  198. * - User email or username or nickname
  199. * - User array with at least the uid and the hashed password
  200. *
  201. * @param mixed $user_info
  202. * @return array
  203. * @throws Exception
  204. */
  205. private static function getAuthenticationInfo($user_info)
  206. {
  207. $user = null;
  208. if (is_object($user_info) || is_array($user_info)) {
  209. if (is_object($user_info)) {
  210. $user = (array) $user_info;
  211. } else {
  212. $user = $user_info;
  213. }
  214. if (!isset($user['uid'])
  215. || !isset($user['password'])
  216. || !isset($user['legacy_password'])
  217. ) {
  218. throw new Exception(L10n::t('Not enough information to authenticate'));
  219. }
  220. } elseif (is_int($user_info) || is_string($user_info)) {
  221. if (is_int($user_info)) {
  222. $user = DBA::selectFirst('user', ['uid', 'password', 'legacy_password'],
  223. [
  224. 'uid' => $user_info,
  225. 'blocked' => 0,
  226. 'account_expired' => 0,
  227. 'account_removed' => 0,
  228. 'verified' => 1
  229. ]
  230. );
  231. } else {
  232. $fields = ['uid', 'password', 'legacy_password'];
  233. $condition = ["(`email` = ? OR `username` = ? OR `nickname` = ?)
  234. AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified`",
  235. $user_info, $user_info, $user_info];
  236. $user = DBA::selectFirst('user', $fields, $condition);
  237. }
  238. if (!DBA::isResult($user)) {
  239. throw new Exception(L10n::t('User not found'));
  240. }
  241. }
  242. return $user;
  243. }
  244. /**
  245. * Generates a human-readable random password
  246. *
  247. * @return string
  248. */
  249. public static function generateNewPassword()
  250. {
  251. return Strings::getRandomName(6) . mt_rand(100, 9999);
  252. }
  253. /**
  254. * Checks if the provided plaintext password has been exposed or not
  255. *
  256. * @param string $password
  257. * @return bool
  258. */
  259. public static function isPasswordExposed($password)
  260. {
  261. $cache = new \DivineOmega\DOFileCachePSR6\CacheItemPool();
  262. $cache->changeConfig([
  263. 'cacheDirectory' => get_temppath() . '/password-exposed-cache/',
  264. ]);
  265. $PasswordExposedCHecker = new PasswordExposed\PasswordExposedChecker(null, $cache);
  266. return $PasswordExposedCHecker->passwordExposed($password) === PasswordExposed\PasswordStatus::EXPOSED;
  267. }
  268. /**
  269. * Legacy hashing function, kept for password migration purposes
  270. *
  271. * @param string $password
  272. * @return string
  273. */
  274. private static function hashPasswordLegacy($password)
  275. {
  276. return hash('whirlpool', $password);
  277. }
  278. /**
  279. * Global user password hashing function
  280. *
  281. * @param string $password
  282. * @return string
  283. */
  284. public static function hashPassword($password)
  285. {
  286. if (!trim($password)) {
  287. throw new Exception(L10n::t('Password can\'t be empty'));
  288. }
  289. return password_hash($password, PASSWORD_DEFAULT);
  290. }
  291. /**
  292. * Updates a user row with a new plaintext password
  293. *
  294. * @param int $uid
  295. * @param string $password
  296. * @return bool
  297. */
  298. public static function updatePassword($uid, $password)
  299. {
  300. return self::updatePasswordHashed($uid, self::hashPassword($password));
  301. }
  302. /**
  303. * Updates a user row with a new hashed password.
  304. * Empties the password reset token field just in case.
  305. *
  306. * @param int $uid
  307. * @param string $pasword_hashed
  308. * @return bool
  309. */
  310. private static function updatePasswordHashed($uid, $pasword_hashed)
  311. {
  312. $fields = [
  313. 'password' => $pasword_hashed,
  314. 'pwdreset' => null,
  315. 'pwdreset_time' => null,
  316. 'legacy_password' => false
  317. ];
  318. return DBA::update('user', $fields, ['uid' => $uid]);
  319. }
  320. /**
  321. * @brief Checks if a nickname is in the list of the forbidden nicknames
  322. *
  323. * Check if a nickname is forbidden from registration on the node by the
  324. * admin. Forbidden nicknames (e.g. role namess) can be configured in the
  325. * admin panel.
  326. *
  327. * @param string $nickname The nickname that should be checked
  328. * @return boolean True is the nickname is blocked on the node
  329. */
  330. public static function isNicknameBlocked($nickname)
  331. {
  332. $forbidden_nicknames = Config::get('system', 'forbidden_nicknames', '');
  333. // if the config variable is empty return false
  334. if (empty($forbidden_nicknames)) {
  335. return false;
  336. }
  337. // check if the nickname is in the list of blocked nicknames
  338. $forbidden = explode(',', $forbidden_nicknames);
  339. $forbidden = array_map('trim', $forbidden);
  340. if (in_array(strtolower($nickname), $forbidden)) {
  341. return true;
  342. }
  343. // else return false
  344. return false;
  345. }
  346. /**
  347. * @brief Catch-all user creation function
  348. *
  349. * Creates a user from the provided data array, either form fields or OpenID.
  350. * Required: { username, nickname, email } or { openid_url }
  351. *
  352. * Performs the following:
  353. * - Sends to the OpenId auth URL (if relevant)
  354. * - Creates new key pairs for crypto
  355. * - Create self-contact
  356. * - Create profile image
  357. *
  358. * @param array $data
  359. * @return string
  360. * @throw Exception
  361. */
  362. public static function create(array $data)
  363. {
  364. $a = get_app();
  365. $return = ['user' => null, 'password' => ''];
  366. $using_invites = Config::get('system', 'invitation_only');
  367. $num_invites = Config::get('system', 'number_invites');
  368. $invite_id = !empty($data['invite_id']) ? Strings::escapeTags(trim($data['invite_id'])) : '';
  369. $username = !empty($data['username']) ? Strings::escapeTags(trim($data['username'])) : '';
  370. $nickname = !empty($data['nickname']) ? Strings::escapeTags(trim($data['nickname'])) : '';
  371. $email = !empty($data['email']) ? Strings::escapeTags(trim($data['email'])) : '';
  372. $openid_url = !empty($data['openid_url']) ? Strings::escapeTags(trim($data['openid_url'])) : '';
  373. $photo = !empty($data['photo']) ? Strings::escapeTags(trim($data['photo'])) : '';
  374. $password = !empty($data['password']) ? trim($data['password']) : '';
  375. $password1 = !empty($data['password1']) ? trim($data['password1']) : '';
  376. $confirm = !empty($data['confirm']) ? trim($data['confirm']) : '';
  377. $blocked = !empty($data['blocked']);
  378. $verified = !empty($data['verified']);
  379. $language = !empty($data['language']) ? Strings::escapeTags(trim($data['language'])) : 'en';
  380. $publish = !empty($data['profile_publish_reg']);
  381. $netpublish = $publish && Config::get('system', 'directory');
  382. if ($password1 != $confirm) {
  383. throw new Exception(L10n::t('Passwords do not match. Password unchanged.'));
  384. } elseif ($password1 != '') {
  385. $password = $password1;
  386. }
  387. if ($using_invites) {
  388. if (!$invite_id) {
  389. throw new Exception(L10n::t('An invitation is required.'));
  390. }
  391. if (!Register::existsByHash($invite_id)) {
  392. throw new Exception(L10n::t('Invitation could not be verified.'));
  393. }
  394. }
  395. if (empty($username) || empty($email) || empty($nickname)) {
  396. if ($openid_url) {
  397. if (!Network::isUrlValid($openid_url)) {
  398. throw new Exception(L10n::t('Invalid OpenID url'));
  399. }
  400. $_SESSION['register'] = 1;
  401. $_SESSION['openid'] = $openid_url;
  402. $openid = new LightOpenID($a->getHostName());
  403. $openid->identity = $openid_url;
  404. $openid->returnUrl = System::baseUrl() . '/openid';
  405. $openid->required = ['namePerson/friendly', 'contact/email', 'namePerson'];
  406. $openid->optional = ['namePerson/first', 'media/image/aspect11', 'media/image/default'];
  407. try {
  408. $authurl = $openid->authUrl();
  409. } catch (Exception $e) {
  410. 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);
  411. }
  412. System::externalRedirect($authurl);
  413. // NOTREACHED
  414. }
  415. throw new Exception(L10n::t('Please enter the required information.'));
  416. }
  417. if (!Network::isUrlValid($openid_url)) {
  418. $openid_url = '';
  419. }
  420. $err = '';
  421. // collapse multiple spaces in name
  422. $username = preg_replace('/ +/', ' ', $username);
  423. $username_min_length = max(1, min(64, intval(Config::get('system', 'username_min_length', 3))));
  424. $username_max_length = max(1, min(64, intval(Config::get('system', 'username_max_length', 48))));
  425. if ($username_min_length > $username_max_length) {
  426. 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);
  427. $tmp = $username_min_length;
  428. $username_min_length = $username_max_length;
  429. $username_max_length = $tmp;
  430. }
  431. if (mb_strlen($username) < $username_min_length) {
  432. throw new Exception(L10n::tt('Username should be at least %s character.', 'Username should be at least %s characters.', $username_min_length));
  433. }
  434. if (mb_strlen($username) > $username_max_length) {
  435. throw new Exception(L10n::tt('Username should be at most %s character.', 'Username should be at most %s characters.', $username_max_length));
  436. }
  437. // So now we are just looking for a space in the full name.
  438. $loose_reg = Config::get('system', 'no_regfullname');
  439. if (!$loose_reg) {
  440. $username = mb_convert_case($username, MB_CASE_TITLE, 'UTF-8');
  441. if (strpos($username, ' ') === false) {
  442. throw new Exception(L10n::t("That doesn't appear to be your full (First Last) name."));
  443. }
  444. }
  445. if (!Network::isEmailDomainAllowed($email)) {
  446. throw new Exception(L10n::t('Your email domain is not among those allowed on this site.'));
  447. }
  448. if (!filter_var($email, FILTER_VALIDATE_EMAIL) || !Network::isEmailDomainValid($email)) {
  449. throw new Exception(L10n::t('Not a valid email address.'));
  450. }
  451. if (self::isNicknameBlocked($nickname)) {
  452. throw new Exception(L10n::t('The nickname was blocked from registration by the nodes admin.'));
  453. }
  454. if (Config::get('system', 'block_extended_register', false) && DBA::exists('user', ['email' => $email])) {
  455. throw new Exception(L10n::t('Cannot use that email.'));
  456. }
  457. // Disallow somebody creating an account using openid that uses the admin email address,
  458. // since openid bypasses email verification. We'll allow it if there is not yet an admin account.
  459. if (Config::get('config', 'admin_email') && strlen($openid_url)) {
  460. $adminlist = explode(',', str_replace(' ', '', strtolower(Config::get('config', 'admin_email'))));
  461. if (in_array(strtolower($email), $adminlist)) {
  462. throw new Exception(L10n::t('Cannot use that email.'));
  463. }
  464. }
  465. $nickname = $data['nickname'] = strtolower($nickname);
  466. if (!preg_match('/^[a-z0-9][a-z0-9\_]*$/', $nickname)) {
  467. throw new Exception(L10n::t('Your nickname can only contain a-z, 0-9 and _.'));
  468. }
  469. // Check existing and deleted accounts for this nickname.
  470. if (DBA::exists('user', ['nickname' => $nickname])
  471. || DBA::exists('userd', ['username' => $nickname])
  472. ) {
  473. throw new Exception(L10n::t('Nickname is already registered. Please choose another.'));
  474. }
  475. $new_password = strlen($password) ? $password : User::generateNewPassword();
  476. $new_password_encoded = self::hashPassword($new_password);
  477. $return['password'] = $new_password;
  478. $keys = Crypto::newKeypair(4096);
  479. if ($keys === false) {
  480. throw new Exception(L10n::t('SERIOUS ERROR: Generation of security keys failed.'));
  481. }
  482. $prvkey = $keys['prvkey'];
  483. $pubkey = $keys['pubkey'];
  484. // Create another keypair for signing/verifying salmon protocol messages.
  485. $sres = Crypto::newKeypair(512);
  486. $sprvkey = $sres['prvkey'];
  487. $spubkey = $sres['pubkey'];
  488. $insert_result = DBA::insert('user', [
  489. 'guid' => System::createUUID(),
  490. 'username' => $username,
  491. 'password' => $new_password_encoded,
  492. 'email' => $email,
  493. 'openid' => $openid_url,
  494. 'nickname' => $nickname,
  495. 'pubkey' => $pubkey,
  496. 'prvkey' => $prvkey,
  497. 'spubkey' => $spubkey,
  498. 'sprvkey' => $sprvkey,
  499. 'verified' => $verified,
  500. 'blocked' => $blocked,
  501. 'language' => $language,
  502. 'timezone' => 'UTC',
  503. 'register_date' => DateTimeFormat::utcNow(),
  504. 'default-location' => ''
  505. ]);
  506. if ($insert_result) {
  507. $uid = DBA::lastInsertId();
  508. $user = DBA::selectFirst('user', [], ['uid' => $uid]);
  509. } else {
  510. throw new Exception(L10n::t('An error occurred during registration. Please try again.'));
  511. }
  512. if (!$uid) {
  513. throw new Exception(L10n::t('An error occurred during registration. Please try again.'));
  514. }
  515. // if somebody clicked submit twice very quickly, they could end up with two accounts
  516. // due to race condition. Remove this one.
  517. $user_count = DBA::count('user', ['nickname' => $nickname]);
  518. if ($user_count > 1) {
  519. DBA::delete('user', ['uid' => $uid]);
  520. throw new Exception(L10n::t('Nickname is already registered. Please choose another.'));
  521. }
  522. $insert_result = DBA::insert('profile', [
  523. 'uid' => $uid,
  524. 'name' => $username,
  525. 'photo' => System::baseUrl() . "/photo/profile/{$uid}.jpg",
  526. 'thumb' => System::baseUrl() . "/photo/avatar/{$uid}.jpg",
  527. 'publish' => $publish,
  528. 'is-default' => 1,
  529. 'net-publish' => $netpublish,
  530. 'profile-name' => L10n::t('default')
  531. ]);
  532. if (!$insert_result) {
  533. DBA::delete('user', ['uid' => $uid]);
  534. throw new Exception(L10n::t('An error occurred creating your default profile. Please try again.'));
  535. }
  536. // Create the self contact
  537. if (!Contact::createSelfFromUserId($uid)) {
  538. DBA::delete('user', ['uid' => $uid]);
  539. throw new Exception(L10n::t('An error occurred creating your self contact. Please try again.'));
  540. }
  541. // Create a group with no members. This allows somebody to use it
  542. // right away as a default group for new contacts.
  543. $def_gid = Group::create($uid, L10n::t('Friends'));
  544. if (!$def_gid) {
  545. DBA::delete('user', ['uid' => $uid]);
  546. throw new Exception(L10n::t('An error occurred creating your default contact group. Please try again.'));
  547. }
  548. $fields = ['def_gid' => $def_gid];
  549. if (Config::get('system', 'newuser_private') && $def_gid) {
  550. $fields['allow_gid'] = '<' . $def_gid . '>';
  551. }
  552. DBA::update('user', $fields, ['uid' => $uid]);
  553. // if we have no OpenID photo try to look up an avatar
  554. if (!strlen($photo)) {
  555. $photo = Network::lookupAvatarByEmail($email);
  556. }
  557. // unless there is no avatar-addon loaded
  558. if (strlen($photo)) {
  559. $photo_failure = false;
  560. $filename = basename($photo);
  561. $img_str = Network::fetchUrl($photo, true);
  562. // guess mimetype from headers or filename
  563. $type = Image::guessType($photo, true);
  564. $Image = new Image($img_str, $type);
  565. if ($Image->isValid()) {
  566. $Image->scaleToSquare(300);
  567. $hash = Photo::newResource();
  568. $r = Photo::store($Image, $uid, 0, $hash, $filename, L10n::t('Profile Photos'), 4);
  569. if ($r === false) {
  570. $photo_failure = true;
  571. }
  572. $Image->scaleDown(80);
  573. $r = Photo::store($Image, $uid, 0, $hash, $filename, L10n::t('Profile Photos'), 5);
  574. if ($r === false) {
  575. $photo_failure = true;
  576. }
  577. $Image->scaleDown(48);
  578. $r = Photo::store($Image, $uid, 0, $hash, $filename, L10n::t('Profile Photos'), 6);
  579. if ($r === false) {
  580. $photo_failure = true;
  581. }
  582. if (!$photo_failure) {
  583. DBA::update('photo', ['profile' => 1], ['resource-id' => $hash]);
  584. }
  585. }
  586. }
  587. Addon::callHooks('register_account', $uid);
  588. $return['user'] = $user;
  589. return $return;
  590. }
  591. /**
  592. * @brief Sends pending registration confirmation email
  593. *
  594. * @param array $user User record array
  595. * @param string $sitename
  596. * @param string $siteurl
  597. * @param string $password Plaintext password
  598. * @return NULL|boolean from notification() and email() inherited
  599. */
  600. public static function sendRegisterPendingEmail($user, $sitename, $siteurl, $password)
  601. {
  602. $body = Strings::deindent(L10n::t('
  603. Dear %1$s,
  604. Thank you for registering at %2$s. Your account is pending for approval by the administrator.
  605. Your login details are as follows:
  606. Site Location: %3$s
  607. Login Name: %4$s
  608. Password: %5$s
  609. ',
  610. $user['username'], $sitename, $siteurl, $user['nickname'], $password
  611. ));
  612. return notification([
  613. 'type' => SYSTEM_EMAIL,
  614. 'uid' => $user['uid'],
  615. 'to_email' => $user['email'],
  616. 'subject' => L10n::t('Registration at %s', $sitename),
  617. 'body' => $body
  618. ]);
  619. }
  620. /**
  621. * @brief Sends registration confirmation
  622. *
  623. * It's here as a function because the mail is sent from different parts
  624. *
  625. * @param array $user User record array
  626. * @param string $sitename
  627. * @param string $siteurl
  628. * @param string $password Plaintext password
  629. * @return NULL|boolean from notification() and email() inherited
  630. */
  631. public static function sendRegisterOpenEmail($user, $sitename, $siteurl, $password)
  632. {
  633. $preamble = Strings::deindent(L10n::t('
  634. Dear %1$s,
  635. Thank you for registering at %2$s. Your account has been created.
  636. ',
  637. $user['username'], $sitename
  638. ));
  639. $body = Strings::deindent(L10n::t('
  640. The login details are as follows:
  641. Site Location: %3$s
  642. Login Name: %1$s
  643. Password: %5$s
  644. You may change your password from your account "Settings" page after logging
  645. in.
  646. Please take a few moments to review the other account settings on that page.
  647. You may also wish to add some basic information to your default profile
  648. ' . "\x28" . 'on the "Profiles" page' . "\x29" . ' so that other people can easily find you.
  649. We recommend setting your full name, adding a profile photo,
  650. adding some profile "keywords" ' . "\x28" . 'very useful in making new friends' . "\x29" . ' - and
  651. perhaps what country you live in; if you do not wish to be more specific
  652. than that.
  653. We fully respect your right to privacy, and none of these items are necessary.
  654. If you are new and do not know anybody here, they may help
  655. you to make some new and interesting friends.
  656. If you ever want to delete your account, you can do so at %3$s/removeme
  657. Thank you and welcome to %2$s.',
  658. $user['email'], $sitename, $siteurl, $user['username'], $password
  659. ));
  660. return notification([
  661. 'uid' => $user['uid'],
  662. 'language' => $user['language'],
  663. 'type' => SYSTEM_EMAIL,
  664. 'to_email' => $user['email'],
  665. 'subject' => L10n::t('Registration details for %s', $sitename),
  666. 'preamble' => $preamble,
  667. 'body' => $body
  668. ]);
  669. }
  670. /**
  671. * @param object $uid user to remove
  672. * @return void
  673. */
  674. public static function remove($uid)
  675. {
  676. if (!$uid) {
  677. return false;
  678. }
  679. $a = get_app();
  680. Logger::log('Removing user: ' . $uid);
  681. $user = DBA::selectFirst('user', [], ['uid' => $uid]);
  682. Hook::callAll('remove_user', $user);
  683. // save username (actually the nickname as it is guaranteed
  684. // unique), so it cannot be re-registered in the future.
  685. DBA::insert('userd', ['username' => $user['nickname']]);
  686. // The user and related data will be deleted in "cron_expire_and_remove_users" (cronjobs.php)
  687. DBA::update('user', ['account_removed' => true, 'account_expires_on' => DateTimeFormat::utc('now + 7 day')], ['uid' => $uid]);
  688. Worker::add(PRIORITY_HIGH, 'Notifier', 'removeme', $uid);
  689. // Send an update to the directory
  690. $self = DBA::selectFirst('contact', ['url'], ['uid' => $uid, 'self' => true]);
  691. Worker::add(PRIORITY_LOW, 'Directory', $self['url']);
  692. // Remove the user relevant data
  693. Worker::add(PRIORITY_LOW, 'RemoveUser', $uid);
  694. return true;
  695. }
  696. /**
  697. * Return all identities to a user
  698. *
  699. * @param int $uid The user id
  700. * @return array All identities for this user
  701. *
  702. * Example for a return:
  703. * [
  704. * [
  705. * 'uid' => 1,
  706. * 'username' => 'maxmuster',
  707. * 'nickname' => 'Max Mustermann'
  708. * ],
  709. * [
  710. * 'uid' => 2,
  711. * 'username' => 'johndoe',
  712. * 'nickname' => 'John Doe'
  713. * ]
  714. * ]
  715. */
  716. public static function identities($uid)
  717. {
  718. $identities = [];
  719. $user = DBA::selectFirst('user', ['uid', 'nickname', 'username', 'parent-uid'], ['uid' => $uid]);
  720. if (!DBA::isResult($user)) {
  721. return $identities;
  722. }
  723. if ($user['parent-uid'] == 0) {
  724. // First add our own entry
  725. $identities = [['uid' => $user['uid'],
  726. 'username' => $user['username'],
  727. 'nickname' => $user['nickname']]];
  728. // Then add all the children
  729. $r = DBA::select('user', ['uid', 'username', 'nickname'],
  730. ['parent-uid' => $user['uid'], 'account_removed' => false]);
  731. if (DBA::isResult($r)) {
  732. $identities = array_merge($identities, DBA::toArray($r));
  733. }
  734. } else {
  735. // First entry is our parent
  736. $r = DBA::select('user', ['uid', 'username', 'nickname'],
  737. ['uid' => $user['parent-uid'], 'account_removed' => false]);
  738. if (DBA::isResult($r)) {
  739. $identities = DBA::toArray($r);
  740. }
  741. // Then add all siblings
  742. $r = DBA::select('user', ['uid', 'username', 'nickname'],
  743. ['parent-uid' => $user['parent-uid'], 'account_removed' => false]);
  744. if (DBA::isResult($r)) {
  745. $identities = array_merge($identities, DBA::toArray($r));
  746. }
  747. }
  748. $r = DBA::p("SELECT `user`.`uid`, `user`.`username`, `user`.`nickname`
  749. FROM `manage`
  750. INNER JOIN `user` ON `manage`.`mid` = `user`.`uid`
  751. WHERE `user`.`account_removed` = 0 AND `manage`.`uid` = ?",
  752. $user['uid']
  753. );
  754. if (DBA::isResult($r)) {
  755. $identities = array_merge($identities, DBA::toArray($r));
  756. }
  757. return $identities;
  758. }
  759. }