User.php 35 KB

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