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 Memcached_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 $design_id; // int(4)
65 public $viewdesigns; // tinyint(1) default_1
66 public $private_stream; // tinyint(1) default_0
67 public $created; // datetime() not_null
68 public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
71 function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('User',$k,$v); }
73 /* the code above is auto generated do not remove the tag below */
76 protected $_profile = -1;
83 if (is_int($this->_profile) && $this->_profile == -1) { // invalid but distinct from null
84 $this->_profile = Profile::staticGet('id', $this->id);
85 if (empty($this->_profile)) {
86 throw new UserNoProfileException($this);
90 return $this->_profile;
93 function isSubscribed($other)
95 $profile = $this->getProfile();
96 return $profile->isSubscribed($other);
99 function hasPendingSubscription($other)
101 $profile = $this->getProfile();
102 return $profile->hasPendingSubscription($other);
105 // 'update' won't write key columns, so we have to do it ourselves.
107 function updateKeys(&$orig)
111 foreach (array('nickname', 'email', 'incomingemail', 'sms', 'carrier', 'smsemail', 'language', 'timezone') as $k) {
112 if (strcmp($this->$k, $orig->$k) != 0) {
113 $parts[] = $k . ' = ' . $this->_quote($this->$k);
116 if (count($parts) == 0) {
120 $toupdate = implode(', ', $parts);
122 $table = common_database_tablename($this->tableName());
123 $qry = 'UPDATE ' . $table . ' SET ' . $toupdate .
124 ' WHERE id = ' . $this->id;
126 $result = $this->query($qry);
134 * Check whether the given nickname is potentially usable, or if it's
135 * excluded by any blacklists on this system.
137 * WARNING: INPUT IS NOT VALIDATED OR NORMALIZED. NON-NORMALIZED INPUT
138 * OR INVALID INPUT MAY LEAD TO FALSE RESULTS.
140 * @param string $nickname
141 * @return boolean true if clear, false if blacklisted
143 static function allowed_nickname($nickname)
145 // XXX: should already be validated for size, content, etc.
146 $blacklist = common_config('nickname', 'blacklist');
148 //all directory and file names should be blacklisted
149 $d = dir(INSTALLDIR);
150 while (false !== ($entry = $d->read())) {
155 //all top level names in the router should be blacklisted
156 $router = Router::get();
157 foreach(array_keys($router->m->getPaths()) as $path){
158 if(preg_match('/^\/(.*?)[\/\?]/',$path,$matches)){
159 $blacklist[]=$matches[1];
162 return !in_array($nickname, $blacklist);
166 * Get the most recent notice posted by this user, if any.
168 * @return mixed Notice or null
170 function getCurrentNotice()
172 $profile = $this->getProfile();
173 return $profile->getCurrentNotice();
176 function getCarrier()
178 return Sms_carrier::staticGet('id', $this->carrier);
182 * @deprecated use Subscription::start($sub, $other);
184 function subscribeTo($other)
186 return Subscription::start($this->getProfile(), $other);
189 function hasBlocked($other)
191 $profile = $this->getProfile();
192 return $profile->hasBlocked($other);
196 * Register a new user account and profile and set up default subscriptions.
197 * If a new-user welcome message is configured, this will be sent.
199 * @param array $fields associative array of optional properties
202 * bool 'email_confirmed' pass true to mark email as pre-confirmed
205 * string 'location' informal string description of geolocation
206 * float 'lat' decimal latitude for geolocation
207 * float 'lon' decimal longitude for geolocation
208 * int 'location_id' geoname identifier
209 * int 'location_ns' geoname namespace to interpret location_id
210 * string 'nickname' REQUIRED
211 * string 'password' (may be missing for eg OpenID registrations)
212 * string 'code' invite code
213 * ?string 'uri' permalink to notice; defaults to local notice URL
214 * @return mixed User object or false on failure
216 static function register($fields) {
218 // MAGICALLY put fields into current scope
222 $profile = new Profile();
226 $email = common_canonical_email($email);
229 $nickname = common_canonical_nickname($nickname);
230 $profile->nickname = $nickname;
231 if(! User::allowed_nickname($nickname)){
232 common_log(LOG_WARNING, sprintf("Attempted to register a nickname that is not allowed: %s", $profile->nickname),
236 $profile->profileurl = common_profile_url($nickname);
238 if (!empty($fullname)) {
239 $profile->fullname = $fullname;
241 if (!empty($homepage)) {
242 $profile->homepage = $homepage;
245 $profile->bio = $bio;
247 if (!empty($location)) {
248 $profile->location = $location;
250 $loc = Location::fromName($location);
253 $profile->lat = $loc->lat;
254 $profile->lon = $loc->lon;
255 $profile->location_id = $loc->location_id;
256 $profile->location_ns = $loc->location_ns;
260 $profile->created = common_sql_now();
264 $user->nickname = $nickname;
268 // Users who respond to invite email have proven their ownership of that address
271 $invite = Invitation::staticGet($code);
272 if ($invite && $invite->address && $invite->address_type == 'email' && $invite->address == $email) {
273 $user->email = $invite->address;
277 if(isset($email_confirmed) && $email_confirmed) {
278 $user->email = $email;
281 // This flag is ignored but still set to 1
285 // Set default-on options here, otherwise they'll be disabled
286 // initially for sites using caching, since the initial encache
287 // doesn't know about the defaults in the database.
288 $user->emailnotifysub = 1;
289 $user->emailnotifyfav = 1;
290 $user->emailnotifynudge = 1;
291 $user->emailnotifymsg = 1;
292 $user->emailnotifyattn = 1;
293 $user->emailmicroid = 1;
294 $user->emailpost = 1;
295 $user->jabbermicroid = 1;
296 $user->viewdesigns = 1;
298 $user->created = common_sql_now();
300 if (Event::handle('StartUserRegister', array(&$user, &$profile))) {
302 $profile->query('BEGIN');
304 $id = $profile->insert();
307 common_log_db_error($profile, 'INSERT', __FILE__);
316 $user->uri = common_user_uri($user);
319 if (!empty($password)) { // may not have a password for OpenID users
320 $user->password = common_munge_password($password, $id);
323 $result = $user->insert();
326 common_log_db_error($user, 'INSERT', __FILE__);
330 // Everyone gets an inbox
332 $inbox = new Inbox();
334 $inbox->user_id = $user->id;
335 $inbox->notice_ids = '';
337 $result = $inbox->insert();
340 common_log_db_error($inbox, 'INSERT', __FILE__);
344 // Everyone is subscribed to themself
346 $subscription = new Subscription();
347 $subscription->subscriber = $user->id;
348 $subscription->subscribed = $user->id;
349 $subscription->created = $user->created;
351 $result = $subscription->insert();
354 common_log_db_error($subscription, 'INSERT', __FILE__);
358 // Mark that this invite was converted
360 if (!empty($invite)) {
361 $invite->convert($user);
364 if (!empty($email) && !$user->email) {
366 $confirm = new Confirm_address();
367 $confirm->code = common_confirmation_code(128);
368 $confirm->user_id = $user->id;
369 $confirm->address = $email;
370 $confirm->address_type = 'email';
372 $result = $confirm->insert();
375 common_log_db_error($confirm, 'INSERT', __FILE__);
380 if (!empty($code) && $user->email) {
381 $user->emailChanged();
384 // Default system subscription
386 $defnick = common_config('newuser', 'default');
388 if (!empty($defnick)) {
389 $defuser = User::staticGet('nickname', $defnick);
390 if (empty($defuser)) {
391 common_log(LOG_WARNING, sprintf("Default user %s does not exist.", $defnick),
394 Subscription::start($user, $defuser);
398 $profile->query('COMMIT');
400 if (!empty($email) && !$user->email) {
401 mail_confirm_address($user, $confirm->code, $profile->nickname, $email);
406 $welcome = common_config('newuser', 'welcome');
408 if (!empty($welcome)) {
409 $welcomeuser = User::staticGet('nickname', $welcome);
410 if (empty($welcomeuser)) {
411 common_log(LOG_WARNING, sprintf("Welcome user %s does not exist.", $defnick),
414 $notice = Notice::saveNew($welcomeuser->id,
415 // TRANS: Notice given on user registration.
416 // TRANS: %1$s is the sitename, $2$s is the registering user's nickname.
417 sprintf(_('Welcome to %1$s, @%2$s!'),
418 common_config('site', 'name'),
424 Event::handle('EndUserRegister', array(&$profile, &$user));
430 // Things we do when the email changes
431 function emailChanged()
434 $invites = new Invitation();
435 $invites->address = $this->email;
436 $invites->address_type = 'email';
438 if ($invites->find()) {
439 while ($invites->fetch()) {
440 $other = User::staticGet($invites->user_id);
441 subs_subscribe_to($other, $this);
446 function hasFave($notice)
448 $profile = $this->getProfile();
449 return $profile->hasFave($notice);
452 function mutuallySubscribed($other)
454 $profile = $this->getProfile();
455 return $profile->mutuallySubscribed($other);
458 function mutuallySubscribedUsers()
460 // 3-way join; probably should get cached
461 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
462 $qry = "SELECT $UT.* " .
463 "FROM subscription sub1 JOIN $UT ON sub1.subscribed = $UT.id " .
464 "JOIN subscription sub2 ON $UT.id = sub2.subscriber " .
465 'WHERE sub1.subscriber = %d and sub2.subscribed = %d ' .
466 "ORDER BY $UT.nickname";
468 $user->query(sprintf($qry, $this->id, $this->id));
473 function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
475 return Reply::stream($this->id, $offset, $limit, $since_id, $before_id);
478 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0) {
479 $profile = $this->getProfile();
480 return $profile->getTaggedNotices($tag, $offset, $limit, $since_id, $before_id);
483 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
485 $profile = $this->getProfile();
486 return $profile->getNotices($offset, $limit, $since_id, $before_id);
489 function favoriteNotices($own=false, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
491 return Fave::stream($this->id, $offset, $limit, $own, $since_id, $max_id);
494 function noticeInbox($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
496 $stream = new InboxNoticeStream($this);
497 return $stream->getNotices($offset, $limit, $since_id, $before_id);
500 // DEPRECATED, use noticeInbox()
502 function noticesWithFriends($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
504 return $this->noticeInbox($offset, $limit, $since_id, $before_id);
507 // DEPRECATED, use noticeInbox()
509 function noticesWithFriendsThreaded($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
511 return $this->noticeInbox($offset, $limit, $since_id, $before_id);
514 // DEPRECATED, use noticeInbox()
516 function noticeInboxThreaded($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
518 return $this->noticeInbox($offset, $limit, $since_id, $before_id);
521 // DEPRECATED, use noticeInbox()
523 function friendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
525 return $this->noticeInbox($offset, $limit, $since_id, $before_id);
528 // DEPRECATED, use noticeInbox()
530 function ownFriendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
532 $this->noticeInbox($offset, $limit, $since_id, $before_id);
535 function blowFavesCache()
537 $profile = $this->getProfile();
538 $profile->blowFavesCache();
541 function getSelfTags()
543 return Profile_tag::getTagsArray($this->id, $this->id, $this->id);
546 function setSelfTags($newtags, $privacy)
548 return Profile_tag::setTags($this->id, $this->id, $newtags, $privacy);
551 function block($other)
553 // Add a new block record
555 // no blocking (and thus unsubbing from) yourself
557 if ($this->id == $other->id) {
558 common_log(LOG_WARNING,
560 "Profile ID %d (%s) tried to block themself.",
568 $block = new Profile_block();
570 // Begin a transaction
572 $block->query('BEGIN');
574 $block->blocker = $this->id;
575 $block->blocked = $other->id;
577 $result = $block->insert();
580 common_log_db_error($block, 'INSERT', __FILE__);
584 $self = $this->getProfile();
585 if (Subscription::exists($other, $self)) {
586 Subscription::cancel($other, $self);
588 if (Subscription::exists($self, $other)) {
589 Subscription::cancel($self, $other);
592 $block->query('COMMIT');
597 function unblock($other)
599 // Get the block record
601 $block = Profile_block::get($this->id, $other->id);
607 $result = $block->delete();
610 common_log_db_error($block, 'DELETE', __FILE__);
617 function isMember($group)
619 $profile = $this->getProfile();
620 return $profile->isMember($group);
623 function isAdmin($group)
625 $profile = $this->getProfile();
626 return $profile->isAdmin($group);
629 function getGroups($offset=0, $limit=null)
631 $profile = $this->getProfile();
632 return $profile->getGroups($offset, $limit);
636 * Request to join the given group.
637 * May throw exceptions on failure.
639 * @param User_group $group
640 * @return Group_member
642 function joinGroup(User_group $group)
644 $profile = $this->getProfile();
645 return $profile->joinGroup($group);
649 * Leave a group that this user is a member of.
651 * @param User_group $group
653 function leaveGroup(User_group $group)
655 $profile = $this->getProfile();
656 return $profile->leaveGroup($group);
659 function getSubscriptions($offset=0, $limit=null)
661 $profile = $this->getProfile();
662 return $profile->getSubscriptions($offset, $limit);
665 function getSubscribers($offset=0, $limit=null)
667 $profile = $this->getProfile();
668 return $profile->getSubscribers($offset, $limit);
671 function getTaggedSubscribers($tag, $offset=0, $limit=null)
674 'SELECT profile.* ' .
675 'FROM profile JOIN subscription ' .
676 'ON profile.id = subscription.subscriber ' .
677 'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
678 'AND profile_tag.tagger = subscription.subscribed) ' .
679 'WHERE subscription.subscribed = %d ' .
680 "AND profile_tag.tag = '%s' " .
681 'AND subscription.subscribed != subscription.subscriber ' .
682 'ORDER BY subscription.created DESC ';
685 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
688 $profile = new Profile();
690 $cnt = $profile->query(sprintf($qry, $this->id, $tag));
695 function getTaggedSubscriptions($tag, $offset=0, $limit=null)
698 'SELECT profile.* ' .
699 'FROM profile JOIN subscription ' .
700 'ON profile.id = subscription.subscribed ' .
701 'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
702 'AND profile_tag.tagger = subscription.subscriber) ' .
703 'WHERE subscription.subscriber = %d ' .
704 "AND profile_tag.tag = '%s' " .
705 'AND subscription.subscribed != subscription.subscriber ' .
706 'ORDER BY subscription.created DESC ';
708 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
710 $profile = new Profile();
712 $profile->query(sprintf($qry, $this->id, $tag));
719 return Design::staticGet('id', $this->design_id);
722 function hasRight($right)
724 $profile = $this->getProfile();
725 return $profile->hasRight($right);
731 $profile = $this->getProfile();
733 } catch (UserNoProfileException $unp) {
734 common_log(LOG_INFO, "User {$this->nickname} has no profile; continuing deletion.");
737 $related = array('Fave',
744 Event::handle('UserDeleteRelated', array($this, &$related));
746 foreach ($related as $cls) {
748 $inst->user_id = $this->id;
752 $this->_deleteTags();
753 $this->_deleteBlocks();
758 function _deleteTags()
760 $tag = new Profile_tag();
761 $tag->tagger = $this->id;
765 function _deleteBlocks()
767 $block = new Profile_block();
768 $block->blocker = $this->id;
770 // XXX delete group block? Reset blocker?
773 function hasRole($name)
775 $profile = $this->getProfile();
776 return $profile->hasRole($name);
779 function grantRole($name)
781 $profile = $this->getProfile();
782 return $profile->grantRole($name);
785 function revokeRole($name)
787 $profile = $this->getProfile();
788 return $profile->revokeRole($name);
791 function isSandboxed()
793 $profile = $this->getProfile();
794 return $profile->isSandboxed();
797 function isSilenced()
799 $profile = $this->getProfile();
800 return $profile->isSilenced();
803 function repeatedByMe($offset=0, $limit=20, $since_id=null, $max_id=null)
805 $stream = new RepeatedByMeNoticeStream($this);
806 return $stream->getNotices($offset, $limit, $since_id, $max_id);
810 function repeatsOfMe($offset=0, $limit=20, $since_id=null, $max_id=null)
812 $stream = new RepeatsOfMeNoticeStream($this);
814 return $stream->getNotices($offset, $limit, $since_id, $max_id);
818 function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
820 // TRANS: Exception thrown when trying view "repeated to me".
821 throw new Exception(_('Not implemented since inbox change.'));
824 function shareLocation()
826 $cfg = common_config('location', 'share');
828 if ($cfg == 'always') {
830 } else if ($cfg == 'never') {
835 $prefs = User_location_prefs::staticGet('user_id', $this->id);
838 $share = common_config('location', 'sharedefault');
840 $share = $prefs->share_location;
848 static function siteOwner()
850 $owner = self::cacheGet('user:site_owner');
852 if ($owner === false) { // cache miss
854 $pr = new Profile_role();
856 $pr->role = Profile_role::OWNER;
858 $pr->orderBy('created');
862 if ($pr->find(true)) {
863 $owner = User::staticGet('id', $pr->profile_id);
868 self::cacheSet('user:site_owner', $owner);
875 * Pull the primary site account to use in single-user mode.
876 * If a valid user nickname is listed in 'singleuser':'nickname'
877 * in the config, this will be used; otherwise the site owner
878 * account is taken by default.
881 * @throws ServerException if no valid single user account is present
882 * @throws ServerException if called when not in single-user mode
884 static function singleUser()
886 if (common_config('singleuser', 'enabled')) {
890 $nickname = common_config('singleuser', 'nickname');
892 if (!empty($nickname)) {
893 $user = User::staticGet('nickname', $nickname);
896 // if there was no nickname or no user by that nickname,
897 // try the site owner.
900 $user = User::siteOwner();
906 // TRANS: Server exception.
907 throw new ServerException(_('No single user defined for single-user mode.'));
910 // TRANS: Server exception.
911 throw new ServerException(_('Single-user mode code called when not enabled.'));
916 * This is kind of a hack for using external setup code that's trying to
917 * build single-user sites.
919 * Will still return a username if the config singleuser/nickname is set
920 * even if the account doesn't exist, which normally indicates that the
921 * site is horribly misconfigured.
923 * At the moment, we need to let it through so that router setup can
924 * complete, otherwise we won't be able to create the account.
926 * This will be easier when we can more easily create the account and
927 * *then* switch the site to 1user mode without jumping through hoops.
930 * @throws ServerException if no valid single user account is present
931 * @throws ServerException if called when not in single-user mode
933 static function singleUserNickname()
936 $user = User::singleUser();
937 return $user->nickname;
938 } catch (Exception $e) {
939 if (common_config('singleuser', 'enabled') && common_config('singleuser', 'nickname')) {
940 common_log(LOG_WARN, "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.");
941 return common_config('singleuser', 'nickname');
948 * Find and shorten links in the given text using this user's URL shortening
951 * By default, links will be left untouched if the text is shorter than the
952 * configured maximum notice length. Pass true for the $always parameter
953 * to force all links to be shortened regardless.
955 * Side effects: may save file and file_redirection records for referenced URLs.
957 * @param string $text
958 * @param boolean $always
961 public function shortenLinks($text, $always=false)
963 return common_shorten_links($text, $always, $this);
967 * Get a list of OAuth client applications that have access to this
970 function getConnectedApps($offset = 0, $limit = null)
974 'FROM oauth_application_user u, oauth_application a ' .
975 'WHERE u.profile_id = %d ' .
976 'AND a.id = u.application_id ' .
977 'AND u.access_type > 0 ' .
978 'ORDER BY u.created DESC ';
981 if (common_config('db','type') == 'pgsql') {
982 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
984 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
988 $apps = new Oauth_application_user();
990 $cnt = $apps->query(sprintf($qry, $this->id));
996 * Magic function called at serialize() time.
998 * We use this to drop a couple process-specific references
999 * from DB_DataObject which can cause trouble in future
1002 * @return array of variable names to include in serialization.
1007 $vars = parent::__sleep();
1008 $skip = array('_profile');
1009 return array_diff($vars, $skip);