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.

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