User.php 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  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_idx' => array('created'),
  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');
  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 AS u, oauth_application AS 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. }