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.

913 lines
26 KiB

4 years ago
4 years ago
Cleanups: isResult() more used, readability improved (#5608) * [diaspora]: Maybe SimpleXMLElement is the right type-hint? * Changes proposed + pre-renaming: - pre-renamed $db -> $connection - added TODOs for not allowing bad method invocations (there is a BadMethodCallException in SPL) * If no record is found, below $r[0] will fail with a E_NOTICE and the code doesn't behave as expected. * Ops, one more left ... * Continued: - added documentation for Contact::updateSslPolicy() method - added type-hint for $contact of same method - empty lines added + TODO where the bug origins that $item has no element 'body' * Added empty lines for better readability * Cleaned up: - no more x() (deprecated) usage but empty() instead - fixed mixing of space/tab indending - merged else/if block goether in elseif() (lesser nested code blocks) * Re-fixed DBM -> DBA switch * Fixes/rewrites: - use empty()/isset() instead of deprecated x() - merged 2 nested if() blocks into one - avoided nested if() block inside else block by rewriting it to elseif() - $contact_id is an integer, let's test on > 0 here - added a lot spaces and some empty lines for better readability * Rewrite: - moved all CONTACT_* constants from boot.php to Contact class * CR request: - renamed Contact::CONTACT_IS_* -> Contact::* ;-) * Rewrites: - moved PAGE_* to Friendica\Model\Profile class - fixed mixure with "Contact::* rewrite" * Ops, one still there (return is no function) * Rewrite to Proxy class: - introduced new Friendica\Network\Proxy class for in exchange of proxy_*() functions - moved also all PROXY_* constants there as Proxy::* - removed now no longer needed mod/proxy.php loading as composer's auto-load will do this for us - renamed those proxy_*() functions to better names: + proxy_init() -> Proxy::init() (public) + proxy_url() -> Proxy::proxifyUrl() (public) + proxy_parse_html() -> Proxy::proxifyHtml() (public) + proxy_is_local_image() -> Proxy::isLocalImage() (private) + proxy_parse_query() -> Proxy::parseQuery() (private) + proxy_img_cb() -> Proxy::replaceUrl() (private) * CR request: - moved all PAGE_* constants to Friendica\Model\Contact class - fixed all references of both classes * Ops, need to set $a here ... * CR request: - moved Proxy class to Friendica\Module - extended BaseModule * Ops, no need for own instance of $a when self::getApp() is around. * Proxy-rewrite: - proxy_url() and proxy_parse_html() are both non-module functions (now methods) - so they must be splitted into a seperate class - also the SIZE_* and DEFAULT_TIME constants are both not relevant to module * No instances from utility classes * Fixed error: - proxify*() is now located in `Friendica\Util\ProxyUtils` * Moved back to original place, ops? How did they move here? Well, it was not intended by me. * Removed duplicate (left-over from split) constants and static array. Thank to MrPetovan finding it. * Renamed ProxyUtils -> Proxy and aliased it back to ProxyUtils. * Rewrite: - stopped using deprecated NETWORK_* constants, now Protocol::* should be used - still left them intact for slow/lazy developers ... * Ops, was added accidentally ... * Ops, why these wrong moves? * Ops, one to much (thanks to MrPetovan) * Ops, wrong moving ... * moved back to original place ... * spaces added * empty lines add for better readability. * convertered spaces -> tab for code indenting. * CR request: Add space between if and brace. * CR requests fixed + move reverted - ops, src/Module/*.php has been moved to src/Network/ accidentally - reverted some parts in src/Database/DBA.php as pointed out by Annando - removed internal TODO items - added some spaces for better readability
3 years ago
Cleanups: isResult() more used, readability improved (#5608) * [diaspora]: Maybe SimpleXMLElement is the right type-hint? * Changes proposed + pre-renaming: - pre-renamed $db -> $connection - added TODOs for not allowing bad method invocations (there is a BadMethodCallException in SPL) * If no record is found, below $r[0] will fail with a E_NOTICE and the code doesn't behave as expected. * Ops, one more left ... * Continued: - added documentation for Contact::updateSslPolicy() method - added type-hint for $contact of same method - empty lines added + TODO where the bug origins that $item has no element 'body' * Added empty lines for better readability * Cleaned up: - no more x() (deprecated) usage but empty() instead - fixed mixing of space/tab indending - merged else/if block goether in elseif() (lesser nested code blocks) * Re-fixed DBM -> DBA switch * Fixes/rewrites: - use empty()/isset() instead of deprecated x() - merged 2 nested if() blocks into one - avoided nested if() block inside else block by rewriting it to elseif() - $contact_id is an integer, let's test on > 0 here - added a lot spaces and some empty lines for better readability * Rewrite: - moved all CONTACT_* constants from boot.php to Contact class * CR request: - renamed Contact::CONTACT_IS_* -> Contact::* ;-) * Rewrites: - moved PAGE_* to Friendica\Model\Profile class - fixed mixure with "Contact::* rewrite" * Ops, one still there (return is no function) * Rewrite to Proxy class: - introduced new Friendica\Network\Proxy class for in exchange of proxy_*() functions - moved also all PROXY_* constants there as Proxy::* - removed now no longer needed mod/proxy.php loading as composer's auto-load will do this for us - renamed those proxy_*() functions to better names: + proxy_init() -> Proxy::init() (public) + proxy_url() -> Proxy::proxifyUrl() (public) + proxy_parse_html() -> Proxy::proxifyHtml() (public) + proxy_is_local_image() -> Proxy::isLocalImage() (private) + proxy_parse_query() -> Proxy::parseQuery() (private) + proxy_img_cb() -> Proxy::replaceUrl() (private) * CR request: - moved all PAGE_* constants to Friendica\Model\Contact class - fixed all references of both classes * Ops, need to set $a here ... * CR request: - moved Proxy class to Friendica\Module - extended BaseModule * Ops, no need for own instance of $a when self::getApp() is around. * Proxy-rewrite: - proxy_url() and proxy_parse_html() are both non-module functions (now methods) - so they must be splitted into a seperate class - also the SIZE_* and DEFAULT_TIME constants are both not relevant to module * No instances from utility classes * Fixed error: - proxify*() is now located in `Friendica\Util\ProxyUtils` * Moved back to original place, ops? How did they move here? Well, it was not intended by me. * Removed duplicate (left-over from split) constants and static array. Thank to MrPetovan finding it. * Renamed ProxyUtils -> Proxy and aliased it back to ProxyUtils. * Rewrite: - stopped using deprecated NETWORK_* constants, now Protocol::* should be used - still left them intact for slow/lazy developers ... * Ops, was added accidentally ... * Ops, why these wrong moves? * Ops, one to much (thanks to MrPetovan) * Ops, wrong moving ... * moved back to original place ... * spaces added * empty lines add for better readability. * convertered spaces -> tab for code indenting. * CR request: Add space between if and brace. * CR requests fixed + move reverted - ops, src/Module/*.php has been moved to src/Network/ accidentally - reverted some parts in src/Database/DBA.php as pointed out by Annando - removed internal TODO items - added some spaces for better readability
3 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;
  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::updatePasswordHashed($user['uid'], self::hashPassword($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::updatePasswordHashed($user['uid'], self::hashPassword($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::updatePasswordHashed($user['uid'], self::hashPassword($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 ucfirst(Strings::getRandomName(8)) . mt_rand(1000, 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. * @throws Exception
  284. */
  285. public static function hashPassword($password)
  286. {
  287. if (!trim($password)) {
  288. throw new Exception(L10n::t('Password can\'t be empty'));
  289. }
  290. return password_hash($password, PASSWORD_DEFAULT);
  291. }
  292. /**
  293. * Updates a user row with a new plaintext password
  294. *
  295. * @param int $uid
  296. * @param string $password
  297. * @return bool
  298. * @throws Exception
  299. */
  300. public static function updatePassword($uid, $password)
  301. {
  302. $password = trim($password);
  303. if (empty($password)) {
  304. throw new Exception(L10n::t('Empty passwords are not allowed.'));
  305. }
  306. if (!Config::get('system', 'disable_password_exposed', false) && self::isPasswordExposed($password)) {
  307. throw new Exception(L10n::t('The new password has been exposed in a public data dump, please choose another.'));
  308. }
  309. $allowed_characters = '!"#$%&\'()*+,-./;<=>?@[\]^_`{|}~';
  310. if (!preg_match('/^[a-z0-9' . preg_quote($allowed_characters, '/') . ']+$/i', $password)) {
  311. throw new Exception(L10n::t('The password can\'t contain accentuated letters, white spaces or colons (:)'));
  312. }
  313. return self::updatePasswordHashed($uid, self::hashPassword($password));
  314. }
  315. /**
  316. * Updates a user row with a new hashed password.
  317. * Empties the password reset token field just in case.
  318. *
  319. * @param int $uid
  320. * @param string $pasword_hashed
  321. * @return bool
  322. */
  323. private static function updatePasswordHashed($uid, $pasword_hashed)
  324. {
  325. $fields = [
  326. 'password' => $pasword_hashed,
  327. 'pwdreset' => null,
  328. 'pwdreset_time' => null,
  329. 'legacy_password' => false
  330. ];
  331. return DBA::update('user', $fields, ['uid' => $uid]);
  332. }
  333. /**
  334. * @brief Checks if a nickname is in the list of the forbidden nicknames
  335. *
  336. * Check if a nickname is forbidden from registration on the node by the
  337. * admin. Forbidden nicknames (e.g. role namess) can be configured in the
  338. * admin panel.
  339. *
  340. * @param string $nickname The nickname that should be checked
  341. * @return boolean True is the nickname is blocked on the node
  342. */
  343. public static function isNicknameBlocked($nickname)
  344. {
  345. $forbidden_nicknames = Config::get('system', 'forbidden_nicknames', '');
  346. // if the config variable is empty return false
  347. if (empty($forbidden_nicknames)) {
  348. return false;
  349. }
  350. // check if the nickname is in the list of blocked nicknames
  351. $forbidden = explode(',', $forbidden_nicknames);
  352. $forbidden = array_map('trim', $forbidden);
  353. if (in_array(strtolower($nickname), $forbidden)) {
  354. return true;
  355. }
  356. // else return false
  357. return false;
  358. }
  359. /**
  360. * @brief Catch-all user creation function
  361. *
  362. * Creates a user from the provided data array, either form fields or OpenID.
  363. * Required: { username, nickname, email } or { openid_url }
  364. *
  365. * Performs the following:
  366. * - Sends to the OpenId auth URL (if relevant)
  367. * - Creates new key pairs for crypto
  368. * - Create self-contact
  369. * - Create profile image
  370. *
  371. * @param array $data
  372. * @return array
  373. * @throws \ErrorException
  374. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  375. * @throws Exception
  376. */
  377. public static function create(array $data)
  378. {
  379. $a = get_app();
  380. $return = ['user' => null, 'password' => ''];
  381. $using_invites = Config::get('system', 'invitation_only');
  382. $num_invites = Config::get('system', 'number_invites');
  383. $invite_id = !empty($data['invite_id']) ? Strings::escapeTags(trim($data['invite_id'])) : '';
  384. $username = !empty($data['username']) ? Strings::escapeTags(trim($data['username'])) : '';
  385. $nickname = !empty($data['nickname']) ? Strings::escapeTags(trim($data['nickname'])) : '';
  386. $email = !empty($data['email']) ? Strings::escapeTags(trim($data['email'])) : '';
  387. $openid_url = !empty($data['openid_url']) ? Strings::escapeTags(trim($data['openid_url'])) : '';
  388. $photo = !empty($data['photo']) ? Strings::escapeTags(trim($data['photo'])) : '';
  389. $password = !empty($data['password']) ? trim($data['password']) : '';
  390. $password1 = !empty($data['password1']) ? trim($data['password1']) : '';
  391. $confirm = !empty($data['confirm']) ? trim($data['confirm']) : '';
  392. $blocked = !empty($data['blocked']);
  393. $verified = !empty($data['verified']);
  394. $language = !empty($data['language']) ? Strings::escapeTags(trim($data['language'])) : 'en';
  395. $publish = !empty($data['profile_publish_reg']);
  396. $netpublish = $publish && Config::get('system', 'directory');
  397. if ($password1 != $confirm) {
  398. throw new Exception(L10n::t('Passwords do not match. Password unchanged.'));
  399. } elseif ($password1 != '') {
  400. $password = $password1;
  401. }
  402. if ($using_invites) {
  403. if (!$invite_id) {
  404. throw new Exception(L10n::t('An invitation is required.'));
  405. }
  406. if (!Register::existsByHash($invite_id)) {
  407. throw new Exception(L10n::t('Invitation could not be verified.'));
  408. }
  409. }
  410. if (empty($username) || empty($email) || empty($nickname)) {
  411. if ($openid_url) {
  412. if (!Network::isUrlValid($openid_url)) {
  413. throw new Exception(L10n::t('Invalid OpenID url'));
  414. }
  415. $_SESSION['register'] = 1;
  416. $_SESSION['openid'] = $openid_url;
  417. $openid = new LightOpenID($a->getHostName());
  418. $openid->identity = $openid_url;
  419. $openid->returnUrl = System::baseUrl() . '/openid';
  420. $openid->required = ['namePerson/friendly', 'contact/email', 'namePerson'];
  421. $openid->optional = ['namePerson/first', 'media/image/aspect11', 'media/image/default'];
  422. try {
  423. $authurl = $openid->authUrl();
  424. } catch (Exception $e) {
  425. 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);
  426. }
  427. System::externalRedirect($authurl);
  428. // NOTREACHED
  429. }
  430. throw new Exception(L10n::t('Please enter the required information.'));
  431. }
  432. if (!Network::isUrlValid($openid_url)) {
  433. $openid_url = '';
  434. }
  435. $err = '';
  436. // collapse multiple spaces in name
  437. $username = preg_replace('/ +/', ' ', $username);
  438. $username_min_length = max(1, min(64, intval(Config::get('system', 'username_min_length', 3))));
  439. $username_max_length = max(1, min(64, intval(Config::get('system', 'username_max_length', 48))));
  440. if ($username_min_length > $username_max_length) {
  441. 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);
  442. $tmp = $username_min_length;
  443. $username_min_length = $username_max_length;
  444. $username_max_length = $tmp;
  445. }
  446. if (mb_strlen($username) < $username_min_length) {
  447. throw new Exception(L10n::tt('Username should be at least %s character.', 'Username should be at least %s characters.', $username_min_length));
  448. }
  449. if (mb_strlen($username) > $username_max_length) {
  450. throw new Exception(L10n::tt('Username should be at most %s character.', 'Username should be at most %s characters.', $username_max_length));
  451. }
  452. // So now we are just looking for a space in the full name.
  453. $loose_reg = Config::get('system', 'no_regfullname');
  454. if (!$loose_reg) {
  455. $username = mb_convert_case($username, MB_CASE_TITLE, 'UTF-8');
  456. if (strpos($username, ' ') === false) {
  457. throw new Exception(L10n::t("That doesn't appear to be your full (First Last) name."));
  458. }
  459. }
  460. if (!Network::isEmailDomainAllowed($email)) {
  461. throw new Exception(L10n::t('Your email domain is not among those allowed on this site.'));
  462. }
  463. if (!filter_var($email, FILTER_VALIDATE_EMAIL) || !Network::isEmailDomainValid($email)) {
  464. throw new Exception(L10n::t('Not a valid email address.'));
  465. }
  466. if (self::isNicknameBlocked($nickname)) {
  467. throw new Exception(L10n::t('The nickname was blocked from registration by the nodes admin.'));
  468. }
  469. if (Config::get('system', 'block_extended_register', false) && DBA::exists('user', ['email' => $email])) {
  470. throw new Exception(L10n::t('Cannot use that email.'));
  471. }
  472. // Disallow somebody creating an account using openid that uses the admin email address,
  473. // since openid bypasses email verification. We'll allow it if there is not yet an admin account.
  474. if (Config::get('config', 'admin_email') && strlen($openid_url)) {
  475. $adminlist = explode(',', str_replace(' ', '', strtolower(Config::get('config', 'admin_email'))));
  476. if (in_array(strtolower($email), $adminlist)) {
  477. throw new Exception(L10n::t('Cannot use that email.'));
  478. }
  479. }
  480. $nickname = $data['nickname'] = strtolower($nickname);
  481. if (!preg_match('/^[a-z0-9][a-z0-9\_]*$/', $nickname)) {
  482. throw new Exception(L10n::t('Your nickname can only contain a-z, 0-9 and _.'));
  483. }
  484. // Check existing and deleted accounts for this nickname.
  485. if (DBA::exists('user', ['nickname' => $nickname])
  486. || DBA::exists('userd', ['username' => $nickname])
  487. ) {
  488. throw new Exception(L10n::t('Nickname is already registered. Please choose another.'));
  489. }
  490. $new_password = strlen($password) ? $password : User::generateNewPassword();
  491. $new_password_encoded = self::hashPassword($new_password);
  492. $return['password'] = $new_password;
  493. $keys = Crypto::newKeypair(4096);
  494. if ($keys === false) {
  495. throw new Exception(L10n::t('SERIOUS ERROR: Generation of security keys failed.'));
  496. }
  497. $prvkey = $keys['prvkey'];
  498. $pubkey = $keys['pubkey'];
  499. // Create another keypair for signing/verifying salmon protocol messages.
  500. $sres = Crypto::newKeypair(512);
  501. $sprvkey = $sres['prvkey'];
  502. $spubkey = $sres['pubkey'];
  503. $insert_result = DBA::insert('user', [
  504. 'guid' => System::createUUID(),
  505. 'username' => $username,
  506. 'password' => $new_password_encoded,
  507. 'email' => $email,
  508. 'openid' => $openid_url,
  509. 'nickname' => $nickname,
  510. 'pubkey' => $pubkey,
  511. 'prvkey' => $prvkey,
  512. 'spubkey' => $spubkey,
  513. 'sprvkey' => $sprvkey,
  514. 'verified' => $verified,
  515. 'blocked' => $blocked,
  516. 'language' => $language,
  517. 'timezone' => 'UTC',
  518. 'register_date' => DateTimeFormat::utcNow(),
  519. 'default-location' => ''
  520. ]);
  521. if ($insert_result) {
  522. $uid = DBA::lastInsertId();
  523. $user = DBA::selectFirst('user', [], ['uid' => $uid]);
  524. } else {
  525. throw new Exception(L10n::t('An error occurred during registration. Please try again.'));
  526. }
  527. if (!$uid) {
  528. throw new Exception(L10n::t('An error occurred during registration. Please try again.'));
  529. }
  530. // if somebody clicked submit twice very quickly, they could end up with two accounts
  531. // due to race condition. Remove this one.
  532. $user_count = DBA::count('user', ['nickname' => $nickname]);
  533. if ($user_count > 1) {
  534. DBA::delete('user', ['uid' => $uid]);
  535. throw new Exception(L10n::t('Nickname is already registered. Please choose another.'));
  536. }
  537. $insert_result = DBA::insert('profile', [
  538. 'uid' => $uid,
  539. 'name' => $username,
  540. 'photo' => System::baseUrl() . "/photo/profile/{$uid}.jpg",
  541. 'thumb' => System::baseUrl() . "/photo/avatar/{$uid}.jpg",
  542. 'publish' => $publish,
  543. 'is-default' => 1,
  544. 'net-publish' => $netpublish,
  545. 'profile-name' => L10n::t('default')
  546. ]);
  547. if (!$insert_result) {
  548. DBA::delete('user', ['uid' => $uid]);
  549. throw new Exception(L10n::t('An error occurred creating your default profile. Please try again.'));
  550. }
  551. // Create the self contact
  552. if (!Contact::createSelfFromUserId($uid)) {
  553. DBA::delete('user', ['uid' => $uid]);
  554. throw new Exception(L10n::t('An error occurred creating your self contact. Please try again.'));
  555. }
  556. // Create a group with no members. This allows somebody to use it
  557. // right away as a default group for new contacts.
  558. $def_gid = Group::create($uid, L10n::t('Friends'));
  559. if (!$def_gid) {
  560. DBA::delete('user', ['uid' => $uid]);
  561. throw new Exception(L10n::t('An error occurred creating your default contact group. Please try again.'));
  562. }
  563. $fields = ['def_gid' => $def_gid];
  564. if (Config::get('system', 'newuser_private') && $def_gid) {
  565. $fields['allow_gid'] = '<' . $def_gid . '>';
  566. }
  567. DBA::update('user', $fields, ['uid' => $uid]);
  568. // if we have no OpenID photo try to look up an avatar
  569. if (!strlen($photo)) {
  570. $photo = Network::lookupAvatarByEmail($email);
  571. }
  572. // unless there is no avatar-addon loaded
  573. if (strlen($photo)) {
  574. $photo_failure = false;
  575. $filename = basename($photo);
  576. $img_str = Network::fetchUrl($photo, true);
  577. // guess mimetype from headers or filename
  578. $type = Image::guessType($photo, true);
  579. $Image = new Image($img_str, $type);
  580. if ($Image->isValid()) {
  581. $Image->scaleToSquare(300);
  582. $hash = Photo::newResource();
  583. $r = Photo::store($Image, $uid, 0, $hash, $filename, L10n::t('Profile Photos'), 4);
  584. if ($r === false) {
  585. $photo_failure = true;
  586. }
  587. $Image->scaleDown(80);
  588. $r = Photo::store($Image, $uid, 0, $hash, $filename, L10n::t('Profile Photos'), 5);
  589. if ($r === false) {
  590. $photo_failure = true;
  591. }
  592. $Image->scaleDown(48);
  593. $r = Photo::store($Image, $uid, 0, $hash, $filename, L10n::t('Profile Photos'), 6);
  594. if ($r === false) {
  595. $photo_failure = true;
  596. }
  597. if (!$photo_failure) {
  598. DBA::update('photo', ['profile' => 1], ['resource-id' => $hash]);
  599. }
  600. }
  601. }
  602. Addon::callHooks('register_account', $uid);
  603. $return['user'] = $user;
  604. return $return;
  605. }
  606. /**
  607. * @brief Sends pending registration confirmation email
  608. *
  609. * @param array $user User record array
  610. * @param string $sitename
  611. * @param string $siteurl
  612. * @param string $password Plaintext password
  613. * @return NULL|boolean from notification() and email() inherited
  614. */
  615. public static function sendRegisterPendingEmail($user, $sitename, $siteurl, $password)
  616. {
  617. $body = Strings::deindent(L10n::t('
  618. Dear %1$s,
  619. Thank you for registering at %2$s. Your account is pending for approval by the administrator.
  620. Your login details are as follows:
  621. Site Location: %3$s
  622. Login Name: %4$s
  623. Password: %5$s
  624. ',
  625. $user['username'], $sitename, $siteurl, $user['nickname'], $password
  626. ));
  627. return notification([
  628. 'type' => SYSTEM_EMAIL,
  629. 'uid' => $user['uid'],
  630. 'to_email' => $user['email'],
  631. 'subject' => L10n::t('Registration at %s', $sitename),
  632. 'body' => $body
  633. ]);
  634. }
  635. /**
  636. * @brief Sends registration confirmation
  637. *
  638. * It's here as a function because the mail is sent from different parts
  639. *
  640. * @param array $user User record array
  641. * @param string $sitename
  642. * @param string $siteurl
  643. * @param string $password Plaintext password
  644. * @return NULL|boolean from notification() and email() inherited
  645. */
  646. public static function sendRegisterOpenEmail($user, $sitename, $siteurl, $password)
  647. {
  648. $preamble = Strings::deindent(L10n::t('
  649. Dear %1$s,
  650. Thank you for registering at %2$s. Your account has been created.
  651. ',
  652. $user['username'], $sitename
  653. ));
  654. $body = Strings::deindent(L10n::t('
  655. The login details are as follows:
  656. Site Location: %3$s
  657. Login Name: %1$s
  658. Password: %5$s
  659. You may change your password from your account "Settings" page after logging
  660. in.
  661. Please take a few moments to review the other account settings on that page.
  662. You may also wish to add some basic information to your default profile
  663. ' . "\x28" . 'on the "Profiles" page' . "\x29" . ' so that other people can easily find you.
  664. We recommend setting your full name, adding a profile photo,
  665. adding some profile "keywords" ' . "\x28" . 'very useful in making new friends' . "\x29" . ' - and
  666. perhaps what country you live in; if you do not wish to be more specific
  667. than that.
  668. We fully respect your right to privacy, and none of these items are necessary.
  669. If you are new and do not know anybody here, they may help
  670. you to make some new and interesting friends.
  671. If you ever want to delete your account, you can do so at %3$s/removeme
  672. Thank you and welcome to %2$s.',
  673. $user['email'], $sitename, $siteurl, $user['username'], $password
  674. ));
  675. return notification([
  676. 'uid' => $user['uid'],
  677. 'language' => $user['language'],
  678. 'type' => SYSTEM_EMAIL,
  679. 'to_email' => $user['email'],
  680. 'subject' => L10n::t('Registration details for %s', $sitename),
  681. 'preamble' => $preamble,
  682. 'body' => $body
  683. ]);
  684. }
  685. /**
  686. * @param object $uid user to remove
  687. * @return void
  688. */
  689. public static function remove($uid)
  690. {
  691. if (!$uid) {
  692. return false;
  693. }
  694. $a = get_app();
  695. Logger::log('Removing user: ' . $uid);
  696. $user = DBA::selectFirst('user', [], ['uid' => $uid]);
  697. Hook::callAll('remove_user', $user);
  698. // save username (actually the nickname as it is guaranteed
  699. // unique), so it cannot be re-registered in the future.
  700. DBA::insert('userd', ['username' => $user['nickname']]);
  701. // The user and related data will be deleted in "cron_expire_and_remove_users" (cronjobs.php)
  702. DBA::update('user', ['account_removed' => true, 'account_expires_on' => DateTimeFormat::utc('now + 7 day')], ['uid' => $uid]);
  703. Worker::add(PRIORITY_HIGH, 'Notifier', 'removeme', $uid);
  704. // Send an update to the directory
  705. $self = DBA::selectFirst('contact', ['url'], ['uid' => $uid, 'self' => true]);
  706. Worker::add(PRIORITY_LOW, 'Directory', $self['url']);
  707. // Remove the user relevant data
  708. Worker::add(PRIORITY_LOW, 'RemoveUser', $uid);
  709. return true;
  710. }
  711. /**
  712. * Return all identities to a user
  713. *
  714. * @param int $uid The user id
  715. * @return array All identities for this user
  716. *
  717. * Example for a return:
  718. * [
  719. * [
  720. * 'uid' => 1,
  721. * 'username' => 'maxmuster',
  722. * 'nickname' => 'Max Mustermann'
  723. * ],
  724. * [
  725. * 'uid' => 2,
  726. * 'username' => 'johndoe',
  727. * 'nickname' => 'John Doe'
  728. * ]
  729. * ]
  730. */
  731. public static function identities($uid)
  732. {
  733. $identities = [];
  734. $user = DBA::selectFirst('user', ['uid', 'nickname', 'username', 'parent-uid'], ['uid' => $uid]);
  735. if (!DBA::isResult($user)) {
  736. return $identities;
  737. }
  738. if ($user['parent-uid'] == 0) {
  739. // First add our own entry
  740. $identities = [['uid' => $user['uid'],
  741. 'username' => $user['username'],
  742. 'nickname' => $user['nickname']]];
  743. // Then add all the children
  744. $r = DBA::select('user', ['uid', 'username', 'nickname'],
  745. ['parent-uid' => $user['uid'], 'account_removed' => false]);
  746. if (DBA::isResult($r)) {
  747. $identities = array_merge($identities, DBA::toArray($r));
  748. }
  749. } else {
  750. // First entry is our parent
  751. $r = DBA::select('user', ['uid', 'username', 'nickname'],
  752. ['uid' => $user['parent-uid'], 'account_removed' => false]);
  753. if (DBA::isResult($r)) {
  754. $identities = DBA::toArray($r);
  755. }
  756. // Then add all siblings
  757. $r = DBA::select('user', ['uid', 'username', 'nickname'],
  758. ['parent-uid' => $user['parent-uid'], 'account_removed' => false]);
  759. if (DBA::isResult($r)) {
  760. $identities = array_merge($identities, DBA::toArray($r));
  761. }
  762. }
  763. $r = DBA::p("SELECT `user`.`uid`, `user`.`username`, `user`.`nickname`
  764. FROM `manage`
  765. INNER JOIN `user` ON `manage`.`mid` = `user`.`uid`
  766. WHERE `user`.`account_removed` = 0 AND `manage`.`uid` = ?",
  767. $user['uid']
  768. );
  769. if (DBA::isResult($r)) {
  770. $identities = array_merge($identities, DBA::toArray($r));
  771. }
  772. return $identities;
  773. }
  774. }