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
34 /* the code below is auto generated do not remove the above tag */
36 public $__table = 'user'; // table name
37 public $id; // int(4) primary_key not_null
38 public $nickname; // varchar(64) unique_key
39 public $password; // varchar(255)
40 public $email; // varchar(255) unique_key
41 public $incomingemail; // varchar(255) unique_key
42 public $emailnotifysub; // tinyint(1) default_1
43 public $emailnotifyfav; // tinyint(1) default_1
44 public $emailnotifynudge; // tinyint(1) default_1
45 public $emailnotifymsg; // tinyint(1) default_1
46 public $emailnotifyattn; // tinyint(1) default_1
47 public $emailmicroid; // tinyint(1) default_1
48 public $language; // varchar(50)
49 public $timezone; // varchar(50)
50 public $emailpost; // tinyint(1) default_1
51 public $sms; // varchar(64) unique_key
52 public $carrier; // int(4)
53 public $smsnotify; // tinyint(1)
54 public $smsreplies; // tinyint(1)
55 public $smsemail; // varchar(255)
56 public $uri; // varchar(255) unique_key
57 public $autosubscribe; // tinyint(1)
58 public $urlshorteningservice; // varchar(50) default_ur1.ca
59 public $inboxed; // tinyint(1)
60 public $design_id; // int(4)
61 public $viewdesigns; // tinyint(1) default_1
62 public $created; // datetime() not_null
63 public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
66 function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('User',$k,$v); }
68 /* the code above is auto generated do not remove the tag below */
76 $profile = Profile::staticGet('id', $this->id);
77 if (empty($profile)) {
78 throw new UserNoProfileException($this);
83 function isSubscribed($other)
85 $profile = $this->getProfile();
86 return $profile->isSubscribed($other);
89 // 'update' won't write key columns, so we have to do it ourselves.
91 function updateKeys(&$orig)
95 foreach (array('nickname', 'email', 'incomingemail', 'sms', 'carrier', 'smsemail', 'language', 'timezone') as $k) {
96 if (strcmp($this->$k, $orig->$k) != 0) {
97 $parts[] = $k . ' = ' . $this->_quote($this->$k);
100 if (count($parts) == 0) {
104 $toupdate = implode(', ', $parts);
106 $table = common_database_tablename($this->tableName());
107 $qry = 'UPDATE ' . $table . ' SET ' . $toupdate .
108 ' WHERE id = ' . $this->id;
110 $result = $this->query($qry);
118 * Check whether the given nickname is potentially usable, or if it's
119 * excluded by any blacklists on this system.
121 * WARNING: INPUT IS NOT VALIDATED OR NORMALIZED. NON-NORMALIZED INPUT
122 * OR INVALID INPUT MAY LEAD TO FALSE RESULTS.
124 * @param string $nickname
125 * @return boolean true if clear, false if blacklisted
127 static function allowed_nickname($nickname)
129 // XXX: should already be validated for size, content, etc.
130 $blacklist = common_config('nickname', 'blacklist');
132 //all directory and file names should be blacklisted
133 $d = dir(INSTALLDIR);
134 while (false !== ($entry = $d->read())) {
139 //all top level names in the router should be blacklisted
140 $router = Router::get();
141 foreach(array_keys($router->m->getPaths()) as $path){
142 if(preg_match('/^\/(.*?)[\/\?]/',$path,$matches)){
143 $blacklist[]=$matches[1];
146 return !in_array($nickname, $blacklist);
150 * Get the most recent notice posted by this user, if any.
152 * @return mixed Notice or null
154 function getCurrentNotice()
156 $profile = $this->getProfile();
157 return $profile->getCurrentNotice();
160 function getCarrier()
162 return Sms_carrier::staticGet('id', $this->carrier);
166 * @deprecated use Subscription::start($sub, $other);
168 function subscribeTo($other)
170 return Subscription::start($this->getProfile(), $other);
173 function hasBlocked($other)
175 $profile = $this->getProfile();
176 return $profile->hasBlocked($other);
180 * Register a new user account and profile and set up default subscriptions.
181 * If a new-user welcome message is configured, this will be sent.
183 * @param array $fields associative array of optional properties
186 * bool 'email_confirmed' pass true to mark email as pre-confirmed
189 * string 'location' informal string description of geolocation
190 * float 'lat' decimal latitude for geolocation
191 * float 'lon' decimal longitude for geolocation
192 * int 'location_id' geoname identifier
193 * int 'location_ns' geoname namespace to interpret location_id
194 * string 'nickname' REQUIRED
195 * string 'password' (may be missing for eg OpenID registrations)
196 * string 'code' invite code
197 * ?string 'uri' permalink to notice; defaults to local notice URL
198 * @return mixed User object or false on failure
200 static function register($fields) {
202 // MAGICALLY put fields into current scope
206 $profile = new Profile();
210 $email = common_canonical_email($email);
213 $nickname = common_canonical_nickname($nickname);
214 $profile->nickname = $nickname;
215 if(! User::allowed_nickname($nickname)){
216 common_log(LOG_WARNING, sprintf("Attempted to register a nickname that is not allowed: %s", $profile->nickname),
220 $profile->profileurl = common_profile_url($nickname);
222 if (!empty($fullname)) {
223 $profile->fullname = $fullname;
225 if (!empty($homepage)) {
226 $profile->homepage = $homepage;
229 $profile->bio = $bio;
231 if (!empty($location)) {
232 $profile->location = $location;
234 $loc = Location::fromName($location);
237 $profile->lat = $loc->lat;
238 $profile->lon = $loc->lon;
239 $profile->location_id = $loc->location_id;
240 $profile->location_ns = $loc->location_ns;
244 $profile->created = common_sql_now();
248 $user->nickname = $nickname;
250 // Users who respond to invite email have proven their ownership of that address
253 $invite = Invitation::staticGet($code);
254 if ($invite && $invite->address && $invite->address_type == 'email' && $invite->address == $email) {
255 $user->email = $invite->address;
259 if(isset($email_confirmed) && $email_confirmed) {
260 $user->email = $email;
263 // This flag is ignored but still set to 1
267 // Set default-on options here, otherwise they'll be disabled
268 // initially for sites using caching, since the initial encache
269 // doesn't know about the defaults in the database.
270 $user->emailnotifysub = 1;
271 $user->emailnotifyfav = 1;
272 $user->emailnotifynudge = 1;
273 $user->emailnotifymsg = 1;
274 $user->emailnotifyattn = 1;
275 $user->emailmicroid = 1;
276 $user->emailpost = 1;
277 $user->jabbermicroid = 1;
278 $user->viewdesigns = 1;
280 $user->created = common_sql_now();
282 if (Event::handle('StartUserRegister', array(&$user, &$profile))) {
284 $profile->query('BEGIN');
286 $id = $profile->insert();
289 common_log_db_error($profile, 'INSERT', __FILE__);
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, $id);
305 $result = $user->insert();
308 common_log_db_error($user, 'INSERT', __FILE__);
312 // Everyone gets an inbox
314 $inbox = new Inbox();
316 $inbox->user_id = $user->id;
317 $inbox->notice_ids = '';
319 $result = $inbox->insert();
322 common_log_db_error($inbox, 'INSERT', __FILE__);
326 // Everyone is subscribed to themself
328 $subscription = new Subscription();
329 $subscription->subscriber = $user->id;
330 $subscription->subscribed = $user->id;
331 $subscription->created = $user->created;
333 $result = $subscription->insert();
336 common_log_db_error($subscription, 'INSERT', __FILE__);
340 if (!empty($email) && !$user->email) {
342 $confirm = new Confirm_address();
343 $confirm->code = common_confirmation_code(128);
344 $confirm->user_id = $user->id;
345 $confirm->address = $email;
346 $confirm->address_type = 'email';
348 $result = $confirm->insert();
351 common_log_db_error($confirm, 'INSERT', __FILE__);
356 if (!empty($code) && $user->email) {
357 $user->emailChanged();
360 // Default system subscription
362 $defnick = common_config('newuser', 'default');
364 if (!empty($defnick)) {
365 $defuser = User::staticGet('nickname', $defnick);
366 if (empty($defuser)) {
367 common_log(LOG_WARNING, sprintf("Default user %s does not exist.", $defnick),
370 Subscription::start($user, $defuser);
374 $profile->query('COMMIT');
376 if (!empty($email) && !$user->email) {
377 mail_confirm_address($user, $confirm->code, $profile->nickname, $email);
382 $welcome = common_config('newuser', 'welcome');
384 if (!empty($welcome)) {
385 $welcomeuser = User::staticGet('nickname', $welcome);
386 if (empty($welcomeuser)) {
387 common_log(LOG_WARNING, sprintf("Welcome user %s does not exist.", $defnick),
390 $notice = Notice::saveNew($welcomeuser->id,
391 // TRANS: Notice given on user registration.
392 // TRANS: %1$s is the sitename, $2$s is the registering user's nickname.
393 sprintf(_('Welcome to %1$s, @%2$s!'),
394 common_config('site', 'name'),
400 Event::handle('EndUserRegister', array(&$profile, &$user));
406 // Things we do when the email changes
407 function emailChanged()
410 $invites = new Invitation();
411 $invites->address = $this->email;
412 $invites->address_type = 'email';
414 if ($invites->find()) {
415 while ($invites->fetch()) {
416 $other = User::staticGet($invites->user_id);
417 subs_subscribe_to($other, $this);
422 function hasFave($notice)
424 $profile = $this->getProfile();
425 return $profile->hasFave($notice);
428 function mutuallySubscribed($other)
430 $profile = $this->getProfile();
431 return $profile->mutuallySubscribed($other);
434 function mutuallySubscribedUsers()
436 // 3-way join; probably should get cached
437 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
438 $qry = "SELECT $UT.* " .
439 "FROM subscription sub1 JOIN $UT ON sub1.subscribed = $UT.id " .
440 "JOIN subscription sub2 ON $UT.id = sub2.subscriber " .
441 'WHERE sub1.subscriber = %d and sub2.subscribed = %d ' .
442 "ORDER BY $UT.nickname";
444 $user->query(sprintf($qry, $this->id, $this->id));
449 function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
451 return Reply::stream($this->id, $offset, $limit, $since_id, $before_id);
454 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0) {
455 $profile = $this->getProfile();
456 return $profile->getTaggedNotices($tag, $offset, $limit, $since_id, $before_id);
459 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
461 $profile = $this->getProfile();
462 return $profile->getNotices($offset, $limit, $since_id, $before_id);
465 function favoriteNotices($own=false, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
467 return Fave::stream($this->id, $offset, $limit, $own, $since_id, $max_id);
470 function noticesWithFriends($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
472 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, false);
475 function noticesWithFriendsThreaded($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
477 return Inbox::streamNoticesThreaded($this->id, $offset, $limit, $since_id, $before_id, false);
480 function noticeInbox($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
482 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, true);
485 function noticeInboxThreaded($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
487 return Inbox::streamNoticesThreaded($this->id, $offset, $limit, $since_id, $before_id, true);
490 function friendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
492 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, false);
495 function ownFriendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
497 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, true);
500 function blowFavesCache()
502 $profile = $this->getProfile();
503 $profile->blowFavesCache();
506 function getSelfTags()
508 return Profile_tag::getTags($this->id, $this->id);
511 function setSelfTags($newtags)
513 return Profile_tag::setTags($this->id, $this->id, $newtags);
516 function block($other)
518 // Add a new block record
520 // no blocking (and thus unsubbing from) yourself
522 if ($this->id == $other->id) {
523 common_log(LOG_WARNING,
525 "Profile ID %d (%s) tried to block themself.",
533 $block = new Profile_block();
535 // Begin a transaction
537 $block->query('BEGIN');
539 $block->blocker = $this->id;
540 $block->blocked = $other->id;
542 $result = $block->insert();
545 common_log_db_error($block, 'INSERT', __FILE__);
549 $self = $this->getProfile();
550 if (Subscription::exists($other, $self)) {
551 Subscription::cancel($other, $self);
553 if (Subscription::exists($self, $other)) {
554 Subscription::cancel($self, $other);
557 $block->query('COMMIT');
562 function unblock($other)
564 // Get the block record
566 $block = Profile_block::get($this->id, $other->id);
572 $result = $block->delete();
575 common_log_db_error($block, 'DELETE', __FILE__);
582 function isMember($group)
584 $profile = $this->getProfile();
585 return $profile->isMember($group);
588 function isAdmin($group)
590 $profile = $this->getProfile();
591 return $profile->isAdmin($group);
594 function getGroups($offset=0, $limit=null)
596 $profile = $this->getProfile();
597 return $profile->getGroups($offset, $limit);
601 * Request to join the given group.
602 * May throw exceptions on failure.
604 * @param User_group $group
605 * @return Group_member
607 function joinGroup(User_group $group)
609 $profile = $this->getProfile();
610 return $profile->joinGroup($group);
614 * Leave a group that this user is a member of.
616 * @param User_group $group
618 function leaveGroup(User_group $group)
620 $profile = $this->getProfile();
621 return $profile->leaveGroup($group);
624 function getSubscriptions($offset=0, $limit=null)
626 $profile = $this->getProfile();
627 return $profile->getSubscriptions($offset, $limit);
630 function getSubscribers($offset=0, $limit=null)
632 $profile = $this->getProfile();
633 return $profile->getSubscribers($offset, $limit);
636 function getTaggedSubscribers($tag, $offset=0, $limit=null)
639 'SELECT profile.* ' .
640 'FROM profile JOIN subscription ' .
641 'ON profile.id = subscription.subscriber ' .
642 'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
643 'AND profile_tag.tagger = subscription.subscribed) ' .
644 'WHERE subscription.subscribed = %d ' .
645 "AND profile_tag.tag = '%s' " .
646 'AND subscription.subscribed != subscription.subscriber ' .
647 'ORDER BY subscription.created DESC ';
650 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
653 $profile = new Profile();
655 $cnt = $profile->query(sprintf($qry, $this->id, $tag));
660 function getTaggedSubscriptions($tag, $offset=0, $limit=null)
663 'SELECT profile.* ' .
664 'FROM profile JOIN subscription ' .
665 'ON profile.id = subscription.subscribed ' .
666 'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
667 'AND profile_tag.tagger = subscription.subscriber) ' .
668 'WHERE subscription.subscriber = %d ' .
669 "AND profile_tag.tag = '%s' " .
670 'AND subscription.subscribed != subscription.subscriber ' .
671 'ORDER BY subscription.created DESC ';
673 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
675 $profile = new Profile();
677 $profile->query(sprintf($qry, $this->id, $tag));
684 return Design::staticGet('id', $this->design_id);
687 function hasRight($right)
689 $profile = $this->getProfile();
690 return $profile->hasRight($right);
696 $profile = $this->getProfile();
698 } catch (UserNoProfileException $unp) {
699 common_log(LOG_INFO, "User {$this->nickname} has no profile; continuing deletion.");
702 $related = array('Fave',
709 Event::handle('UserDeleteRelated', array($this, &$related));
711 foreach ($related as $cls) {
713 $inst->user_id = $this->id;
717 $this->_deleteTags();
718 $this->_deleteBlocks();
723 function _deleteTags()
725 $tag = new Profile_tag();
726 $tag->tagger = $this->id;
730 function _deleteBlocks()
732 $block = new Profile_block();
733 $block->blocker = $this->id;
735 // XXX delete group block? Reset blocker?
738 function hasRole($name)
740 $profile = $this->getProfile();
741 return $profile->hasRole($name);
744 function grantRole($name)
746 $profile = $this->getProfile();
747 return $profile->grantRole($name);
750 function revokeRole($name)
752 $profile = $this->getProfile();
753 return $profile->revokeRole($name);
756 function isSandboxed()
758 $profile = $this->getProfile();
759 return $profile->isSandboxed();
762 function isSilenced()
764 $profile = $this->getProfile();
765 return $profile->isSilenced();
768 function repeatedByMe($offset=0, $limit=20, $since_id=null, $max_id=null)
770 $stream = new NoticeStream(array($this, '_repeatedByMeDirect'),
772 'user:repeated_by_me:'.$this->id);
774 return $stream->getNotices($offset, $limit, $since_id, $max_id);
777 function _repeatedByMeDirect($offset, $limit, $since_id, $max_id)
779 $notice = new Notice();
781 $notice->selectAdd(); // clears it
782 $notice->selectAdd('id');
784 $notice->profile_id = $this->id;
785 $notice->whereAdd('repeat_of IS NOT NULL');
787 $notice->orderBy('created DESC, id DESC');
789 if (!is_null($offset)) {
790 $notice->limit($offset, $limit);
793 Notice::addWhereSinceId($notice, $since_id);
794 Notice::addWhereMaxId($notice, $max_id);
798 if ($notice->find()) {
799 while ($notice->fetch()) {
800 $ids[] = $notice->id;
810 function repeatsOfMe($offset=0, $limit=20, $since_id=null, $max_id=null)
812 $stream = new NoticeStream(array($this, '_repeatsOfMeDirect'),
814 'user:repeats_of_me:'.$this->id);
816 return $stream->getNotices($offset, $limit, $since_id, $max_id);
819 function _repeatsOfMeDirect($offset, $limit, $since_id, $max_id)
822 'SELECT DISTINCT original.id AS id ' .
823 'FROM notice original JOIN notice rept ON original.id = rept.repeat_of ' .
824 'WHERE original.profile_id = ' . $this->id . ' ';
826 $since = Notice::whereSinceId($since_id, 'original.id', 'original.created');
828 $qry .= "AND ($since) ";
831 $max = Notice::whereMaxId($max_id, 'original.id', 'original.created');
833 $qry .= "AND ($max) ";
836 $qry .= 'ORDER BY original.created, original.id DESC ';
838 if (!is_null($offset)) {
839 $qry .= "LIMIT $limit OFFSET $offset";
844 $notice = new Notice();
846 $notice->query($qry);
848 while ($notice->fetch()) {
849 $ids[] = $notice->id;
858 function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
860 throw new Exception("Not implemented since inbox change.");
863 function shareLocation()
865 $cfg = common_config('location', 'share');
867 if ($cfg == 'always') {
869 } else if ($cfg == 'never') {
874 $prefs = User_location_prefs::staticGet('user_id', $this->id);
877 $share = common_config('location', 'sharedefault');
879 $share = $prefs->share_location;
887 static function siteOwner()
889 $owner = self::cacheGet('user:site_owner');
891 if ($owner === false) { // cache miss
893 $pr = new Profile_role();
895 $pr->role = Profile_role::OWNER;
897 $pr->orderBy('created');
901 if ($pr->find(true)) {
902 $owner = User::staticGet('id', $pr->profile_id);
907 self::cacheSet('user:site_owner', $owner);
914 * Pull the primary site account to use in single-user mode.
915 * If a valid user nickname is listed in 'singleuser':'nickname'
916 * in the config, this will be used; otherwise the site owner
917 * account is taken by default.
920 * @throws ServerException if no valid single user account is present
921 * @throws ServerException if called when not in single-user mode
923 static function singleUser()
925 if (common_config('singleuser', 'enabled')) {
929 $nickname = common_config('singleuser', 'nickname');
931 if (!empty($nickname)) {
932 $user = User::staticGet('nickname', $nickname);
935 // if there was no nickname or no user by that nickname,
936 // try the site owner.
939 $user = User::siteOwner();
945 // TRANS: Server exception.
946 throw new ServerException(_('No single user defined for single-user mode.'));
949 // TRANS: Server exception.
950 throw new ServerException(_('Single-user mode code called when not enabled.'));
955 * This is kind of a hack for using external setup code that's trying to
956 * build single-user sites.
958 * Will still return a username if the config singleuser/nickname is set
959 * even if the account doesn't exist, which normally indicates that the
960 * site is horribly misconfigured.
962 * At the moment, we need to let it through so that router setup can
963 * complete, otherwise we won't be able to create the account.
965 * This will be easier when we can more easily create the account and
966 * *then* switch the site to 1user mode without jumping through hoops.
969 * @throws ServerException if no valid single user account is present
970 * @throws ServerException if called when not in single-user mode
972 static function singleUserNickname()
975 $user = User::singleUser();
976 return $user->nickname;
977 } catch (Exception $e) {
978 if (common_config('singleuser', 'enabled') && common_config('singleuser', 'nickname')) {
979 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.");
980 return common_config('singleuser', 'nickname');
987 * Find and shorten links in the given text using this user's URL shortening
990 * By default, links will be left untouched if the text is shorter than the
991 * configured maximum notice length. Pass true for the $always parameter
992 * to force all links to be shortened regardless.
994 * Side effects: may save file and file_redirection records for referenced URLs.
996 * @param string $text
997 * @param boolean $always
1000 public function shortenLinks($text, $always=false)
1002 return common_shorten_links($text, $always, $this);
1006 * Get a list of OAuth client applications that have access to this
1009 function getConnectedApps($offset = 0, $limit = null)
1013 'FROM oauth_application_user u, oauth_application a ' .
1014 'WHERE u.profile_id = %d ' .
1015 'AND a.id = u.application_id ' .
1016 'AND u.access_type > 0 ' .
1017 'ORDER BY u.created DESC ';
1020 if (common_config('db','type') == 'pgsql') {
1021 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
1023 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
1027 $apps = new Oauth_application_user();
1029 $cnt = $apps->query(sprintf($qry, $this->id));