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);
119 static function allowed_nickname($nickname)
121 // XXX: should already be validated for size, content, etc.
122 $blacklist = common_config('nickname', 'blacklist');
124 //all directory and file names should be blacklisted
125 $d = dir(INSTALLDIR);
126 while (false !== ($entry = $d->read())) {
131 //all top level names in the router should be blacklisted
132 $router = Router::get();
133 foreach(array_keys($router->m->getPaths()) as $path){
134 if(preg_match('/^\/(.*?)[\/\?]/',$path,$matches)){
135 $blacklist[]=$matches[1];
138 return !in_array($nickname, $blacklist);
142 * Get the most recent notice posted by this user, if any.
144 * @return mixed Notice or null
146 function getCurrentNotice()
148 $profile = $this->getProfile();
149 return $profile->getCurrentNotice();
152 function getCarrier()
154 return Sms_carrier::staticGet('id', $this->carrier);
158 * @deprecated use Subscription::start($sub, $other);
160 function subscribeTo($other)
162 return Subscription::start($this->getProfile(), $other);
165 function hasBlocked($other)
167 $profile = $this->getProfile();
168 return $profile->hasBlocked($other);
172 * Register a new user account and profile and set up default subscriptions.
173 * If a new-user welcome message is configured, this will be sent.
175 * @param array $fields associative array of optional properties
178 * bool 'email_confirmed' pass true to mark email as pre-confirmed
181 * string 'location' informal string description of geolocation
182 * float 'lat' decimal latitude for geolocation
183 * float 'lon' decimal longitude for geolocation
184 * int 'location_id' geoname identifier
185 * int 'location_ns' geoname namespace to interpret location_id
186 * string 'nickname' REQUIRED
187 * string 'password' (may be missing for eg OpenID registrations)
188 * string 'code' invite code
189 * ?string 'uri' permalink to notice; defaults to local notice URL
190 * @return mixed User object or false on failure
192 static function register($fields) {
194 // MAGICALLY put fields into current scope
198 $profile = new Profile();
202 $email = common_canonical_email($email);
205 $nickname = common_canonical_nickname($nickname);
206 $profile->nickname = $nickname;
207 if(! User::allowed_nickname($nickname)){
208 common_log(LOG_WARNING, sprintf("Attempted to register a nickname that is not allowed: %s", $profile->nickname),
212 $profile->profileurl = common_profile_url($nickname);
214 if (!empty($fullname)) {
215 $profile->fullname = $fullname;
217 if (!empty($homepage)) {
218 $profile->homepage = $homepage;
221 $profile->bio = $bio;
223 if (!empty($location)) {
224 $profile->location = $location;
226 $loc = Location::fromName($location);
229 $profile->lat = $loc->lat;
230 $profile->lon = $loc->lon;
231 $profile->location_id = $loc->location_id;
232 $profile->location_ns = $loc->location_ns;
236 $profile->created = common_sql_now();
240 $user->nickname = $nickname;
242 // Users who respond to invite email have proven their ownership of that address
245 $invite = Invitation::staticGet($code);
246 if ($invite && $invite->address && $invite->address_type == 'email' && $invite->address == $email) {
247 $user->email = $invite->address;
251 if(isset($email_confirmed) && $email_confirmed) {
252 $user->email = $email;
255 // This flag is ignored but still set to 1
259 // Set default-on options here, otherwise they'll be disabled
260 // initially for sites using caching, since the initial encache
261 // doesn't know about the defaults in the database.
262 $user->emailnotifysub = 1;
263 $user->emailnotifyfav = 1;
264 $user->emailnotifynudge = 1;
265 $user->emailnotifymsg = 1;
266 $user->emailnotifyattn = 1;
267 $user->emailmicroid = 1;
268 $user->emailpost = 1;
269 $user->jabbermicroid = 1;
270 $user->viewdesigns = 1;
272 $user->created = common_sql_now();
274 if (Event::handle('StartUserRegister', array(&$user, &$profile))) {
276 $profile->query('BEGIN');
278 $id = $profile->insert();
281 common_log_db_error($profile, 'INSERT', __FILE__);
290 $user->uri = common_user_uri($user);
293 if (!empty($password)) { // may not have a password for OpenID users
294 $user->password = common_munge_password($password, $id);
297 $result = $user->insert();
300 common_log_db_error($user, 'INSERT', __FILE__);
304 // Everyone gets an inbox
306 $inbox = new Inbox();
308 $inbox->user_id = $user->id;
309 $inbox->notice_ids = '';
311 $result = $inbox->insert();
314 common_log_db_error($inbox, 'INSERT', __FILE__);
318 // Everyone is subscribed to themself
320 $subscription = new Subscription();
321 $subscription->subscriber = $user->id;
322 $subscription->subscribed = $user->id;
323 $subscription->created = $user->created;
325 $result = $subscription->insert();
328 common_log_db_error($subscription, 'INSERT', __FILE__);
332 if (!empty($email) && !$user->email) {
334 $confirm = new Confirm_address();
335 $confirm->code = common_confirmation_code(128);
336 $confirm->user_id = $user->id;
337 $confirm->address = $email;
338 $confirm->address_type = 'email';
340 $result = $confirm->insert();
343 common_log_db_error($confirm, 'INSERT', __FILE__);
348 if (!empty($code) && $user->email) {
349 $user->emailChanged();
352 // Default system subscription
354 $defnick = common_config('newuser', 'default');
356 if (!empty($defnick)) {
357 $defuser = User::staticGet('nickname', $defnick);
358 if (empty($defuser)) {
359 common_log(LOG_WARNING, sprintf("Default user %s does not exist.", $defnick),
362 Subscription::start($user, $defuser);
366 $profile->query('COMMIT');
368 if (!empty($email) && !$user->email) {
369 mail_confirm_address($user, $confirm->code, $profile->nickname, $email);
374 $welcome = common_config('newuser', 'welcome');
376 if (!empty($welcome)) {
377 $welcomeuser = User::staticGet('nickname', $welcome);
378 if (empty($welcomeuser)) {
379 common_log(LOG_WARNING, sprintf("Welcome user %s does not exist.", $defnick),
382 $notice = Notice::saveNew($welcomeuser->id,
383 // TRANS: Notice given on user registration.
384 // TRANS: %1$s is the sitename, $2$s is the registering user's nickname.
385 sprintf(_('Welcome to %1$s, @%2$s!'),
386 common_config('site', 'name'),
392 Event::handle('EndUserRegister', array(&$profile, &$user));
398 // Things we do when the email changes
399 function emailChanged()
402 $invites = new Invitation();
403 $invites->address = $this->email;
404 $invites->address_type = 'email';
406 if ($invites->find()) {
407 while ($invites->fetch()) {
408 $other = User::staticGet($invites->user_id);
409 subs_subscribe_to($other, $this);
414 function hasFave($notice)
416 $profile = $this->getProfile();
417 return $profile->hasFave($notice);
420 function mutuallySubscribed($other)
422 $profile = $this->getProfile();
423 return $profile->mutuallySubscribed($other);
426 function mutuallySubscribedUsers()
428 // 3-way join; probably should get cached
429 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
430 $qry = "SELECT $UT.* " .
431 "FROM subscription sub1 JOIN $UT ON sub1.subscribed = $UT.id " .
432 "JOIN subscription sub2 ON $UT.id = sub2.subscriber " .
433 'WHERE sub1.subscriber = %d and sub2.subscribed = %d ' .
434 "ORDER BY $UT.nickname";
436 $user->query(sprintf($qry, $this->id, $this->id));
441 function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
443 $ids = Reply::stream($this->id, $offset, $limit, $since_id, $before_id);
444 return Notice::getStreamByIds($ids);
447 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0) {
448 $profile = $this->getProfile();
449 return $profile->getTaggedNotices($tag, $offset, $limit, $since_id, $before_id);
452 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
454 $profile = $this->getProfile();
455 return $profile->getNotices($offset, $limit, $since_id, $before_id);
458 function favoriteNotices($own=false, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
460 $ids = Fave::stream($this->id, $offset, $limit, $own, $since_id, $max_id);
461 return Notice::getStreamByIds($ids);
464 function noticesWithFriends($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
466 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, false);
469 function noticeInbox($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
471 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, true);
474 function friendsTimeline($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 ownFriendsTimeline($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 blowFavesCache()
486 $profile = $this->getProfile();
487 $profile->blowFavesCache();
490 function getSelfTags()
492 return Profile_tag::getTags($this->id, $this->id);
495 function setSelfTags($newtags)
497 return Profile_tag::setTags($this->id, $this->id, $newtags);
500 function block($other)
502 // Add a new block record
504 // no blocking (and thus unsubbing from) yourself
506 if ($this->id == $other->id) {
507 common_log(LOG_WARNING,
509 "Profile ID %d (%s) tried to block themself.",
517 $block = new Profile_block();
519 // Begin a transaction
521 $block->query('BEGIN');
523 $block->blocker = $this->id;
524 $block->blocked = $other->id;
526 $result = $block->insert();
529 common_log_db_error($block, 'INSERT', __FILE__);
533 $self = $this->getProfile();
534 if (Subscription::exists($other, $self)) {
535 Subscription::cancel($other, $self);
537 if (Subscription::exists($self, $other)) {
538 Subscription::cancel($self, $other);
541 $block->query('COMMIT');
546 function unblock($other)
548 // Get the block record
550 $block = Profile_block::get($this->id, $other->id);
556 $result = $block->delete();
559 common_log_db_error($block, 'DELETE', __FILE__);
566 function isMember($group)
568 $profile = $this->getProfile();
569 return $profile->isMember($group);
572 function isAdmin($group)
574 $profile = $this->getProfile();
575 return $profile->isAdmin($group);
578 function getGroups($offset=0, $limit=null)
580 $profile = $this->getProfile();
581 return $profile->getGroups($offset, $limit);
584 function getSubscriptions($offset=0, $limit=null)
586 $profile = $this->getProfile();
587 return $profile->getSubscriptions($offset, $limit);
590 function getSubscribers($offset=0, $limit=null)
592 $profile = $this->getProfile();
593 return $profile->getSubscribers($offset, $limit);
596 function getTaggedSubscribers($tag, $offset=0, $limit=null)
599 'SELECT profile.* ' .
600 'FROM profile JOIN subscription ' .
601 'ON profile.id = subscription.subscriber ' .
602 'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
603 'AND profile_tag.tagger = subscription.subscribed) ' .
604 'WHERE subscription.subscribed = %d ' .
605 "AND profile_tag.tag = '%s' " .
606 'AND subscription.subscribed != subscription.subscriber ' .
607 'ORDER BY subscription.created DESC ';
610 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
613 $profile = new Profile();
615 $cnt = $profile->query(sprintf($qry, $this->id, $tag));
620 function getTaggedSubscriptions($tag, $offset=0, $limit=null)
623 'SELECT profile.* ' .
624 'FROM profile JOIN subscription ' .
625 'ON profile.id = subscription.subscribed ' .
626 'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
627 'AND profile_tag.tagger = subscription.subscriber) ' .
628 'WHERE subscription.subscriber = %d ' .
629 "AND profile_tag.tag = '%s' " .
630 'AND subscription.subscribed != subscription.subscriber ' .
631 'ORDER BY subscription.created DESC ';
633 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
635 $profile = new Profile();
637 $profile->query(sprintf($qry, $this->id, $tag));
644 return Design::staticGet('id', $this->design_id);
647 function hasRight($right)
649 $profile = $this->getProfile();
650 return $profile->hasRight($right);
656 $profile = $this->getProfile();
658 } catch (UserNoProfileException $unp) {
659 common_log(LOG_INFO, "User {$this->nickname} has no profile; continuing deletion.");
662 $related = array('Fave',
669 Event::handle('UserDeleteRelated', array($this, &$related));
671 foreach ($related as $cls) {
673 $inst->user_id = $this->id;
677 $this->_deleteTags();
678 $this->_deleteBlocks();
683 function _deleteTags()
685 $tag = new Profile_tag();
686 $tag->tagger = $this->id;
690 function _deleteBlocks()
692 $block = new Profile_block();
693 $block->blocker = $this->id;
695 // XXX delete group block? Reset blocker?
698 function hasRole($name)
700 $profile = $this->getProfile();
701 return $profile->hasRole($name);
704 function grantRole($name)
706 $profile = $this->getProfile();
707 return $profile->grantRole($name);
710 function revokeRole($name)
712 $profile = $this->getProfile();
713 return $profile->revokeRole($name);
716 function isSandboxed()
718 $profile = $this->getProfile();
719 return $profile->isSandboxed();
722 function isSilenced()
724 $profile = $this->getProfile();
725 return $profile->isSilenced();
728 function repeatedByMe($offset=0, $limit=20, $since_id=null, $max_id=null)
730 $ids = Notice::stream(array($this, '_repeatedByMeDirect'),
732 'user:repeated_by_me:'.$this->id,
733 $offset, $limit, $since_id, $max_id, null);
735 return Notice::getStreamByIds($ids);
738 function _repeatedByMeDirect($offset, $limit, $since_id, $max_id)
740 $notice = new Notice();
742 $notice->selectAdd(); // clears it
743 $notice->selectAdd('id');
745 $notice->profile_id = $this->id;
746 $notice->whereAdd('repeat_of IS NOT NULL');
748 $notice->orderBy('id DESC');
750 if (!is_null($offset)) {
751 $notice->limit($offset, $limit);
754 if ($since_id != 0) {
755 $notice->whereAdd('id > ' . $since_id);
759 $notice->whereAdd('id <= ' . $max_id);
764 if ($notice->find()) {
765 while ($notice->fetch()) {
766 $ids[] = $notice->id;
776 function repeatsOfMe($offset=0, $limit=20, $since_id=null, $max_id=null)
778 $ids = Notice::stream(array($this, '_repeatsOfMeDirect'),
780 'user:repeats_of_me:'.$this->id,
781 $offset, $limit, $since_id, $max_id);
783 return Notice::getStreamByIds($ids);
786 function _repeatsOfMeDirect($offset, $limit, $since_id, $max_id)
789 'SELECT DISTINCT original.id AS id ' .
790 'FROM notice original JOIN notice rept ON original.id = rept.repeat_of ' .
791 'WHERE original.profile_id = ' . $this->id . ' ';
793 if ($since_id != 0) {
794 $qry .= 'AND original.id > ' . $since_id . ' ';
798 $qry .= 'AND original.id <= ' . $max_id . ' ';
801 // NOTE: we sort by fave time, not by notice time!
803 $qry .= 'ORDER BY original.id DESC ';
805 if (!is_null($offset)) {
806 $qry .= "LIMIT $limit OFFSET $offset";
811 $notice = new Notice();
813 $notice->query($qry);
815 while ($notice->fetch()) {
816 $ids[] = $notice->id;
825 function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
827 throw new Exception("Not implemented since inbox change.");
830 function shareLocation()
832 $cfg = common_config('location', 'share');
834 if ($cfg == 'always') {
836 } else if ($cfg == 'never') {
841 $prefs = User_location_prefs::staticGet('user_id', $this->id);
844 $share = common_config('location', 'sharedefault');
846 $share = $prefs->share_location;
854 static function siteOwner()
856 $owner = self::cacheGet('user:site_owner');
858 if ($owner === false) { // cache miss
860 $pr = new Profile_role();
862 $pr->role = Profile_role::OWNER;
864 $pr->orderBy('created');
868 if ($pr->find(true)) {
869 $owner = User::staticGet('id', $pr->profile_id);
874 self::cacheSet('user:site_owner', $owner);
881 * Pull the primary site account to use in single-user mode.
882 * If a valid user nickname is listed in 'singleuser':'nickname'
883 * in the config, this will be used; otherwise the site owner
884 * account is taken by default.
887 * @throws ServerException if no valid single user account is present
888 * @throws ServerException if called when not in single-user mode
890 static function singleUser()
892 if (common_config('singleuser', 'enabled')) {
896 $nickname = common_config('singleuser', 'nickname');
898 if (!empty($nickname)) {
899 $user = User::staticGet('nickname', $nickname);
902 // if there was no nickname or no user by that nickname,
903 // try the site owner.
906 $user = User::siteOwner();
912 // TRANS: Server exception.
913 throw new ServerException(_('No single user defined for single-user mode.'));
916 // TRANS: Server exception.
917 throw new ServerException(_('Single-user mode code called when not enabled.'));
922 * This is kind of a hack for using external setup code that's trying to
923 * build single-user sites.
925 * Will still return a username if the config singleuser/nickname is set
926 * even if the account doesn't exist, which normally indicates that the
927 * site is horribly misconfigured.
929 * At the moment, we need to let it through so that router setup can
930 * complete, otherwise we won't be able to create the account.
932 * This will be easier when we can more easily create the account and
933 * *then* switch the site to 1user mode without jumping through hoops.
936 * @throws ServerException if no valid single user account is present
937 * @throws ServerException if called when not in single-user mode
939 static function singleUserNickname()
942 $user = User::singleUser();
943 return $user->nickname;
944 } catch (Exception $e) {
945 if (common_config('singleuser', 'enabled') && common_config('singleuser', 'nickname')) {
946 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.");
947 return common_config('singleuser', 'nickname');