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 $jabber; // varchar(255) unique_key
52 public $jabbernotify; // tinyint(1)
53 public $jabberreplies; // tinyint(1)
54 public $jabbermicroid; // tinyint(1) default_1
55 public $updatefrompresence; // tinyint(1)
56 public $sms; // varchar(64) unique_key
57 public $carrier; // int(4)
58 public $smsnotify; // tinyint(1)
59 public $smsreplies; // tinyint(1)
60 public $smsemail; // varchar(255)
61 public $uri; // varchar(255) unique_key
62 public $autosubscribe; // tinyint(1)
63 public $urlshorteningservice; // varchar(50) default_ur1.ca
64 public $inboxed; // tinyint(1)
65 public $design_id; // int(4)
66 public $viewdesigns; // tinyint(1) default_1
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 */
78 $profile = Profile::staticGet('id', $this->id);
79 if (empty($profile)) {
80 throw new UserNoProfileException($this);
85 function isSubscribed($other)
87 $profile = $this->getProfile();
88 return $profile->isSubscribed($other);
91 // 'update' won't write key columns, so we have to do it ourselves.
93 function updateKeys(&$orig)
97 foreach (array('nickname', 'email', 'jabber', 'incomingemail', 'sms', 'carrier', 'smsemail', 'language', 'timezone') as $k) {
98 if (strcmp($this->$k, $orig->$k) != 0) {
99 $parts[] = $k . ' = ' . $this->_quote($this->$k);
102 if (count($parts) == 0) {
106 $toupdate = implode(', ', $parts);
108 $table = common_database_tablename($this->tableName());
109 $qry = 'UPDATE ' . $table . ' SET ' . $toupdate .
110 ' WHERE id = ' . $this->id;
112 $result = $this->query($qry);
120 * Check whether the given nickname is potentially usable, or if it's
121 * excluded by any blacklists on this system.
123 * WARNING: INPUT IS NOT VALIDATED OR NORMALIZED. NON-NORMALIZED INPUT
124 * OR INVALID INPUT MAY LEAD TO FALSE RESULTS.
126 * @param string $nickname
127 * @return boolean true if clear, false if blacklisted
129 static function allowed_nickname($nickname)
131 // XXX: should already be validated for size, content, etc.
132 $blacklist = common_config('nickname', 'blacklist');
134 //all directory and file names should be blacklisted
135 $d = dir(INSTALLDIR);
136 while (false !== ($entry = $d->read())) {
141 //all top level names in the router should be blacklisted
142 $router = Router::get();
143 foreach(array_keys($router->m->getPaths()) as $path){
144 if(preg_match('/^\/(.*?)[\/\?]/',$path,$matches)){
145 $blacklist[]=$matches[1];
148 return !in_array($nickname, $blacklist);
152 * Get the most recent notice posted by this user, if any.
154 * @return mixed Notice or null
156 function getCurrentNotice()
158 $profile = $this->getProfile();
159 return $profile->getCurrentNotice();
162 function getCarrier()
164 return Sms_carrier::staticGet('id', $this->carrier);
168 * @deprecated use Subscription::start($sub, $other);
170 function subscribeTo($other)
172 return Subscription::start($this->getProfile(), $other);
175 function hasBlocked($other)
177 $profile = $this->getProfile();
178 return $profile->hasBlocked($other);
182 * Register a new user account and profile and set up default subscriptions.
183 * If a new-user welcome message is configured, this will be sent.
185 * @param array $fields associative array of optional properties
188 * bool 'email_confirmed' pass true to mark email as pre-confirmed
191 * string 'location' informal string description of geolocation
192 * float 'lat' decimal latitude for geolocation
193 * float 'lon' decimal longitude for geolocation
194 * int 'location_id' geoname identifier
195 * int 'location_ns' geoname namespace to interpret location_id
196 * string 'nickname' REQUIRED
197 * string 'password' (may be missing for eg OpenID registrations)
198 * string 'code' invite code
199 * ?string 'uri' permalink to notice; defaults to local notice URL
200 * @return mixed User object or false on failure
202 static function register($fields) {
204 // MAGICALLY put fields into current scope
208 $profile = new Profile();
212 $email = common_canonical_email($email);
215 $nickname = common_canonical_nickname($nickname);
216 $profile->nickname = $nickname;
217 if(! User::allowed_nickname($nickname)){
218 common_log(LOG_WARNING, sprintf("Attempted to register a nickname that is not allowed: %s", $profile->nickname),
222 $profile->profileurl = common_profile_url($nickname);
224 if (!empty($fullname)) {
225 $profile->fullname = $fullname;
227 if (!empty($homepage)) {
228 $profile->homepage = $homepage;
231 $profile->bio = $bio;
233 if (!empty($location)) {
234 $profile->location = $location;
236 $loc = Location::fromName($location);
239 $profile->lat = $loc->lat;
240 $profile->lon = $loc->lon;
241 $profile->location_id = $loc->location_id;
242 $profile->location_ns = $loc->location_ns;
246 $profile->created = common_sql_now();
250 $user->nickname = $nickname;
252 // Users who respond to invite email have proven their ownership of that address
255 $invite = Invitation::staticGet($code);
256 if ($invite && $invite->address && $invite->address_type == 'email' && $invite->address == $email) {
257 $user->email = $invite->address;
261 if(isset($email_confirmed) && $email_confirmed) {
262 $user->email = $email;
265 // This flag is ignored but still set to 1
269 // Set default-on options here, otherwise they'll be disabled
270 // initially for sites using caching, since the initial encache
271 // doesn't know about the defaults in the database.
272 $user->emailnotifysub = 1;
273 $user->emailnotifyfav = 1;
274 $user->emailnotifynudge = 1;
275 $user->emailnotifymsg = 1;
276 $user->emailnotifyattn = 1;
277 $user->emailmicroid = 1;
278 $user->emailpost = 1;
279 $user->jabbermicroid = 1;
280 $user->viewdesigns = 1;
282 $user->created = common_sql_now();
284 if (Event::handle('StartUserRegister', array(&$user, &$profile))) {
286 $profile->query('BEGIN');
288 $id = $profile->insert();
291 common_log_db_error($profile, 'INSERT', __FILE__);
300 $user->uri = common_user_uri($user);
303 if (!empty($password)) { // may not have a password for OpenID users
304 $user->password = common_munge_password($password, $id);
307 $result = $user->insert();
310 common_log_db_error($user, 'INSERT', __FILE__);
314 // Everyone gets an inbox
316 $inbox = new Inbox();
318 $inbox->user_id = $user->id;
319 $inbox->notice_ids = '';
321 $result = $inbox->insert();
324 common_log_db_error($inbox, 'INSERT', __FILE__);
328 // Everyone is subscribed to themself
330 $subscription = new Subscription();
331 $subscription->subscriber = $user->id;
332 $subscription->subscribed = $user->id;
333 $subscription->created = $user->created;
335 $result = $subscription->insert();
338 common_log_db_error($subscription, 'INSERT', __FILE__);
342 if (!empty($email) && !$user->email) {
344 $confirm = new Confirm_address();
345 $confirm->code = common_confirmation_code(128);
346 $confirm->user_id = $user->id;
347 $confirm->address = $email;
348 $confirm->address_type = 'email';
350 $result = $confirm->insert();
353 common_log_db_error($confirm, 'INSERT', __FILE__);
358 if (!empty($code) && $user->email) {
359 $user->emailChanged();
362 // Default system subscription
364 $defnick = common_config('newuser', 'default');
366 if (!empty($defnick)) {
367 $defuser = User::staticGet('nickname', $defnick);
368 if (empty($defuser)) {
369 common_log(LOG_WARNING, sprintf("Default user %s does not exist.", $defnick),
372 Subscription::start($user, $defuser);
376 $profile->query('COMMIT');
378 if (!empty($email) && !$user->email) {
379 mail_confirm_address($user, $confirm->code, $profile->nickname, $email);
384 $welcome = common_config('newuser', 'welcome');
386 if (!empty($welcome)) {
387 $welcomeuser = User::staticGet('nickname', $welcome);
388 if (empty($welcomeuser)) {
389 common_log(LOG_WARNING, sprintf("Welcome user %s does not exist.", $defnick),
392 $notice = Notice::saveNew($welcomeuser->id,
393 // TRANS: Notice given on user registration.
394 // TRANS: %1$s is the sitename, $2$s is the registering user's nickname.
395 sprintf(_('Welcome to %1$s, @%2$s!'),
396 common_config('site', 'name'),
402 Event::handle('EndUserRegister', array(&$profile, &$user));
408 // Things we do when the email changes
409 function emailChanged()
412 $invites = new Invitation();
413 $invites->address = $this->email;
414 $invites->address_type = 'email';
416 if ($invites->find()) {
417 while ($invites->fetch()) {
418 $other = User::staticGet($invites->user_id);
419 subs_subscribe_to($other, $this);
424 function hasFave($notice)
426 $profile = $this->getProfile();
427 return $profile->hasFave($notice);
430 function mutuallySubscribed($other)
432 $profile = $this->getProfile();
433 return $profile->mutuallySubscribed($other);
436 function mutuallySubscribedUsers()
438 // 3-way join; probably should get cached
439 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
440 $qry = "SELECT $UT.* " .
441 "FROM subscription sub1 JOIN $UT ON sub1.subscribed = $UT.id " .
442 "JOIN subscription sub2 ON $UT.id = sub2.subscriber " .
443 'WHERE sub1.subscriber = %d and sub2.subscribed = %d ' .
444 "ORDER BY $UT.nickname";
446 $user->query(sprintf($qry, $this->id, $this->id));
451 function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
453 $ids = Reply::stream($this->id, $offset, $limit, $since_id, $before_id);
454 return Notice::getStreamByIds($ids);
457 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0) {
458 $profile = $this->getProfile();
459 return $profile->getTaggedNotices($tag, $offset, $limit, $since_id, $before_id);
462 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
464 $profile = $this->getProfile();
465 return $profile->getNotices($offset, $limit, $since_id, $before_id);
468 function favoriteNotices($own=false, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
470 $ids = Fave::stream($this->id, $offset, $limit, $own, $since_id, $max_id);
471 return Notice::getStreamByIds($ids);
474 function noticesWithFriends($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
476 return Inbox::streamNotices($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 friendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
486 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, false);
489 function ownFriendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
491 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, true);
494 function blowFavesCache()
496 $profile = $this->getProfile();
497 $profile->blowFavesCache();
500 function getSelfTags()
502 return Profile_tag::getTags($this->id, $this->id);
505 function setSelfTags($newtags)
507 return Profile_tag::setTags($this->id, $this->id, $newtags);
510 function block($other)
512 // Add a new block record
514 // no blocking (and thus unsubbing from) yourself
516 if ($this->id == $other->id) {
517 common_log(LOG_WARNING,
519 "Profile ID %d (%s) tried to block themself.",
527 $block = new Profile_block();
529 // Begin a transaction
531 $block->query('BEGIN');
533 $block->blocker = $this->id;
534 $block->blocked = $other->id;
536 $result = $block->insert();
539 common_log_db_error($block, 'INSERT', __FILE__);
543 $self = $this->getProfile();
544 if (Subscription::exists($other, $self)) {
545 Subscription::cancel($other, $self);
547 if (Subscription::exists($self, $other)) {
548 Subscription::cancel($self, $other);
551 $block->query('COMMIT');
556 function unblock($other)
558 // Get the block record
560 $block = Profile_block::get($this->id, $other->id);
566 $result = $block->delete();
569 common_log_db_error($block, 'DELETE', __FILE__);
576 function isMember($group)
578 $profile = $this->getProfile();
579 return $profile->isMember($group);
582 function isAdmin($group)
584 $profile = $this->getProfile();
585 return $profile->isAdmin($group);
588 function getGroups($offset=0, $limit=null)
590 $profile = $this->getProfile();
591 return $profile->getGroups($offset, $limit);
594 function getSubscriptions($offset=0, $limit=null)
596 $profile = $this->getProfile();
597 return $profile->getSubscriptions($offset, $limit);
600 function getSubscribers($offset=0, $limit=null)
602 $profile = $this->getProfile();
603 return $profile->getSubscribers($offset, $limit);
606 function getTaggedSubscribers($tag, $offset=0, $limit=null)
609 'SELECT profile.* ' .
610 'FROM profile JOIN subscription ' .
611 'ON profile.id = subscription.subscriber ' .
612 'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
613 'AND profile_tag.tagger = subscription.subscribed) ' .
614 'WHERE subscription.subscribed = %d ' .
615 "AND profile_tag.tag = '%s' " .
616 'AND subscription.subscribed != subscription.subscriber ' .
617 'ORDER BY subscription.created DESC ';
620 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
623 $profile = new Profile();
625 $cnt = $profile->query(sprintf($qry, $this->id, $tag));
630 function getTaggedSubscriptions($tag, $offset=0, $limit=null)
633 'SELECT profile.* ' .
634 'FROM profile JOIN subscription ' .
635 'ON profile.id = subscription.subscribed ' .
636 'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
637 'AND profile_tag.tagger = subscription.subscriber) ' .
638 'WHERE subscription.subscriber = %d ' .
639 "AND profile_tag.tag = '%s' " .
640 'AND subscription.subscribed != subscription.subscriber ' .
641 'ORDER BY subscription.created DESC ';
643 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
645 $profile = new Profile();
647 $profile->query(sprintf($qry, $this->id, $tag));
654 return Design::staticGet('id', $this->design_id);
657 function hasRight($right)
659 $profile = $this->getProfile();
660 return $profile->hasRight($right);
666 $profile = $this->getProfile();
668 } catch (UserNoProfileException $unp) {
669 common_log(LOG_INFO, "User {$this->nickname} has no profile; continuing deletion.");
672 $related = array('Fave',
679 Event::handle('UserDeleteRelated', array($this, &$related));
681 foreach ($related as $cls) {
683 $inst->user_id = $this->id;
687 $this->_deleteTags();
688 $this->_deleteBlocks();
693 function _deleteTags()
695 $tag = new Profile_tag();
696 $tag->tagger = $this->id;
700 function _deleteBlocks()
702 $block = new Profile_block();
703 $block->blocker = $this->id;
705 // XXX delete group block? Reset blocker?
708 function hasRole($name)
710 $profile = $this->getProfile();
711 return $profile->hasRole($name);
714 function grantRole($name)
716 $profile = $this->getProfile();
717 return $profile->grantRole($name);
720 function revokeRole($name)
722 $profile = $this->getProfile();
723 return $profile->revokeRole($name);
726 function isSandboxed()
728 $profile = $this->getProfile();
729 return $profile->isSandboxed();
732 function isSilenced()
734 $profile = $this->getProfile();
735 return $profile->isSilenced();
738 function repeatedByMe($offset=0, $limit=20, $since_id=null, $max_id=null)
740 $ids = Notice::stream(array($this, '_repeatedByMeDirect'),
742 'user:repeated_by_me:'.$this->id,
743 $offset, $limit, $since_id, $max_id, null);
745 return Notice::getStreamByIds($ids);
748 function _repeatedByMeDirect($offset, $limit, $since_id, $max_id)
750 $notice = new Notice();
752 $notice->selectAdd(); // clears it
753 $notice->selectAdd('id');
755 $notice->profile_id = $this->id;
756 $notice->whereAdd('repeat_of IS NOT NULL');
758 $notice->orderBy('created DESC, id DESC');
760 if (!is_null($offset)) {
761 $notice->limit($offset, $limit);
764 Notice::addWhereSinceId($notice, $since_id);
765 Notice::addWhereMaxId($notice, $max_id);
769 if ($notice->find()) {
770 while ($notice->fetch()) {
771 $ids[] = $notice->id;
781 function repeatsOfMe($offset=0, $limit=20, $since_id=null, $max_id=null)
783 $ids = Notice::stream(array($this, '_repeatsOfMeDirect'),
785 'user:repeats_of_me:'.$this->id,
786 $offset, $limit, $since_id, $max_id);
788 return Notice::getStreamByIds($ids);
791 function _repeatsOfMeDirect($offset, $limit, $since_id, $max_id)
794 'SELECT DISTINCT original.id AS id ' .
795 'FROM notice original JOIN notice rept ON original.id = rept.repeat_of ' .
796 'WHERE original.profile_id = ' . $this->id . ' ';
798 $since = Notice::whereSinceId($since_id, 'original.id', 'original.created');
800 $qry .= "AND ($since) ";
803 $max = Notice::whereMaxId($max_id, 'original.id', 'original.created');
805 $qry .= "AND ($max) ";
808 $qry .= 'ORDER BY original.created, original.id DESC ';
810 if (!is_null($offset)) {
811 $qry .= "LIMIT $limit OFFSET $offset";
816 $notice = new Notice();
818 $notice->query($qry);
820 while ($notice->fetch()) {
821 $ids[] = $notice->id;
830 function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
832 throw new Exception("Not implemented since inbox change.");
835 function shareLocation()
837 $cfg = common_config('location', 'share');
839 if ($cfg == 'always') {
841 } else if ($cfg == 'never') {
846 $prefs = User_location_prefs::staticGet('user_id', $this->id);
849 $share = common_config('location', 'sharedefault');
851 $share = $prefs->share_location;
859 static function siteOwner()
861 $owner = self::cacheGet('user:site_owner');
863 if ($owner === false) { // cache miss
865 $pr = new Profile_role();
867 $pr->role = Profile_role::OWNER;
869 $pr->orderBy('created');
873 if ($pr->find(true)) {
874 $owner = User::staticGet('id', $pr->profile_id);
879 self::cacheSet('user:site_owner', $owner);
886 * Pull the primary site account to use in single-user mode.
887 * If a valid user nickname is listed in 'singleuser':'nickname'
888 * in the config, this will be used; otherwise the site owner
889 * account is taken by default.
892 * @throws ServerException if no valid single user account is present
893 * @throws ServerException if called when not in single-user mode
895 static function singleUser()
897 if (common_config('singleuser', 'enabled')) {
901 $nickname = common_config('singleuser', 'nickname');
903 if (!empty($nickname)) {
904 $user = User::staticGet('nickname', $nickname);
907 // if there was no nickname or no user by that nickname,
908 // try the site owner.
911 $user = User::siteOwner();
917 // TRANS: Server exception.
918 throw new ServerException(_('No single user defined for single-user mode.'));
921 // TRANS: Server exception.
922 throw new ServerException(_('Single-user mode code called when not enabled.'));
927 * This is kind of a hack for using external setup code that's trying to
928 * build single-user sites.
930 * Will still return a username if the config singleuser/nickname is set
931 * even if the account doesn't exist, which normally indicates that the
932 * site is horribly misconfigured.
934 * At the moment, we need to let it through so that router setup can
935 * complete, otherwise we won't be able to create the account.
937 * This will be easier when we can more easily create the account and
938 * *then* switch the site to 1user mode without jumping through hoops.
941 * @throws ServerException if no valid single user account is present
942 * @throws ServerException if called when not in single-user mode
944 static function singleUserNickname()
947 $user = User::singleUser();
948 return $user->nickname;
949 } catch (Exception $e) {
950 if (common_config('singleuser', 'enabled') && common_config('singleuser', 'nickname')) {
951 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.");
952 return common_config('singleuser', 'nickname');
959 * Find and shorten links in the given text using this user's URL shortening
962 * By default, links will be left untouched if the text is shorter than the
963 * configured maximum notice length. Pass true for the $always parameter
964 * to force all links to be shortened regardless.
966 * Side effects: may save file and file_redirection records for referenced URLs.
968 * @param string $text
969 * @param boolean $always
972 public function shortenLinks($text, $always=false)
974 return common_shorten_links($text, $always, $this);
978 * Get a list of OAuth client application that have access to this
981 function getConnectedApps($offset = 0, $limit = null)
985 'FROM oauth_application_user u, oauth_application a ' .
986 'WHERE u.profile_id = %d ' .
987 'AND a.id = u.application_id ' .
988 'AND u.access_type > 0 ' .
989 'ORDER BY u.created DESC ';
992 if (common_config('db','type') == 'pgsql') {
993 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
995 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
999 $apps = new Oauth_application_user();
1001 $cnt = $apps->query(sprintf($qry, $this->id));