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('STATUSNET') && !defined('LACONICA')) {
25 * Table Definition for user
28 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
29 require_once 'Validate.php';
31 class User extends Managed_DataObject
33 const SUBSCRIBE_POLICY_OPEN = 0;
34 const SUBSCRIBE_POLICY_MODERATE = 1;
37 /* the code below is auto generated do not remove the above tag */
39 public $__table = 'user'; // table name
40 public $id; // int(4) primary_key not_null
41 public $nickname; // varchar(64) unique_key
42 public $password; // varchar(255)
43 public $email; // varchar(255) unique_key
44 public $incomingemail; // varchar(255) unique_key
45 public $emailnotifysub; // tinyint(1) default_1
46 public $emailnotifyfav; // tinyint(1) default_1
47 public $emailnotifynudge; // tinyint(1) default_1
48 public $emailnotifymsg; // tinyint(1) default_1
49 public $emailnotifyattn; // tinyint(1) default_1
50 public $emailmicroid; // tinyint(1) default_1
51 public $language; // varchar(50)
52 public $timezone; // varchar(50)
53 public $emailpost; // tinyint(1) default_1
54 public $sms; // varchar(64) unique_key
55 public $carrier; // int(4)
56 public $smsnotify; // tinyint(1)
57 public $smsreplies; // tinyint(1)
58 public $smsemail; // varchar(255)
59 public $uri; // varchar(255) unique_key
60 public $autosubscribe; // tinyint(1)
61 public $subscribe_policy; // tinyint(1)
62 public $urlshorteningservice; // varchar(50) default_ur1.ca
63 public $inboxed; // tinyint(1)
64 public $private_stream; // tinyint(1) default_0
65 public $created; // datetime() not_null
66 public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
68 /* the code above is auto generated do not remove the tag below */
71 public static function schemaDef()
74 'description' => 'local users',
76 'id' => array('type' => 'int', 'not null' => true, 'description' => 'foreign key to profile table'),
77 'nickname' => array('type' => 'varchar', 'length' => 64, 'description' => 'nickname or username, duped in profile'),
78 'password' => array('type' => 'varchar', 'length' => 255, 'description' => 'salted password, can be null for OpenID users'),
79 'email' => array('type' => 'varchar', 'length' => 255, 'description' => 'email address for password recovery etc.'),
80 'incomingemail' => array('type' => 'varchar', 'length' => 255, 'description' => 'email address for post-by-email'),
81 'emailnotifysub' => array('type' => 'int', 'size' => 'tiny', 'default' => 1, 'description' => 'Notify by email of subscriptions'),
82 'emailnotifyfav' => array('type' => 'int', 'size' => 'tiny', 'default' => 1, 'description' => 'Notify by email of favorites'),
83 'emailnotifynudge' => array('type' => 'int', 'size' => 'tiny', 'default' => 1, 'description' => 'Notify by email of nudges'),
84 'emailnotifymsg' => array('type' => 'int', 'size' => 'tiny', 'default' => 1, 'description' => 'Notify by email of direct messages'),
85 'emailnotifyattn' => array('type' => 'int', 'size' => 'tiny', 'default' => 1, 'description' => 'Notify by email of @-replies'),
86 'emailmicroid' => array('type' => 'int', 'size' => 'tiny', 'default' => 1, 'description' => 'whether to publish email microid'),
87 'language' => array('type' => 'varchar', 'length' => 50, 'description' => 'preferred language'),
88 'timezone' => array('type' => 'varchar', 'length' => 50, 'description' => 'timezone'),
89 'emailpost' => array('type' => 'int', 'size' => 'tiny', 'default' => 1, 'description' => 'Post by email'),
90 'sms' => array('type' => 'varchar', 'length' => 64, 'description' => 'sms phone number'),
91 'carrier' => array('type' => 'int', 'description' => 'foreign key to sms_carrier'),
92 'smsnotify' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'whether to send notices to SMS'),
93 'smsreplies' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'whether to send notices to SMS on replies'),
94 'smsemail' => array('type' => 'varchar', 'length' => 255, 'description' => 'built from sms and carrier'),
95 'uri' => array('type' => 'varchar', 'length' => 255, 'description' => 'universally unique identifier, usually a tag URI'),
96 'autosubscribe' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'automatically subscribe to users who subscribe to us'),
97 'subscribe_policy' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => '0 = anybody can subscribe; 1 = require approval'),
98 'urlshorteningservice' => array('type' => 'varchar', 'length' => 50, 'default' => 'internal', 'description' => 'service to use for auto-shortening URLs'),
99 'inboxed' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'has an inbox been created for this user?'),
100 'private_stream' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'whether to limit all notices to followers only'),
102 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
103 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
105 'primary key' => array('id'),
106 'unique keys' => array(
107 'user_nickname_key' => array('nickname'),
108 'user_email_key' => array('email'),
109 'user_incomingemail_key' => array('incomingemail'),
110 'user_sms_key' => array('sms'),
111 'user_uri_key' => array('uri'),
113 'foreign keys' => array(
114 'user_id_fkey' => array('profile', array('id' => 'id')),
115 'user_carrier_fkey' => array('sms_carrier', array('carrier' => 'id')),
118 'user_smsemail_idx' => array('smsemail'),
123 protected $_profile = null;
128 * @throws UserNoProfileException if user has no profile
130 public function getProfile()
132 if (!($this->_profile instanceof Profile)) {
133 $this->_profile = Profile::getKV('id', $this->id);
134 if (!($this->_profile instanceof Profile)) {
135 throw new UserNoProfileException($this);
139 return $this->_profile;
142 function isSubscribed($other)
144 $profile = $this->getProfile();
145 return $profile->isSubscribed($other);
148 function hasPendingSubscription($other)
150 $profile = $this->getProfile();
151 return $profile->hasPendingSubscription($other);
154 // 'update' won't write key columns, so we have to do it ourselves.
156 function updateKeys(&$orig)
160 foreach (array('nickname', 'email', 'incomingemail', 'sms', 'carrier', 'smsemail', 'language', 'timezone') as $k) {
161 if (strcmp($this->$k, $orig->$k) != 0) {
162 $parts[] = $k . ' = ' . $this->_quote($this->$k);
165 if (count($parts) == 0) {
169 $toupdate = implode(', ', $parts);
171 $table = common_database_tablename($this->tableName());
172 $qry = 'UPDATE ' . $table . ' SET ' . $toupdate .
173 ' WHERE id = ' . $this->id;
175 $result = $this->query($qry);
183 * Check whether the given nickname is potentially usable, or if it's
184 * excluded by any blacklists on this system.
186 * WARNING: INPUT IS NOT VALIDATED OR NORMALIZED. NON-NORMALIZED INPUT
187 * OR INVALID INPUT MAY LEAD TO FALSE RESULTS.
189 * @param string $nickname
190 * @return boolean true if clear, false if blacklisted
192 static function allowed_nickname($nickname)
194 // XXX: should already be validated for size, content, etc.
195 $blacklist = common_config('nickname', 'blacklist');
197 //all directory and file names should be blacklisted
198 $d = dir(INSTALLDIR);
199 while (false !== ($entry = $d->read())) {
204 //all top level names in the router should be blacklisted
205 $router = Router::get();
206 foreach(array_keys($router->m->getPaths()) as $path){
207 if(preg_match('/^\/(.*?)[\/\?]/',$path,$matches)){
208 $blacklist[]=$matches[1];
211 return !in_array($nickname, $blacklist);
215 * Get the most recent notice posted by this user, if any.
217 * @return mixed Notice or null
219 function getCurrentNotice()
221 $profile = $this->getProfile();
222 return $profile->getCurrentNotice();
225 function getCarrier()
227 return Sms_carrier::getKV('id', $this->carrier);
230 function hasBlocked($other)
232 $profile = $this->getProfile();
233 return $profile->hasBlocked($other);
237 * Register a new user account and profile and set up default subscriptions.
238 * If a new-user welcome message is configured, this will be sent.
240 * @param array $fields associative array of optional properties
243 * bool 'email_confirmed' pass true to mark email as pre-confirmed
246 * string 'location' informal string description of geolocation
247 * float 'lat' decimal latitude for geolocation
248 * float 'lon' decimal longitude for geolocation
249 * int 'location_id' geoname identifier
250 * int 'location_ns' geoname namespace to interpret location_id
251 * string 'nickname' REQUIRED
252 * string 'password' (may be missing for eg OpenID registrations)
253 * string 'code' invite code
254 * ?string 'uri' permalink to notice; defaults to local notice URL
255 * @return mixed User object or false on failure
257 static function register(array $fields) {
259 // MAGICALLY put fields into current scope
263 $profile = new Profile();
267 $email = common_canonical_email($email);
270 $nickname = common_canonical_nickname($nickname);
271 $profile->nickname = $nickname;
272 if(! User::allowed_nickname($nickname)){
273 common_log(LOG_WARNING, sprintf("Attempted to register a nickname that is not allowed: %s", $profile->nickname),
277 $profile->profileurl = common_profile_url($nickname);
279 if (!empty($fullname)) {
280 $profile->fullname = $fullname;
282 if (!empty($homepage)) {
283 $profile->homepage = $homepage;
286 $profile->bio = $bio;
288 if (!empty($location)) {
289 $profile->location = $location;
291 $loc = Location::fromName($location);
294 $profile->lat = $loc->lat;
295 $profile->lon = $loc->lon;
296 $profile->location_id = $loc->location_id;
297 $profile->location_ns = $loc->location_ns;
301 $profile->created = common_sql_now();
305 $user->nickname = $nickname;
309 // Users who respond to invite email have proven their ownership of that address
312 $invite = Invitation::getKV($code);
313 if ($invite && $invite->address && $invite->address_type == 'email' && $invite->address == $email) {
314 $user->email = $invite->address;
318 if(isset($email_confirmed) && $email_confirmed) {
319 $user->email = $email;
322 // This flag is ignored but still set to 1
326 // Set default-on options here, otherwise they'll be disabled
327 // initially for sites using caching, since the initial encache
328 // doesn't know about the defaults in the database.
329 $user->emailnotifysub = 1;
330 $user->emailnotifyfav = 1;
331 $user->emailnotifynudge = 1;
332 $user->emailnotifymsg = 1;
333 $user->emailnotifyattn = 1;
334 $user->emailmicroid = 1;
335 $user->emailpost = 1;
336 $user->jabbermicroid = 1;
338 $user->created = common_sql_now();
340 if (Event::handle('StartUserRegister', array($profile))) {
342 $profile->query('BEGIN');
344 $id = $profile->insert();
347 common_log_db_error($profile, 'INSERT', __FILE__);
356 $user->uri = common_user_uri($user);
359 if (!empty($password)) { // may not have a password for OpenID users
360 $user->password = common_munge_password($password, $id);
363 $result = $user->insert();
366 common_log_db_error($user, 'INSERT', __FILE__);
370 // Everyone gets an inbox
372 $inbox = new Inbox();
374 $inbox->user_id = $user->id;
375 $inbox->notice_ids = '';
377 $result = $inbox->insert();
380 common_log_db_error($inbox, 'INSERT', __FILE__);
384 // Everyone is subscribed to themself
386 $subscription = new Subscription();
387 $subscription->subscriber = $user->id;
388 $subscription->subscribed = $user->id;
389 $subscription->created = $user->created;
391 $result = $subscription->insert();
394 common_log_db_error($subscription, 'INSERT', __FILE__);
398 // Mark that this invite was converted
400 if (!empty($invite)) {
401 $invite->convert($user);
404 if (!empty($email) && !$user->email) {
406 $confirm = new Confirm_address();
407 $confirm->code = common_confirmation_code(128);
408 $confirm->user_id = $user->id;
409 $confirm->address = $email;
410 $confirm->address_type = 'email';
412 $result = $confirm->insert();
415 common_log_db_error($confirm, 'INSERT', __FILE__);
420 if (!empty($code) && $user->email) {
421 $user->emailChanged();
424 // Default system subscription
426 $defnick = common_config('newuser', 'default');
428 if (!empty($defnick)) {
429 $defuser = User::getKV('nickname', $defnick);
430 if (empty($defuser)) {
431 common_log(LOG_WARNING, sprintf("Default user %s does not exist.", $defnick),
434 Subscription::start($profile, $defuser->getProfile());
438 $profile->query('COMMIT');
440 if (!empty($email) && !$user->email) {
441 mail_confirm_address($user, $confirm->code, $profile->nickname, $email);
446 $welcome = common_config('newuser', 'welcome');
448 if (!empty($welcome)) {
449 $welcomeuser = User::getKV('nickname', $welcome);
450 if (empty($welcomeuser)) {
451 common_log(LOG_WARNING, sprintf("Welcome user %s does not exist.", $defnick),
454 $notice = Notice::saveNew($welcomeuser->id,
455 // TRANS: Notice given on user registration.
456 // TRANS: %1$s is the sitename, $2$s is the registering user's nickname.
457 sprintf(_('Welcome to %1$s, @%2$s!'),
458 common_config('site', 'name'),
464 Event::handle('EndUserRegister', array($profile));
470 // Things we do when the email changes
471 function emailChanged()
474 $invites = new Invitation();
475 $invites->address = $this->email;
476 $invites->address_type = 'email';
478 if ($invites->find()) {
479 while ($invites->fetch()) {
481 $other = Profile::getKV('id', $invites->user_id);
482 if (!($other instanceof Profile)) { // remove when getKV throws exceptions
485 Subscription::start($other, $this->getProfile());
486 } catch (Exception $e) {
493 function hasFave($notice)
495 $profile = $this->getProfile();
496 return $profile->hasFave($notice);
499 function mutuallySubscribed($other)
501 $profile = $this->getProfile();
502 return $profile->mutuallySubscribed($other);
505 function mutuallySubscribedUsers()
507 // 3-way join; probably should get cached
508 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
509 $qry = "SELECT $UT.* " .
510 "FROM subscription sub1 JOIN $UT ON sub1.subscribed = $UT.id " .
511 "JOIN subscription sub2 ON $UT.id = sub2.subscriber " .
512 'WHERE sub1.subscriber = %d and sub2.subscribed = %d ' .
513 "ORDER BY $UT.nickname";
515 $user->query(sprintf($qry, $this->id, $this->id));
520 function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
522 return Reply::stream($this->id, $offset, $limit, $since_id, $before_id);
525 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0) {
526 $profile = $this->getProfile();
527 return $profile->getTaggedNotices($tag, $offset, $limit, $since_id, $before_id);
530 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
532 $profile = $this->getProfile();
533 return $profile->getNotices($offset, $limit, $since_id, $before_id);
536 function favoriteNotices($own=false, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
538 return Fave::stream($this->id, $offset, $limit, $own, $since_id, $max_id);
541 function noticeInbox($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
543 $stream = new InboxNoticeStream($this);
544 return $stream->getNotices($offset, $limit, $since_id, $before_id);
547 // DEPRECATED, use noticeInbox()
549 function noticesWithFriends($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
551 return $this->noticeInbox($offset, $limit, $since_id, $before_id);
554 // DEPRECATED, use noticeInbox()
556 function noticesWithFriendsThreaded($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
558 return $this->noticeInbox($offset, $limit, $since_id, $before_id);
561 // DEPRECATED, use noticeInbox()
563 function noticeInboxThreaded($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
565 return $this->noticeInbox($offset, $limit, $since_id, $before_id);
568 // DEPRECATED, use noticeInbox()
570 function friendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
572 return $this->noticeInbox($offset, $limit, $since_id, $before_id);
575 // DEPRECATED, use noticeInbox()
577 function ownFriendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
579 $this->noticeInbox($offset, $limit, $since_id, $before_id);
582 function blowFavesCache()
584 $profile = $this->getProfile();
585 $profile->blowFavesCache();
588 function getSelfTags()
590 return Profile_tag::getTagsArray($this->id, $this->id, $this->id);
593 function setSelfTags($newtags, $privacy)
595 return Profile_tag::setTags($this->id, $this->id, $newtags, $privacy);
598 function block(Profile $other)
600 // Add a new block record
602 // no blocking (and thus unsubbing from) yourself
604 if ($this->id == $other->id) {
605 common_log(LOG_WARNING,
607 "Profile ID %d (%s) tried to block themself.",
615 $block = new Profile_block();
617 // Begin a transaction
619 $block->query('BEGIN');
621 $block->blocker = $this->id;
622 $block->blocked = $other->id;
624 $result = $block->insert();
627 common_log_db_error($block, 'INSERT', __FILE__);
631 $self = $this->getProfile();
632 if (Subscription::exists($other, $self)) {
633 Subscription::cancel($other, $self);
635 if (Subscription::exists($self, $other)) {
636 Subscription::cancel($self, $other);
639 $block->query('COMMIT');
644 function unblock(Profile $other)
646 // Get the block record
648 $block = Profile_block::exists($this->getProfile(), $other);
654 $result = $block->delete();
657 common_log_db_error($block, 'DELETE', __FILE__);
664 function isMember($group)
666 $profile = $this->getProfile();
667 return $profile->isMember($group);
670 function isAdmin($group)
672 $profile = $this->getProfile();
673 return $profile->isAdmin($group);
676 function getGroups($offset=0, $limit=null)
678 $profile = $this->getProfile();
679 return $profile->getGroups($offset, $limit);
683 * Request to join the given group.
684 * May throw exceptions on failure.
686 * @param User_group $group
687 * @return Group_member
689 function joinGroup(User_group $group)
691 $profile = $this->getProfile();
692 return $profile->joinGroup($group);
696 * Leave a group that this user is a member of.
698 * @param User_group $group
700 function leaveGroup(User_group $group)
702 $profile = $this->getProfile();
703 return $profile->leaveGroup($group);
706 function getSubscribed($offset=0, $limit=null)
708 $profile = $this->getProfile();
709 return $profile->getSubscribed($offset, $limit);
712 function getSubscribers($offset=0, $limit=null)
714 $profile = $this->getProfile();
715 return $profile->getSubscribers($offset, $limit);
718 function getTaggedSubscribers($tag, $offset=0, $limit=null)
721 'SELECT profile.* ' .
722 'FROM profile JOIN subscription ' .
723 'ON profile.id = subscription.subscriber ' .
724 'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
725 'AND profile_tag.tagger = subscription.subscribed) ' .
726 'WHERE subscription.subscribed = %d ' .
727 "AND profile_tag.tag = '%s' " .
728 'AND subscription.subscribed != subscription.subscriber ' .
729 'ORDER BY subscription.created DESC ';
732 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
735 $profile = new Profile();
737 $cnt = $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
742 function getTaggedSubscriptions($tag, $offset=0, $limit=null)
745 'SELECT profile.* ' .
746 'FROM profile JOIN subscription ' .
747 'ON profile.id = subscription.subscribed ' .
748 'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
749 'AND profile_tag.tagger = subscription.subscriber) ' .
750 'WHERE subscription.subscriber = %d ' .
751 "AND profile_tag.tag = '%s' " .
752 'AND subscription.subscribed != subscription.subscriber ' .
753 'ORDER BY subscription.created DESC ';
755 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
757 $profile = new Profile();
759 $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
764 function hasRight($right)
766 $profile = $this->getProfile();
767 return $profile->hasRight($right);
773 $profile = $this->getProfile();
775 } catch (UserNoProfileException $unp) {
776 common_log(LOG_INFO, "User {$this->nickname} has no profile; continuing deletion.");
779 $related = array('Fave',
786 Event::handle('UserDeleteRelated', array($this, &$related));
788 foreach ($related as $cls) {
790 $inst->user_id = $this->id;
794 $this->_deleteTags();
795 $this->_deleteBlocks();
800 function _deleteTags()
802 $tag = new Profile_tag();
803 $tag->tagger = $this->id;
807 function _deleteBlocks()
809 $block = new Profile_block();
810 $block->blocker = $this->id;
812 // XXX delete group block? Reset blocker?
815 function hasRole($name)
817 $profile = $this->getProfile();
818 return $profile->hasRole($name);
821 function grantRole($name)
823 $profile = $this->getProfile();
824 return $profile->grantRole($name);
827 function revokeRole($name)
829 $profile = $this->getProfile();
830 return $profile->revokeRole($name);
833 function isSandboxed()
835 $profile = $this->getProfile();
836 return $profile->isSandboxed();
839 function isSilenced()
841 $profile = $this->getProfile();
842 return $profile->isSilenced();
845 function repeatedByMe($offset=0, $limit=20, $since_id=null, $max_id=null)
847 $stream = new RepeatedByMeNoticeStream($this);
848 return $stream->getNotices($offset, $limit, $since_id, $max_id);
852 function repeatsOfMe($offset=0, $limit=20, $since_id=null, $max_id=null)
854 $stream = new RepeatsOfMeNoticeStream($this);
856 return $stream->getNotices($offset, $limit, $since_id, $max_id);
860 function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
862 // TRANS: Exception thrown when trying view "repeated to me".
863 throw new Exception(_('Not implemented since inbox change.'));
866 public static function siteOwner()
868 $owner = self::cacheGet('user:site_owner');
870 if ($owner === false) { // cache miss
872 $pr = new Profile_role();
873 $pr->role = Profile_role::OWNER;
874 $pr->orderBy('created');
877 if (!$pr->find(true)) {
878 throw new NoResultException($pr);
881 $owner = User::getKV('id', $pr->profile_id);
883 self::cacheSet('user:site_owner', $owner);
886 if ($owner instanceof User) {
890 throw new ServerException(_('No site owner configured.'));
894 * Pull the primary site account to use in single-user mode.
895 * If a valid user nickname is listed in 'singleuser':'nickname'
896 * in the config, this will be used; otherwise the site owner
897 * account is taken by default.
900 * @throws ServerException if no valid single user account is present
901 * @throws ServerException if called when not in single-user mode
903 public static function singleUser()
905 if (!common_config('singleuser', 'enabled')) {
906 // TRANS: Server exception.
907 throw new ServerException(_('Single-user mode code called when not enabled.'));
910 if ($nickname = common_config('singleuser', 'nickname')) {
911 $user = User::getKV('nickname', $nickname);
912 if ($user instanceof User) {
917 // If there was no nickname or no user by that nickname,
918 // try the site owner. Throws exception if not configured.
919 return User::siteOwner();
923 * This is kind of a hack for using external setup code that's trying to
924 * build single-user sites.
926 * Will still return a username if the config singleuser/nickname is set
927 * even if the account doesn't exist, which normally indicates that the
928 * site is horribly misconfigured.
930 * At the moment, we need to let it through so that router setup can
931 * complete, otherwise we won't be able to create the account.
933 * This will be easier when we can more easily create the account and
934 * *then* switch the site to 1user mode without jumping through hoops.
937 * @throws ServerException if no valid single user account is present
938 * @throws ServerException if called when not in single-user mode
940 static function singleUserNickname()
943 $user = User::singleUser();
944 return $user->nickname;
945 } catch (Exception $e) {
946 if (common_config('singleuser', 'enabled') && common_config('singleuser', 'nickname')) {
947 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.");
948 return common_config('singleuser', 'nickname');
955 * Find and shorten links in the given text using this user's URL shortening
958 * By default, links will be left untouched if the text is shorter than the
959 * configured maximum notice length. Pass true for the $always parameter
960 * to force all links to be shortened regardless.
962 * Side effects: may save file and file_redirection records for referenced URLs.
964 * @param string $text
965 * @param boolean $always
968 public function shortenLinks($text, $always=false)
970 return common_shorten_links($text, $always, $this);
974 * Get a list of OAuth client applications that have access to this
977 function getConnectedApps($offset = 0, $limit = null)
981 'FROM oauth_application_user u, oauth_application a ' .
982 'WHERE u.profile_id = %d ' .
983 'AND a.id = u.application_id ' .
984 'AND u.access_type > 0 ' .
985 'ORDER BY u.created DESC ';
988 if (common_config('db','type') == 'pgsql') {
989 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
991 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
995 $apps = new Oauth_application_user();
997 $cnt = $apps->query(sprintf($qry, $this->id));
1003 * Magic function called at serialize() time.
1005 * We use this to drop a couple process-specific references
1006 * from DB_DataObject which can cause trouble in future
1009 * @return array of variable names to include in serialization.
1014 $vars = parent::__sleep();
1015 $skip = array('_profile');
1016 return array_diff($vars, $skip);
1019 static function recoverPassword($nore)
1021 $user = User::getKV('email', common_canonical_email($nore));
1025 $user = User::getKV('nickname', common_canonical_nickname($nore));
1026 } catch (NicknameException $e) {
1031 // See if it's an unconfirmed email address
1034 // Warning: it may actually be legit to have multiple folks
1035 // who have claimed, but not yet confirmed, the same address.
1036 // We'll only send to the first one that comes up.
1037 $confirm_email = new Confirm_address();
1038 $confirm_email->address = common_canonical_email($nore);
1039 $confirm_email->address_type = 'email';
1040 $confirm_email->find();
1041 if ($confirm_email->fetch()) {
1042 $user = User::getKV($confirm_email->user_id);
1044 $confirm_email = null;
1047 $confirm_email = null;
1051 // TRANS: Information on password recovery form if no known username or e-mail address was specified.
1052 throw new ClientException(_('No user with that email address or username.'));
1056 // Try to get an unconfirmed email address if they used a user name
1058 if (!$user->email && !$confirm_email) {
1059 $confirm_email = new Confirm_address();
1060 $confirm_email->user_id = $user->id;
1061 $confirm_email->address_type = 'email';
1062 $confirm_email->find();
1063 if (!$confirm_email->fetch()) {
1064 $confirm_email = null;
1068 if (!$user->email && !$confirm_email) {
1069 // TRANS: Client error displayed on password recovery form if a user does not have a registered e-mail address.
1070 throw new ClientException(_('No registered email address for that user.'));
1074 // Success! We have a valid user and a confirmed or unconfirmed email address
1076 $confirm = new Confirm_address();
1077 $confirm->code = common_confirmation_code(128);
1078 $confirm->address_type = 'recover';
1079 $confirm->user_id = $user->id;
1080 $confirm->address = (!empty($user->email)) ? $user->email : $confirm_email->address;
1082 if (!$confirm->insert()) {
1083 common_log_db_error($confirm, 'INSERT', __FILE__);
1084 // TRANS: Server error displayed if e-mail address confirmation fails in the database on the password recovery form.
1085 throw new ServerException(_('Error saving address confirmation.'));
1089 // @todo FIXME: needs i18n.
1090 $body = "Hey, $user->nickname.";
1092 $body .= 'Someone just asked for a new password ' .
1093 'for this account on ' . common_config('site', 'name') . '.';
1095 $body .= 'If it was you, and you want to confirm, use the URL below:';
1097 $body .= "\t".common_local_url('recoverpassword',
1098 array('code' => $confirm->code));
1100 $body .= 'If not, just ignore this message.';
1102 $body .= 'Thanks for your time, ';
1104 $body .= common_config('site', 'name');
1107 $headers = _mail_prepare_headers('recoverpassword', $user->nickname, $user->nickname);
1108 // TRANS: Subject for password recovery e-mail.
1109 mail_to_user($user, _('Password recovery requested'), $body, $headers, $confirm->address);
1112 function streamModeOnly()
1114 if (common_config('oldschool', 'enabled')) {
1115 $osp = Old_school_prefs::getKV('user_id', $this->id);
1117 return $osp->stream_mode_only;
1124 function conversationTree()
1126 if (common_config('oldschool', 'enabled')) {
1127 $osp = Old_school_prefs::getKV('user_id', $this->id);
1129 return $osp->conversation_tree;
1136 function streamNicknames()
1138 if (common_config('oldschool', 'enabled')) {
1139 $osp = Old_school_prefs::getKV('user_id', $this->id);
1141 return $osp->stream_nicknames;
1147 function registrationActivity()
1149 $profile = $this->getProfile();
1151 $service = new ActivityObject();
1153 $service->type = ActivityObject::SERVICE;
1154 $service->title = common_config('site', 'name');
1155 $service->link = common_root_url();
1156 $service->id = $service->link;
1158 $act = new Activity();
1160 $act->actor = ActivityObject::fromProfile($profile);
1161 $act->verb = ActivityVerb::JOIN;
1163 $act->objects[] = $service;
1165 $act->id = TagURI::mint('user:register:%d',
1168 $act->time = strtotime($this->created);
1170 $act->title = _("Register");
1172 $act->content = sprintf(_('%1$s joined %2$s.'),
1173 $profile->getBestName(),