User.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083
  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; // varchar(191) not 255 because utf8mb4 takes more space
  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() not_null default_0000-00-00%2000%3A00%3A00
  51. public $modified; // datetime() 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' => 'varchar', 'length' => 191, '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', 'not null' => true, 'default' => '0000-00-00 00:00:00', 'description' => 'date this record was created'),
  83. 'modified' => array('type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', '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_created_idx' => array('created'),
  99. 'user_smsemail_idx' => array('smsemail'),
  100. ),
  101. );
  102. }
  103. protected $_profile = array();
  104. /**
  105. * @return Profile
  106. *
  107. * @throws UserNoProfileException if user has no profile
  108. */
  109. public function getProfile()
  110. {
  111. if (!isset($this->_profile[$this->id])) {
  112. $profile = Profile::getKV('id', $this->id);
  113. if (!$profile instanceof Profile) {
  114. throw new UserNoProfileException($this);
  115. }
  116. $this->_profile[$this->id] = $profile;
  117. }
  118. return $this->_profile[$this->id];
  119. }
  120. public function sameAs(Profile $other)
  121. {
  122. return $this->getProfile()->sameAs($other);
  123. }
  124. public function getUri()
  125. {
  126. return $this->uri;
  127. }
  128. public function getNickname()
  129. {
  130. return $this->getProfile()->getNickname();
  131. }
  132. public static function getByNickname($nickname)
  133. {
  134. $user = User::getKV('nickname', $nickname);
  135. if (!$user instanceof User) {
  136. throw new NoSuchUserException(array('nickname' => $nickname));
  137. }
  138. return $user;
  139. }
  140. public function isSubscribed(Profile $other)
  141. {
  142. return $this->getProfile()->isSubscribed($other);
  143. }
  144. public function hasPendingSubscription(Profile $other)
  145. {
  146. return $this->getProfile()->hasPendingSubscription($other);
  147. }
  148. /**
  149. * Get the most recent notice posted by this user, if any.
  150. *
  151. * @return mixed Notice or null
  152. */
  153. public function getCurrentNotice()
  154. {
  155. return $this->getProfile()->getCurrentNotice();
  156. }
  157. public function getCarrier()
  158. {
  159. return Sms_carrier::getKV('id', $this->carrier);
  160. }
  161. public function hasBlocked(Profile $other)
  162. {
  163. return $this->getProfile()->hasBlocked($other);
  164. }
  165. /**
  166. * Register a new user account and profile and set up default subscriptions.
  167. * If a new-user welcome message is configured, this will be sent.
  168. *
  169. * @param array $fields associative array of optional properties
  170. * string 'bio'
  171. * string 'email'
  172. * bool 'email_confirmed' pass true to mark email as pre-confirmed
  173. * string 'fullname'
  174. * string 'homepage'
  175. * string 'location' informal string description of geolocation
  176. * float 'lat' decimal latitude for geolocation
  177. * float 'lon' decimal longitude for geolocation
  178. * int 'location_id' geoname identifier
  179. * int 'location_ns' geoname namespace to interpret location_id
  180. * string 'nickname' REQUIRED
  181. * string 'password' (may be missing for eg OpenID registrations)
  182. * string 'code' invite code
  183. * ?string 'uri' permalink to notice; defaults to local notice URL
  184. * @return User object
  185. * @throws Exception on failure
  186. */
  187. public static function register(array $fields, $accept_email_fail = false)
  188. {
  189. // MAGICALLY put fields into current scope
  190. extract($fields);
  191. $profile = new Profile();
  192. if (!empty($email)) {
  193. $email = common_canonical_email($email);
  194. }
  195. // Normalize _and_ check whether it is in use. Throw NicknameException on failure.
  196. $profile->nickname = Nickname::normalize($nickname, true);
  197. $profile->profileurl = common_profile_url($profile->nickname);
  198. if (!empty($fullname)) {
  199. $profile->fullname = $fullname;
  200. }
  201. if (!empty($homepage)) {
  202. $profile->homepage = $homepage;
  203. }
  204. if (!empty($bio)) {
  205. $profile->bio = $bio;
  206. }
  207. if (!empty($location)) {
  208. $profile->location = $location;
  209. $loc = Location::fromName($location);
  210. if (!empty($loc)) {
  211. $profile->lat = $loc->lat;
  212. $profile->lon = $loc->lon;
  213. $profile->location_id = $loc->location_id;
  214. $profile->location_ns = $loc->location_ns;
  215. }
  216. }
  217. $profile->created = common_sql_now();
  218. $user = new User();
  219. $user->nickname = $profile->nickname;
  220. $invite = null;
  221. // Users who respond to invite email have proven their ownership of that address
  222. if (!empty($code)) {
  223. $invite = Invitation::getKV($code);
  224. if ($invite instanceof Invitation && $invite->address && $invite->address_type == 'email' && $invite->address == $email) {
  225. $user->email = $invite->address;
  226. }
  227. }
  228. if (isset($email_confirmed) && $email_confirmed) {
  229. $user->email = $email;
  230. }
  231. // Set default-on options here, otherwise they'll be disabled
  232. // initially for sites using caching, since the initial encache
  233. // doesn't know about the defaults in the database.
  234. $user->emailnotifysub = true;
  235. $user->emailnotifynudge = true;
  236. $user->emailnotifymsg = true;
  237. $user->emailnotifyattn = true;
  238. $user->emailpost = true;
  239. $user->created = common_sql_now();
  240. if (Event::handle('StartUserRegister', array($profile))) {
  241. $profile->query('BEGIN');
  242. $id = $profile->insert();
  243. if ($id === false) {
  244. common_log_db_error($profile, 'INSERT', __FILE__);
  245. $profile->query('ROLLBACK');
  246. // TRANS: Profile data could not be inserted for some reason.
  247. throw new ServerException(_m('Could not insert profile data for new user.'));
  248. }
  249. // Necessary because id has been known to be reissued.
  250. if ($profile->hasRole(Profile_role::DELETED)) {
  251. $profile->revokeRole(Profile_role::DELETED);
  252. }
  253. $user->id = $id;
  254. if (!empty($uri)) {
  255. $user->uri = $uri;
  256. } else {
  257. $user->uri = common_user_uri($user);
  258. }
  259. if (!empty($password)) { // may not have a password for OpenID users
  260. $user->password = common_munge_password($password);
  261. }
  262. $result = $user->insert();
  263. if ($result === false) {
  264. common_log_db_error($user, 'INSERT', __FILE__);
  265. $profile->query('ROLLBACK');
  266. // TRANS: User data could not be inserted for some reason.
  267. throw new ServerException(_m('Could not insert user data for new user.'));
  268. }
  269. // Everyone is subscribed to themself
  270. $subscription = new Subscription();
  271. $subscription->subscriber = $user->id;
  272. $subscription->subscribed = $user->id;
  273. $subscription->created = $user->created;
  274. $result = $subscription->insert();
  275. if (!$result) {
  276. common_log_db_error($subscription, 'INSERT', __FILE__);
  277. $profile->query('ROLLBACK');
  278. // TRANS: Subscription data could not be inserted for some reason.
  279. throw new ServerException(_m('Could not insert subscription data for new user.'));
  280. }
  281. // Mark that this invite was converted
  282. if (!empty($invite)) {
  283. $invite->convert($user);
  284. }
  285. if (!empty($email) && empty($user->email)) {
  286. // The actual email will be sent further down, after the database COMMIT
  287. $confirm = new Confirm_address();
  288. $confirm->code = common_confirmation_code(128);
  289. $confirm->user_id = $user->id;
  290. $confirm->address = $email;
  291. $confirm->address_type = 'email';
  292. $result = $confirm->insert();
  293. if ($result===false) {
  294. common_log_db_error($confirm, 'INSERT', __FILE__);
  295. $profile->query('ROLLBACK');
  296. // TRANS: Email confirmation data could not be inserted for some reason.
  297. throw new ServerException(_m('Could not insert email confirmation data for new user.'));
  298. }
  299. }
  300. if (!empty($code) && $user->email) {
  301. $user->emailChanged();
  302. }
  303. // Default system subscription
  304. $defnick = common_config('newuser', 'default');
  305. if (!empty($defnick)) {
  306. $defuser = User::getKV('nickname', $defnick);
  307. if (empty($defuser)) {
  308. common_log(
  309. LOG_WARNING,
  310. sprintf('Default user %s does not exist.', $defnick),
  311. __FILE__
  312. );
  313. } else {
  314. Subscription::ensureStart($profile, $defuser->getProfile());
  315. }
  316. }
  317. $profile->query('COMMIT');
  318. if (!empty($email) && empty($user->email)) {
  319. try {
  320. $confirm->sendConfirmation();
  321. } catch (EmailException $e) {
  322. common_log(LOG_ERR, "Could not send user registration email for user id=={$profile->getID()}: {$e->getMessage()}");
  323. if (!$accept_email_fail) {
  324. throw $e;
  325. }
  326. }
  327. }
  328. // Welcome message
  329. $welcome = common_config('newuser', 'welcome');
  330. if (!empty($welcome)) {
  331. $welcomeuser = User::getKV('nickname', $welcome);
  332. if (empty($welcomeuser)) {
  333. common_log(
  334. LOG_WARNING,
  335. sprintf('Welcome user %s does not exist.', $defnick),
  336. __FILE__
  337. );
  338. } else {
  339. $notice = Notice::saveNew(
  340. $welcomeuser->id,
  341. // TRANS: Notice given on user registration.
  342. // TRANS: %1$s is the sitename, $2$s is the registering user's nickname.
  343. sprintf(
  344. _('Welcome to %1$s, @%2$s!'),
  345. common_config('site', 'name'),
  346. $profile->getNickname()
  347. ),
  348. 'system'
  349. );
  350. }
  351. }
  352. Event::handle('EndUserRegister', array($profile));
  353. }
  354. if (!$user instanceof User || empty($user->id)) {
  355. throw new ServerException('User could not be registered. Probably an event hook that failed.');
  356. }
  357. return $user;
  358. }
  359. // Things we do when the email changes
  360. public function emailChanged()
  361. {
  362. $invites = new Invitation();
  363. $invites->address = $this->email;
  364. $invites->address_type = 'email';
  365. if ($invites->find()) {
  366. while ($invites->fetch()) {
  367. try {
  368. $other = Profile::getByID($invites->user_id);
  369. Subscription::start($other, $this->getProfile());
  370. } catch (NoResultException $e) {
  371. // profile did not exist
  372. } catch (AlreadyFulfilledException $e) {
  373. // already subscribed to this profile
  374. } catch (Exception $e) {
  375. common_log(LOG_ERR, 'On-invitation-completion subscription failed when subscribing '._ve($invites->user_id).' to '.$this->getProfile()->getID().': '._ve($e->getMessage()));
  376. }
  377. }
  378. }
  379. }
  380. public function mutuallySubscribed(Profile $other)
  381. {
  382. return $this->getProfile()->mutuallySubscribed($other);
  383. }
  384. public function mutuallySubscribedUsers()
  385. {
  386. $user = new User();
  387. // 3-way join; probably should get cached
  388. $user->query(sprintf(
  389. 'SELECT %1$s.* ' .
  390. 'FROM subscription AS sub1 INNER JOIN %1$s ON sub1.subscribed = %1$s.id ' .
  391. 'INNER JOIN subscription AS sub2 ON %1$s.id = sub2.subscriber ' .
  392. 'WHERE sub1.subscriber = %2$d AND sub2.subscribed = %2$d ' .
  393. 'ORDER BY %1$s.nickname',
  394. $user->escapedTableName(),
  395. $this->id
  396. ));
  397. return $user;
  398. }
  399. public function getReplies($offset = 0, $limit = NOTICES_PER_PAGE, $since_id = 0, $before_id = 0)
  400. {
  401. return $this->getProfile()->getReplies($offset, $limit, $since_id, $before_id);
  402. }
  403. public function getTaggedNotices($tag, $offset = 0, $limit = NOTICES_PER_PAGE, $since_id = 0, $before_id = 0)
  404. {
  405. return $this->getProfile()->getTaggedNotices($tag, $offset, $limit, $since_id, $before_id);
  406. }
  407. public function getNotices($offset = 0, $limit = NOTICES_PER_PAGE, $since_id = 0, $before_id = 0)
  408. {
  409. return $this->getProfile()->getNotices($offset, $limit, $since_id, $before_id);
  410. }
  411. public function block(Profile $other)
  412. {
  413. // Add a new block record
  414. // no blocking (and thus unsubbing from) yourself
  415. if ($this->id == $other->id) {
  416. common_log(
  417. LOG_WARNING,
  418. sprintf(
  419. "Profile ID %d (%s) tried to block themself.",
  420. $this->id,
  421. $this->nickname
  422. )
  423. );
  424. return false;
  425. }
  426. $block = new Profile_block();
  427. // Begin a transaction
  428. $block->query('BEGIN');
  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');
  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 ($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. $qry =
  708. 'SELECT u.* ' .
  709. 'FROM oauth_application_user u, oauth_application a ' .
  710. 'WHERE u.profile_id = %d ' .
  711. 'AND a.id = u.application_id ' .
  712. 'AND u.access_type > 0 ' .
  713. 'ORDER BY u.created DESC ';
  714. if ($offset > 0) {
  715. $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
  716. }
  717. $apps = new Oauth_application_user();
  718. $cnt = $apps->query(sprintf($qry, $this->id));
  719. return $apps;
  720. }
  721. /**
  722. * Magic function called at serialize() time.
  723. *
  724. * We use this to drop a couple process-specific references
  725. * from DB_DataObject which can cause trouble in future
  726. * processes.
  727. *
  728. * @return array of variable names to include in serialization.
  729. */
  730. public function __sleep()
  731. {
  732. $vars = parent::__sleep();
  733. $skip = array('_profile');
  734. return array_diff($vars, $skip);
  735. }
  736. public static function recoverPassword($nore)
  737. {
  738. require_once INSTALLDIR . '/lib/util/mail.php';
  739. // $confirm_email will be used as a fallback if our user doesn't have a confirmed email
  740. $confirm_email = null;
  741. if (common_is_email($nore)) {
  742. $user = User::getKV('email', common_canonical_email($nore));
  743. // See if it's an unconfirmed email address
  744. if (!$user instanceof User) {
  745. // Warning: it may actually be legit to have multiple folks
  746. // who have claimed, but not yet confirmed, the same address.
  747. // We'll only send to the first one that comes up.
  748. $confirm_email = new Confirm_address();
  749. $confirm_email->address = common_canonical_email($nore);
  750. $confirm_email->address_type = 'email';
  751. if ($confirm_email->find(true)) {
  752. $user = User::getKV('id', $confirm_email->user_id);
  753. }
  754. }
  755. // No luck finding anyone by that email address.
  756. if (!$user instanceof User) {
  757. if (common_config('site', 'fakeaddressrecovery')) {
  758. // Return without actually doing anything! We fake address recovery
  759. // to avoid revealing which email addresses are registered with the site.
  760. return;
  761. }
  762. // TRANS: Information on password recovery form if no known e-mail address was specified.
  763. throw new ClientException(_('No user with that email address exists here.'));
  764. }
  765. } else {
  766. // This might throw a NicknameException on bad nicknames
  767. $user = User::getKV('nickname', common_canonical_nickname($nore));
  768. if (!$user instanceof User) {
  769. // TRANS: Information on password recovery form if no known username was specified.
  770. throw new ClientException(_('No user with that nickname exists here.'));
  771. }
  772. }
  773. // Try to get an unconfirmed email address if they used a user name
  774. if (empty($user->email) && $confirm_email === null) {
  775. $confirm_email = new Confirm_address();
  776. $confirm_email->user_id = $user->id;
  777. $confirm_email->address_type = 'email';
  778. $confirm_email->find();
  779. if (!$confirm_email->fetch()) {
  780. // Nothing found, so let's reset it to null
  781. $confirm_email = null;
  782. }
  783. }
  784. if (empty($user->email) && !$confirm_email instanceof Confirm_address) {
  785. // TRANS: Client error displayed on password recovery form if a user does not have a registered e-mail address.
  786. throw new ClientException(_('No registered email address for that user.'));
  787. }
  788. // Success! We have a valid user and a confirmed or unconfirmed email address
  789. $confirm = new Confirm_address();
  790. $confirm->code = common_confirmation_code(128);
  791. $confirm->address_type = 'recover';
  792. $confirm->user_id = $user->id;
  793. $confirm->address = $user->email ?: $confirm_email->address;
  794. if (!$confirm->insert()) {
  795. common_log_db_error($confirm, 'INSERT', __FILE__);
  796. // TRANS: Server error displayed if e-mail address confirmation fails in the database on the password recovery form.
  797. throw new ServerException(_('Error saving address confirmation.'));
  798. }
  799. // @todo FIXME: needs i18n.
  800. $body = "Hey, $user->nickname.";
  801. $body .= "\n\n";
  802. $body .= 'Someone just asked for a new password ' .
  803. 'for this account on ' . common_config('site', 'name') . '.';
  804. $body .= "\n\n";
  805. $body .= 'If it was you, and you want to confirm, use the URL below:';
  806. $body .= "\n\n";
  807. $body .= "\t" . common_local_url(
  808. 'recoverpassword',
  809. ['code' => $confirm->code]
  810. );
  811. $body .= "\n\n";
  812. $body .= 'If not, just ignore this message.';
  813. $body .= "\n\n";
  814. $body .= 'Thanks for your time, ';
  815. $body .= "\n";
  816. $body .= common_config('site', 'name');
  817. $body .= "\n";
  818. $headers = _mail_prepare_headers('recoverpassword', $user->nickname, $user->nickname);
  819. // TRANS: Subject for password recovery e-mail.
  820. mail_to_user($user, _('Password recovery requested'), $body, $headers, $confirm->address);
  821. }
  822. public function streamModeOnly()
  823. {
  824. if (common_config('oldschool', 'enabled')) {
  825. $osp = Old_school_prefs::getKV('user_id', $this->id);
  826. if (!empty($osp)) {
  827. return $osp->stream_mode_only;
  828. }
  829. }
  830. return false;
  831. }
  832. public function streamNicknames()
  833. {
  834. if (common_config('oldschool', 'enabled')) {
  835. $osp = Old_school_prefs::getKV('user_id', $this->id);
  836. if (!empty($osp)) {
  837. return $osp->stream_nicknames;
  838. }
  839. }
  840. return false;
  841. }
  842. public function registrationActivity()
  843. {
  844. $profile = $this->getProfile();
  845. $service = new ActivityObject();
  846. $service->type = ActivityObject::SERVICE;
  847. $service->title = common_config('site', 'name');
  848. $service->link = common_root_url();
  849. $service->id = $service->link;
  850. $act = new Activity();
  851. $act->actor = $profile->asActivityObject();
  852. $act->verb = ActivityVerb::JOIN;
  853. $act->objects[] = $service;
  854. $act->id = TagURI::mint(
  855. 'user:register:%d',
  856. $this->id
  857. );
  858. $act->time = strtotime($this->created);
  859. $act->title = _("Register");
  860. $act->content = sprintf(
  861. _('%1$s joined %2$s.'),
  862. $profile->getBestName(),
  863. $service->title
  864. );
  865. return $act;
  866. }
  867. public function isPrivateStream()
  868. {
  869. return $this->getProfile()->isPrivateStream();
  870. }
  871. public function hasPassword()
  872. {
  873. return !empty($this->password);
  874. }
  875. public function setPassword($password)
  876. {
  877. $orig = clone($this);
  878. $this->password = common_munge_password($password, $this->getProfile());
  879. if ($this->validate() !== true) {
  880. // TRANS: Form validation error on page where to change password.
  881. throw new ServerException(_('Error saving user; invalid.'));
  882. }
  883. if (!$this->update($orig)) {
  884. common_log_db_error($this, 'UPDATE', __FILE__);
  885. // TRANS: Server error displayed on page where to change password when password change
  886. // TRANS: could not be made because of a server error.
  887. throw new ServerException(_('Cannot save new password.'));
  888. }
  889. }
  890. public function delPref($namespace, $topic)
  891. {
  892. return $this->getProfile()->delPref($namespace, $topic);
  893. }
  894. public function getPref($namespace, $topic, $default=null)
  895. {
  896. return $this->getProfile()->getPref($namespace, $topic, $default);
  897. }
  898. public function getConfigPref($namespace, $topic)
  899. {
  900. return $this->getProfile()->getConfigPref($namespace, $topic);
  901. }
  902. public function setPref($namespace, $topic, $data)
  903. {
  904. return $this->getProfile()->setPref($namespace, $topic, $data);
  905. }
  906. }