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
69 function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('User',$k,$v); }
71 /* the code above is auto generated do not remove the tag below */
74 public static function schemaDef()
77 'description' => 'local users',
79 'id' => array('type' => 'int', 'not null' => true, 'description' => 'foreign key to profile table'),
80 'nickname' => array('type' => 'varchar', 'length' => 64, 'description' => 'nickname or username, duped in profile'),
81 'password' => array('type' => 'varchar', 'length' => 255, 'description' => 'salted password, can be null for OpenID users'),
82 'email' => array('type' => 'varchar', 'length' => 255, 'description' => 'email address for password recovery etc.'),
83 'incomingemail' => array('type' => 'varchar', 'length' => 255, 'description' => 'email address for post-by-email'),
84 'emailnotifysub' => array('type' => 'int', 'size' => 'tiny', 'default' => 1, 'description' => 'Notify by email of subscriptions'),
85 'emailnotifyfav' => array('type' => 'int', 'size' => 'tiny', 'default' => 1, 'description' => 'Notify by email of favorites'),
86 'emailnotifynudge' => array('type' => 'int', 'size' => 'tiny', 'default' => 1, 'description' => 'Notify by email of nudges'),
87 'emailnotifymsg' => array('type' => 'int', 'size' => 'tiny', 'default' => 1, 'description' => 'Notify by email of direct messages'),
88 'emailnotifyattn' => array('type' => 'int', 'size' => 'tiny', 'default' => 1, 'description' => 'Notify by email of @-replies'),
89 'emailmicroid' => array('type' => 'int', 'size' => 'tiny', 'default' => 1, 'description' => 'whether to publish email microid'),
90 'language' => array('type' => 'varchar', 'length' => 50, 'description' => 'preferred language'),
91 'timezone' => array('type' => 'varchar', 'length' => 50, 'description' => 'timezone'),
92 'emailpost' => array('type' => 'int', 'size' => 'tiny', 'default' => 1, 'description' => 'Post by email'),
93 'sms' => array('type' => 'varchar', 'length' => 64, 'description' => 'sms phone number'),
94 'carrier' => array('type' => 'int', 'description' => 'foreign key to sms_carrier'),
95 'smsnotify' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'whether to send notices to SMS'),
96 'smsreplies' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'whether to send notices to SMS on replies'),
97 'smsemail' => array('type' => 'varchar', 'length' => 255, 'description' => 'built from sms and carrier'),
98 'uri' => array('type' => 'varchar', 'length' => 255, 'description' => 'universally unique identifier, usually a tag URI'),
99 'autosubscribe' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'automatically subscribe to users who subscribe to us'),
100 'subscribe_policy' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => '0 = anybody can subscribe; 1 = require approval'),
101 'urlshorteningservice' => array('type' => 'varchar', 'length' => 50, 'default' => 'internal', 'description' => 'service to use for auto-shortening URLs'),
102 'inboxed' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'has an inbox been created for this user?'),
103 'private_stream' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'whether to limit all notices to followers only'),
105 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
106 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
108 'primary key' => array('id'),
109 'unique keys' => array(
110 'user_nickname_key' => array('nickname'),
111 'user_email_key' => array('email'),
112 'user_incomingemail_key' => array('incomingemail'),
113 'user_sms_key' => array('sms'),
114 'user_uri_key' => array('uri'),
116 'foreign keys' => array(
117 'user_id_fkey' => array('profile', array('id' => 'id')),
118 'user_carrier_fkey' => array('sms_carrier', array('carrier' => 'id')),
121 'user_smsemail_idx' => array('smsemail'),
126 protected $_profile = -1;
131 function getProfile()
133 if (is_int($this->_profile) && $this->_profile == -1) { // invalid but distinct from null
134 $this->_profile = Profile::staticGet('id', $this->id);
135 if (empty($this->_profile)) {
136 throw new UserNoProfileException($this);
140 return $this->_profile;
143 function isSubscribed($other)
145 $profile = $this->getProfile();
146 return $profile->isSubscribed($other);
149 function hasPendingSubscription($other)
151 $profile = $this->getProfile();
152 return $profile->hasPendingSubscription($other);
155 // 'update' won't write key columns, so we have to do it ourselves.
157 function updateKeys(&$orig)
161 foreach (array('nickname', 'email', 'incomingemail', 'sms', 'carrier', 'smsemail', 'language', 'timezone') as $k) {
162 if (strcmp($this->$k, $orig->$k) != 0) {
163 $parts[] = $k . ' = ' . $this->_quote($this->$k);
166 if (count($parts) == 0) {
170 $toupdate = implode(', ', $parts);
172 $table = common_database_tablename($this->tableName());
173 $qry = 'UPDATE ' . $table . ' SET ' . $toupdate .
174 ' WHERE id = ' . $this->id;
176 $result = $this->query($qry);
184 * Check whether the given nickname is potentially usable, or if it's
185 * excluded by any blacklists on this system.
187 * WARNING: INPUT IS NOT VALIDATED OR NORMALIZED. NON-NORMALIZED INPUT
188 * OR INVALID INPUT MAY LEAD TO FALSE RESULTS.
190 * @param string $nickname
191 * @return boolean true if clear, false if blacklisted
193 static function allowed_nickname($nickname)
195 // XXX: should already be validated for size, content, etc.
196 $blacklist = common_config('nickname', 'blacklist');
198 //all directory and file names should be blacklisted
199 $d = dir(INSTALLDIR);
200 while (false !== ($entry = $d->read())) {
205 //all top level names in the router should be blacklisted
206 $router = Router::get();
207 foreach(array_keys($router->m->getPaths()) as $path){
208 if(preg_match('/^\/(.*?)[\/\?]/',$path,$matches)){
209 $blacklist[]=$matches[1];
212 return !in_array($nickname, $blacklist);
216 * Get the most recent notice posted by this user, if any.
218 * @return mixed Notice or null
220 function getCurrentNotice()
222 $profile = $this->getProfile();
223 return $profile->getCurrentNotice();
226 function getCarrier()
228 return Sms_carrier::staticGet('id', $this->carrier);
232 * @deprecated use Subscription::start($sub, $other);
234 function subscribeTo($other)
236 return Subscription::start($this->getProfile(), $other);
239 function hasBlocked($other)
241 $profile = $this->getProfile();
242 return $profile->hasBlocked($other);
246 * Register a new user account and profile and set up default subscriptions.
247 * If a new-user welcome message is configured, this will be sent.
249 * @param array $fields associative array of optional properties
252 * bool 'email_confirmed' pass true to mark email as pre-confirmed
255 * string 'location' informal string description of geolocation
256 * float 'lat' decimal latitude for geolocation
257 * float 'lon' decimal longitude for geolocation
258 * int 'location_id' geoname identifier
259 * int 'location_ns' geoname namespace to interpret location_id
260 * string 'nickname' REQUIRED
261 * string 'password' (may be missing for eg OpenID registrations)
262 * string 'code' invite code
263 * ?string 'uri' permalink to notice; defaults to local notice URL
264 * @return mixed User object or false on failure
266 static function register($fields) {
268 // MAGICALLY put fields into current scope
272 $profile = new Profile();
276 $email = common_canonical_email($email);
279 $nickname = common_canonical_nickname($nickname);
280 $profile->nickname = $nickname;
281 if(! User::allowed_nickname($nickname)){
282 common_log(LOG_WARNING, sprintf("Attempted to register a nickname that is not allowed: %s", $profile->nickname),
286 $profile->profileurl = common_profile_url($nickname);
288 if (!empty($fullname)) {
289 $profile->fullname = $fullname;
291 if (!empty($homepage)) {
292 $profile->homepage = $homepage;
295 $profile->bio = $bio;
297 if (!empty($location)) {
298 $profile->location = $location;
300 $loc = Location::fromName($location);
303 $profile->lat = $loc->lat;
304 $profile->lon = $loc->lon;
305 $profile->location_id = $loc->location_id;
306 $profile->location_ns = $loc->location_ns;
310 $profile->created = common_sql_now();
314 $user->nickname = $nickname;
318 // Users who respond to invite email have proven their ownership of that address
321 $invite = Invitation::staticGet($code);
322 if ($invite && $invite->address && $invite->address_type == 'email' && $invite->address == $email) {
323 $user->email = $invite->address;
327 if(isset($email_confirmed) && $email_confirmed) {
328 $user->email = $email;
331 // This flag is ignored but still set to 1
335 // Set default-on options here, otherwise they'll be disabled
336 // initially for sites using caching, since the initial encache
337 // doesn't know about the defaults in the database.
338 $user->emailnotifysub = 1;
339 $user->emailnotifyfav = 1;
340 $user->emailnotifynudge = 1;
341 $user->emailnotifymsg = 1;
342 $user->emailnotifyattn = 1;
343 $user->emailmicroid = 1;
344 $user->emailpost = 1;
345 $user->jabbermicroid = 1;
347 $user->created = common_sql_now();
349 if (Event::handle('StartUserRegister', array(&$user, &$profile))) {
351 $profile->query('BEGIN');
353 $id = $profile->insert();
356 common_log_db_error($profile, 'INSERT', __FILE__);
365 $user->uri = common_user_uri($user);
368 if (!empty($password)) { // may not have a password for OpenID users
369 $user->password = common_munge_password($password, $id);
372 $result = $user->insert();
375 common_log_db_error($user, 'INSERT', __FILE__);
379 // Everyone gets an inbox
381 $inbox = new Inbox();
383 $inbox->user_id = $user->id;
384 $inbox->notice_ids = '';
386 $result = $inbox->insert();
389 common_log_db_error($inbox, 'INSERT', __FILE__);
393 // Everyone is subscribed to themself
395 $subscription = new Subscription();
396 $subscription->subscriber = $user->id;
397 $subscription->subscribed = $user->id;
398 $subscription->created = $user->created;
400 $result = $subscription->insert();
403 common_log_db_error($subscription, 'INSERT', __FILE__);
407 // Mark that this invite was converted
409 if (!empty($invite)) {
410 $invite->convert($user);
413 if (!empty($email) && !$user->email) {
415 $confirm = new Confirm_address();
416 $confirm->code = common_confirmation_code(128);
417 $confirm->user_id = $user->id;
418 $confirm->address = $email;
419 $confirm->address_type = 'email';
421 $result = $confirm->insert();
424 common_log_db_error($confirm, 'INSERT', __FILE__);
429 if (!empty($code) && $user->email) {
430 $user->emailChanged();
433 // Default system subscription
435 $defnick = common_config('newuser', 'default');
437 if (!empty($defnick)) {
438 $defuser = User::staticGet('nickname', $defnick);
439 if (empty($defuser)) {
440 common_log(LOG_WARNING, sprintf("Default user %s does not exist.", $defnick),
443 Subscription::start($user, $defuser);
447 $profile->query('COMMIT');
449 if (!empty($email) && !$user->email) {
450 mail_confirm_address($user, $confirm->code, $profile->nickname, $email);
455 $welcome = common_config('newuser', 'welcome');
457 if (!empty($welcome)) {
458 $welcomeuser = User::staticGet('nickname', $welcome);
459 if (empty($welcomeuser)) {
460 common_log(LOG_WARNING, sprintf("Welcome user %s does not exist.", $defnick),
463 $notice = Notice::saveNew($welcomeuser->id,
464 // TRANS: Notice given on user registration.
465 // TRANS: %1$s is the sitename, $2$s is the registering user's nickname.
466 sprintf(_('Welcome to %1$s, @%2$s!'),
467 common_config('site', 'name'),
473 Event::handle('EndUserRegister', array(&$profile, &$user));
479 // Things we do when the email changes
480 function emailChanged()
483 $invites = new Invitation();
484 $invites->address = $this->email;
485 $invites->address_type = 'email';
487 if ($invites->find()) {
488 while ($invites->fetch()) {
489 $other = User::staticGet($invites->user_id);
490 subs_subscribe_to($other, $this);
495 function hasFave($notice)
497 $profile = $this->getProfile();
498 return $profile->hasFave($notice);
501 function mutuallySubscribed($other)
503 $profile = $this->getProfile();
504 return $profile->mutuallySubscribed($other);
507 function mutuallySubscribedUsers()
509 // 3-way join; probably should get cached
510 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
511 $qry = "SELECT $UT.* " .
512 "FROM subscription sub1 JOIN $UT ON sub1.subscribed = $UT.id " .
513 "JOIN subscription sub2 ON $UT.id = sub2.subscriber " .
514 'WHERE sub1.subscriber = %d and sub2.subscribed = %d ' .
515 "ORDER BY $UT.nickname";
517 $user->query(sprintf($qry, $this->id, $this->id));
522 function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
524 return Reply::stream($this->id, $offset, $limit, $since_id, $before_id);
527 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0) {
528 $profile = $this->getProfile();
529 return $profile->getTaggedNotices($tag, $offset, $limit, $since_id, $before_id);
532 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
534 $profile = $this->getProfile();
535 return $profile->getNotices($offset, $limit, $since_id, $before_id);
538 function favoriteNotices($own=false, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
540 return Fave::stream($this->id, $offset, $limit, $own, $since_id, $max_id);
543 function noticeInbox($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
545 $stream = new InboxNoticeStream($this);
546 return $stream->getNotices($offset, $limit, $since_id, $before_id);
549 // DEPRECATED, use noticeInbox()
551 function noticesWithFriends($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
553 return $this->noticeInbox($offset, $limit, $since_id, $before_id);
556 // DEPRECATED, use noticeInbox()
558 function noticesWithFriendsThreaded($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
560 return $this->noticeInbox($offset, $limit, $since_id, $before_id);
563 // DEPRECATED, use noticeInbox()
565 function noticeInboxThreaded($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
567 return $this->noticeInbox($offset, $limit, $since_id, $before_id);
570 // DEPRECATED, use noticeInbox()
572 function friendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
574 return $this->noticeInbox($offset, $limit, $since_id, $before_id);
577 // DEPRECATED, use noticeInbox()
579 function ownFriendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
581 $this->noticeInbox($offset, $limit, $since_id, $before_id);
584 function blowFavesCache()
586 $profile = $this->getProfile();
587 $profile->blowFavesCache();
590 function getSelfTags()
592 return Profile_tag::getTagsArray($this->id, $this->id, $this->id);
595 function setSelfTags($newtags, $privacy)
597 return Profile_tag::setTags($this->id, $this->id, $newtags, $privacy);
600 function block($other)
602 // Add a new block record
604 // no blocking (and thus unsubbing from) yourself
606 if ($this->id == $other->id) {
607 common_log(LOG_WARNING,
609 "Profile ID %d (%s) tried to block themself.",
617 $block = new Profile_block();
619 // Begin a transaction
621 $block->query('BEGIN');
623 $block->blocker = $this->id;
624 $block->blocked = $other->id;
626 $result = $block->insert();
629 common_log_db_error($block, 'INSERT', __FILE__);
633 $self = $this->getProfile();
634 if (Subscription::exists($other, $self)) {
635 Subscription::cancel($other, $self);
637 if (Subscription::exists($self, $other)) {
638 Subscription::cancel($self, $other);
641 $block->query('COMMIT');
646 function unblock($other)
648 // Get the block record
650 $block = Profile_block::get($this->id, $other->id);
656 $result = $block->delete();
659 common_log_db_error($block, 'DELETE', __FILE__);
666 function isMember($group)
668 $profile = $this->getProfile();
669 return $profile->isMember($group);
672 function isAdmin($group)
674 $profile = $this->getProfile();
675 return $profile->isAdmin($group);
678 function getGroups($offset=0, $limit=null)
680 $profile = $this->getProfile();
681 return $profile->getGroups($offset, $limit);
685 * Request to join the given group.
686 * May throw exceptions on failure.
688 * @param User_group $group
689 * @return Group_member
691 function joinGroup(User_group $group)
693 $profile = $this->getProfile();
694 return $profile->joinGroup($group);
698 * Leave a group that this user is a member of.
700 * @param User_group $group
702 function leaveGroup(User_group $group)
704 $profile = $this->getProfile();
705 return $profile->leaveGroup($group);
708 function getSubscriptions($offset=0, $limit=null)
710 $profile = $this->getProfile();
711 return $profile->getSubscriptions($offset, $limit);
714 function getSubscribers($offset=0, $limit=null)
716 $profile = $this->getProfile();
717 return $profile->getSubscribers($offset, $limit);
720 function getTaggedSubscribers($tag, $offset=0, $limit=null)
723 'SELECT profile.* ' .
724 'FROM profile JOIN subscription ' .
725 'ON profile.id = subscription.subscriber ' .
726 'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
727 'AND profile_tag.tagger = subscription.subscribed) ' .
728 'WHERE subscription.subscribed = %d ' .
729 "AND profile_tag.tag = '%s' " .
730 'AND subscription.subscribed != subscription.subscriber ' .
731 'ORDER BY subscription.created DESC ';
734 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
737 $profile = new Profile();
739 $cnt = $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
744 function getTaggedSubscriptions($tag, $offset=0, $limit=null)
747 'SELECT profile.* ' .
748 'FROM profile JOIN subscription ' .
749 'ON profile.id = subscription.subscribed ' .
750 'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
751 'AND profile_tag.tagger = subscription.subscriber) ' .
752 'WHERE subscription.subscriber = %d ' .
753 "AND profile_tag.tag = '%s' " .
754 'AND subscription.subscribed != subscription.subscriber ' .
755 'ORDER BY subscription.created DESC ';
757 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
759 $profile = new Profile();
761 $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
766 function hasRight($right)
768 $profile = $this->getProfile();
769 return $profile->hasRight($right);
775 $profile = $this->getProfile();
777 } catch (UserNoProfileException $unp) {
778 common_log(LOG_INFO, "User {$this->nickname} has no profile; continuing deletion.");
781 $related = array('Fave',
788 Event::handle('UserDeleteRelated', array($this, &$related));
790 foreach ($related as $cls) {
792 $inst->user_id = $this->id;
796 $this->_deleteTags();
797 $this->_deleteBlocks();
802 function _deleteTags()
804 $tag = new Profile_tag();
805 $tag->tagger = $this->id;
809 function _deleteBlocks()
811 $block = new Profile_block();
812 $block->blocker = $this->id;
814 // XXX delete group block? Reset blocker?
817 function hasRole($name)
819 $profile = $this->getProfile();
820 return $profile->hasRole($name);
823 function grantRole($name)
825 $profile = $this->getProfile();
826 return $profile->grantRole($name);
829 function revokeRole($name)
831 $profile = $this->getProfile();
832 return $profile->revokeRole($name);
835 function isSandboxed()
837 $profile = $this->getProfile();
838 return $profile->isSandboxed();
841 function isSilenced()
843 $profile = $this->getProfile();
844 return $profile->isSilenced();
847 function repeatedByMe($offset=0, $limit=20, $since_id=null, $max_id=null)
849 $stream = new RepeatedByMeNoticeStream($this);
850 return $stream->getNotices($offset, $limit, $since_id, $max_id);
854 function repeatsOfMe($offset=0, $limit=20, $since_id=null, $max_id=null)
856 $stream = new RepeatsOfMeNoticeStream($this);
858 return $stream->getNotices($offset, $limit, $since_id, $max_id);
862 function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
864 // TRANS: Exception thrown when trying view "repeated to me".
865 throw new Exception(_('Not implemented since inbox change.'));
868 function shareLocation()
870 $cfg = common_config('location', 'share');
872 if ($cfg == 'always') {
874 } else if ($cfg == 'never') {
879 $prefs = User_location_prefs::staticGet('user_id', $this->id);
882 $share = common_config('location', 'sharedefault');
884 $share = $prefs->share_location;
892 static function siteOwner()
894 $owner = self::cacheGet('user:site_owner');
896 if ($owner === false) { // cache miss
898 $pr = new Profile_role();
900 $pr->role = Profile_role::OWNER;
902 $pr->orderBy('created');
906 if ($pr->find(true)) {
907 $owner = User::staticGet('id', $pr->profile_id);
912 self::cacheSet('user:site_owner', $owner);
919 * Pull the primary site account to use in single-user mode.
920 * If a valid user nickname is listed in 'singleuser':'nickname'
921 * in the config, this will be used; otherwise the site owner
922 * account is taken by default.
925 * @throws ServerException if no valid single user account is present
926 * @throws ServerException if called when not in single-user mode
928 static function singleUser()
930 if (common_config('singleuser', 'enabled')) {
934 $nickname = common_config('singleuser', 'nickname');
936 if (!empty($nickname)) {
937 $user = User::staticGet('nickname', $nickname);
940 // if there was no nickname or no user by that nickname,
941 // try the site owner.
944 $user = User::siteOwner();
950 // TRANS: Server exception.
951 throw new ServerException(_('No single user defined for single-user mode.'));
954 // TRANS: Server exception.
955 throw new ServerException(_('Single-user mode code called when not enabled.'));
960 * This is kind of a hack for using external setup code that's trying to
961 * build single-user sites.
963 * Will still return a username if the config singleuser/nickname is set
964 * even if the account doesn't exist, which normally indicates that the
965 * site is horribly misconfigured.
967 * At the moment, we need to let it through so that router setup can
968 * complete, otherwise we won't be able to create the account.
970 * This will be easier when we can more easily create the account and
971 * *then* switch the site to 1user mode without jumping through hoops.
974 * @throws ServerException if no valid single user account is present
975 * @throws ServerException if called when not in single-user mode
977 static function singleUserNickname()
980 $user = User::singleUser();
981 return $user->nickname;
982 } catch (Exception $e) {
983 if (common_config('singleuser', 'enabled') && common_config('singleuser', 'nickname')) {
984 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.");
985 return common_config('singleuser', 'nickname');
992 * Find and shorten links in the given text using this user's URL shortening
995 * By default, links will be left untouched if the text is shorter than the
996 * configured maximum notice length. Pass true for the $always parameter
997 * to force all links to be shortened regardless.
999 * Side effects: may save file and file_redirection records for referenced URLs.
1001 * @param string $text
1002 * @param boolean $always
1005 public function shortenLinks($text, $always=false)
1007 return common_shorten_links($text, $always, $this);
1011 * Get a list of OAuth client applications that have access to this
1014 function getConnectedApps($offset = 0, $limit = null)
1018 'FROM oauth_application_user u, oauth_application a ' .
1019 'WHERE u.profile_id = %d ' .
1020 'AND a.id = u.application_id ' .
1021 'AND u.access_type > 0 ' .
1022 'ORDER BY u.created DESC ';
1025 if (common_config('db','type') == 'pgsql') {
1026 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
1028 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
1032 $apps = new Oauth_application_user();
1034 $cnt = $apps->query(sprintf($qry, $this->id));
1040 * Magic function called at serialize() time.
1042 * We use this to drop a couple process-specific references
1043 * from DB_DataObject which can cause trouble in future
1046 * @return array of variable names to include in serialization.
1051 $vars = parent::__sleep();
1052 $skip = array('_profile');
1053 return array_diff($vars, $skip);
1056 static function recoverPassword($nore)
1058 $user = User::staticGet('email', common_canonical_email($nore));
1062 $user = User::staticGet('nickname', common_canonical_nickname($nore));
1063 } catch (NicknameException $e) {
1068 // See if it's an unconfirmed email address
1071 // Warning: it may actually be legit to have multiple folks
1072 // who have claimed, but not yet confirmed, the same address.
1073 // We'll only send to the first one that comes up.
1074 $confirm_email = new Confirm_address();
1075 $confirm_email->address = common_canonical_email($nore);
1076 $confirm_email->address_type = 'email';
1077 $confirm_email->find();
1078 if ($confirm_email->fetch()) {
1079 $user = User::staticGet($confirm_email->user_id);
1081 $confirm_email = null;
1084 $confirm_email = null;
1088 // TRANS: Information on password recovery form if no known username or e-mail address was specified.
1089 throw new ClientException(_('No user with that email address or username.'));
1093 // Try to get an unconfirmed email address if they used a user name
1095 if (!$user->email && !$confirm_email) {
1096 $confirm_email = new Confirm_address();
1097 $confirm_email->user_id = $user->id;
1098 $confirm_email->address_type = 'email';
1099 $confirm_email->find();
1100 if (!$confirm_email->fetch()) {
1101 $confirm_email = null;
1105 if (!$user->email && !$confirm_email) {
1106 // TRANS: Client error displayed on password recovery form if a user does not have a registered e-mail address.
1107 throw new ClientException(_('No registered email address for that user.'));
1111 // Success! We have a valid user and a confirmed or unconfirmed email address
1113 $confirm = new Confirm_address();
1114 $confirm->code = common_confirmation_code(128);
1115 $confirm->address_type = 'recover';
1116 $confirm->user_id = $user->id;
1117 $confirm->address = (!empty($user->email)) ? $user->email : $confirm_email->address;
1119 if (!$confirm->insert()) {
1120 common_log_db_error($confirm, 'INSERT', __FILE__);
1121 // TRANS: Server error displayed if e-mail address confirmation fails in the database on the password recovery form.
1122 throw new ServerException(_('Error saving address confirmation.'));
1126 // @todo FIXME: needs i18n.
1127 $body = "Hey, $user->nickname.";
1129 $body .= 'Someone just asked for a new password ' .
1130 'for this account on ' . common_config('site', 'name') . '.';
1132 $body .= 'If it was you, and you want to confirm, use the URL below:';
1134 $body .= "\t".common_local_url('recoverpassword',
1135 array('code' => $confirm->code));
1137 $body .= 'If not, just ignore this message.';
1139 $body .= 'Thanks for your time, ';
1141 $body .= common_config('site', 'name');
1144 $headers = _mail_prepare_headers('recoverpassword', $user->nickname, $user->nickname);
1145 // TRANS: Subject for password recovery e-mail.
1146 mail_to_user($user, _('Password recovery requested'), $body, $headers, $confirm->address);
1149 function streamModeOnly()
1151 if (common_config('oldschool', 'enabled')) {
1152 $osp = Old_school_prefs::staticGet('user_id', $this->id);
1154 return $osp->stream_mode_only;
1161 function conversationTree()
1163 if (common_config('oldschool', 'enabled')) {
1164 $osp = Old_school_prefs::staticGet('user_id', $this->id);
1166 return $osp->conversation_tree;
1173 function streamNicknames()
1175 if (common_config('oldschool', 'enabled')) {
1176 $osp = Old_school_prefs::staticGet('user_id', $this->id);
1178 return $osp->stream_nicknames;
1184 function registrationActivity()
1186 $profile = $this->getProfile();
1188 $service = new ActivityObject();
1190 $service->type = ActivityObject::SERVICE;
1191 $service->title = common_config('site', 'name');
1192 $service->link = common_root_url();
1193 $service->id = $service->link;
1195 $act = new Activity();
1197 $act->actor = ActivityObject::fromProfile($profile);
1198 $act->verb = ActivityVerb::JOIN;
1200 $act->objects[] = $service;
1202 $act->id = TagURI::mint('user:register:%d',
1205 $act->time = strtotime($this->created);
1207 $act->title = _("Register");
1209 $act->content = sprintf(_('%1$s joined %2$s.'),
1210 $profile->getBestName(),