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 */
73 $profile = Profile::staticGet('id', $this->id);
74 if (empty($profile)) {
75 throw new UserNoProfileException($this);
80 function isSubscribed($other)
82 $profile = $this->getProfile();
83 return $profile->isSubscribed($other);
86 // 'update' won't write key columns, so we have to do it ourselves.
88 function updateKeys(&$orig)
92 foreach (array('nickname', 'email', 'incomingemail', 'sms', 'carrier', 'smsemail', 'language', 'timezone') as $k) {
93 if (strcmp($this->$k, $orig->$k) != 0) {
94 $parts[] = $k . ' = ' . $this->_quote($this->$k);
97 if (count($parts) == 0) {
101 $toupdate = implode(', ', $parts);
103 $table = common_database_tablename($this->tableName());
104 $qry = 'UPDATE ' . $table . ' SET ' . $toupdate .
105 ' WHERE id = ' . $this->id;
107 $result = $this->query($qry);
115 * Check whether the given nickname is potentially usable, or if it's
116 * excluded by any blacklists on this system.
118 * WARNING: INPUT IS NOT VALIDATED OR NORMALIZED. NON-NORMALIZED INPUT
119 * OR INVALID INPUT MAY LEAD TO FALSE RESULTS.
121 * @param string $nickname
122 * @return boolean true if clear, false if blacklisted
124 static function allowed_nickname($nickname)
126 // XXX: should already be validated for size, content, etc.
127 $blacklist = common_config('nickname', 'blacklist');
129 //all directory and file names should be blacklisted
130 $d = dir(INSTALLDIR);
131 while (false !== ($entry = $d->read())) {
136 //all top level names in the router should be blacklisted
137 $router = Router::get();
138 foreach(array_keys($router->m->getPaths()) as $path){
139 if(preg_match('/^\/(.*?)[\/\?]/',$path,$matches)){
140 $blacklist[]=$matches[1];
143 return !in_array($nickname, $blacklist);
147 * Get the most recent notice posted by this user, if any.
149 * @return mixed Notice or null
151 function getCurrentNotice()
153 $profile = $this->getProfile();
154 return $profile->getCurrentNotice();
157 function getCarrier()
159 return Sms_carrier::staticGet('id', $this->carrier);
163 * @deprecated use Subscription::start($sub, $other);
165 function subscribeTo($other)
167 return Subscription::start($this->getProfile(), $other);
170 function hasBlocked($other)
172 $profile = $this->getProfile();
173 return $profile->hasBlocked($other);
177 * Register a new user account and profile and set up default subscriptions.
178 * If a new-user welcome message is configured, this will be sent.
180 * @param array $fields associative array of optional properties
183 * bool 'email_confirmed' pass true to mark email as pre-confirmed
186 * string 'location' informal string description of geolocation
187 * float 'lat' decimal latitude for geolocation
188 * float 'lon' decimal longitude for geolocation
189 * int 'location_id' geoname identifier
190 * int 'location_ns' geoname namespace to interpret location_id
191 * string 'nickname' REQUIRED
192 * string 'password' (may be missing for eg OpenID registrations)
193 * string 'code' invite code
194 * ?string 'uri' permalink to notice; defaults to local notice URL
195 * @return mixed User object or false on failure
197 static function register($fields) {
199 // MAGICALLY put fields into current scope
203 $profile = new Profile();
207 $email = common_canonical_email($email);
210 $nickname = common_canonical_nickname($nickname);
211 $profile->nickname = $nickname;
212 if(! User::allowed_nickname($nickname)){
213 common_log(LOG_WARNING, sprintf("Attempted to register a nickname that is not allowed: %s", $profile->nickname),
217 $profile->profileurl = common_profile_url($nickname);
219 if (!empty($fullname)) {
220 $profile->fullname = $fullname;
222 if (!empty($homepage)) {
223 $profile->homepage = $homepage;
226 $profile->bio = $bio;
228 if (!empty($location)) {
229 $profile->location = $location;
231 $loc = Location::fromName($location);
234 $profile->lat = $loc->lat;
235 $profile->lon = $loc->lon;
236 $profile->location_id = $loc->location_id;
237 $profile->location_ns = $loc->location_ns;
241 $profile->created = common_sql_now();
245 $user->nickname = $nickname;
247 // Users who respond to invite email have proven their ownership of that address
250 $invite = Invitation::staticGet($code);
251 if ($invite && $invite->address && $invite->address_type == 'email' && $invite->address == $email) {
252 $user->email = $invite->address;
256 if(isset($email_confirmed) && $email_confirmed) {
257 $user->email = $email;
260 // This flag is ignored but still set to 1
264 // Set default-on options here, otherwise they'll be disabled
265 // initially for sites using caching, since the initial encache
266 // doesn't know about the defaults in the database.
267 $user->emailnotifysub = 1;
268 $user->emailnotifyfav = 1;
269 $user->emailnotifynudge = 1;
270 $user->emailnotifymsg = 1;
271 $user->emailnotifyattn = 1;
272 $user->emailmicroid = 1;
273 $user->emailpost = 1;
274 $user->jabbermicroid = 1;
275 $user->viewdesigns = 1;
277 $user->created = common_sql_now();
279 if (Event::handle('StartUserRegister', array(&$user, &$profile))) {
281 $profile->query('BEGIN');
283 $id = $profile->insert();
286 common_log_db_error($profile, 'INSERT', __FILE__);
295 $user->uri = common_user_uri($user);
298 if (!empty($password)) { // may not have a password for OpenID users
299 $user->password = common_munge_password($password, $id);
302 $result = $user->insert();
305 common_log_db_error($user, 'INSERT', __FILE__);
309 // Everyone gets an inbox
311 $inbox = new Inbox();
313 $inbox->user_id = $user->id;
314 $inbox->notice_ids = '';
316 $result = $inbox->insert();
319 common_log_db_error($inbox, 'INSERT', __FILE__);
323 // Everyone is subscribed to themself
325 $subscription = new Subscription();
326 $subscription->subscriber = $user->id;
327 $subscription->subscribed = $user->id;
328 $subscription->created = $user->created;
330 $result = $subscription->insert();
333 common_log_db_error($subscription, 'INSERT', __FILE__);
337 if (!empty($email) && !$user->email) {
339 $confirm = new Confirm_address();
340 $confirm->code = common_confirmation_code(128);
341 $confirm->user_id = $user->id;
342 $confirm->address = $email;
343 $confirm->address_type = 'email';
345 $result = $confirm->insert();
348 common_log_db_error($confirm, 'INSERT', __FILE__);
353 if (!empty($code) && $user->email) {
354 $user->emailChanged();
357 // Default system subscription
359 $defnick = common_config('newuser', 'default');
361 if (!empty($defnick)) {
362 $defuser = User::staticGet('nickname', $defnick);
363 if (empty($defuser)) {
364 common_log(LOG_WARNING, sprintf("Default user %s does not exist.", $defnick),
367 Subscription::start($user, $defuser);
371 $profile->query('COMMIT');
373 if (!empty($email) && !$user->email) {
374 mail_confirm_address($user, $confirm->code, $profile->nickname, $email);
379 $welcome = common_config('newuser', 'welcome');
381 if (!empty($welcome)) {
382 $welcomeuser = User::staticGet('nickname', $welcome);
383 if (empty($welcomeuser)) {
384 common_log(LOG_WARNING, sprintf("Welcome user %s does not exist.", $defnick),
387 $notice = Notice::saveNew($welcomeuser->id,
388 // TRANS: Notice given on user registration.
389 // TRANS: %1$s is the sitename, $2$s is the registering user's nickname.
390 sprintf(_('Welcome to %1$s, @%2$s!'),
391 common_config('site', 'name'),
397 Event::handle('EndUserRegister', array(&$profile, &$user));
403 // Things we do when the email changes
404 function emailChanged()
407 $invites = new Invitation();
408 $invites->address = $this->email;
409 $invites->address_type = 'email';
411 if ($invites->find()) {
412 while ($invites->fetch()) {
413 $other = User::staticGet($invites->user_id);
414 subs_subscribe_to($other, $this);
419 function hasFave($notice)
421 $profile = $this->getProfile();
422 return $profile->hasFave($notice);
425 function mutuallySubscribed($other)
427 $profile = $this->getProfile();
428 return $profile->mutuallySubscribed($other);
431 function mutuallySubscribedUsers()
433 // 3-way join; probably should get cached
434 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
435 $qry = "SELECT $UT.* " .
436 "FROM subscription sub1 JOIN $UT ON sub1.subscribed = $UT.id " .
437 "JOIN subscription sub2 ON $UT.id = sub2.subscriber " .
438 'WHERE sub1.subscriber = %d and sub2.subscribed = %d ' .
439 "ORDER BY $UT.nickname";
441 $user->query(sprintf($qry, $this->id, $this->id));
446 function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
448 $ids = Reply::stream($this->id, $offset, $limit, $since_id, $before_id);
449 return Notice::getStreamByIds($ids);
452 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0) {
453 $profile = $this->getProfile();
454 return $profile->getTaggedNotices($tag, $offset, $limit, $since_id, $before_id);
457 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
459 $profile = $this->getProfile();
460 return $profile->getNotices($offset, $limit, $since_id, $before_id);
463 function favoriteNotices($own=false, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
465 $ids = Fave::stream($this->id, $offset, $limit, $own, $since_id, $max_id);
466 return Notice::getStreamByIds($ids);
469 function noticesWithFriends($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
471 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, false);
474 function noticesWithFriendsThreaded($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
476 return Inbox::streamNoticesThreaded($this->id, $offset, $limit, $since_id, $before_id, false);
479 function noticeInbox($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
481 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, true);
484 function noticeInboxThreaded($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
486 return Inbox::streamNoticesThreaded($this->id, $offset, $limit, $since_id, $before_id, true);
489 function friendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
491 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, false);
494 function ownFriendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
496 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, true);
499 function blowFavesCache()
501 $profile = $this->getProfile();
502 $profile->blowFavesCache();
505 function getSelfTags()
507 return Profile_tag::getTags($this->id, $this->id);
510 function setSelfTags($newtags)
512 return Profile_tag::setTags($this->id, $this->id, $newtags);
515 function block($other)
517 // Add a new block record
519 // no blocking (and thus unsubbing from) yourself
521 if ($this->id == $other->id) {
522 common_log(LOG_WARNING,
524 "Profile ID %d (%s) tried to block themself.",
532 $block = new Profile_block();
534 // Begin a transaction
536 $block->query('BEGIN');
538 $block->blocker = $this->id;
539 $block->blocked = $other->id;
541 $result = $block->insert();
544 common_log_db_error($block, 'INSERT', __FILE__);
548 $self = $this->getProfile();
549 if (Subscription::exists($other, $self)) {
550 Subscription::cancel($other, $self);
552 if (Subscription::exists($self, $other)) {
553 Subscription::cancel($self, $other);
556 $block->query('COMMIT');
561 function unblock($other)
563 // Get the block record
565 $block = Profile_block::get($this->id, $other->id);
571 $result = $block->delete();
574 common_log_db_error($block, 'DELETE', __FILE__);
581 function isMember($group)
583 $profile = $this->getProfile();
584 return $profile->isMember($group);
587 function isAdmin($group)
589 $profile = $this->getProfile();
590 return $profile->isAdmin($group);
593 function getGroups($offset=0, $limit=null)
595 $profile = $this->getProfile();
596 return $profile->getGroups($offset, $limit);
599 function getSubscriptions($offset=0, $limit=null)
601 $profile = $this->getProfile();
602 return $profile->getSubscriptions($offset, $limit);
605 function getSubscribers($offset=0, $limit=null)
607 $profile = $this->getProfile();
608 return $profile->getSubscribers($offset, $limit);
611 function getTaggedSubscribers($tag, $offset=0, $limit=null)
614 'SELECT profile.* ' .
615 'FROM profile JOIN subscription ' .
616 'ON profile.id = subscription.subscriber ' .
617 'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
618 'AND profile_tag.tagger = subscription.subscribed) ' .
619 'WHERE subscription.subscribed = %d ' .
620 "AND profile_tag.tag = '%s' " .
621 'AND subscription.subscribed != subscription.subscriber ' .
622 'ORDER BY subscription.created DESC ';
625 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
628 $profile = new Profile();
630 $cnt = $profile->query(sprintf($qry, $this->id, $tag));
635 function getTaggedSubscriptions($tag, $offset=0, $limit=null)
638 'SELECT profile.* ' .
639 'FROM profile JOIN subscription ' .
640 'ON profile.id = subscription.subscribed ' .
641 'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
642 'AND profile_tag.tagger = subscription.subscriber) ' .
643 'WHERE subscription.subscriber = %d ' .
644 "AND profile_tag.tag = '%s' " .
645 'AND subscription.subscribed != subscription.subscriber ' .
646 'ORDER BY subscription.created DESC ';
648 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
650 $profile = new Profile();
652 $profile->query(sprintf($qry, $this->id, $tag));
659 return Design::staticGet('id', $this->design_id);
662 function hasRight($right)
664 $profile = $this->getProfile();
665 return $profile->hasRight($right);
671 $profile = $this->getProfile();
673 } catch (UserNoProfileException $unp) {
674 common_log(LOG_INFO, "User {$this->nickname} has no profile; continuing deletion.");
677 $related = array('Fave',
684 Event::handle('UserDeleteRelated', array($this, &$related));
686 foreach ($related as $cls) {
688 $inst->user_id = $this->id;
692 $this->_deleteTags();
693 $this->_deleteBlocks();
698 function _deleteTags()
700 $tag = new Profile_tag();
701 $tag->tagger = $this->id;
705 function _deleteBlocks()
707 $block = new Profile_block();
708 $block->blocker = $this->id;
710 // XXX delete group block? Reset blocker?
713 function hasRole($name)
715 $profile = $this->getProfile();
716 return $profile->hasRole($name);
719 function grantRole($name)
721 $profile = $this->getProfile();
722 return $profile->grantRole($name);
725 function revokeRole($name)
727 $profile = $this->getProfile();
728 return $profile->revokeRole($name);
731 function isSandboxed()
733 $profile = $this->getProfile();
734 return $profile->isSandboxed();
737 function isSilenced()
739 $profile = $this->getProfile();
740 return $profile->isSilenced();
743 function repeatedByMe($offset=0, $limit=20, $since_id=null, $max_id=null)
745 $ids = Notice::stream(array($this, '_repeatedByMeDirect'),
747 'user:repeated_by_me:'.$this->id,
748 $offset, $limit, $since_id, $max_id, null);
750 return Notice::getStreamByIds($ids);
753 function _repeatedByMeDirect($offset, $limit, $since_id, $max_id)
755 $notice = new Notice();
757 $notice->selectAdd(); // clears it
758 $notice->selectAdd('id');
760 $notice->profile_id = $this->id;
761 $notice->whereAdd('repeat_of IS NOT NULL');
763 $notice->orderBy('created DESC, id DESC');
765 if (!is_null($offset)) {
766 $notice->limit($offset, $limit);
769 Notice::addWhereSinceId($notice, $since_id);
770 Notice::addWhereMaxId($notice, $max_id);
774 if ($notice->find()) {
775 while ($notice->fetch()) {
776 $ids[] = $notice->id;
786 function repeatsOfMe($offset=0, $limit=20, $since_id=null, $max_id=null)
788 $ids = Notice::stream(array($this, '_repeatsOfMeDirect'),
790 'user:repeats_of_me:'.$this->id,
791 $offset, $limit, $since_id, $max_id);
793 return Notice::getStreamByIds($ids);
796 function _repeatsOfMeDirect($offset, $limit, $since_id, $max_id)
799 'SELECT DISTINCT original.id AS id ' .
800 'FROM notice original JOIN notice rept ON original.id = rept.repeat_of ' .
801 'WHERE original.profile_id = ' . $this->id . ' ';
803 $since = Notice::whereSinceId($since_id, 'original.id', 'original.created');
805 $qry .= "AND ($since) ";
808 $max = Notice::whereMaxId($max_id, 'original.id', 'original.created');
810 $qry .= "AND ($max) ";
813 $qry .= 'ORDER BY original.created, original.id DESC ';
815 if (!is_null($offset)) {
816 $qry .= "LIMIT $limit OFFSET $offset";
821 $notice = new Notice();
823 $notice->query($qry);
825 while ($notice->fetch()) {
826 $ids[] = $notice->id;
835 function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
837 throw new Exception("Not implemented since inbox change.");
840 function shareLocation()
842 $cfg = common_config('location', 'share');
844 if ($cfg == 'always') {
846 } else if ($cfg == 'never') {
851 $prefs = User_location_prefs::staticGet('user_id', $this->id);
854 $share = common_config('location', 'sharedefault');
856 $share = $prefs->share_location;
864 static function siteOwner()
866 $owner = self::cacheGet('user:site_owner');
868 if ($owner === false) { // cache miss
870 $pr = new Profile_role();
872 $pr->role = Profile_role::OWNER;
874 $pr->orderBy('created');
878 if ($pr->find(true)) {
879 $owner = User::staticGet('id', $pr->profile_id);
884 self::cacheSet('user:site_owner', $owner);
891 * Pull the primary site account to use in single-user mode.
892 * If a valid user nickname is listed in 'singleuser':'nickname'
893 * in the config, this will be used; otherwise the site owner
894 * account is taken by default.
897 * @throws ServerException if no valid single user account is present
898 * @throws ServerException if called when not in single-user mode
900 static function singleUser()
902 if (common_config('singleuser', 'enabled')) {
906 $nickname = common_config('singleuser', 'nickname');
908 if (!empty($nickname)) {
909 $user = User::staticGet('nickname', $nickname);
912 // if there was no nickname or no user by that nickname,
913 // try the site owner.
916 $user = User::siteOwner();
922 // TRANS: Server exception.
923 throw new ServerException(_('No single user defined for single-user mode.'));
926 // TRANS: Server exception.
927 throw new ServerException(_('Single-user mode code called when not enabled.'));
932 * This is kind of a hack for using external setup code that's trying to
933 * build single-user sites.
935 * Will still return a username if the config singleuser/nickname is set
936 * even if the account doesn't exist, which normally indicates that the
937 * site is horribly misconfigured.
939 * At the moment, we need to let it through so that router setup can
940 * complete, otherwise we won't be able to create the account.
942 * This will be easier when we can more easily create the account and
943 * *then* switch the site to 1user mode without jumping through hoops.
946 * @throws ServerException if no valid single user account is present
947 * @throws ServerException if called when not in single-user mode
949 static function singleUserNickname()
952 $user = User::singleUser();
953 return $user->nickname;
954 } catch (Exception $e) {
955 if (common_config('singleuser', 'enabled') && common_config('singleuser', 'nickname')) {
956 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.");
957 return common_config('singleuser', 'nickname');
964 * Find and shorten links in the given text using this user's URL shortening
967 * By default, links will be left untouched if the text is shorter than the
968 * configured maximum notice length. Pass true for the $always parameter
969 * to force all links to be shortened regardless.
971 * Side effects: may save file and file_redirection records for referenced URLs.
973 * @param string $text
974 * @param boolean $always
977 public function shortenLinks($text, $always=false)
979 return common_shorten_links($text, $always, $this);
983 * Get a list of OAuth client applications that have access to this
986 function getConnectedApps($offset = 0, $limit = null)
990 'FROM oauth_application_user u, oauth_application a ' .
991 'WHERE u.profile_id = %d ' .
992 'AND a.id = u.application_id ' .
993 'AND u.access_type > 0 ' .
994 'ORDER BY u.created DESC ';
997 if (common_config('db','type') == 'pgsql') {
998 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
1000 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
1004 $apps = new Oauth_application_user();
1006 $cnt = $apps->query(sprintf($qry, $this->id));