User.php 38 KB

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