User.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  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(255)
  33. public $email; // varchar(255) unique_key
  34. public $incomingemail; // varchar(255) unique_key
  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(255)
  49. public $uri; // varchar(255) unique_key
  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' => 255, 'description' => 'salted password, can be null for OpenID users'),
  66. 'email' => array('type' => 'varchar', 'length' => 255, 'description' => 'email address for password recovery etc.'),
  67. 'incomingemail' => array('type' => 'varchar', 'length' => 255, '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' => 255, 'description' => 'built from sms and carrier'),
  82. 'uri' => array('type' => 'varchar', 'length' => 255, '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 mixed User object or false on failure
  177. */
  178. static function register(array $fields) {
  179. // MAGICALLY put fields into current scope
  180. extract($fields);
  181. $profile = new Profile();
  182. if (!empty($email)) {
  183. $email = common_canonical_email($email);
  184. }
  185. try {
  186. $profile->nickname = Nickname::normalize($nickname, true);
  187. } catch (NicknameException $e) {
  188. common_log(LOG_WARNING, sprintf('Bad nickname during User registration for %s: %s', $nickname, $e->getMessage()), __FILE__);
  189. return false;
  190. }
  191. $profile->profileurl = common_profile_url($profile->nickname);
  192. if (!empty($fullname)) {
  193. $profile->fullname = $fullname;
  194. }
  195. if (!empty($homepage)) {
  196. $profile->homepage = $homepage;
  197. }
  198. if (!empty($bio)) {
  199. $profile->bio = $bio;
  200. }
  201. if (!empty($location)) {
  202. $profile->location = $location;
  203. $loc = Location::fromName($location);
  204. if (!empty($loc)) {
  205. $profile->lat = $loc->lat;
  206. $profile->lon = $loc->lon;
  207. $profile->location_id = $loc->location_id;
  208. $profile->location_ns = $loc->location_ns;
  209. }
  210. }
  211. $profile->created = common_sql_now();
  212. $user = new User();
  213. $user->nickname = $profile->nickname;
  214. $invite = null;
  215. // Users who respond to invite email have proven their ownership of that address
  216. if (!empty($code)) {
  217. $invite = Invitation::getKV($code);
  218. if ($invite instanceof Invitation && $invite->address && $invite->address_type == 'email' && $invite->address == $email) {
  219. $user->email = $invite->address;
  220. }
  221. }
  222. if(isset($email_confirmed) && $email_confirmed) {
  223. $user->email = $email;
  224. }
  225. // Set default-on options here, otherwise they'll be disabled
  226. // initially for sites using caching, since the initial encache
  227. // doesn't know about the defaults in the database.
  228. $user->emailnotifysub = 1;
  229. $user->emailnotifynudge = 1;
  230. $user->emailnotifymsg = 1;
  231. $user->emailnotifyattn = 1;
  232. $user->emailmicroid = 1;
  233. $user->emailpost = 1;
  234. $user->jabbermicroid = 1;
  235. $user->created = common_sql_now();
  236. if (Event::handle('StartUserRegister', array($profile))) {
  237. $profile->query('BEGIN');
  238. $id = $profile->insert();
  239. if ($id === false) {
  240. common_log_db_error($profile, 'INSERT', __FILE__);
  241. return false;
  242. }
  243. $user->id = $id;
  244. if (!empty($uri)) {
  245. $user->uri = $uri;
  246. } else {
  247. $user->uri = common_user_uri($user);
  248. }
  249. if (!empty($password)) { // may not have a password for OpenID users
  250. $user->password = common_munge_password($password, $id);
  251. }
  252. $result = $user->insert();
  253. if ($result === false) {
  254. common_log_db_error($user, 'INSERT', __FILE__);
  255. $profile->query('ROLLBACK');
  256. return false;
  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. return false;
  268. }
  269. // Mark that this invite was converted
  270. if (!empty($invite)) {
  271. $invite->convert($user);
  272. }
  273. if (!empty($email) && !$user->email) {
  274. $confirm = new Confirm_address();
  275. $confirm->code = common_confirmation_code(128);
  276. $confirm->user_id = $user->id;
  277. $confirm->address = $email;
  278. $confirm->address_type = 'email';
  279. $result = $confirm->insert();
  280. if (!$result) {
  281. common_log_db_error($confirm, 'INSERT', __FILE__);
  282. $profile->query('ROLLBACK');
  283. return false;
  284. }
  285. }
  286. if (!empty($code) && $user->email) {
  287. $user->emailChanged();
  288. }
  289. // Default system subscription
  290. $defnick = common_config('newuser', 'default');
  291. if (!empty($defnick)) {
  292. $defuser = User::getKV('nickname', $defnick);
  293. if (empty($defuser)) {
  294. common_log(LOG_WARNING, sprintf("Default user %s does not exist.", $defnick),
  295. __FILE__);
  296. } else {
  297. Subscription::start($profile, $defuser->getProfile());
  298. }
  299. }
  300. $profile->query('COMMIT');
  301. if (!empty($email) && !$user->email) {
  302. mail_confirm_address($user, $confirm->code, $profile->nickname, $email);
  303. }
  304. // Welcome message
  305. $welcome = common_config('newuser', 'welcome');
  306. if (!empty($welcome)) {
  307. $welcomeuser = User::getKV('nickname', $welcome);
  308. if (empty($welcomeuser)) {
  309. common_log(LOG_WARNING, sprintf("Welcome user %s does not exist.", $defnick),
  310. __FILE__);
  311. } else {
  312. $notice = Notice::saveNew($welcomeuser->id,
  313. // TRANS: Notice given on user registration.
  314. // TRANS: %1$s is the sitename, $2$s is the registering user's nickname.
  315. sprintf(_('Welcome to %1$s, @%2$s!'),
  316. common_config('site', 'name'),
  317. $user->nickname),
  318. 'system');
  319. }
  320. }
  321. Event::handle('EndUserRegister', array($profile));
  322. }
  323. return $user;
  324. }
  325. // Things we do when the email changes
  326. function emailChanged()
  327. {
  328. $invites = new Invitation();
  329. $invites->address = $this->email;
  330. $invites->address_type = 'email';
  331. if ($invites->find()) {
  332. while ($invites->fetch()) {
  333. try {
  334. $other = Profile::getKV('id', $invites->user_id);
  335. if (!($other instanceof Profile)) { // remove when getKV throws exceptions
  336. continue;
  337. }
  338. Subscription::start($other, $this->getProfile());
  339. } catch (Exception $e) {
  340. continue;
  341. }
  342. }
  343. }
  344. }
  345. function mutuallySubscribed(Profile $other)
  346. {
  347. return $this->getProfile()->mutuallySubscribed($other);
  348. }
  349. function mutuallySubscribedUsers()
  350. {
  351. // 3-way join; probably should get cached
  352. $UT = common_config('db','type')=='pgsql'?'"user"':'user';
  353. $qry = "SELECT $UT.* " .
  354. "FROM subscription sub1 JOIN $UT ON sub1.subscribed = $UT.id " .
  355. "JOIN subscription sub2 ON $UT.id = sub2.subscriber " .
  356. 'WHERE sub1.subscriber = %d and sub2.subscribed = %d ' .
  357. "ORDER BY $UT.nickname";
  358. $user = new User();
  359. $user->query(sprintf($qry, $this->id, $this->id));
  360. return $user;
  361. }
  362. function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
  363. {
  364. return Reply::stream($this->id, $offset, $limit, $since_id, $before_id);
  365. }
  366. function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0) {
  367. return $this->getProfile()->getTaggedNotices($tag, $offset, $limit, $since_id, $before_id);
  368. }
  369. function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
  370. {
  371. return $this->getProfile()->getNotices($offset, $limit, $since_id, $before_id);
  372. }
  373. function getSelfTags()
  374. {
  375. return Profile_tag::getTagsArray($this->id, $this->id, $this->id);
  376. }
  377. function setSelfTags($newtags, $privacy)
  378. {
  379. return Profile_tag::setTags($this->id, $this->id, $newtags, $privacy);
  380. }
  381. function block(Profile $other)
  382. {
  383. // Add a new block record
  384. // no blocking (and thus unsubbing from) yourself
  385. if ($this->id == $other->id) {
  386. common_log(LOG_WARNING,
  387. sprintf(
  388. "Profile ID %d (%s) tried to block themself.",
  389. $this->id,
  390. $this->nickname
  391. )
  392. );
  393. return false;
  394. }
  395. $block = new Profile_block();
  396. // Begin a transaction
  397. $block->query('BEGIN');
  398. $block->blocker = $this->id;
  399. $block->blocked = $other->id;
  400. $result = $block->insert();
  401. if (!$result) {
  402. common_log_db_error($block, 'INSERT', __FILE__);
  403. return false;
  404. }
  405. $self = $this->getProfile();
  406. if (Subscription::exists($other, $self)) {
  407. Subscription::cancel($other, $self);
  408. }
  409. if (Subscription::exists($self, $other)) {
  410. Subscription::cancel($self, $other);
  411. }
  412. $block->query('COMMIT');
  413. return true;
  414. }
  415. function unblock(Profile $other)
  416. {
  417. // Get the block record
  418. $block = Profile_block::exists($this->getProfile(), $other);
  419. if (!$block) {
  420. return false;
  421. }
  422. $result = $block->delete();
  423. if (!$result) {
  424. common_log_db_error($block, 'DELETE', __FILE__);
  425. return false;
  426. }
  427. return true;
  428. }
  429. function isMember(User_group $group)
  430. {
  431. return $this->getProfile()->isMember($group);
  432. }
  433. function isAdmin(User_group $group)
  434. {
  435. return $this->getProfile()->isAdmin($group);
  436. }
  437. function getGroups($offset=0, $limit=null)
  438. {
  439. return $this->getProfile()->getGroups($offset, $limit);
  440. }
  441. /**
  442. * Request to join the given group.
  443. * May throw exceptions on failure.
  444. *
  445. * @param User_group $group
  446. * @return Group_member
  447. */
  448. function joinGroup(User_group $group)
  449. {
  450. return $this->getProfile()->joinGroup($group);
  451. }
  452. /**
  453. * Leave a group that this user is a member of.
  454. *
  455. * @param User_group $group
  456. */
  457. function leaveGroup(User_group $group)
  458. {
  459. return $this->getProfile()->leaveGroup($group);
  460. }
  461. function getSubscribed($offset=0, $limit=null)
  462. {
  463. return $this->getProfile()->getSubscribed($offset, $limit);
  464. }
  465. function getSubscribers($offset=0, $limit=null)
  466. {
  467. return $this->getProfile()->getSubscribers($offset, $limit);
  468. }
  469. function getTaggedSubscribers($tag, $offset=0, $limit=null)
  470. {
  471. return $this->getProfile()->getTaggedSubscribers($tag, $offset, $limit);
  472. }
  473. function getTaggedSubscriptions($tag, $offset=0, $limit=null)
  474. {
  475. return $this->getProfile()->getTaggedSubscriptions($tag, $offset, $limit);
  476. }
  477. function hasRight($right)
  478. {
  479. return $this->getProfile()->hasRight($right);
  480. }
  481. function delete($useWhere=false)
  482. {
  483. if (empty($this->id)) {
  484. common_log(LOG_WARNING, "Ambiguous User->delete(); skipping related tables.");
  485. return parent::delete($useWhere);
  486. }
  487. try {
  488. $profile = $this->getProfile();
  489. $profile->delete();
  490. } catch (UserNoProfileException $unp) {
  491. common_log(LOG_INFO, "User {$this->nickname} has no profile; continuing deletion.");
  492. }
  493. $related = array(
  494. 'Confirm_address',
  495. 'Remember_me',
  496. 'Foreign_link',
  497. 'Invitation',
  498. );
  499. Event::handle('UserDeleteRelated', array($this, &$related));
  500. foreach ($related as $cls) {
  501. $inst = new $cls();
  502. $inst->user_id = $this->id;
  503. $inst->delete();
  504. }
  505. $this->_deleteTags();
  506. $this->_deleteBlocks();
  507. return parent::delete($useWhere);
  508. }
  509. function _deleteTags()
  510. {
  511. $tag = new Profile_tag();
  512. $tag->tagger = $this->id;
  513. $tag->delete();
  514. }
  515. function _deleteBlocks()
  516. {
  517. $block = new Profile_block();
  518. $block->blocker = $this->id;
  519. $block->delete();
  520. // XXX delete group block? Reset blocker?
  521. }
  522. function hasRole($name)
  523. {
  524. return $this->getProfile()->hasRole($name);
  525. }
  526. function grantRole($name)
  527. {
  528. return $this->getProfile()->grantRole($name);
  529. }
  530. function revokeRole($name)
  531. {
  532. return $this->getProfile()->revokeRole($name);
  533. }
  534. function isSandboxed()
  535. {
  536. return $this->getProfile()->isSandboxed();
  537. }
  538. function isSilenced()
  539. {
  540. return $this->getProfile()->isSilenced();
  541. }
  542. function receivesEmailNotifications()
  543. {
  544. // We could do this in one large if statement, but that's not as easy to read
  545. // Don't send notifications if we don't know the user's email address or it is
  546. // explicitly undesired by the user's own settings.
  547. if (empty($this->email) || !$this->emailnotifyattn) {
  548. return false;
  549. }
  550. // Don't send notifications to a user who is sandboxed or silenced
  551. if ($this->isSandboxed() || $this->isSilenced()) {
  552. return false;
  553. }
  554. return true;
  555. }
  556. function repeatedByMe($offset=0, $limit=20, $since_id=null, $max_id=null)
  557. {
  558. $stream = new RepeatedByMeNoticeStream($this);
  559. return $stream->getNotices($offset, $limit, $since_id, $max_id);
  560. }
  561. function repeatsOfMe($offset=0, $limit=20, $since_id=null, $max_id=null)
  562. {
  563. $stream = new RepeatsOfMeNoticeStream($this);
  564. return $stream->getNotices($offset, $limit, $since_id, $max_id);
  565. }
  566. function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
  567. {
  568. // TRANS: Exception thrown when trying view "repeated to me".
  569. throw new Exception(_('Not implemented since inbox change.'));
  570. }
  571. public static function siteOwner()
  572. {
  573. $owner = self::cacheGet('user:site_owner');
  574. if ($owner === false) { // cache miss
  575. $pr = new Profile_role();
  576. $pr->role = Profile_role::OWNER;
  577. $pr->orderBy('created');
  578. $pr->limit(1);
  579. if (!$pr->find(true)) {
  580. throw new NoResultException($pr);
  581. }
  582. $owner = User::getKV('id', $pr->profile_id);
  583. self::cacheSet('user:site_owner', $owner);
  584. }
  585. if ($owner instanceof User) {
  586. return $owner;
  587. }
  588. throw new ServerException(_('No site owner configured.'));
  589. }
  590. /**
  591. * Pull the primary site account to use in single-user mode.
  592. * If a valid user nickname is listed in 'singleuser':'nickname'
  593. * in the config, this will be used; otherwise the site owner
  594. * account is taken by default.
  595. *
  596. * @return User
  597. * @throws ServerException if no valid single user account is present
  598. * @throws ServerException if called when not in single-user mode
  599. */
  600. public static function singleUser()
  601. {
  602. if (!common_config('singleuser', 'enabled')) {
  603. // TRANS: Server exception.
  604. throw new ServerException(_('Single-user mode code called when not enabled.'));
  605. }
  606. if ($nickname = common_config('singleuser', 'nickname')) {
  607. $user = User::getKV('nickname', $nickname);
  608. if ($user instanceof User) {
  609. return $user;
  610. }
  611. }
  612. // If there was no nickname or no user by that nickname,
  613. // try the site owner. Throws exception if not configured.
  614. return User::siteOwner();
  615. }
  616. /**
  617. * This is kind of a hack for using external setup code that's trying to
  618. * build single-user sites.
  619. *
  620. * Will still return a username if the config singleuser/nickname is set
  621. * even if the account doesn't exist, which normally indicates that the
  622. * site is horribly misconfigured.
  623. *
  624. * At the moment, we need to let it through so that router setup can
  625. * complete, otherwise we won't be able to create the account.
  626. *
  627. * This will be easier when we can more easily create the account and
  628. * *then* switch the site to 1user mode without jumping through hoops.
  629. *
  630. * @return string
  631. * @throws ServerException if no valid single user account is present
  632. * @throws ServerException if called when not in single-user mode
  633. */
  634. static function singleUserNickname()
  635. {
  636. try {
  637. $user = User::singleUser();
  638. return $user->nickname;
  639. } catch (Exception $e) {
  640. if (common_config('singleuser', 'enabled') && common_config('singleuser', 'nickname')) {
  641. 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.");
  642. return common_config('singleuser', 'nickname');
  643. }
  644. throw $e;
  645. }
  646. }
  647. /**
  648. * Find and shorten links in the given text using this user's URL shortening
  649. * settings.
  650. *
  651. * By default, links will be left untouched if the text is shorter than the
  652. * configured maximum notice length. Pass true for the $always parameter
  653. * to force all links to be shortened regardless.
  654. *
  655. * Side effects: may save file and file_redirection records for referenced URLs.
  656. *
  657. * @param string $text
  658. * @param boolean $always
  659. * @return string
  660. */
  661. public function shortenLinks($text, $always=false)
  662. {
  663. return common_shorten_links($text, $always, $this);
  664. }
  665. /*
  666. * Get a list of OAuth client applications that have access to this
  667. * user's account.
  668. */
  669. function getConnectedApps($offset = 0, $limit = null)
  670. {
  671. $qry =
  672. 'SELECT u.* ' .
  673. 'FROM oauth_application_user u, oauth_application a ' .
  674. 'WHERE u.profile_id = %d ' .
  675. 'AND a.id = u.application_id ' .
  676. 'AND u.access_type > 0 ' .
  677. 'ORDER BY u.created DESC ';
  678. if ($offset > 0) {
  679. if (common_config('db','type') == 'pgsql') {
  680. $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
  681. } else {
  682. $qry .= ' LIMIT ' . $offset . ', ' . $limit;
  683. }
  684. }
  685. $apps = new Oauth_application_user();
  686. $cnt = $apps->query(sprintf($qry, $this->id));
  687. return $apps;
  688. }
  689. /**
  690. * Magic function called at serialize() time.
  691. *
  692. * We use this to drop a couple process-specific references
  693. * from DB_DataObject which can cause trouble in future
  694. * processes.
  695. *
  696. * @return array of variable names to include in serialization.
  697. */
  698. function __sleep()
  699. {
  700. $vars = parent::__sleep();
  701. $skip = array('_profile');
  702. return array_diff($vars, $skip);
  703. }
  704. static function recoverPassword($nore)
  705. {
  706. $user = User::getKV('email', common_canonical_email($nore));
  707. if (!$user) {
  708. try {
  709. $user = User::getKV('nickname', common_canonical_nickname($nore));
  710. } catch (NicknameException $e) {
  711. // invalid
  712. }
  713. }
  714. // See if it's an unconfirmed email address
  715. if (!$user) {
  716. // Warning: it may actually be legit to have multiple folks
  717. // who have claimed, but not yet confirmed, the same address.
  718. // We'll only send to the first one that comes up.
  719. $confirm_email = new Confirm_address();
  720. $confirm_email->address = common_canonical_email($nore);
  721. $confirm_email->address_type = 'email';
  722. $confirm_email->find();
  723. if ($confirm_email->fetch()) {
  724. $user = User::getKV($confirm_email->user_id);
  725. } else {
  726. $confirm_email = null;
  727. }
  728. } else {
  729. $confirm_email = null;
  730. }
  731. if (!$user) {
  732. // TRANS: Information on password recovery form if no known username or e-mail address was specified.
  733. throw new ClientException(_('No user with that email address or username.'));
  734. return;
  735. }
  736. // Try to get an unconfirmed email address if they used a user name
  737. if (!$user->email && !$confirm_email) {
  738. $confirm_email = new Confirm_address();
  739. $confirm_email->user_id = $user->id;
  740. $confirm_email->address_type = 'email';
  741. $confirm_email->find();
  742. if (!$confirm_email->fetch()) {
  743. $confirm_email = null;
  744. }
  745. }
  746. if (!$user->email && !$confirm_email) {
  747. // TRANS: Client error displayed on password recovery form if a user does not have a registered e-mail address.
  748. throw new ClientException(_('No registered email address for that user.'));
  749. return;
  750. }
  751. // Success! We have a valid user and a confirmed or unconfirmed email address
  752. $confirm = new Confirm_address();
  753. $confirm->code = common_confirmation_code(128);
  754. $confirm->address_type = 'recover';
  755. $confirm->user_id = $user->id;
  756. $confirm->address = (!empty($user->email)) ? $user->email : $confirm_email->address;
  757. if (!$confirm->insert()) {
  758. common_log_db_error($confirm, 'INSERT', __FILE__);
  759. // TRANS: Server error displayed if e-mail address confirmation fails in the database on the password recovery form.
  760. throw new ServerException(_('Error saving address confirmation.'));
  761. return;
  762. }
  763. // @todo FIXME: needs i18n.
  764. $body = "Hey, $user->nickname.";
  765. $body .= "\n\n";
  766. $body .= 'Someone just asked for a new password ' .
  767. 'for this account on ' . common_config('site', 'name') . '.';
  768. $body .= "\n\n";
  769. $body .= 'If it was you, and you want to confirm, use the URL below:';
  770. $body .= "\n\n";
  771. $body .= "\t".common_local_url('recoverpassword',
  772. array('code' => $confirm->code));
  773. $body .= "\n\n";
  774. $body .= 'If not, just ignore this message.';
  775. $body .= "\n\n";
  776. $body .= 'Thanks for your time, ';
  777. $body .= "\n";
  778. $body .= common_config('site', 'name');
  779. $body .= "\n";
  780. $headers = _mail_prepare_headers('recoverpassword', $user->nickname, $user->nickname);
  781. // TRANS: Subject for password recovery e-mail.
  782. mail_to_user($user, _('Password recovery requested'), $body, $headers, $confirm->address);
  783. }
  784. function streamModeOnly()
  785. {
  786. if (common_config('oldschool', 'enabled')) {
  787. $osp = Old_school_prefs::getKV('user_id', $this->id);
  788. if (!empty($osp)) {
  789. return $osp->stream_mode_only;
  790. }
  791. }
  792. return false;
  793. }
  794. function streamNicknames()
  795. {
  796. if (common_config('oldschool', 'enabled')) {
  797. $osp = Old_school_prefs::getKV('user_id', $this->id);
  798. if (!empty($osp)) {
  799. return $osp->stream_nicknames;
  800. }
  801. }
  802. return false;
  803. }
  804. function registrationActivity()
  805. {
  806. $profile = $this->getProfile();
  807. $service = new ActivityObject();
  808. $service->type = ActivityObject::SERVICE;
  809. $service->title = common_config('site', 'name');
  810. $service->link = common_root_url();
  811. $service->id = $service->link;
  812. $act = new Activity();
  813. $act->actor = $profile->asActivityObject();
  814. $act->verb = ActivityVerb::JOIN;
  815. $act->objects[] = $service;
  816. $act->id = TagURI::mint('user:register:%d',
  817. $this->id);
  818. $act->time = strtotime($this->created);
  819. $act->title = _("Register");
  820. $act->content = sprintf(_('%1$s joined %2$s.'),
  821. $profile->getBestName(),
  822. $service->title);
  823. return $act;
  824. }
  825. public function delPref($namespace, $topic)
  826. {
  827. return $this->getProfile()->delPref($namespace, $topic);
  828. }
  829. public function getPref($namespace, $topic, $default=null)
  830. {
  831. return $this->getProfile()->getPref($namespace, $topic, $default);
  832. }
  833. public function getConfigPref($namespace, $topic)
  834. {
  835. return $this->getProfile()->getConfigPref($namespace, $topic);
  836. }
  837. public function setPref($namespace, $topic, $data)
  838. {
  839. return $this->getProfile()->setPref($namespace, $topic, $data);
  840. }
  841. }