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.

1045 lines
31 KiB

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