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 $ids = Reply::stream($this->id, $offset, $limit, $since_id, $before_id);
452 return Notice::getStreamByIds($ids);
455 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0) {
456 $profile = $this->getProfile();
457 return $profile->getTaggedNotices($tag, $offset, $limit, $since_id, $before_id);
460 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
462 $profile = $this->getProfile();
463 return $profile->getNotices($offset, $limit, $since_id, $before_id);
466 function favoriteNotices($own=false, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
468 $ids = Fave::stream($this->id, $offset, $limit, $own, $since_id, $max_id);
469 return Notice::getStreamByIds($ids);
472 function noticesWithFriends($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
474 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, false);
477 function noticesWithFriendsThreaded($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
479 return Inbox::streamNoticesThreaded($this->id, $offset, $limit, $since_id, $before_id, false);
482 function noticeInbox($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
484 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, true);
487 function noticeInboxThreaded($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
489 return Inbox::streamNoticesThreaded($this->id, $offset, $limit, $since_id, $before_id, true);
492 function friendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
494 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, false);
497 function ownFriendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
499 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, true);
502 function blowFavesCache()
504 $profile = $this->getProfile();
505 $profile->blowFavesCache();
508 function getSelfTags()
510 return Profile_tag::getTagsArray($this->id, $this->id, $this->id);
513 function setSelfTags($newtags, $privacy)
515 return Profile_tag::setTags($this->id, $this->id, $newtags, $privacy);
518 function block($other)
520 // Add a new block record
522 // no blocking (and thus unsubbing from) yourself
524 if ($this->id == $other->id) {
525 common_log(LOG_WARNING,
527 "Profile ID %d (%s) tried to block themself.",
535 $block = new Profile_block();
537 // Begin a transaction
539 $block->query('BEGIN');
541 $block->blocker = $this->id;
542 $block->blocked = $other->id;
544 $result = $block->insert();
547 common_log_db_error($block, 'INSERT', __FILE__);
551 $self = $this->getProfile();
552 if (Subscription::exists($other, $self)) {
553 Subscription::cancel($other, $self);
555 if (Subscription::exists($self, $other)) {
556 Subscription::cancel($self, $other);
559 $block->query('COMMIT');
564 function unblock($other)
566 // Get the block record
568 $block = Profile_block::get($this->id, $other->id);
574 $result = $block->delete();
577 common_log_db_error($block, 'DELETE', __FILE__);
584 function isMember($group)
586 $profile = $this->getProfile();
587 return $profile->isMember($group);
590 function isAdmin($group)
592 $profile = $this->getProfile();
593 return $profile->isAdmin($group);
596 function getGroups($offset=0, $limit=null)
598 $profile = $this->getProfile();
599 return $profile->getGroups($offset, $limit);
603 * Request to join the given group.
604 * May throw exceptions on failure.
606 * @param User_group $group
607 * @return Group_member
609 function joinGroup(User_group $group)
611 $profile = $this->getProfile();
612 return $profile->joinGroup($group);
616 * Leave a group that this user is a member of.
618 * @param User_group $group
620 function leaveGroup(User_group $group)
622 $profile = $this->getProfile();
623 return $profile->leaveGroup($group);
626 function getSubscriptions($offset=0, $limit=null)
628 $profile = $this->getProfile();
629 return $profile->getSubscriptions($offset, $limit);
632 function getSubscribers($offset=0, $limit=null)
634 $profile = $this->getProfile();
635 return $profile->getSubscribers($offset, $limit);
638 function getTaggedSubscribers($tag, $offset=0, $limit=null)
641 'SELECT profile.* ' .
642 'FROM profile JOIN subscription ' .
643 'ON profile.id = subscription.subscriber ' .
644 'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
645 'AND profile_tag.tagger = subscription.subscribed) ' .
646 'WHERE subscription.subscribed = %d ' .
647 "AND profile_tag.tag = '%s' " .
648 'AND subscription.subscribed != subscription.subscriber ' .
649 'ORDER BY subscription.created DESC ';
652 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
655 $profile = new Profile();
657 $cnt = $profile->query(sprintf($qry, $this->id, $tag));
662 function getTaggedSubscriptions($tag, $offset=0, $limit=null)
665 'SELECT profile.* ' .
666 'FROM profile JOIN subscription ' .
667 'ON profile.id = subscription.subscribed ' .
668 'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
669 'AND profile_tag.tagger = subscription.subscriber) ' .
670 'WHERE subscription.subscriber = %d ' .
671 "AND profile_tag.tag = '%s' " .
672 'AND subscription.subscribed != subscription.subscriber ' .
673 'ORDER BY subscription.created DESC ';
675 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
677 $profile = new Profile();
679 $profile->query(sprintf($qry, $this->id, $tag));
686 return Design::staticGet('id', $this->design_id);
689 function hasRight($right)
691 $profile = $this->getProfile();
692 return $profile->hasRight($right);
698 $profile = $this->getProfile();
700 } catch (UserNoProfileException $unp) {
701 common_log(LOG_INFO, "User {$this->nickname} has no profile; continuing deletion.");
704 $related = array('Fave',
711 Event::handle('UserDeleteRelated', array($this, &$related));
713 foreach ($related as $cls) {
715 $inst->user_id = $this->id;
719 $this->_deleteTags();
720 $this->_deleteBlocks();
725 function _deleteTags()
727 $tag = new Profile_tag();
728 $tag->tagger = $this->id;
732 function _deleteBlocks()
734 $block = new Profile_block();
735 $block->blocker = $this->id;
737 // XXX delete group block? Reset blocker?
740 function hasRole($name)
742 $profile = $this->getProfile();
743 return $profile->hasRole($name);
746 function grantRole($name)
748 $profile = $this->getProfile();
749 return $profile->grantRole($name);
752 function revokeRole($name)
754 $profile = $this->getProfile();
755 return $profile->revokeRole($name);
758 function isSandboxed()
760 $profile = $this->getProfile();
761 return $profile->isSandboxed();
764 function isSilenced()
766 $profile = $this->getProfile();
767 return $profile->isSilenced();
770 function repeatedByMe($offset=0, $limit=20, $since_id=null, $max_id=null)
772 $ids = Notice::stream(array($this, '_repeatedByMeDirect'),
774 'user:repeated_by_me:'.$this->id,
775 $offset, $limit, $since_id, $max_id, null);
777 return Notice::getStreamByIds($ids);
780 function _repeatedByMeDirect($offset, $limit, $since_id, $max_id)
782 $notice = new Notice();
784 $notice->selectAdd(); // clears it
785 $notice->selectAdd('id');
787 $notice->profile_id = $this->id;
788 $notice->whereAdd('repeat_of IS NOT NULL');
790 $notice->orderBy('created DESC, id DESC');
792 if (!is_null($offset)) {
793 $notice->limit($offset, $limit);
796 Notice::addWhereSinceId($notice, $since_id);
797 Notice::addWhereMaxId($notice, $max_id);
801 if ($notice->find()) {
802 while ($notice->fetch()) {
803 $ids[] = $notice->id;
813 function repeatsOfMe($offset=0, $limit=20, $since_id=null, $max_id=null)
815 $ids = Notice::stream(array($this, '_repeatsOfMeDirect'),
817 'user:repeats_of_me:'.$this->id,
818 $offset, $limit, $since_id, $max_id);
820 return Notice::getStreamByIds($ids);
823 function _repeatsOfMeDirect($offset, $limit, $since_id, $max_id)
826 'SELECT DISTINCT original.id AS id ' .
827 'FROM notice original JOIN notice rept ON original.id = rept.repeat_of ' .
828 'WHERE original.profile_id = ' . $this->id . ' ';
830 $since = Notice::whereSinceId($since_id, 'original.id', 'original.created');
832 $qry .= "AND ($since) ";
835 $max = Notice::whereMaxId($max_id, 'original.id', 'original.created');
837 $qry .= "AND ($max) ";
840 $qry .= 'ORDER BY original.created, original.id DESC ';
842 if (!is_null($offset)) {
843 $qry .= "LIMIT $limit OFFSET $offset";
848 $notice = new Notice();
850 $notice->query($qry);
852 while ($notice->fetch()) {
853 $ids[] = $notice->id;
862 function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
864 throw new Exception("Not implemented since inbox change.");
867 function shareLocation()
869 $cfg = common_config('location', 'share');
871 if ($cfg == 'always') {
873 } else if ($cfg == 'never') {
878 $prefs = User_location_prefs::staticGet('user_id', $this->id);
881 $share = common_config('location', 'sharedefault');
883 $share = $prefs->share_location;
891 static function siteOwner()
893 $owner = self::cacheGet('user:site_owner');
895 if ($owner === false) { // cache miss
897 $pr = new Profile_role();
899 $pr->role = Profile_role::OWNER;
901 $pr->orderBy('created');
905 if ($pr->find(true)) {
906 $owner = User::staticGet('id', $pr->profile_id);
911 self::cacheSet('user:site_owner', $owner);
918 * Pull the primary site account to use in single-user mode.
919 * If a valid user nickname is listed in 'singleuser':'nickname'
920 * in the config, this will be used; otherwise the site owner
921 * account is taken by default.
924 * @throws ServerException if no valid single user account is present
925 * @throws ServerException if called when not in single-user mode
927 static function singleUser()
929 if (common_config('singleuser', 'enabled')) {
933 $nickname = common_config('singleuser', 'nickname');
935 if (!empty($nickname)) {
936 $user = User::staticGet('nickname', $nickname);
939 // if there was no nickname or no user by that nickname,
940 // try the site owner.
943 $user = User::siteOwner();
949 // TRANS: Server exception.
950 throw new ServerException(_('No single user defined for single-user mode.'));
953 // TRANS: Server exception.
954 throw new ServerException(_('Single-user mode code called when not enabled.'));
959 * This is kind of a hack for using external setup code that's trying to
960 * build single-user sites.
962 * Will still return a username if the config singleuser/nickname is set
963 * even if the account doesn't exist, which normally indicates that the
964 * site is horribly misconfigured.
966 * At the moment, we need to let it through so that router setup can
967 * complete, otherwise we won't be able to create the account.
969 * This will be easier when we can more easily create the account and
970 * *then* switch the site to 1user mode without jumping through hoops.
973 * @throws ServerException if no valid single user account is present
974 * @throws ServerException if called when not in single-user mode
976 static function singleUserNickname()
979 $user = User::singleUser();
980 return $user->nickname;
981 } catch (Exception $e) {
982 if (common_config('singleuser', 'enabled') && common_config('singleuser', 'nickname')) {
983 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.");
984 return common_config('singleuser', 'nickname');
991 * Find and shorten links in the given text using this user's URL shortening
994 * By default, links will be left untouched if the text is shorter than the
995 * configured maximum notice length. Pass true for the $always parameter
996 * to force all links to be shortened regardless.
998 * Side effects: may save file and file_redirection records for referenced URLs.
1000 * @param string $text
1001 * @param boolean $always
1004 public function shortenLinks($text, $always=false)
1006 return common_shorten_links($text, $always, $this);
1010 * Get a list of OAuth client applications that have access to this
1013 function getConnectedApps($offset = 0, $limit = null)
1017 'FROM oauth_application_user u, oauth_application a ' .
1018 'WHERE u.profile_id = %d ' .
1019 'AND a.id = u.application_id ' .
1020 'AND u.access_type > 0 ' .
1021 'ORDER BY u.created DESC ';
1024 if (common_config('db','type') == 'pgsql') {
1025 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
1027 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
1031 $apps = new Oauth_application_user();
1033 $cnt = $apps->query(sprintf($qry, $this->id));