User.php 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  1. <?php
  2. // This file is part of GNU social - https://www.gnu.org/software/social
  3. //
  4. // GNU social is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // GNU social is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  16. defined('GNUSOCIAL') || die();
  17. /**
  18. * Table Definition for user
  19. */
  20. class User extends Managed_DataObject
  21. {
  22. const SUBSCRIBE_POLICY_OPEN = 0;
  23. const SUBSCRIBE_POLICY_MODERATE = 1;
  24. ###START_AUTOCODE
  25. /* the code below is auto generated do not remove the above tag */
  26. public $__table = 'user'; // table name
  27. public $id; // int(4) primary_key not_null
  28. public $nickname; // varchar(64) unique_key
  29. public $password; // text
  30. public $email; // varchar(191) unique_key not 255 because utf8mb4 takes more space
  31. public $incomingemail; // varchar(191) unique_key not 255 because utf8mb4 takes more space
  32. public $emailnotifysub; // bool default_true
  33. public $emailnotifyfav; // tinyint(1) default_null
  34. public $emailnotifynudge; // bool default_true
  35. public $emailnotifymsg; // bool default_true
  36. public $emailnotifyattn; // bool default_true
  37. public $language; // varchar(50)
  38. public $timezone; // varchar(50)
  39. public $emailpost; // bool default_true
  40. public $sms; // varchar(64) unique_key
  41. public $carrier; // int(4)
  42. public $smsnotify; // bool default_false
  43. public $smsreplies; // bool default_false
  44. public $smsemail; // varchar(191) not 255 because utf8mb4 takes more space
  45. public $uri; // varchar(191) unique_key not 255 because utf8mb4 takes more space
  46. public $autosubscribe; // bool default_false
  47. public $subscribe_policy; // tinyint(1)
  48. public $urlshorteningservice; // varchar(50) default_ur1.ca
  49. public $private_stream; // bool default_false
  50. public $created; // datetime()
  51. public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
  52. /* the code above is auto generated do not remove the tag below */
  53. ###END_AUTOCODE
  54. public static function schemaDef()
  55. {
  56. return array(
  57. 'description' => 'local users',
  58. 'fields' => array(
  59. 'id' => array('type' => 'int', 'not null' => true, 'description' => 'foreign key to profile table'),
  60. 'nickname' => array('type' => 'varchar', 'length' => 64, 'description' => 'nickname or username, duped in profile'),
  61. 'password' => array('type' => 'text', 'description' => 'salted password, can be null for OpenID users'),
  62. 'email' => array('type' => 'varchar', 'length' => 191, 'description' => 'email address for password recovery etc.'),
  63. 'incomingemail' => array('type' => 'varchar', 'length' => 191, 'description' => 'email address for post-by-email'),
  64. 'emailnotifysub' => array('type' => 'bool', 'default' => true, 'description' => 'Notify by email of subscriptions'),
  65. 'emailnotifyfav' => array('type' => 'int', 'size' => 'tiny', 'default' => null, 'description' => 'Notify by email of favorites'),
  66. 'emailnotifynudge' => array('type' => 'bool', 'default' => true, 'description' => 'Notify by email of nudges'),
  67. 'emailnotifymsg' => array('type' => 'bool', 'default' => true, 'description' => 'Notify by email of direct messages'),
  68. 'emailnotifyattn' => array('type' => 'bool', 'default' => true, 'description' => 'Notify by email of @-replies'),
  69. 'language' => array('type' => 'varchar', 'length' => 50, 'description' => 'preferred language'),
  70. 'timezone' => array('type' => 'varchar', 'length' => 50, 'description' => 'timezone'),
  71. 'emailpost' => array('type' => 'bool', 'default' => true, 'description' => 'Post by email'),
  72. 'sms' => array('type' => 'varchar', 'length' => 64, 'description' => 'sms phone number'),
  73. 'carrier' => array('type' => 'int', 'description' => 'foreign key to sms_carrier'),
  74. 'smsnotify' => array('type' => 'bool', 'default' => false, 'description' => 'whether to send notices to SMS'),
  75. 'smsreplies' => array('type' => 'bool', 'default' => false, 'description' => 'whether to send notices to SMS on replies'),
  76. 'smsemail' => array('type' => 'varchar', 'length' => 191, 'description' => 'built from sms and carrier'),
  77. 'uri' => array('type' => 'varchar', 'length' => 191, 'description' => 'universally unique identifier, usually a tag URI'),
  78. 'autosubscribe' => array('type' => 'bool', 'default' => false, 'description' => 'automatically subscribe to users who subscribe to us'),
  79. 'subscribe_policy' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => '0 = anybody can subscribe; 1 = require approval'),
  80. 'urlshorteningservice' => array('type' => 'varchar', 'length' => 50, 'default' => 'internal', 'description' => 'service to use for auto-shortening URLs'),
  81. 'private_stream' => array('type' => 'bool', 'default' => false, 'description' => 'whether to limit all notices to followers only'),
  82. 'created' => array('type' => 'datetime', 'description' => 'date this record was created'),
  83. 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
  84. ),
  85. 'primary key' => array('id'),
  86. 'unique keys' => array(
  87. 'user_nickname_key' => array('nickname'),
  88. 'user_email_key' => array('email'),
  89. 'user_incomingemail_key' => array('incomingemail'),
  90. 'user_sms_key' => array('sms'),
  91. 'user_uri_key' => array('uri'),
  92. ),
  93. 'foreign keys' => array(
  94. 'user_id_fkey' => array('profile', array('id' => 'id')),
  95. 'user_carrier_fkey' => array('sms_carrier', array('carrier' => 'id')),
  96. ),
  97. 'indexes' => array(
  98. 'user_carrier_idx' => array('carrier'),
  99. 'user_created_id_idx' => array('created', 'id'),
  100. 'user_smsemail_idx' => array('smsemail'),
  101. ),
  102. );
  103. }
  104. protected $_profile = array();
  105. /**
  106. * @return Profile
  107. *
  108. * @throws UserNoProfileException if user has no profile
  109. */
  110. public function getProfile()
  111. {
  112. if (!isset($this->_profile[$this->id])) {
  113. $profile = Profile::getKV('id', $this->id);
  114. if (!$profile instanceof Profile) {
  115. throw new UserNoProfileException($this);
  116. }
  117. $this->_profile[$this->id] = $profile;
  118. }
  119. return $this->_profile[$this->id];
  120. }
  121. public function sameAs(Profile $other)
  122. {
  123. return $this->getProfile()->sameAs($other);
  124. }
  125. public function getUri()
  126. {
  127. return $this->uri;
  128. }
  129. public function getNickname()
  130. {
  131. return $this->getProfile()->getNickname();
  132. }
  133. public static function getByNickname($nickname)
  134. {
  135. $user = User::getKV('nickname', $nickname);
  136. if (!$user instanceof User) {
  137. throw new NoSuchUserException(array('nickname' => $nickname));
  138. }
  139. return $user;
  140. }
  141. public function isSubscribed(Profile $other)
  142. {
  143. return $this->getProfile()->isSubscribed($other);
  144. }
  145. public function hasPendingSubscription(Profile $other)
  146. {
  147. return $this->getProfile()->hasPendingSubscription($other);
  148. }
  149. /**
  150. * Get the most recent notice posted by this user, if any.
  151. *
  152. * @return mixed Notice or null
  153. */
  154. public function getCurrentNotice()
  155. {
  156. return $this->getProfile()->getCurrentNotice();
  157. }
  158. public function getCarrier()
  159. {
  160. return Sms_carrier::getKV('id', $this->carrier);
  161. }
  162. public function hasBlocked(Profile $other)
  163. {
  164. return $this->getProfile()->hasBlocked($other);
  165. }
  166. /**
  167. * Register a new user account and profile and set up default subscriptions.
  168. * If a new-user welcome message is configured, this will be sent.
  169. *
  170. * @param array $fields associative array of optional properties
  171. * string 'bio'
  172. * string 'email'
  173. * bool 'email_confirmed' pass true to mark email as pre-confirmed
  174. * string 'fullname'
  175. * string 'homepage'
  176. * string 'location' informal string description of geolocation
  177. * float 'lat' decimal latitude for geolocation
  178. * float 'lon' decimal longitude for geolocation
  179. * int 'location_id' geoname identifier
  180. * int 'location_ns' geoname namespace to interpret location_id
  181. * string 'nickname' REQUIRED
  182. * string 'password' (may be missing for eg OpenID registrations)
  183. * string 'code' invite code
  184. * ?string 'uri' permalink to notice; defaults to local notice URL
  185. * @return User object
  186. * @throws Exception on failure
  187. */
  188. public static function register(array $fields, $accept_email_fail = false)
  189. {
  190. // MAGICALLY put fields into current scope
  191. extract($fields);
  192. $profile = new Profile();
  193. if (!empty($email)) {
  194. $email = common_canonical_email($email);
  195. }
  196. // Normalize _and_ check whether it is in use. Throw NicknameException on failure.
  197. $profile->nickname = Nickname::normalize($nickname, true);
  198. $profile->profileurl = common_profile_url($profile->nickname);
  199. if (!empty($fullname)) {
  200. $profile->fullname = $fullname;
  201. }
  202. if (!empty($homepage)) {
  203. $profile->homepage = $homepage;
  204. }
  205. if (!empty($bio)) {
  206. $profile->bio = $bio;
  207. }
  208. if (!empty($location)) {
  209. $profile->location = $location;
  210. $loc = Location::fromName($location);
  211. if (!empty($loc)) {
  212. $profile->lat = $loc->lat;
  213. $profile->lon = $loc->lon;
  214. $profile->location_id = $loc->location_id;
  215. $profile->location_ns = $loc->location_ns;
  216. }
  217. }
  218. $profile->created = common_sql_now();
  219. $user = new User();
  220. $user->nickname = $profile->nickname;
  221. $invite = null;
  222. // Users who respond to invite email have proven their ownership of that address
  223. if (!empty($code)) {
  224. $invite = Invitation::getKV($code);
  225. if ($invite instanceof Invitation && $invite->address && $invite->address_type == 'email' && $invite->address == $email) {
  226. $user->email = $invite->address;
  227. }
  228. }
  229. if (isset($email_confirmed) && $email_confirmed) {
  230. $user->email = $email;
  231. }
  232. // Set default-on options here, otherwise they'll be disabled
  233. // initially for sites using caching, since the initial encache
  234. // doesn't know about the defaults in the database.
  235. $user->emailnotifysub = true;
  236. $user->emailnotifynudge = true;
  237. $user->emailnotifymsg = true;
  238. $user->emailnotifyattn = true;
  239. $user->emailpost = true;
  240. $user->created = common_sql_now();
  241. if (Event::handle('StartUserRegister', array($profile))) {
  242. $profile->query('START TRANSACTION');
  243. $id = $profile->insert();
  244. if ($id === false) {
  245. common_log_db_error($profile, 'INSERT', __FILE__);
  246. $profile->query('ROLLBACK');
  247. // TRANS: Profile data could not be inserted for some reason.
  248. throw new ServerException(_m('Could not insert profile data for new user.'));
  249. }
  250. // Necessary because id has been known to be reissued.
  251. if ($profile->hasRole(Profile_role::DELETED)) {
  252. $profile->revokeRole(Profile_role::DELETED);
  253. }
  254. $user->id = $id;
  255. if (!empty($uri)) {
  256. $user->uri = $uri;
  257. } else {
  258. $user->uri = common_user_uri($user);
  259. }
  260. if (!empty($password)) { // may not have a password for OpenID users
  261. $user->password = common_munge_password($password);
  262. }
  263. $result = $user->insert();
  264. if ($result === false) {
  265. common_log_db_error($user, 'INSERT', __FILE__);
  266. $profile->query('ROLLBACK');
  267. // TRANS: User data could not be inserted for some reason.
  268. throw new ServerException(_m('Could not insert user data for new user.'));
  269. }
  270. // Everyone is subscribed to themself
  271. $subscription = new Subscription();
  272. $subscription->subscriber = $user->id;
  273. $subscription->subscribed = $user->id;
  274. $subscription->created = $user->created;
  275. $result = $subscription->insert();
  276. if (!$result) {
  277. common_log_db_error($subscription, 'INSERT', __FILE__);
  278. $profile->query('ROLLBACK');
  279. // TRANS: Subscription data could not be inserted for some reason.
  280. throw new ServerException(_m('Could not insert subscription data for new user.'));
  281. }
  282. // Mark that this invite was converted
  283. if (!empty($invite)) {
  284. $invite->convert($user);
  285. }
  286. if (!empty($email) && empty($user->email)) {
  287. // The actual email will be sent further down, after the database COMMIT
  288. $confirm = new Confirm_address();
  289. $confirm->code = common_confirmation_code(128);
  290. $confirm->user_id = $user->id;
  291. $confirm->address = $email;
  292. $confirm->address_type = 'email';
  293. $result = $confirm->insert();
  294. if ($result===false) {
  295. common_log_db_error($confirm, 'INSERT', __FILE__);
  296. $profile->query('ROLLBACK');
  297. // TRANS: Email confirmation data could not be inserted for some reason.
  298. throw new ServerException(_m('Could not insert email confirmation data for new user.'));
  299. }
  300. }
  301. if (!empty($code) && $user->email) {
  302. $user->emailChanged();
  303. }
  304. // Default system subscription
  305. $defnick = common_config('newuser', 'default');
  306. if (!empty($defnick)) {
  307. $defuser = User::getKV('nickname', $defnick);
  308. if (empty($defuser)) {
  309. common_log(
  310. LOG_WARNING,
  311. sprintf('Default user %s does not exist.', $defnick),
  312. __FILE__
  313. );
  314. } else {
  315. Subscription::ensureStart($profile, $defuser->getProfile());
  316. }
  317. }
  318. $profile->query('COMMIT');
  319. if (!empty($email) && empty($user->email)) {
  320. try {
  321. $confirm->sendConfirmation();
  322. } catch (EmailException $e) {
  323. common_log(LOG_ERR, "Could not send user registration email for user id=={$profile->getID()}: {$e->getMessage()}");
  324. if (!$accept_email_fail) {
  325. throw $e;
  326. }
  327. }
  328. }
  329. // Welcome message
  330. $welcome = common_config('newuser', 'welcome');
  331. if (!empty($welcome)) {
  332. $welcomeuser = User::getKV('nickname', $welcome);
  333. if (empty($welcomeuser)) {
  334. common_log(
  335. LOG_WARNING,
  336. sprintf('Welcome user %s does not exist.', $defnick),
  337. __FILE__
  338. );
  339. } else {
  340. $notice = Notice::saveNew(
  341. $welcomeuser->id,
  342. // TRANS: Notice given on user registration.
  343. // TRANS: %1$s is the sitename, $2$s is the registering user's nickname.
  344. sprintf(
  345. _('Welcome to %1$s, @%2$s!'),
  346. common_config('site', 'name'),
  347. $profile->getNickname()
  348. ),
  349. 'system'
  350. );
  351. }
  352. }
  353. Event::handle('EndUserRegister', array($profile));
  354. }
  355. if (!$user instanceof User || empty($user->id)) {
  356. throw new ServerException('User could not be registered. Probably an event hook that failed.');
  357. }
  358. return $user;
  359. }
  360. // Things we do when the email changes
  361. public function emailChanged()
  362. {
  363. $invites = new Invitation();
  364. $invites->address = $this->email;
  365. $invites->address_type = 'email';
  366. if ($invites->find()) {
  367. while ($invites->fetch()) {
  368. try {
  369. $other = Profile::getByID($invites->user_id);
  370. Subscription::start($other, $this->getProfile());
  371. } catch (NoResultException $e) {
  372. // profile did not exist
  373. } catch (AlreadyFulfilledException $e) {
  374. // already subscribed to this profile
  375. } catch (Exception $e) {
  376. common_log(LOG_ERR, 'On-invitation-completion subscription failed when subscribing '._ve($invites->user_id).' to '.$this->getProfile()->getID().': '._ve($e->getMessage()));
  377. }
  378. }
  379. }
  380. }
  381. public function mutuallySubscribed(Profile $other)
  382. {
  383. return $this->getProfile()->mutuallySubscribed($other);
  384. }
  385. public function mutuallySubscribedUsers()
  386. {
  387. $user = new User();
  388. // 3-way join; probably should get cached
  389. $user->query(sprintf(
  390. 'SELECT %1$s.* ' .
  391. 'FROM subscription AS sub1 INNER JOIN %1$s ON sub1.subscribed = %1$s.id ' .
  392. 'INNER JOIN subscription AS sub2 ON %1$s.id = sub2.subscriber ' .
  393. 'WHERE sub1.subscriber = %2$d AND sub2.subscribed = %2$d ' .
  394. 'ORDER BY %1$s.nickname',
  395. $user->escapedTableName(),
  396. $this->id
  397. ));
  398. return $user;
  399. }
  400. public function getReplies($offset = 0, $limit = NOTICES_PER_PAGE, $since_id = 0, $before_id = 0)
  401. {
  402. return $this->getProfile()->getReplies($offset, $limit, $since_id, $before_id);
  403. }
  404. public function getTaggedNotices($tag, $offset = 0, $limit = NOTICES_PER_PAGE, $since_id = 0, $before_id = 0)
  405. {
  406. return $this->getProfile()->getTaggedNotices($tag, $offset, $limit, $since_id, $before_id);
  407. }
  408. public function getNotices($offset = 0, $limit = NOTICES_PER_PAGE, $since_id = 0, $before_id = 0)
  409. {
  410. return $this->getProfile()->getNotices($offset, $limit, $since_id, $before_id);
  411. }
  412. public function block(Profile $other)
  413. {
  414. // Add a new block record
  415. // no blocking (and thus unsubbing from) yourself
  416. if ($this->id == $other->id) {
  417. common_log(
  418. LOG_WARNING,
  419. sprintf(
  420. "Profile ID %d (%s) tried to block themself.",
  421. $this->id,
  422. $this->nickname
  423. )
  424. );
  425. return false;
  426. }
  427. $block = new Profile_block();
  428. $block->query('START TRANSACTION');
  429. $block->blocker = $this->id;
  430. $block->blocked = $other->id;
  431. $result = $block->insert();
  432. if (!$result) {
  433. common_log_db_error($block, 'INSERT', __FILE__);
  434. return false;
  435. }
  436. $self = $this->getProfile();
  437. if (Subscription::exists($other, $self)) {
  438. Subscription::cancel($other, $self);
  439. }
  440. if (Subscription::exists($self, $other)) {
  441. Subscription::cancel($self, $other);
  442. }
  443. $block->query('COMMIT');
  444. return true;
  445. }
  446. public function unblock(Profile $other)
  447. {
  448. // Get the block record
  449. $block = Profile_block::exists($this->getProfile(), $other);
  450. if (!$block) {
  451. return false;
  452. }
  453. $result = $block->delete();
  454. if (!$result) {
  455. common_log_db_error($block, 'DELETE', __FILE__);
  456. return false;
  457. }
  458. return true;
  459. }
  460. public function isMember(User_group $group)
  461. {
  462. return $this->getProfile()->isMember($group);
  463. }
  464. public function isAdmin(User_group $group)
  465. {
  466. return $this->getProfile()->isAdmin($group);
  467. }
  468. public function getGroups($offset = 0, $limit = null)
  469. {
  470. return $this->getProfile()->getGroups($offset, $limit);
  471. }
  472. /**
  473. * Request to join the given group.
  474. * May throw exceptions on failure.
  475. *
  476. * @param User_group $group
  477. * @return Group_member
  478. */
  479. public function joinGroup(User_group $group)
  480. {
  481. return $this->getProfile()->joinGroup($group);
  482. }
  483. /**
  484. * Leave a group that this user is a member of.
  485. *
  486. * @param User_group $group
  487. */
  488. public function leaveGroup(User_group $group)
  489. {
  490. return $this->getProfile()->leaveGroup($group);
  491. }
  492. public function getSubscribed($offset = 0, $limit = null)
  493. {
  494. return $this->getProfile()->getSubscribed($offset, $limit);
  495. }
  496. public function getSubscribers($offset = 0, $limit = null)
  497. {
  498. return $this->getProfile()->getSubscribers($offset, $limit);
  499. }
  500. public function getTaggedSubscribers($tag, $offset = 0, $limit = null)
  501. {
  502. return $this->getProfile()->getTaggedSubscribers($tag, $offset, $limit);
  503. }
  504. public function getTaggedSubscriptions($tag, $offset = 0, $limit = null)
  505. {
  506. return $this->getProfile()->getTaggedSubscriptions($tag, $offset, $limit);
  507. }
  508. public function hasRight($right)
  509. {
  510. return $this->getProfile()->hasRight($right);
  511. }
  512. public function delete($useWhere = false)
  513. {
  514. if (empty($this->id)) {
  515. common_log(LOG_WARNING, "Ambiguous User->delete(); skipping related tables.");
  516. return parent::delete($useWhere);
  517. }
  518. try {
  519. if (!$this->hasRole(Profile_role::DELETED)) {
  520. $profile = $this->getProfile();
  521. $profile->delete();
  522. }
  523. } catch (UserNoProfileException $unp) {
  524. common_log(LOG_INFO, "User {$this->nickname} has no profile; continuing deletion.");
  525. }
  526. $related = array(
  527. 'Confirm_address',
  528. 'Remember_me',
  529. 'Foreign_link',
  530. 'Invitation',
  531. );
  532. Event::handle('UserDeleteRelated', array($this, &$related));
  533. foreach ($related as $cls) {
  534. $inst = new $cls();
  535. $inst->user_id = $this->id;
  536. $inst->delete();
  537. }
  538. $this->_deleteTags();
  539. $this->_deleteBlocks();
  540. return parent::delete($useWhere);
  541. }
  542. public function _deleteTags()
  543. {
  544. $tag = new Profile_tag();
  545. $tag->tagger = $this->id;
  546. $tag->delete();
  547. }
  548. public function _deleteBlocks()
  549. {
  550. $block = new Profile_block();
  551. $block->blocker = $this->id;
  552. $block->delete();
  553. // XXX delete group block? Reset blocker?
  554. }
  555. public function hasRole($name)
  556. {
  557. return $this->getProfile()->hasRole($name);
  558. }
  559. public function grantRole($name)
  560. {
  561. return $this->getProfile()->grantRole($name);
  562. }
  563. public function revokeRole($name)
  564. {
  565. return $this->getProfile()->revokeRole($name);
  566. }
  567. public function isSandboxed()
  568. {
  569. return $this->getProfile()->isSandboxed();
  570. }
  571. public function isSilenced()
  572. {
  573. return $this->getProfile()->isSilenced();
  574. }
  575. public function receivesEmailNotifications()
  576. {
  577. // We could do this in one large if statement, but that's not as easy to read
  578. // Don't send notifications if we don't know the user's email address or it is
  579. // explicitly undesired by the user's own settings.
  580. if (empty($this->email) || !$this->emailnotifyattn) {
  581. return false;
  582. }
  583. // Don't send notifications to a user who is sandboxed or silenced
  584. if ($this->isSandboxed() || $this->isSilenced()) {
  585. return false;
  586. }
  587. return true;
  588. }
  589. public function repeatedByMe($offset = 0, $limit = 20, $since_id = null, $max_id = null)
  590. {
  591. // FIXME: Use another way to get Profile::current() since we
  592. // want to avoid confusion between session user and queue processing.
  593. $stream = new RepeatedByMeNoticeStream($this->getProfile(), Profile::current());
  594. return $stream->getNotices($offset, $limit, $since_id, $max_id);
  595. }
  596. public function repeatsOfMe($offset = 0, $limit = 20, $since_id = null, $max_id = null)
  597. {
  598. // FIXME: Use another way to get Profile::current() since we
  599. // want to avoid confusion between session user and queue processing.
  600. $stream = new RepeatsOfMeNoticeStream($this->getProfile(), Profile::current());
  601. return $stream->getNotices($offset, $limit, $since_id, $max_id);
  602. }
  603. public function repeatedToMe($offset = 0, $limit = 20, $since_id = null, $max_id = null)
  604. {
  605. return $this->getProfile()->repeatedToMe($offset, $limit, $since_id, $max_id);
  606. }
  607. public static function siteOwner()
  608. {
  609. $owner = self::cacheGet('user:site_owner');
  610. if ($owner === false) { // cache miss
  611. $pr = new Profile_role();
  612. $pr->role = Profile_role::OWNER;
  613. $pr->orderBy('created, profile_id');
  614. $pr->limit(1);
  615. if (!$pr->find(true)) {
  616. throw new NoResultException($pr);
  617. }
  618. $owner = User::getKV('id', $pr->profile_id);
  619. self::cacheSet('user:site_owner', $owner);
  620. }
  621. if ($owner instanceof User) {
  622. return $owner;
  623. }
  624. throw new ServerException(_('No site owner configured.'));
  625. }
  626. /**
  627. * Pull the primary site account to use in single-user mode.
  628. * If a valid user nickname is listed in 'singleuser':'nickname'
  629. * in the config, this will be used; otherwise the site owner
  630. * account is taken by default.
  631. *
  632. * @return User
  633. * @throws ServerException if no valid single user account is present
  634. * @throws ServerException if called when not in single-user mode
  635. */
  636. public static function singleUser()
  637. {
  638. if (!common_config('singleuser', 'enabled')) {
  639. // TRANS: Server exception.
  640. throw new ServerException(_('Single-user mode code called when not enabled.'));
  641. }
  642. if (!empty($nickname = common_config('singleuser', 'nickname'))) {
  643. $user = User::getKV('nickname', $nickname);
  644. if ($user instanceof User) {
  645. return $user;
  646. }
  647. }
  648. // If there was no nickname or no user by that nickname,
  649. // try the site owner. Throws exception if not configured.
  650. return User::siteOwner();
  651. }
  652. /**
  653. * This is kind of a hack for using external setup code that's trying to
  654. * build single-user sites.
  655. *
  656. * Will still return a username if the config singleuser/nickname is set
  657. * even if the account doesn't exist, which normally indicates that the
  658. * site is horribly misconfigured.
  659. *
  660. * At the moment, we need to let it through so that router setup can
  661. * complete, otherwise we won't be able to create the account.
  662. *
  663. * This will be easier when we can more easily create the account and
  664. * *then* switch the site to 1user mode without jumping through hoops.
  665. *
  666. * @return string
  667. * @throws ServerException if no valid single user account is present
  668. * @throws ServerException if called when not in single-user mode
  669. */
  670. public static function singleUserNickname()
  671. {
  672. try {
  673. $user = User::singleUser();
  674. return $user->nickname;
  675. } catch (Exception $e) {
  676. if (common_config('singleuser', 'enabled') && common_config('singleuser', 'nickname')) {
  677. common_log(LOG_WARNING, "Warning: code attempting to pull single-user nickname when the account does not exist. If this is not setup time, this is probably a bug.");
  678. return common_config('singleuser', 'nickname');
  679. }
  680. throw $e;
  681. }
  682. }
  683. /**
  684. * Find and shorten links in the given text using this user's URL shortening
  685. * settings.
  686. *
  687. * By default, links will be left untouched if the text is shorter than the
  688. * configured maximum notice length. Pass true for the $always parameter
  689. * to force all links to be shortened regardless.
  690. *
  691. * Side effects: may save file and file_redirection records for referenced URLs.
  692. *
  693. * @param string $text
  694. * @param boolean $always
  695. * @return string
  696. */
  697. public function shortenLinks($text, $always=false)
  698. {
  699. return common_shorten_links($text, $always, $this);
  700. }
  701. /*
  702. * Get a list of OAuth client applications that have access to this
  703. * user's account.
  704. */
  705. public function getConnectedApps($offset = 0, $limit = null)
  706. {
  707. $apps = new Oauth_application_user();
  708. $apps->selectAdd();
  709. $apps->selectAdd('oauth_application_user.*');
  710. $apps->joinAdd(['application_id', 'oauth_application:id']);
  711. $apps->profile_id = $this->getID();
  712. $apps->whereAdd('oauth_application_user.access_type > 0');
  713. $apps->orderBy('oauth_application_user.created DESC, oauth_application.id DESC');
  714. if ($offset > 0) {
  715. $apps->limit($offset, $limit);
  716. }
  717. $apps->find();
  718. return $apps;
  719. }
  720. /**
  721. * Magic function called at serialize() time.
  722. *
  723. * We use this to drop a couple process-specific references
  724. * from DB_DataObject which can cause trouble in future
  725. * processes.
  726. *
  727. * @return array of variable names to include in serialization.
  728. */
  729. public function __sleep()
  730. {
  731. $vars = parent::__sleep();
  732. $skip = array('_profile');
  733. return array_diff($vars, $skip);
  734. }
  735. public static function recoverPassword($nore)
  736. {
  737. require_once INSTALLDIR . '/lib/util/mail.php';
  738. // $confirm_email will be used as a fallback if our user doesn't have a confirmed email
  739. $confirm_email = null;
  740. if (common_is_email($nore)) {
  741. $user = User::getKV('email', common_canonical_email($nore));
  742. // See if it's an unconfirmed email address
  743. if (!$user instanceof User) {
  744. // Warning: it may actually be legit to have multiple folks
  745. // who have claimed, but not yet confirmed, the same address.
  746. // We'll only send to the first one that comes up.
  747. $confirm_email = new Confirm_address();
  748. $confirm_email->address = common_canonical_email($nore);
  749. $confirm_email->address_type = 'email';
  750. if ($confirm_email->find(true)) {
  751. $user = User::getKV('id', $confirm_email->user_id);
  752. }
  753. }
  754. // No luck finding anyone by that email address.
  755. if (!$user instanceof User) {
  756. if (common_config('site', 'fakeaddressrecovery')) {
  757. // Return without actually doing anything! We fake address recovery
  758. // to avoid revealing which email addresses are registered with the site.
  759. return;
  760. }
  761. // TRANS: Information on password recovery form if no known e-mail address was specified.
  762. throw new ClientException(_('No user with that email address exists here.'));
  763. }
  764. } else {
  765. // This might throw a NicknameException on bad nicknames
  766. $user = User::getKV('nickname', common_canonical_nickname($nore));
  767. if (!$user instanceof User) {
  768. // TRANS: Information on password recovery form if no known username was specified.
  769. throw new ClientException(_('No user with that nickname exists here.'));
  770. }
  771. }
  772. // Try to get an unconfirmed email address if they used a user name
  773. if (empty($user->email) && $confirm_email === null) {
  774. $confirm_email = new Confirm_address();
  775. $confirm_email->user_id = $user->id;
  776. $confirm_email->address_type = 'email';
  777. $confirm_email->find();
  778. if (!$confirm_email->fetch()) {
  779. // Nothing found, so let's reset it to null
  780. $confirm_email = null;
  781. }
  782. }
  783. if (empty($user->email) && !$confirm_email instanceof Confirm_address) {
  784. // TRANS: Client error displayed on password recovery form if a user does not have a registered e-mail address.
  785. throw new ClientException(_('No registered email address for that user.'));
  786. }
  787. // Success! We have a valid user and a confirmed or unconfirmed email address
  788. $confirm = new Confirm_address();
  789. $confirm->code = common_confirmation_code(128);
  790. $confirm->address_type = 'recover';
  791. $confirm->user_id = $user->id;
  792. $confirm->address = $user->email ?: $confirm_email->address;
  793. if (!$confirm->insert()) {
  794. common_log_db_error($confirm, 'INSERT', __FILE__);
  795. // TRANS: Server error displayed if e-mail address confirmation fails in the database on the password recovery form.
  796. throw new ServerException(_('Error saving address confirmation.'));
  797. }
  798. // @todo FIXME: needs i18n.
  799. $body = "Hey, $user->nickname.";
  800. $body .= "\n\n";
  801. $body .= 'Someone just asked for a new password ' .
  802. 'for this account on ' . common_config('site', 'name') . '.';
  803. $body .= "\n\n";
  804. $body .= 'If it was you, and you want to confirm, use the URL below:';
  805. $body .= "\n\n";
  806. $body .= "\t" . common_local_url(
  807. 'recoverpassword',
  808. ['code' => $confirm->code]
  809. );
  810. $body .= "\n\n";
  811. $body .= 'If not, just ignore this message.';
  812. $body .= "\n\n";
  813. $body .= 'Thanks for your time, ';
  814. $body .= "\n";
  815. $body .= common_config('site', 'name');
  816. $body .= "\n";
  817. $headers = _mail_prepare_headers('recoverpassword', $user->nickname, $user->nickname);
  818. // TRANS: Subject for password recovery e-mail.
  819. mail_to_user($user, _('Password recovery requested'), $body, $headers, $confirm->address);
  820. }
  821. public function streamModeOnly()
  822. {
  823. if (common_config('oldschool', 'enabled')) {
  824. $osp = Old_school_prefs::getKV('user_id', $this->id);
  825. if (!empty($osp)) {
  826. return $osp->stream_mode_only;
  827. }
  828. }
  829. return false;
  830. }
  831. public function streamNicknames()
  832. {
  833. if (common_config('oldschool', 'enabled')) {
  834. $osp = Old_school_prefs::getKV('user_id', $this->id);
  835. if (!empty($osp)) {
  836. return $osp->stream_nicknames;
  837. }
  838. }
  839. return false;
  840. }
  841. public function registrationActivity()
  842. {
  843. $profile = $this->getProfile();
  844. $service = new ActivityObject();
  845. $service->type = ActivityObject::SERVICE;
  846. $service->title = common_config('site', 'name');
  847. $service->link = common_root_url();
  848. $service->id = $service->link;
  849. $act = new Activity();
  850. $act->actor = $profile->asActivityObject();
  851. $act->verb = ActivityVerb::JOIN;
  852. $act->objects[] = $service;
  853. $act->id = TagURI::mint(
  854. 'user:register:%d',
  855. $this->id
  856. );
  857. $act->time = strtotime($this->created);
  858. $act->title = _("Register");
  859. $act->content = sprintf(
  860. _('%1$s joined %2$s.'),
  861. $profile->getBestName(),
  862. $service->title
  863. );
  864. return $act;
  865. }
  866. public function isPrivateStream()
  867. {
  868. return $this->getProfile()->isPrivateStream();
  869. }
  870. public function hasPassword()
  871. {
  872. return !empty($this->password);
  873. }
  874. public function setPassword($password)
  875. {
  876. $orig = clone($this);
  877. $this->password = common_munge_password($password, $this->getProfile());
  878. if ($this->validate() !== true) {
  879. // TRANS: Form validation error on page where to change password.
  880. throw new ServerException(_('Error saving user; invalid.'));
  881. }
  882. if (!$this->update($orig)) {
  883. common_log_db_error($this, 'UPDATE', __FILE__);
  884. // TRANS: Server error displayed on page where to change password when password change
  885. // TRANS: could not be made because of a server error.
  886. throw new ServerException(_('Cannot save new password.'));
  887. }
  888. }
  889. public function delPref($namespace, $topic)
  890. {
  891. return $this->getProfile()->delPref($namespace, $topic);
  892. }
  893. public function getPref($namespace, $topic, $default=null)
  894. {
  895. return $this->getProfile()->getPref($namespace, $topic, $default);
  896. }
  897. public function getConfigPref($namespace, $topic)
  898. {
  899. return $this->getProfile()->getConfigPref($namespace, $topic);
  900. }
  901. public function setPref($namespace, $topic, $data)
  902. {
  903. return $this->getProfile()->setPref($namespace, $topic, $data);
  904. }
  905. }