3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008, 2009, StatusNet, Inc.
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.
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.
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/>.
20 if (!defined('GNUSOCIAL')) { exit(1); }
23 * Table Definition for user
26 class User extends Managed_DataObject
28 const SUBSCRIBE_POLICY_OPEN = 0;
29 const SUBSCRIBE_POLICY_MODERATE = 1;
32 /* the code below is auto generated do not remove the above tag */
34 public $__table = 'user'; // table name
35 public $id; // int(4) primary_key not_null
36 public $nickname; // varchar(64) unique_key
37 public $password; // varchar(191) not 255 because utf8mb4 takes more space
38 public $email; // varchar(191) unique_key not 255 because utf8mb4 takes more space
39 public $incomingemail; // varchar(191) unique_key not 255 because utf8mb4 takes more space
40 public $emailnotifysub; // tinyint(1) default_1
41 public $emailnotifyfav; // tinyint(1) default_1
42 public $emailnotifynudge; // tinyint(1) default_1
43 public $emailnotifymsg; // tinyint(1) default_1
44 public $emailnotifyattn; // tinyint(1) default_1
45 public $language; // varchar(50)
46 public $timezone; // varchar(50)
47 public $emailpost; // tinyint(1) default_1
48 public $sms; // varchar(64) unique_key
49 public $carrier; // int(4)
50 public $smsnotify; // tinyint(1)
51 public $smsreplies; // tinyint(1)
52 public $smsemail; // varchar(191) not 255 because utf8mb4 takes more space
53 public $uri; // varchar(191) unique_key not 255 because utf8mb4 takes more space
54 public $autosubscribe; // tinyint(1)
55 public $subscribe_policy; // tinyint(1)
56 public $urlshorteningservice; // varchar(50) default_ur1.ca
57 public $private_stream; // tinyint(1) default_0
58 public $created; // datetime() not_null
59 public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
61 /* the code above is auto generated do not remove the tag below */
64 public static function schemaDef()
67 'description' => 'local users',
69 'id' => array('type' => 'int', 'not null' => true, 'description' => 'foreign key to profile table'),
70 'nickname' => array('type' => 'varchar', 'length' => 64, 'description' => 'nickname or username, duped in profile'),
71 'password' => array('type' => 'varchar', 'length' => 191, 'description' => 'salted password, can be null for OpenID users'),
72 'email' => array('type' => 'varchar', 'length' => 191, 'description' => 'email address for password recovery etc.'),
73 'incomingemail' => array('type' => 'varchar', 'length' => 191, 'description' => 'email address for post-by-email'),
74 'emailnotifysub' => array('type' => 'int', 'size' => 'tiny', 'default' => 1, 'description' => 'Notify by email of subscriptions'),
75 'emailnotifyfav' => array('type' => 'int', 'size' => 'tiny', 'default' => null, 'description' => 'Notify by email of favorites'),
76 'emailnotifynudge' => array('type' => 'int', 'size' => 'tiny', 'default' => 1, 'description' => 'Notify by email of nudges'),
77 'emailnotifymsg' => array('type' => 'int', 'size' => 'tiny', 'default' => 1, 'description' => 'Notify by email of direct messages'),
78 'emailnotifyattn' => array('type' => 'int', 'size' => 'tiny', 'default' => 1, 'description' => 'Notify by email of @-replies'),
79 'language' => array('type' => 'varchar', 'length' => 50, 'description' => 'preferred language'),
80 'timezone' => array('type' => 'varchar', 'length' => 50, 'description' => 'timezone'),
81 'emailpost' => array('type' => 'int', 'size' => 'tiny', 'default' => 1, 'description' => 'Post by email'),
82 'sms' => array('type' => 'varchar', 'length' => 64, 'description' => 'sms phone number'),
83 'carrier' => array('type' => 'int', 'description' => 'foreign key to sms_carrier'),
84 'smsnotify' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'whether to send notices to SMS'),
85 'smsreplies' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'whether to send notices to SMS on replies'),
86 'smsemail' => array('type' => 'varchar', 'length' => 191, 'description' => 'built from sms and carrier'),
87 'uri' => array('type' => 'varchar', 'length' => 191, 'description' => 'universally unique identifier, usually a tag URI'),
88 'autosubscribe' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'automatically subscribe to users who subscribe to us'),
89 'subscribe_policy' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => '0 = anybody can subscribe; 1 = require approval'),
90 'urlshorteningservice' => array('type' => 'varchar', 'length' => 50, 'default' => 'internal', 'description' => 'service to use for auto-shortening URLs'),
91 'private_stream' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'whether to limit all notices to followers only'),
93 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
94 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
96 'primary key' => array('id'),
97 'unique keys' => array(
98 'user_nickname_key' => array('nickname'),
99 'user_email_key' => array('email'),
100 'user_incomingemail_key' => array('incomingemail'),
101 'user_sms_key' => array('sms'),
102 'user_uri_key' => array('uri'),
104 'foreign keys' => array(
105 'user_id_fkey' => array('profile', array('id' => 'id')),
106 'user_carrier_fkey' => array('sms_carrier', array('carrier' => 'id')),
109 'user_smsemail_idx' => array('smsemail'),
114 protected $_profile = array();
119 * @throws UserNoProfileException if user has no profile
121 public function getProfile()
123 if (!isset($this->_profile[$this->id])) {
124 $profile = Profile::getKV('id', $this->id);
125 if (!$profile instanceof Profile) {
126 throw new UserNoProfileException($this);
128 $this->_profile[$this->id] = $profile;
130 return $this->_profile[$this->id];
133 public function sameAs(Profile $other)
135 return $this->getProfile()->sameAs($other);
138 public function getUri()
143 public function getNickname()
145 return $this->getProfile()->getNickname();
148 static function getByNickname($nickname)
150 $user = User::getKV('nickname', $nickname);
151 if (!$user instanceof User) {
152 throw new NoSuchUserException(array('nickname' => $nickname));
158 function isSubscribed(Profile $other)
160 return $this->getProfile()->isSubscribed($other);
163 function hasPendingSubscription(Profile $other)
165 return $this->getProfile()->hasPendingSubscription($other);
169 * Get the most recent notice posted by this user, if any.
171 * @return mixed Notice or null
173 function getCurrentNotice()
175 return $this->getProfile()->getCurrentNotice();
178 function getCarrier()
180 return Sms_carrier::getKV('id', $this->carrier);
183 function hasBlocked($other)
185 return $this->getProfile()->hasBlocked($other);
189 * Register a new user account and profile and set up default subscriptions.
190 * If a new-user welcome message is configured, this will be sent.
192 * @param array $fields associative array of optional properties
195 * bool 'email_confirmed' pass true to mark email as pre-confirmed
198 * string 'location' informal string description of geolocation
199 * float 'lat' decimal latitude for geolocation
200 * float 'lon' decimal longitude for geolocation
201 * int 'location_id' geoname identifier
202 * int 'location_ns' geoname namespace to interpret location_id
203 * string 'nickname' REQUIRED
204 * string 'password' (may be missing for eg OpenID registrations)
205 * string 'code' invite code
206 * ?string 'uri' permalink to notice; defaults to local notice URL
207 * @return User object
208 * @throws Exception on failure
210 static function register(array $fields) {
212 // MAGICALLY put fields into current scope
216 $profile = new Profile();
218 if (!empty($email)) {
219 $email = common_canonical_email($email);
222 // Normalize _and_ check whether it is in use. Throw NicknameException on failure.
223 $profile->nickname = Nickname::normalize($nickname, true);
225 $profile->profileurl = common_profile_url($profile->nickname);
227 if (!empty($fullname)) {
228 $profile->fullname = $fullname;
230 if (!empty($homepage)) {
231 $profile->homepage = $homepage;
234 $profile->bio = $bio;
236 if (!empty($location)) {
237 $profile->location = $location;
239 $loc = Location::fromName($location);
242 $profile->lat = $loc->lat;
243 $profile->lon = $loc->lon;
244 $profile->location_id = $loc->location_id;
245 $profile->location_ns = $loc->location_ns;
249 $profile->created = common_sql_now();
253 $user->nickname = $profile->nickname;
257 // Users who respond to invite email have proven their ownership of that address
260 $invite = Invitation::getKV($code);
261 if ($invite instanceof Invitation && $invite->address && $invite->address_type == 'email' && $invite->address == $email) {
262 $user->email = $invite->address;
266 if(isset($email_confirmed) && $email_confirmed) {
267 $user->email = $email;
270 // Set default-on options here, otherwise they'll be disabled
271 // initially for sites using caching, since the initial encache
272 // doesn't know about the defaults in the database.
273 $user->emailnotifysub = 1;
274 $user->emailnotifynudge = 1;
275 $user->emailnotifymsg = 1;
276 $user->emailnotifyattn = 1;
277 $user->emailpost = 1;
279 $user->created = common_sql_now();
281 if (Event::handle('StartUserRegister', array($profile))) {
283 $profile->query('BEGIN');
285 $id = $profile->insert();
287 common_log_db_error($profile, 'INSERT', __FILE__);
288 $profile->query('ROLLBACK');
289 // TRANS: Profile data could not be inserted for some reason.
290 throw new ServerException(_m('Could not insert profile data for new user.'));
298 $user->uri = common_user_uri($user);
301 if (!empty($password)) { // may not have a password for OpenID users
302 $user->password = common_munge_password($password);
305 $result = $user->insert();
307 if ($result === false) {
308 common_log_db_error($user, 'INSERT', __FILE__);
309 $profile->query('ROLLBACK');
310 // TRANS: User data could not be inserted for some reason.
311 throw new ServerException(_m('Could not insert user data for new user.'));
314 // Everyone is subscribed to themself
316 $subscription = new Subscription();
317 $subscription->subscriber = $user->id;
318 $subscription->subscribed = $user->id;
319 $subscription->created = $user->created;
321 $result = $subscription->insert();
324 common_log_db_error($subscription, 'INSERT', __FILE__);
325 $profile->query('ROLLBACK');
326 // TRANS: Subscription data could not be inserted for some reason.
327 throw new ServerException(_m('Could not insert subscription data for new user.'));
330 // Mark that this invite was converted
332 if (!empty($invite)) {
333 $invite->convert($user);
336 if (!empty($email) && !$user->email) {
338 $confirm = new Confirm_address();
339 $confirm->code = common_confirmation_code(128);
340 $confirm->user_id = $user->id;
341 $confirm->address = $email;
342 $confirm->address_type = 'email';
344 $result = $confirm->insert();
347 common_log_db_error($confirm, 'INSERT', __FILE__);
348 $profile->query('ROLLBACK');
349 // TRANS: Email confirmation data could not be inserted for some reason.
350 throw new ServerException(_m('Could not insert email confirmation data for new user.'));
354 if (!empty($code) && $user->email) {
355 $user->emailChanged();
358 // Default system subscription
360 $defnick = common_config('newuser', 'default');
362 if (!empty($defnick)) {
363 $defuser = User::getKV('nickname', $defnick);
364 if (empty($defuser)) {
365 common_log(LOG_WARNING, sprintf("Default user %s does not exist.", $defnick),
368 Subscription::ensureStart($profile, $defuser->getProfile());
372 $profile->query('COMMIT');
374 if (!empty($email) && !$user->email) {
375 mail_confirm_address($user, $confirm->code, $profile->nickname, $email);
380 $welcome = common_config('newuser', 'welcome');
382 if (!empty($welcome)) {
383 $welcomeuser = User::getKV('nickname', $welcome);
384 if (empty($welcomeuser)) {
385 common_log(LOG_WARNING, sprintf("Welcome user %s does not exist.", $defnick),
388 $notice = Notice::saveNew($welcomeuser->id,
389 // TRANS: Notice given on user registration.
390 // TRANS: %1$s is the sitename, $2$s is the registering user's nickname.
391 sprintf(_('Welcome to %1$s, @%2$s!'),
392 common_config('site', 'name'),
398 Event::handle('EndUserRegister', array($profile));
401 if (!$user instanceof User) {
402 throw new ServerException('User could not be registered. Probably an event hook that failed.');
408 // Things we do when the email changes
409 function emailChanged()
412 $invites = new Invitation();
413 $invites->address = $this->email;
414 $invites->address_type = 'email';
416 if ($invites->find()) {
417 while ($invites->fetch()) {
419 $other = Profile::getKV('id', $invites->user_id);
420 if (!($other instanceof Profile)) { // remove when getKV throws exceptions
423 Subscription::start($other, $this->getProfile());
424 } catch (Exception $e) {
431 function mutuallySubscribed(Profile $other)
433 return $this->getProfile()->mutuallySubscribed($other);
436 function mutuallySubscribedUsers()
438 // 3-way join; probably should get cached
439 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
440 $qry = "SELECT $UT.* " .
441 "FROM subscription sub1 JOIN $UT ON sub1.subscribed = $UT.id " .
442 "JOIN subscription sub2 ON $UT.id = sub2.subscriber " .
443 'WHERE sub1.subscriber = %d and sub2.subscribed = %d ' .
444 "ORDER BY $UT.nickname";
446 $user->query(sprintf($qry, $this->id, $this->id));
451 function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
453 return $this->getProfile()->getReplies($offset, $limit, $since_id, $before_id);
456 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0) {
457 return $this->getProfile()->getTaggedNotices($tag, $offset, $limit, $since_id, $before_id);
460 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
462 return $this->getProfile()->getNotices($offset, $limit, $since_id, $before_id);
465 function block(Profile $other)
467 // Add a new block record
469 // no blocking (and thus unsubbing from) yourself
471 if ($this->id == $other->id) {
472 common_log(LOG_WARNING,
474 "Profile ID %d (%s) tried to block themself.",
482 $block = new Profile_block();
484 // Begin a transaction
486 $block->query('BEGIN');
488 $block->blocker = $this->id;
489 $block->blocked = $other->id;
491 $result = $block->insert();
494 common_log_db_error($block, 'INSERT', __FILE__);
498 $self = $this->getProfile();
499 if (Subscription::exists($other, $self)) {
500 Subscription::cancel($other, $self);
502 if (Subscription::exists($self, $other)) {
503 Subscription::cancel($self, $other);
506 $block->query('COMMIT');
511 function unblock(Profile $other)
513 // Get the block record
515 $block = Profile_block::exists($this->getProfile(), $other);
521 $result = $block->delete();
524 common_log_db_error($block, 'DELETE', __FILE__);
531 function isMember(User_group $group)
533 return $this->getProfile()->isMember($group);
536 function isAdmin(User_group $group)
538 return $this->getProfile()->isAdmin($group);
541 function getGroups($offset=0, $limit=null)
543 return $this->getProfile()->getGroups($offset, $limit);
547 * Request to join the given group.
548 * May throw exceptions on failure.
550 * @param User_group $group
551 * @return Group_member
553 function joinGroup(User_group $group)
555 return $this->getProfile()->joinGroup($group);
559 * Leave a group that this user is a member of.
561 * @param User_group $group
563 function leaveGroup(User_group $group)
565 return $this->getProfile()->leaveGroup($group);
568 function getSubscribed($offset=0, $limit=null)
570 return $this->getProfile()->getSubscribed($offset, $limit);
573 function getSubscribers($offset=0, $limit=null)
575 return $this->getProfile()->getSubscribers($offset, $limit);
578 function getTaggedSubscribers($tag, $offset=0, $limit=null)
580 return $this->getProfile()->getTaggedSubscribers($tag, $offset, $limit);
583 function getTaggedSubscriptions($tag, $offset=0, $limit=null)
585 return $this->getProfile()->getTaggedSubscriptions($tag, $offset, $limit);
588 function hasRight($right)
590 return $this->getProfile()->hasRight($right);
593 function delete($useWhere=false)
595 if (empty($this->id)) {
596 common_log(LOG_WARNING, "Ambiguous User->delete(); skipping related tables.");
597 return parent::delete($useWhere);
601 if (!$this->hasRole(Profile_role::DELETED)) {
602 $profile = $this->getProfile();
605 } catch (UserNoProfileException $unp) {
606 common_log(LOG_INFO, "User {$this->nickname} has no profile; continuing deletion.");
616 Event::handle('UserDeleteRelated', array($this, &$related));
618 foreach ($related as $cls) {
620 $inst->user_id = $this->id;
624 $this->_deleteTags();
625 $this->_deleteBlocks();
627 return parent::delete($useWhere);
630 function _deleteTags()
632 $tag = new Profile_tag();
633 $tag->tagger = $this->id;
637 function _deleteBlocks()
639 $block = new Profile_block();
640 $block->blocker = $this->id;
642 // XXX delete group block? Reset blocker?
645 function hasRole($name)
647 return $this->getProfile()->hasRole($name);
650 function grantRole($name)
652 return $this->getProfile()->grantRole($name);
655 function revokeRole($name)
657 return $this->getProfile()->revokeRole($name);
660 function isSandboxed()
662 return $this->getProfile()->isSandboxed();
665 function isSilenced()
667 return $this->getProfile()->isSilenced();
670 function receivesEmailNotifications()
672 // We could do this in one large if statement, but that's not as easy to read
673 // Don't send notifications if we don't know the user's email address or it is
674 // explicitly undesired by the user's own settings.
675 if (empty($this->email) || !$this->emailnotifyattn) {
678 // Don't send notifications to a user who is sandboxed or silenced
679 if ($this->isSandboxed() || $this->isSilenced()) {
685 function repeatedByMe($offset=0, $limit=20, $since_id=null, $max_id=null)
687 $stream = new RepeatedByMeNoticeStream($this);
688 return $stream->getNotices($offset, $limit, $since_id, $max_id);
692 function repeatsOfMe($offset=0, $limit=20, $since_id=null, $max_id=null)
694 $stream = new RepeatsOfMeNoticeStream($this);
696 return $stream->getNotices($offset, $limit, $since_id, $max_id);
699 public function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
701 return $this->getProfile()->repeatedToMe($offset, $limit, $since_id, $max_id);
704 public static function siteOwner()
706 $owner = self::cacheGet('user:site_owner');
708 if ($owner === false) { // cache miss
710 $pr = new Profile_role();
711 $pr->role = Profile_role::OWNER;
712 $pr->orderBy('created');
715 if (!$pr->find(true)) {
716 throw new NoResultException($pr);
719 $owner = User::getKV('id', $pr->profile_id);
721 self::cacheSet('user:site_owner', $owner);
724 if ($owner instanceof User) {
728 throw new ServerException(_('No site owner configured.'));
732 * Pull the primary site account to use in single-user mode.
733 * If a valid user nickname is listed in 'singleuser':'nickname'
734 * in the config, this will be used; otherwise the site owner
735 * account is taken by default.
738 * @throws ServerException if no valid single user account is present
739 * @throws ServerException if called when not in single-user mode
741 public static function singleUser()
743 if (!common_config('singleuser', 'enabled')) {
744 // TRANS: Server exception.
745 throw new ServerException(_('Single-user mode code called when not enabled.'));
748 if ($nickname = common_config('singleuser', 'nickname')) {
749 $user = User::getKV('nickname', $nickname);
750 if ($user instanceof User) {
755 // If there was no nickname or no user by that nickname,
756 // try the site owner. Throws exception if not configured.
757 return User::siteOwner();
761 * This is kind of a hack for using external setup code that's trying to
762 * build single-user sites.
764 * Will still return a username if the config singleuser/nickname is set
765 * even if the account doesn't exist, which normally indicates that the
766 * site is horribly misconfigured.
768 * At the moment, we need to let it through so that router setup can
769 * complete, otherwise we won't be able to create the account.
771 * This will be easier when we can more easily create the account and
772 * *then* switch the site to 1user mode without jumping through hoops.
775 * @throws ServerException if no valid single user account is present
776 * @throws ServerException if called when not in single-user mode
778 static function singleUserNickname()
781 $user = User::singleUser();
782 return $user->nickname;
783 } catch (Exception $e) {
784 if (common_config('singleuser', 'enabled') && common_config('singleuser', 'nickname')) {
785 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.");
786 return common_config('singleuser', 'nickname');
793 * Find and shorten links in the given text using this user's URL shortening
796 * By default, links will be left untouched if the text is shorter than the
797 * configured maximum notice length. Pass true for the $always parameter
798 * to force all links to be shortened regardless.
800 * Side effects: may save file and file_redirection records for referenced URLs.
802 * @param string $text
803 * @param boolean $always
806 public function shortenLinks($text, $always=false)
808 return common_shorten_links($text, $always, $this);
812 * Get a list of OAuth client applications that have access to this
815 function getConnectedApps($offset = 0, $limit = null)
819 'FROM oauth_application_user u, oauth_application a ' .
820 'WHERE u.profile_id = %d ' .
821 'AND a.id = u.application_id ' .
822 'AND u.access_type > 0 ' .
823 'ORDER BY u.created DESC ';
826 if (common_config('db','type') == 'pgsql') {
827 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
829 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
833 $apps = new Oauth_application_user();
835 $cnt = $apps->query(sprintf($qry, $this->id));
841 * Magic function called at serialize() time.
843 * We use this to drop a couple process-specific references
844 * from DB_DataObject which can cause trouble in future
847 * @return array of variable names to include in serialization.
852 $vars = parent::__sleep();
853 $skip = array('_profile');
854 return array_diff($vars, $skip);
857 static function recoverPassword($nore)
859 // $confirm_email will be used as a fallback if our user doesn't have a confirmed email
860 $confirm_email = null;
862 if (common_is_email($nore)) {
863 $user = User::getKV('email', common_canonical_email($nore));
865 // See if it's an unconfirmed email address
866 if (!$user instanceof User) {
867 // Warning: it may actually be legit to have multiple folks
868 // who have claimed, but not yet confirmed, the same address.
869 // We'll only send to the first one that comes up.
870 $confirm_email = new Confirm_address();
871 $confirm_email->address = common_canonical_email($nore);
872 $confirm_email->address_type = 'email';
873 if ($confirm_email->find(true)) {
874 $user = User::getKV('id', $confirm_email->user_id);
878 // No luck finding anyone by that email address.
879 if (!$user instanceof User) {
880 if (common_config('site', 'fakeaddressrecovery')) {
881 // Return without actually doing anything! We fake address recovery
882 // to avoid revealing which email addresses are registered with the site.
885 // TRANS: Information on password recovery form if no known e-mail address was specified.
886 throw new ClientException(_('No user with that email address exists here.'));
889 // This might throw a NicknameException on bad nicknames
890 $user = User::getKV('nickname', common_canonical_nickname($nore));
891 if (!$user instanceof User) {
892 // TRANS: Information on password recovery form if no known username was specified.
893 throw new ClientException(_('No user with that nickname exists here.'));
897 // Try to get an unconfirmed email address if they used a user name
898 if (empty($user->email) && $confirm_email === null) {
899 $confirm_email = new Confirm_address();
900 $confirm_email->user_id = $user->id;
901 $confirm_email->address_type = 'email';
902 $confirm_email->find();
903 if (!$confirm_email->fetch()) {
904 // Nothing found, so let's reset it to null
905 $confirm_email = null;
909 if (empty($user->email) && !$confirm_email instanceof Confirm_address) {
910 // TRANS: Client error displayed on password recovery form if a user does not have a registered e-mail address.
911 throw new ClientException(_('No registered email address for that user.'));
914 // Success! We have a valid user and a confirmed or unconfirmed email address
916 $confirm = new Confirm_address();
917 $confirm->code = common_confirmation_code(128);
918 $confirm->address_type = 'recover';
919 $confirm->user_id = $user->id;
920 $confirm->address = $user->email ?: $confirm_email->address;
922 if (!$confirm->insert()) {
923 common_log_db_error($confirm, 'INSERT', __FILE__);
924 // TRANS: Server error displayed if e-mail address confirmation fails in the database on the password recovery form.
925 throw new ServerException(_('Error saving address confirmation.'));
928 // @todo FIXME: needs i18n.
929 $body = "Hey, $user->nickname.";
931 $body .= 'Someone just asked for a new password ' .
932 'for this account on ' . common_config('site', 'name') . '.';
934 $body .= 'If it was you, and you want to confirm, use the URL below:';
936 $body .= "\t".common_local_url('recoverpassword',
937 array('code' => $confirm->code));
939 $body .= 'If not, just ignore this message.';
941 $body .= 'Thanks for your time, ';
943 $body .= common_config('site', 'name');
946 $headers = _mail_prepare_headers('recoverpassword', $user->nickname, $user->nickname);
947 // TRANS: Subject for password recovery e-mail.
948 mail_to_user($user, _('Password recovery requested'), $body, $headers, $confirm->address);
951 function streamModeOnly()
953 if (common_config('oldschool', 'enabled')) {
954 $osp = Old_school_prefs::getKV('user_id', $this->id);
956 return $osp->stream_mode_only;
963 function streamNicknames()
965 if (common_config('oldschool', 'enabled')) {
966 $osp = Old_school_prefs::getKV('user_id', $this->id);
968 return $osp->stream_nicknames;
974 function registrationActivity()
976 $profile = $this->getProfile();
978 $service = new ActivityObject();
980 $service->type = ActivityObject::SERVICE;
981 $service->title = common_config('site', 'name');
982 $service->link = common_root_url();
983 $service->id = $service->link;
985 $act = new Activity();
987 $act->actor = $profile->asActivityObject();
988 $act->verb = ActivityVerb::JOIN;
990 $act->objects[] = $service;
992 $act->id = TagURI::mint('user:register:%d',
995 $act->time = strtotime($this->created);
997 $act->title = _("Register");
999 $act->content = sprintf(_('%1$s joined %2$s.'),
1000 $profile->getBestName(),
1005 public function isPrivateStream()
1007 return $this->getProfile()->isPrivateStream();
1010 public function hasPassword()
1012 return !empty($this->password);
1015 public function setPassword($password)
1017 $orig = clone($this);
1018 $this->password = common_munge_password($password, $this->getProfile());
1020 if (!$this->update($orig)) {
1021 throw new ServerException("Error updating user '{$nickname}'.");
1025 public function delPref($namespace, $topic)
1027 return $this->getProfile()->delPref($namespace, $topic);
1030 public function getPref($namespace, $topic, $default=null)
1032 return $this->getProfile()->getPref($namespace, $topic, $default);
1035 public function getConfigPref($namespace, $topic)
1037 return $this->getProfile()->getConfigPref($namespace, $topic);
1040 public function setPref($namespace, $topic, $data)
1042 return $this->getProfile()->setPref($namespace, $topic, $data);