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.

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